Skip to main content
summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorPhilipe Mulet2001-06-27 11:27:24 +0000
committerPhilipe Mulet2001-06-27 11:27:24 +0000
commit6a230a9d6ae1a4a6adbf38879cb9ee685eccffe9 (patch)
treee05b8ab1235babd084ed8b274999d167d939ae44 /org.eclipse.jdt.core
parentb04602938404af4f8569a399fb36a5018768a262 (diff)
downloadeclipse.jdt.core-6a230a9d6ae1a4a6adbf38879cb9ee685eccffe9.tar.gz
eclipse.jdt.core-6a230a9d6ae1a4a6adbf38879cb9ee685eccffe9.tar.xz
eclipse.jdt.core-6a230a9d6ae1a4a6adbf38879cb9ee685eccffe9.zip
externalization in progress
Diffstat (limited to 'org.eclipse.jdt.core')
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetCodeStream.java2
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetCompiler.java32
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetConstantPool.java3094
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetEnvironment.java107
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetEvaluator.java318
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetFieldReference.java578
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetMessageSend.java410
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetParser.java1253
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetQualifiedNameReference.java998
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetReturnStatement.java199
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetScope.java1495
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetSingleNameReference.java1044
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetSkeleton.java155
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetThisReference.java129
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetToCuMapper.java563
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetTypeDeclaration.java106
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/EvaluationConstants.java25
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/EvaluationContext.java1767
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/EvaluationResult.java341
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/Evaluator.java252
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/GlobalVariable.java98
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/IRequestor.java16
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/InstallException.java32
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/VariablesEvaluator.java507
-rw-r--r--org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/VariablesInfo.java83
-rw-r--r--org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/CodeFormatter.java4014
-rw-r--r--org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/impl/FormatterOptions.java390
-rw-r--r--org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/impl/SplitLine.java381
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/BufferChangedEvent.java101
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/ElementChangedEvent.java34
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/Flags.java66
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IBuffer.java397
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IClassFile.java91
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IClasspathEntry.java190
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/ICodeAssist.java61
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/ICodeCompletionRequestor.java485
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/ICompilationUnit.java376
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IElementChangedListener.java16
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IField.java48
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IImportContainer.java13
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IImportDeclaration.java31
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IInitializer.java2
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaElement.java218
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaElementDelta.java126
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModel.java319
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelMarker.java21
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelStatus.java82
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelStatusConstants.java56
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaProject.java569
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IMember.java95
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IMethod.java172
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IOpenable.java217
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IPackageDeclaration.java10
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IPackageFragment.java210
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IPackageFragmentRoot.java232
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IParent.java36
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IRegion.java50
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/ISourceManipulation.java195
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/ISourceRange.java20
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/ISourceReference.java58
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IType.java562
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/ITypeHierarchy.java326
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/ITypeHierarchyChangedListener.java12
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/IWorkingCopy.java198
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaConventions.java754
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaCore.java1973
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaModelException.java183
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/Signature.java1290
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/eval/ICodeSnippetRequestor.java160
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/eval/IEvaluationContext.java424
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/eval/IGlobalVariable.java48
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/eval/package.html17
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/DOMException.java27
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/DOMFactory.java269
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMCompilationUnit.java82
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMFactory.java262
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMField.java106
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMImport.java44
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMInitializer.java54
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMMember.java70
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMMethod.java318
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMNode.java369
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMPackage.java30
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMType.java201
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/package.html17
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/core/package.html19
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Assert.java161
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BasicCompilationUnit.java115
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryField.java74
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryMember.java186
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryMethod.java264
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryType.java654
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Buffer.java1193
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BufferCache.java60
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BufferManager.java326
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ClassFile.java786
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ClassFileInfo.java273
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ClasspathEntry.java269
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java198
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnit.java1143
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitElementInfo.java62
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitStructureRequestor.java1036
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitVisitor.java39
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompletionRequestorWrapper.java287
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CopyElementsOperation.java400
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java851
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateCompilationUnitOperation.java119
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateElementInCUOperation.java419
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateFieldOperation.java129
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateImportOperation.java166
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateInitializerOperation.java146
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateMethodOperation.java146
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreatePackageDeclarationOperation.java181
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreatePackageFragmentOperation.java175
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateTypeHierarchyOperation.java129
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateTypeMemberOperation.java195
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateTypeOperation.java134
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/DeleteElementsOperation.java226
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/DeleteResourceElementsOperation.java180
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/DeltaProcessor.java56
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ElementCache.java67
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/FailedReconciliationException.java28
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/HandleFactory.java130
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/IBufferManager.java34
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/IJavaElementRequestor.java22
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/IJavaReconciler.java76
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/INameLookup.java214
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/IPathRequestor.java2
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ImportContainer.java127
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ImportDeclaration.java89
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Initializer.java136
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/InitializerElementInfo.java3
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarEntryFile.java79
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragment.java248
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragmentInfo.java41
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java45
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragmentRootInfo.java45
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElement.java1061
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementDelta.java1036
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementDeltaBuilder.java714
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementInfo.java179
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementRequestor.java318
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModel.java1008
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelInfo.java61
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelManager.java87
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelOperation.java932
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelStatus.java563
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaProject.java271
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaProjectElementInfo.java258
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/LRUCacheEnumerator.java46
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Member.java294
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/MemberElementInfo.java123
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Messages.properties136
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/MoveElementsOperation.java44
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/MoveResourceElementsOperation.java45
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/MultiOperation.java555
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/NameLookup.java471
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/NonVoidMethodRequestor.java28
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Openable.java660
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/OpenableElementInfo.java4
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/OverflowingLRUCache.java442
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageDeclaration.java58
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragment.java582
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragmentInfo.java143
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java584
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragmentRootInfo.java179
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Problem.java358
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Region.java218
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/RenameElementsOperation.java115
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/RenameResourceElementsOperation.java84
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SearchableEnvironment.java535
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SearchableEnvironmentRequestor.java107
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SelectionRequestor.java440
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SetClasspathOperation.java289
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SetOutputLocationOperation.java334
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SingleTypeRequestor.java116
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceField.java103
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceFieldElementInfo.java93
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMapper.java908
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMethod.java361
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMethodElementInfo.java100
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceRange.java59
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceRefElement.java360
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceRefElementInfo.java67
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceType.java639
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceTypeElementInfo.java431
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/TypeVector.java188
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Util.java1037
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ValidateSourceElementOperation.java77
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/WorkingCopy.java547
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/BinaryBrokerKey.java11
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/BuildEvent.java16
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/DeltaKey.java224
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IConstructor.java1
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IDelta.java44
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IDeltaKey.java8
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IDevelopmentContext.java27
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IField.java1
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IHandle.java4
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IImage.java7
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IImageBuilder.java34
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IImageContext.java29
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IMember.java1
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IMethod.java1
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IPackage.java6
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IProblemReporter.java114
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IReportCard.java86
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ISearch.java139
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ISearchFactory.java392
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ISearchListener.java44
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ISourceFragment.java3
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IState.java71
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IType.java45
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/InvalidKeyException.java2
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/MemoryBinaryBroker.java80
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/NotPresentException.java6
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/SearchProgressEvent.java32
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/SearchResultEvent.java69
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/StateSpecificException.java6
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractImageBuilder.java298
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractMemberHandle.java65
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractMemberHandleSWH.java21
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractMethodCollaboratorIndictment.java39
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractNode.java138
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ArrayTypeHandleImpl.java209
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ArrayTypeHandleImplSWH.java128
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BatchImageBuilder.java179
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BinaryBrokerOutput.java136
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BinaryOutput.java99
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BinaryStructure.java671
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BuildMonitorImpl.java13
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BuildNotifier.java413
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BuilderEnvironment.java196
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BuilderType.java313
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ClassOrInterfaceHandleImpl.java864
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ClassOrInterfaceHandleImplSWH.java1093
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/CompilerCompilationUnit.java88
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ConsoleProgressMonitor.java15
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ConstructorImpl.java64
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ConstructorImplSWH.java182
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ConvertedCompilationResult.java33
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/DeltaImpl.java483
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/DependencyGraph.java439
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/DependencyGraphImpl.java16
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/FieldCollaboratorIndictment.java34
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/FieldImpl.java49
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/FieldImplSWH.java161
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ImageBuilderInternalException.java51
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ImageContextImpl.java34
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ImageImpl.java322
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ImageImplSWH.java354
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/IncrementalImageBuilder.java3119
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/Indictment.java64
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/IndictmentSet.java210
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JCUNode.java14
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JavaBuilder.java323
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JavaDevelopmentContextImpl.java610
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/MarkerProblemReporter.java472
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/MethodCollaboratorIndictment.java37
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/MethodImpl.java57
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/MethodImplSWH.java214
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ModifiedBuilderType.java406
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/NamespaceNode.java10
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/NewBuilderType.java82
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/NonStateSpecificHandleImpl.java190
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/OldBuilderType.java86
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/OrderedSet.java415
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageElement.java31
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageImpl.java290
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageImplSWH.java267
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageMap.java25
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageMapEntry.java50
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PathMap.java88
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PrimitiveTypeHandleImpl.java389
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PrimitiveTypeHandleImplSWH.java6
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProblemDetailImpl.java369
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProblemFactory.java177
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProblemTable.java270
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProjectBinaryOutput.java378
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProjectResourceCopier.java391
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ReportCardImpl.java235
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/SourceElementTable.java94
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/SourceEntry.java118
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/SourceFragmentImpl.java47
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateImpl.java1097
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSnap.java75
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSnapConstantPool.java1158
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSnapV5.java1315
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSnapV6.java93
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSpecificHandleImpl.java28
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeCollaboratorIndictment.java31
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeHierarchyIndictment.java34
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeImpl.java903
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeImplSWH.java902
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeNode.java21
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeStructureEntry.java57
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/UnmodifiedBuilderType.java90
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/WorkQueue.java157
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ZipNode.java80
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java532
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/eval/GlobalVariableWrapper.java60
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/eval/RequestorWrapper.java93
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBinaryType.java366
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java254
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java823
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedHierarchyBuilder.java323
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedTypeHierarchy.java138
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java2053
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/AbstractDOMBuilder.java292
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/CompilationUnit.java53
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMBuilder.java1353
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMCompilationUnit.java298
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMField.java1117
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMImport.java261
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMInitializer.java404
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMMember.java566
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java1228
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMNode.java1465
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMPackage.java227
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMType.java1120
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/ILineStartFinder.java14
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/NullProblem.java205
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/NullProblemFactory.java53
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/SiblingEnumeration.java50
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/SimpleDOMBuilder.java510
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/lookup/ReferenceInfo.java70
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/AnonymousFileSource.java215
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/CharArrayBuffer.java270
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/CharArrayOps.java243
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/DiskCache.java332
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/DiskCacheEntry.java13
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/Dumper.java514
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/HackFinder.java22
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/IProgressListener.java42
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/LRUCache.java253
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/LookupTable.java286
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/ReferenceInfoAdapter.java82
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/StringHashtableOfInt.java204
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/StringMatcher.java127
-rw-r--r--org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/ToStringSorter.java110
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/IJavaSearchConstants.java39
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/IJavaSearchResultCollector.java74
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/IJavaSearchScope.java104
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/ISearchPattern.java2
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/ITypeNameRequestor.java68
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/SearchEngine.java1037
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/package.html18
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/DocumentFactory.java2
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/IEntryResult.java4
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/IIndexer.java3
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/IndexFactory.java10
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Block.java9
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/BlocksIndexInput.java373
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/BlocksIndexOutput.java81
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/CodeByteStream.java251
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/EntryResult.java99
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Field.java329
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/FileDocument.java14
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/FileListBlock.java62
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/GammaCompressedIndexBlock.java68
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/HashtableOfObject.java76
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IFileDocument.java36
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IIndexConstants.java6
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/InMemoryIndex.java99
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Index.java169
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexBlock.java12
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexInput.java24
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexSummary.java272
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexedFile.java78
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexerOutput.java8
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Int.java3
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/JarFileDocument.java69
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/JarFileEntryDocument.java75
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/LRUCache.java112
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/MemoryCheckThread.java8
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/MergeFactory.java147
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/ObjectVector.java43
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/PropertyDocument.java6
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/SafeRandomAccessFile.java9
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/SimpleIndexBlock.java55
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/SimpleIndexInput.java87
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Util.java236
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/WordEntry.java93
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/AbstractSearchScope.java48
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/HierarchyScope.java219
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/IIndexSearchRequestor.java167
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/IndexSearchAdapter.java150
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/IndexSelector.java338
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/JavaSearchScope.java294
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/JavaWorkspaceScope.java13
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/PathCollector.java255
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/PatternSearchJob.java191
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/SubTypeSearchJob.java137
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AbstractIndexer.java1225
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AddClassFileToIndex.java97
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AddCompilationUnitToIndex.java99
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java274
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java1086
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/IIndexConstants.java41
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java174
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java599
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/ReadWriteMonitor.java80
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/RemoveFromIndex.java70
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/SourceIndexer.java74
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/SourceIndexerRequestor.java474
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/AndPattern.java161
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/ConstructorDeclarationPattern.java441
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/ConstructorReferencePattern.java373
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/FieldDeclarationPattern.java444
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/FieldReferencePattern.java611
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java1406
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MatchLocatorParser.java264
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MatchSet.java459
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MethodDeclarationPattern.java466
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MethodPattern.java206
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MethodReferencePattern.java316
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MultipleSearchPattern.java43
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/OrNameCombiner.java94
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/OrPathCombiner.java202
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/OrPattern.java22
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/PackageDeclarationPattern.java167
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/PackageReferencePattern.java502
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/SearchPattern.java2225
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/SuperInterfaceReferencePattern.java115
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/SuperTypeReferencePattern.java377
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/TypeDeclarationPattern.java560
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/TypeReferencePattern.java794
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/processing/IJob.java20
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/processing/IJobConstants.java2
-rw-r--r--org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/processing/JobManager.java423
430 files changed, 55911 insertions, 67589 deletions
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetCodeStream.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetCodeStream.java
index 500f5bbb57..5011b8c184 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetCodeStream.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetCodeStream.java
@@ -65,7 +65,7 @@ public void generateEmulatedReadAccessForField(FieldBinding fieldBinding) {
// swap the field with the receiver
this.swap();
localCodeStream.invokeJavaLangReflectFieldGetter(fieldBinding.type.id);
- if (fieldBinding.type.isArrayType()) {
+ if (!fieldBinding.type.isBaseType()) {
this.checkcast(fieldBinding.type);
}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetCompiler.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetCompiler.java
index 4f22535e30..00f8dd7cea 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetCompiler.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetCompiler.java
@@ -12,27 +12,21 @@ import org.eclipse.jdt.internal.compiler.env.INameEnvironment;
* A compiler that compiles code snippets.
*/
public class CodeSnippetCompiler extends Compiler {
- /**
- * Creates a new code snippet compiler initialized with a code snippet parser.
- */
- public CodeSnippetCompiler(
- INameEnvironment environment,
- IErrorHandlingPolicy policy,
- ConfigurableOption[] settings,
- ICompilerRequestor requestor,
+/**
+ * Creates a new code snippet compiler initialized with a code snippet parser.
+ */
+public CodeSnippetCompiler(
+ INameEnvironment environment,
+ IErrorHandlingPolicy policy,
+ ConfigurableOption[] settings,
+ ICompilerRequestor requestor,
IProblemFactory problemFactory,
EvaluationContext evaluationContext,
int codeSnippetStart,
int codeSnippetEnd) {
- super(environment, policy, settings, requestor, problemFactory);
- this.parser =
- new CodeSnippetParser(
- problemReporter,
- evaluationContext,
- this.options.parseLiteralExpressionsAsConstants,
- codeSnippetStart,
- codeSnippetEnd);
- this.parseThreshold = 1; // fully parse only the code snippet compilation unit
- }
-
+ super(environment, policy, settings, requestor, problemFactory);
+ this.parser =
+ new CodeSnippetParser(problemReporter, evaluationContext, this.options.parseLiteralExpressionsAsConstants, codeSnippetStart, codeSnippetEnd);
+ this.parseThreshold = 1; // fully parse only the code snippet compilation unit
+}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetConstantPool.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetConstantPool.java
index 0003f376fc..0ceed812ab 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetConstantPool.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetConstantPool.java
@@ -12,34 +12,23 @@ import org.eclipse.jdt.internal.compiler.util.*;
* This constant pool is used to manage well known methods and fields related specifically to the
* code snippet code generation (java.lang.reflect classes).
*/
-public class CodeSnippetConstantPool
- extends ConstantPool
- implements TypeConstants {
+public class CodeSnippetConstantPool extends ConstantPool implements TypeConstants {
// predefined type constant names
- final static char[][] JAVA_LANG_REFLECT_FIELD =
- new char[][] { JAVA, LANG, REFLECT, "Field".toCharArray()};
- final static char[][] JAVA_LANG_REFLECT_ACCESSIBLEOBJECT =
- new char[][] { JAVA, LANG, REFLECT, "AccessibleObject".toCharArray()};
- final static char[][] JAVA_LANG_REFLECT_METHOD =
- new char[][] { JAVA, LANG, REFLECT, "Method".toCharArray()};
- final static char[][] JAVA_LANG_REFLECT_ARRAY =
- new char[][] { JAVA, LANG, REFLECT, "Array".toCharArray()};
+ final static char[][] JAVA_LANG_REFLECT_FIELD = new char[][] {JAVA, LANG, REFLECT, "Field".toCharArray()};
+ final static char[][] JAVA_LANG_REFLECT_ACCESSIBLEOBJECT = new char[][] {JAVA, LANG, REFLECT, "AccessibleObject".toCharArray()};
+ final static char[][] JAVA_LANG_REFLECT_METHOD = new char[][] {JAVA, LANG, REFLECT, "Method".toCharArray()};
+ final static char[][] JAVA_LANG_REFLECT_ARRAY = new char[][] {JAVA, LANG, REFLECT, "Array".toCharArray()};
// predefined methods constant names
final static char[] GETDECLAREDFIELD_NAME = "getDeclaredField".toCharArray();
- final static char[] GETDECLAREDFIELD_SIGNATURE =
- "(Ljava/lang/String;)Ljava/lang/reflect/Field;".toCharArray();
+ final static char[] GETDECLAREDFIELD_SIGNATURE = "(Ljava/lang/String;)Ljava/lang/reflect/Field;".toCharArray();
final static char[] SETACCESSIBLE_NAME = "setAccessible".toCharArray();
final static char[] SETACCESSIBLE_SIGNATURE = "(Z)V".toCharArray();
- final static char[] JAVALANGREFLECTFIELD_CONSTANTPOOLNAME =
- "java/lang/reflect/Field".toCharArray();
- final static char[] JAVALANGREFLECTACCESSIBLEOBJECT_CONSTANTPOOLNAME =
- "java/lang/reflect/AccessibleObject".toCharArray();
- final static char[] JAVALANGREFLECTARRAY_CONSTANTPOOLNAME =
- "java/lang/reflect/Array".toCharArray();
- final static char[] JAVALANGREFLECTMETHOD_CONSTANTPOOLNAME =
- "java/lang/reflect/Method".toCharArray();
+ final static char[] JAVALANGREFLECTFIELD_CONSTANTPOOLNAME = "java/lang/reflect/Field".toCharArray();
+ final static char[] JAVALANGREFLECTACCESSIBLEOBJECT_CONSTANTPOOLNAME = "java/lang/reflect/AccessibleObject".toCharArray();
+ final static char[] JAVALANGREFLECTARRAY_CONSTANTPOOLNAME = "java/lang/reflect/Array".toCharArray();
+ final static char[] JAVALANGREFLECTMETHOD_CONSTANTPOOLNAME = "java/lang/reflect/Method".toCharArray();
final static char[] GET_INT_METHOD_NAME = "getInt".toCharArray();
final static char[] GET_LONG_METHOD_NAME = "getLong".toCharArray();
final static char[] GET_DOUBLE_METHOD_NAME = "getDouble".toCharArray();
@@ -50,24 +39,15 @@ public class CodeSnippetConstantPool
final static char[] GET_OBJECT_METHOD_NAME = "get".toCharArray();
final static char[] GET_SHORT_METHOD_NAME = "getShort".toCharArray();
final static char[] ARRAY_NEWINSTANCE_NAME = "newInstance".toCharArray();
- final static char[] GET_INT_METHOD_SIGNATURE =
- "(Ljava/lang/Object;)I".toCharArray();
- final static char[] GET_LONG_METHOD_SIGNATURE =
- "(Ljava/lang/Object;)J".toCharArray();
- final static char[] GET_DOUBLE_METHOD_SIGNATURE =
- "(Ljava/lang/Object;)D".toCharArray();
- final static char[] GET_FLOAT_METHOD_SIGNATURE =
- "(Ljava/lang/Object;)F".toCharArray();
- final static char[] GET_BYTE_METHOD_SIGNATURE =
- "(Ljava/lang/Object;)B".toCharArray();
- final static char[] GET_CHAR_METHOD_SIGNATURE =
- "(Ljava/lang/Object;)C".toCharArray();
- final static char[] GET_BOOLEAN_METHOD_SIGNATURE =
- "(Ljava/lang/Object;)Z".toCharArray();
- final static char[] GET_OBJECT_METHOD_SIGNATURE =
- "(Ljava/lang/Object;)Ljava/lang/Object;".toCharArray();
- final static char[] GET_SHORT_METHOD_SIGNATURE =
- "(Ljava/lang/Object;)S".toCharArray();
+ final static char[] GET_INT_METHOD_SIGNATURE = "(Ljava/lang/Object;)I".toCharArray();
+ final static char[] GET_LONG_METHOD_SIGNATURE = "(Ljava/lang/Object;)J".toCharArray();
+ final static char[] GET_DOUBLE_METHOD_SIGNATURE = "(Ljava/lang/Object;)D".toCharArray();
+ final static char[] GET_FLOAT_METHOD_SIGNATURE = "(Ljava/lang/Object;)F".toCharArray();
+ final static char[] GET_BYTE_METHOD_SIGNATURE = "(Ljava/lang/Object;)B".toCharArray();
+ final static char[] GET_CHAR_METHOD_SIGNATURE = "(Ljava/lang/Object;)C".toCharArray();
+ final static char[] GET_BOOLEAN_METHOD_SIGNATURE = "(Ljava/lang/Object;)Z".toCharArray();
+ final static char[] GET_OBJECT_METHOD_SIGNATURE = "(Ljava/lang/Object;)Ljava/lang/Object;".toCharArray();
+ final static char[] GET_SHORT_METHOD_SIGNATURE = "(Ljava/lang/Object;)S".toCharArray();
final static char[] SET_INT_METHOD_NAME = "setInt".toCharArray();
final static char[] SET_LONG_METHOD_NAME = "setLong".toCharArray();
final static char[] SET_DOUBLE_METHOD_NAME = "setDouble".toCharArray();
@@ -78,45 +58,29 @@ public class CodeSnippetConstantPool
final static char[] SET_OBJECT_METHOD_NAME = "set".toCharArray();
final static char[] SET_SHORT_METHOD_NAME = "setShort".toCharArray();
final static char[] GETCLASS_OBJECT_METHOD_NAME = "getClass".toCharArray();
- final static char[] SET_INT_METHOD_SIGNATURE =
- "(Ljava/lang/Object;I)V".toCharArray();
- final static char[] SET_LONG_METHOD_SIGNATURE =
- "(Ljava/lang/Object;J)V".toCharArray();
- final static char[] SET_DOUBLE_METHOD_SIGNATURE =
- "(Ljava/lang/Object;D)V".toCharArray();
- final static char[] SET_FLOAT_METHOD_SIGNATURE =
- "(Ljava/lang/Object;F)V".toCharArray();
- final static char[] SET_BYTE_METHOD_SIGNATURE =
- "(Ljava/lang/Object;B)V".toCharArray();
- final static char[] SET_CHAR_METHOD_SIGNATURE =
- "(Ljava/lang/Object;C)V".toCharArray();
- final static char[] SET_BOOLEAN_METHOD_SIGNATURE =
- "(Ljava/lang/Object;Z)V".toCharArray();
- final static char[] SET_OBJECT_METHOD_SIGNATURE =
- "(Ljava/lang/Object;Ljava/lang/Object;)V".toCharArray();
- final static char[] SET_SHORT_METHOD_SIGNATURE =
- "(Ljava/lang/Object;S)V".toCharArray();
+ final static char[] SET_INT_METHOD_SIGNATURE = "(Ljava/lang/Object;I)V".toCharArray();
+ final static char[] SET_LONG_METHOD_SIGNATURE = "(Ljava/lang/Object;J)V".toCharArray();
+ final static char[] SET_DOUBLE_METHOD_SIGNATURE = "(Ljava/lang/Object;D)V".toCharArray();
+ final static char[] SET_FLOAT_METHOD_SIGNATURE = "(Ljava/lang/Object;F)V".toCharArray();
+ final static char[] SET_BYTE_METHOD_SIGNATURE = "(Ljava/lang/Object;B)V".toCharArray();
+ final static char[] SET_CHAR_METHOD_SIGNATURE = "(Ljava/lang/Object;C)V".toCharArray();
+ final static char[] SET_BOOLEAN_METHOD_SIGNATURE = "(Ljava/lang/Object;Z)V".toCharArray();
+ final static char[] SET_OBJECT_METHOD_SIGNATURE = "(Ljava/lang/Object;Ljava/lang/Object;)V".toCharArray();
+ final static char[] SET_SHORT_METHOD_SIGNATURE = "(Ljava/lang/Object;S)V".toCharArray();
final static char[] GETDECLAREDMETHOD_NAME = "getDeclaredMethod".toCharArray();
- final static char[] GETDECLAREDMETHOD_SIGNATURE =
- "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;"
- .toCharArray();
- final static char[] ARRAY_NEWINSTANCE_SIGNATURE =
- "(Ljava/lang/Class;[I)Ljava/lang/Object;".toCharArray();
- final static char[] GETCLASS_OBJECT_METHOD_SIGNATURE =
- "()Ljava/lang/Class;".toCharArray();
+ final static char[] GETDECLAREDMETHOD_SIGNATURE = "(Ljava/lang/String;[Ljava/lang/Class;)Ljava/lang/reflect/Method;".toCharArray();
+ final static char[] ARRAY_NEWINSTANCE_SIGNATURE = "(Ljava/lang/Class;[I)Ljava/lang/Object;".toCharArray();
+ final static char[] GETCLASS_OBJECT_METHOD_SIGNATURE = "()Ljava/lang/Class;".toCharArray();
final static char[] INVOKE_METHOD_METHOD_NAME = "invoke".toCharArray();
- final static char[] INVOKE_METHOD_METHOD_SIGNATURE =
- "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;".toCharArray();
+ final static char[] INVOKE_METHOD_METHOD_SIGNATURE = "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;".toCharArray();
final static char[] BYTEVALUE_BYTE_METHOD_NAME = "byteValue".toCharArray();
final static char[] BYTEVALUE_BYTE_METHOD_SIGNATURE = "()B".toCharArray();
final static char[] SHORTVALUE_SHORT_METHOD_NAME = "shortValue".toCharArray();
- final static char[] DOUBLEVALUE_DOUBLE_METHOD_NAME =
- "doubleValue".toCharArray();
+ final static char[] DOUBLEVALUE_DOUBLE_METHOD_NAME = "doubleValue".toCharArray();
final static char[] FLOATVALUE_FLOAT_METHOD_NAME = "floatValue".toCharArray();
final static char[] INTVALUE_INTEGER_METHOD_NAME = "intValue".toCharArray();
final static char[] CHARVALUE_CHARACTER_METHOD_NAME = "charValue".toCharArray();
- final static char[] BOOLEANVALUE_BOOLEAN_METHOD_NAME =
- "booleanValue".toCharArray();
+ final static char[] BOOLEANVALUE_BOOLEAN_METHOD_NAME = "booleanValue".toCharArray();
final static char[] LONGVALUE_LONG_METHOD_NAME = "longValue".toCharArray();
final static char[] SHORTVALUE_SHORT_METHOD_SIGNATURE = "()S".toCharArray();
final static char[] DOUBLEVALUE_DOUBLE_METHOD_SIGNATURE = "()D".toCharArray();
@@ -125,11 +89,9 @@ public class CodeSnippetConstantPool
final static char[] CHARVALUE_CHARACTER_METHOD_SIGNATURE = "()C".toCharArray();
final static char[] BOOLEANVALUE_BOOLEAN_METHOD_SIGNATURE = "()Z".toCharArray();
final static char[] LONGVALUE_LONG_METHOD_SIGNATURE = "()J".toCharArray();
- final static char[] GETDECLAREDCONSTRUCTOR_NAME =
- "getDeclaredConstructor".toCharArray();
- final static char[] GETDECLAREDCONSTRUCTOR_SIGNATURE =
- "([Ljava/lang/Class;)Ljava/lang/reflect/Constructor;".toCharArray();
-
+ final static char[] GETDECLAREDCONSTRUCTOR_NAME = "getDeclaredConstructor".toCharArray();
+ final static char[] GETDECLAREDCONSTRUCTOR_SIGNATURE = "([Ljava/lang/Class;)Ljava/lang/reflect/Constructor;".toCharArray();
+
// predefined constant index for well known types
final static int JAVA_LANG_REFLECT_FIELD_TYPE = 0;
final static int JAVA_LANG_REFLECT_METHOD_TYPE = 1;
@@ -170,7 +132,7 @@ public class CodeSnippetConstantPool
final static int BOOLEANVALUE_BOOLEAN_METHOD = 30;
final static int LONGVALUE_LONG_METHOD = 31;
final static int GETDECLAREDCONSTRUCTOR_CLASS_METHOD = 32;
-
+
// predefined constant index for well known name and type for methods
final static int GETDECLAREDFIELD_CLASS_METHOD_NAME_AND_TYPE = 0;
final static int SETACCESSIBLE_ACCESSIBLEOBJECT_METHOD_NAME_AND_TYPE = 1;
@@ -205,74 +167,64 @@ public class CodeSnippetConstantPool
final static int BOOLEANVALUE_BOOLEAN_METHOD_NAME_AND_TYPE = 30;
final static int LONGVALUE_LONG_METHOD_NAME_AND_TYPE = 31;
final static int GETDECLAREDCONSTRUCTOR_CLASS_METHOD_NAME_AND_TYPE = 32;
-
+
int[] wellKnownTypes = new int[4];
int[] wellKnownMethods = new int[33];
- int[] wellKnownMethodNameAndTypes = new int[33];
- /**
- * CodeSnippetConstantPool constructor comment.
- * @param classFile org.eclipse.jdt.internal.compiler.ClassFile
- */
- public CodeSnippetConstantPool(
- org.eclipse.jdt.internal.compiler.ClassFile classFile) {
- super(classFile);
- }
-
- /**
- * Return the index of the @methodBinding.
- *
- * Returns -1 if the @methodBinding is not a predefined methodBinding,
- * the right index otherwise.
- *
- * @param methodBinding com.ibm.compiler.namelookup.MethodBinding
- * @return <CODE>int</CODE>
- */
- public int indexOfWellKnownMethodNameAndType(MethodBinding methodBinding) {
- int index = super.indexOfWellKnownMethodNameAndType(methodBinding);
- if (index == -1) {
- char firstChar = methodBinding.selector[0];
- switch (firstChar) {
- case 'g' :
- if (methodBinding.parameters.length == 1
- && methodBinding.parameters[0].id == T_JavaLangString
- && CharOperation.equals(methodBinding.selector, GETDECLAREDFIELD_NAME)
- && methodBinding.returnType instanceof ReferenceBinding
- && CharOperation.equals(
- ((ReferenceBinding) methodBinding.returnType).compoundName,
- JAVA_LANG_REFLECT_FIELD)) {
+ int[] wellKnownMethodNameAndTypes = new int[33];
+/**
+ * CodeSnippetConstantPool constructor comment.
+ * @param classFile org.eclipse.jdt.internal.compiler.ClassFile
+ */
+public CodeSnippetConstantPool(org.eclipse.jdt.internal.compiler.ClassFile classFile) {
+ super(classFile);
+}
+/**
+ * Return the index of the @methodBinding.
+ *
+ * Returns -1 if the @methodBinding is not a predefined methodBinding,
+ * the right index otherwise.
+ *
+ * @param methodBinding com.ibm.compiler.namelookup.MethodBinding
+ * @return <CODE>int</CODE>
+ */
+public int indexOfWellKnownMethodNameAndType(MethodBinding methodBinding) {
+ int index = super.indexOfWellKnownMethodNameAndType(methodBinding);
+ if (index == -1) {
+ char firstChar = methodBinding.selector[0];
+ switch(firstChar) {
+ case 'g':
+ if (methodBinding.parameters.length == 1
+ && methodBinding.parameters[0].id == T_JavaLangString
+ && CharOperation.equals(methodBinding.selector, GETDECLAREDFIELD_NAME)
+ && methodBinding.returnType instanceof ReferenceBinding
+ && CharOperation.equals(((ReferenceBinding) methodBinding.returnType).compoundName,JAVA_LANG_REFLECT_FIELD)) {
return GETDECLAREDFIELD_CLASS_METHOD_NAME_AND_TYPE;
- }
- if (methodBinding.parameters.length == 2
- && methodBinding.parameters[0].id == T_JavaLangString
- && methodBinding.parameters[1].isArrayType()
- && ((ArrayBinding) methodBinding.parameters[1]).leafComponentType.id
- == T_JavaLangClass
- && CharOperation.equals(methodBinding.selector, GETDECLAREDMETHOD_NAME)
- && methodBinding.returnType instanceof ReferenceBinding
- && CharOperation.equals(
- ((ReferenceBinding) methodBinding.returnType).compoundName,
- JAVA_LANG_REFLECT_METHOD)) {
+ }
+ if (methodBinding.parameters.length == 2
+ && methodBinding.parameters[0].id == T_JavaLangString
+ && methodBinding.parameters[1].isArrayType()
+ && ((ArrayBinding) methodBinding.parameters[1]).leafComponentType.id == T_JavaLangClass
+ && CharOperation.equals(methodBinding.selector, GETDECLAREDMETHOD_NAME)
+ && methodBinding.returnType instanceof ReferenceBinding
+ && CharOperation.equals(((ReferenceBinding) methodBinding.returnType).compoundName,JAVA_LANG_REFLECT_METHOD)) {
return GETDECLAREDMETHOD_CLASS_METHOD_NAME_AND_TYPE;
- }
- if (methodBinding.parameters.length == 1
- && methodBinding.parameters[0].isArrayType()
- && ((ArrayBinding) methodBinding.parameters[0]).leafComponentType.id
- == T_JavaLangClass
- && CharOperation.equals(methodBinding.selector, GETDECLAREDCONSTRUCTOR_NAME)
- && methodBinding.returnType instanceof ReferenceBinding
- && CharOperation.equals(
- ((ReferenceBinding) methodBinding.returnType).compoundName,
- JAVA_LANG_REFLECT_CONSTRUCTOR)) {
+ }
+ if (methodBinding.parameters.length == 1
+ && methodBinding.parameters[0].isArrayType()
+ && ((ArrayBinding) methodBinding.parameters[0]).leafComponentType.id == T_JavaLangClass
+ && CharOperation.equals(methodBinding.selector, GETDECLAREDCONSTRUCTOR_NAME)
+ && methodBinding.returnType instanceof ReferenceBinding
+ && CharOperation.equals(((ReferenceBinding) methodBinding.returnType).compoundName,JAVA_LANG_REFLECT_CONSTRUCTOR)) {
return GETDECLAREDCONSTRUCTOR_CLASS_METHOD_NAME_AND_TYPE;
- }
- if (methodBinding.parameters.length == 0
- && CharOperation.equals(methodBinding.selector, GETCLASS_OBJECT_METHOD_NAME)
- && methodBinding.returnType.id == T_JavaLangClass) {
+ }
+ if (methodBinding.parameters.length == 0
+ && CharOperation.equals(methodBinding.selector, GETCLASS_OBJECT_METHOD_NAME)
+ && methodBinding.returnType.id == T_JavaLangClass) {
return GETCLASS_OBJECT_METHOD_NAME_AND_TYPE;
- }
- if (methodBinding.parameters.length == 1
- && methodBinding.parameters[0].id == T_Object) {
- switch (methodBinding.returnType.id) {
+ }
+ if (methodBinding.parameters.length == 1
+ && methodBinding.parameters[0].id == T_Object) {
+ switch(methodBinding.returnType.id) {
case T_int :
if (CharOperation.equals(methodBinding.selector, GET_INT_METHOD_NAME)
&& methodBinding.returnType.id == T_int) {
@@ -284,7 +236,7 @@ public class CodeSnippetConstantPool
&& methodBinding.returnType.id == T_byte) {
return GET_BYTE_METHOD_NAME_AND_TYPE;
}
- break;
+ break;
case T_short :
if (CharOperation.equals(methodBinding.selector, GET_SHORT_METHOD_NAME)
&& methodBinding.returnType.id == T_short) {
@@ -327,212 +279,196 @@ public class CodeSnippetConstantPool
return GET_OBJECT_METHOD_NAME_AND_TYPE;
}
}
- }
- break;
- case 'i' :
- if (methodBinding.parameters.length == 0
- && CharOperation.equals(methodBinding.selector, INTVALUE_INTEGER_METHOD_NAME)
- && methodBinding.returnType.id == T_int) {
+ }
+ break;
+ case 'i':
+ if (methodBinding.parameters.length == 0
+ && CharOperation.equals(methodBinding.selector, INTVALUE_INTEGER_METHOD_NAME)
+ && methodBinding.returnType.id == T_int) {
return INTVALUE_INTEGER_METHOD_NAME_AND_TYPE;
- }
- if (methodBinding.parameters.length == 2
- && methodBinding.parameters[0].id == T_JavaLangObject
- && methodBinding.parameters[1].isArrayType()
- && ((ArrayBinding) methodBinding.parameters[1]).leafComponentType.id
- == T_JavaLangObject
- && CharOperation.equals(methodBinding.selector, INVOKE_METHOD_METHOD_NAME)
- && methodBinding.returnType.id == T_JavaLangObject) {
+ }
+ if (methodBinding.parameters.length == 2
+ && methodBinding.parameters[0].id == T_JavaLangObject
+ && methodBinding.parameters[1].isArrayType()
+ && ((ArrayBinding) methodBinding.parameters[1]).leafComponentType.id == T_JavaLangObject
+ && CharOperation.equals(methodBinding.selector, INVOKE_METHOD_METHOD_NAME)
+ && methodBinding.returnType.id == T_JavaLangObject) {
return INVOKE_METHOD_METHOD_NAME_AND_TYPE;
- }
- break;
- case 's' :
- if (methodBinding.parameters.length == 0
- && CharOperation.equals(methodBinding.selector, SHORTVALUE_SHORT_METHOD_NAME)
- && methodBinding.returnType.id == T_short) {
+ }
+ break;
+ case 's':
+ if (methodBinding.parameters.length == 0
+ && CharOperation.equals(methodBinding.selector, SHORTVALUE_SHORT_METHOD_NAME)
+ && methodBinding.returnType.id == T_short) {
return SHORTVALUE_SHORT_METHOD_NAME_AND_TYPE;
- }
- if (methodBinding.parameters.length == 1
- && methodBinding.parameters[0].id == T_boolean
- && methodBinding.selector.length == 13
- && CharOperation.equals(methodBinding.selector, SETACCESSIBLE_NAME)
- && methodBinding.returnType.id == T_void) {
+ }
+ if (methodBinding.parameters.length == 1
+ && methodBinding.parameters[0].id == T_boolean
+ && methodBinding.selector.length == 13
+ && CharOperation.equals(methodBinding.selector, SETACCESSIBLE_NAME)
+ && methodBinding.returnType.id == T_void) {
return SETACCESSIBLE_ACCESSIBLEOBJECT_METHOD_NAME_AND_TYPE;
- }
- if (methodBinding.returnType.id == T_void
- && methodBinding.parameters.length == 2
- && methodBinding.parameters[0].id == T_Object) {
- switch (methodBinding.returnType.id) {
+ }
+ if (methodBinding.returnType.id == T_void
+ && methodBinding.parameters.length == 2
+ && methodBinding.parameters[0].id == T_Object) {
+ switch(methodBinding.returnType.id) {
case T_int :
- if (methodBinding.parameters[1].id == T_int
- && CharOperation.equals(methodBinding.selector, SET_INT_METHOD_NAME)
+ if (methodBinding.parameters[1].id == T_int && CharOperation.equals(methodBinding.selector, SET_INT_METHOD_NAME)
&& methodBinding.returnType.id == T_void) {
return SET_INT_METHOD_NAME_AND_TYPE;
}
break;
case T_byte :
- if (methodBinding.parameters[1].id == T_byte
- && CharOperation.equals(methodBinding.selector, SET_BYTE_METHOD_NAME)
+ if (methodBinding.parameters[1].id == T_byte && CharOperation.equals(methodBinding.selector, SET_BYTE_METHOD_NAME)
&& methodBinding.returnType.id == T_void) {
return SET_BYTE_METHOD_NAME_AND_TYPE;
}
- break;
+ break;
case T_short :
- if (methodBinding.parameters[1].id == T_short
- && CharOperation.equals(methodBinding.selector, SET_SHORT_METHOD_NAME)
+ if (methodBinding.parameters[1].id == T_short && CharOperation.equals(methodBinding.selector, SET_SHORT_METHOD_NAME)
&& methodBinding.returnType.id == T_void) {
return SET_SHORT_METHOD_NAME_AND_TYPE;
}
break;
case T_char :
- if (methodBinding.parameters[1].id == T_char
- && CharOperation.equals(methodBinding.selector, SET_CHAR_METHOD_NAME)
+ if (methodBinding.parameters[1].id == T_char && CharOperation.equals(methodBinding.selector, SET_CHAR_METHOD_NAME)
&& methodBinding.returnType.id == T_void) {
return SET_CHAR_METHOD_NAME_AND_TYPE;
}
break;
case T_double :
- if (methodBinding.parameters[1].id == T_double
- && CharOperation.equals(methodBinding.selector, SET_DOUBLE_METHOD_NAME)
+ if (methodBinding.parameters[1].id == T_double && CharOperation.equals(methodBinding.selector, SET_DOUBLE_METHOD_NAME)
&& methodBinding.returnType.id == T_void) {
return SET_DOUBLE_METHOD_NAME_AND_TYPE;
}
break;
case T_float :
- if (methodBinding.parameters[1].id == T_float
- && CharOperation.equals(methodBinding.selector, SET_FLOAT_METHOD_NAME)
+ if (methodBinding.parameters[1].id == T_float && CharOperation.equals(methodBinding.selector, SET_FLOAT_METHOD_NAME)
&& methodBinding.returnType.id == T_void) {
return SET_FLOAT_METHOD_NAME_AND_TYPE;
}
break;
case T_long :
- if (methodBinding.parameters[1].id == T_long
- && CharOperation.equals(methodBinding.selector, SET_LONG_METHOD_NAME)
+ if (methodBinding.parameters[1].id == T_long && CharOperation.equals(methodBinding.selector, SET_LONG_METHOD_NAME)
&& methodBinding.returnType.id == T_void) {
return SET_LONG_METHOD_NAME_AND_TYPE;
}
break;
case T_boolean :
- if (methodBinding.parameters[1].id == T_boolean
- && CharOperation.equals(methodBinding.selector, SET_BOOLEAN_METHOD_NAME)
+ if (methodBinding.parameters[1].id == T_boolean && CharOperation.equals(methodBinding.selector, SET_BOOLEAN_METHOD_NAME)
&& methodBinding.returnType.id == T_void) {
return SET_BOOLEAN_METHOD_NAME_AND_TYPE;
}
break;
case T_Object :
- if (methodBinding.parameters[1].id == T_Object
- && CharOperation.equals(methodBinding.selector, SET_OBJECT_METHOD_NAME)
+ if (methodBinding.parameters[1].id == T_Object && CharOperation.equals(methodBinding.selector, SET_OBJECT_METHOD_NAME)
&& methodBinding.returnType.id == T_void) {
return SET_OBJECT_METHOD_NAME_AND_TYPE;
}
}
- }
- break;
- case 'f' :
- if (methodBinding.parameters.length == 0
- && CharOperation.equals(methodBinding.selector, FLOATVALUE_FLOAT_METHOD_NAME)
- && methodBinding.returnType.id == T_float) {
+ }
+ break;
+ case 'f':
+ if (methodBinding.parameters.length == 0
+ && CharOperation.equals(methodBinding.selector, FLOATVALUE_FLOAT_METHOD_NAME)
+ && methodBinding.returnType.id == T_float) {
return FLOATVALUE_FLOAT_METHOD_NAME_AND_TYPE;
- }
- break;
- case 'd' :
- if (methodBinding.parameters.length == 0
- && CharOperation.equals(methodBinding.selector, DOUBLEVALUE_DOUBLE_METHOD_NAME)
- && methodBinding.returnType.id == T_double) {
+ }
+ break;
+ case 'd':
+ if (methodBinding.parameters.length == 0
+ && CharOperation.equals(methodBinding.selector, DOUBLEVALUE_DOUBLE_METHOD_NAME)
+ && methodBinding.returnType.id == T_double) {
return DOUBLEVALUE_DOUBLE_METHOD_NAME_AND_TYPE;
- }
- break;
- case 'c' :
- if (methodBinding.parameters.length == 0
- && CharOperation.equals(methodBinding.selector, CHARVALUE_CHARACTER_METHOD_NAME)
- && methodBinding.returnType.id == T_char) {
+ }
+ break;
+ case 'c':
+ if (methodBinding.parameters.length == 0
+ && CharOperation.equals(methodBinding.selector, CHARVALUE_CHARACTER_METHOD_NAME)
+ && methodBinding.returnType.id == T_char) {
return CHARVALUE_CHARACTER_METHOD_NAME_AND_TYPE;
- }
- break;
- case 'b' :
- if (methodBinding.parameters.length == 0
- && CharOperation.equals(methodBinding.selector, BOOLEANVALUE_BOOLEAN_METHOD_NAME)
- && methodBinding.returnType.id == T_boolean) {
+ }
+ break;
+ case 'b':
+ if (methodBinding.parameters.length == 0
+ && CharOperation.equals(methodBinding.selector, BOOLEANVALUE_BOOLEAN_METHOD_NAME)
+ && methodBinding.returnType.id == T_boolean) {
return BOOLEANVALUE_BOOLEAN_METHOD_NAME_AND_TYPE;
- }
- if (methodBinding.parameters.length == 0
- && CharOperation.equals(methodBinding.selector, BYTEVALUE_BYTE_METHOD_NAME)
- && methodBinding.returnType.id == T_byte) {
+ }
+ if (methodBinding.parameters.length == 0
+ && CharOperation.equals(methodBinding.selector, BYTEVALUE_BYTE_METHOD_NAME)
+ && methodBinding.returnType.id == T_byte) {
return BYTEVALUE_BYTE_METHOD_NAME_AND_TYPE;
- }
- break;
- case 'l' :
- if (methodBinding.parameters.length == 0
- && CharOperation.equals(methodBinding.selector, LONGVALUE_LONG_METHOD_NAME)
- && methodBinding.returnType.id == T_long) {
+ }
+ break;
+ case 'l':
+ if (methodBinding.parameters.length == 0
+ && CharOperation.equals(methodBinding.selector, LONGVALUE_LONG_METHOD_NAME)
+ && methodBinding.returnType.id == T_long) {
return LONGVALUE_LONG_METHOD_NAME_AND_TYPE;
- }
- break;
- case 'n' :
- if (methodBinding.parameters.length == 2
- && methodBinding.parameters[0].id == T_JavaLangClass
- && methodBinding.parameters[1].isArrayType()
- && ((ArrayBinding) methodBinding.parameters[1]).leafComponentType.id == T_int
- && CharOperation.equals(methodBinding.selector, ARRAY_NEWINSTANCE_NAME)
- && methodBinding.returnType instanceof ReferenceBinding
- && CharOperation.equals(
- ((ReferenceBinding) methodBinding.returnType).compoundName,
- JAVA_LANG_REFLECT_ARRAY)) {
+ }
+ break;
+ case 'n':
+ if (methodBinding.parameters.length == 2
+ && methodBinding.parameters[0].id == T_JavaLangClass
+ && methodBinding.parameters[1].isArrayType()
+ && ((ArrayBinding) methodBinding.parameters[1]).leafComponentType.id == T_int
+ && CharOperation.equals(methodBinding.selector, ARRAY_NEWINSTANCE_NAME)
+ && methodBinding.returnType instanceof ReferenceBinding
+ && CharOperation.equals(((ReferenceBinding) methodBinding.returnType).compoundName,JAVA_LANG_REFLECT_ARRAY)) {
return ARRAY_NEWINSTANCE_METHOD_NAME_AND_TYPE;
- }
- }
-
+ }
}
- return index;
- }
- /**
- * Return the index of the @methodBinding.
- *
- * Returns -1 if the @methodBinding is not a predefined methodBinding,
- * the right index otherwise.
- *
- * @param methodBinding com.ibm.compiler.namelookup.MethodBinding
- * @return <CODE>int</CODE>
- */
- public int indexOfWellKnownMethods(MethodBinding methodBinding) {
- int index = super.indexOfWellKnownMethods(methodBinding);
- if (index == -1) {
- char firstChar = methodBinding.selector[0];
- switch (firstChar) {
- case 'g' :
- if (methodBinding.declaringClass.id == T_JavaLangClass
- && methodBinding.parameters.length == 1
- && methodBinding.parameters[0].id == T_JavaLangString
- && CharOperation.equals(methodBinding.selector, GETDECLAREDFIELD_NAME)) {
+ }
+ return index;
+}
+/**
+ * Return the index of the @methodBinding.
+ *
+ * Returns -1 if the @methodBinding is not a predefined methodBinding,
+ * the right index otherwise.
+ *
+ * @param methodBinding com.ibm.compiler.namelookup.MethodBinding
+ * @return <CODE>int</CODE>
+ */
+public int indexOfWellKnownMethods(MethodBinding methodBinding) {
+ int index = super.indexOfWellKnownMethods(methodBinding);
+ if (index == -1) {
+ char firstChar = methodBinding.selector[0];
+ switch(firstChar) {
+ case 'g':
+ if (methodBinding.declaringClass.id == T_JavaLangClass
+ && methodBinding.parameters.length == 1
+ && methodBinding.parameters[0].id == T_JavaLangString
+ && CharOperation.equals(methodBinding.selector, GETDECLAREDFIELD_NAME)) {
return GETDECLAREDFIELD_CLASS_METHOD;
- }
- if (methodBinding.declaringClass.id == T_JavaLangClass
- && methodBinding.parameters.length == 2
- && methodBinding.parameters[0].id == T_JavaLangString
- && methodBinding.parameters[1].isArrayType()
- && ((ArrayBinding) methodBinding.parameters[1]).leafComponentType.id
- == T_JavaLangClass
- && CharOperation.equals(methodBinding.selector, GETDECLAREDMETHOD_NAME)) {
+ }
+ if (methodBinding.declaringClass.id == T_JavaLangClass
+ && methodBinding.parameters.length == 2
+ && methodBinding.parameters[0].id == T_JavaLangString
+ && methodBinding.parameters[1].isArrayType()
+ && ((ArrayBinding) methodBinding.parameters[1]).leafComponentType.id == T_JavaLangClass
+ && CharOperation.equals(methodBinding.selector, GETDECLAREDMETHOD_NAME)) {
return GETDECLAREDMETHOD_CLASS_METHOD;
- }
- if (methodBinding.declaringClass.id == T_JavaLangClass
- && methodBinding.parameters.length == 1
- && methodBinding.parameters[0].isArrayType()
- && ((ArrayBinding) methodBinding.parameters[0]).leafComponentType.id
- == T_JavaLangClass
- && CharOperation.equals(methodBinding.selector, GETDECLAREDCONSTRUCTOR_NAME)) {
+ }
+ if (methodBinding.declaringClass.id == T_JavaLangClass
+ && methodBinding.parameters.length == 1
+ && methodBinding.parameters[0].isArrayType()
+ && ((ArrayBinding) methodBinding.parameters[0]).leafComponentType.id == T_JavaLangClass
+ && CharOperation.equals(methodBinding.selector, GETDECLAREDCONSTRUCTOR_NAME)) {
return GETDECLAREDCONSTRUCTOR_CLASS_METHOD;
- }
- if (methodBinding.declaringClass.id == T_JavaLangObject
- && methodBinding.parameters.length == 0
- && CharOperation.equals(methodBinding.selector, GETCLASS_OBJECT_METHOD_NAME)) {
+ }
+ if (methodBinding.declaringClass.id == T_JavaLangObject
+ && methodBinding.parameters.length == 0
+ && CharOperation.equals(methodBinding.selector, GETCLASS_OBJECT_METHOD_NAME)) {
return GETCLASS_OBJECT_METHOD;
- }
- if (CharOperation
- .equals(methodBinding.declaringClass.compoundName, JAVA_LANG_REFLECT_FIELD)
- && methodBinding.parameters.length == 1
- && methodBinding.parameters[0].id == T_Object) {
- switch (methodBinding.returnType.id) {
+ }
+ if (CharOperation.equals(methodBinding.declaringClass.compoundName, JAVA_LANG_REFLECT_FIELD)
+ && methodBinding.parameters.length == 1
+ && methodBinding.parameters[0].id == T_Object) {
+ switch(methodBinding.returnType.id) {
case T_int :
if (CharOperation.equals(methodBinding.selector, GET_INT_METHOD_NAME)) {
return GET_INT_METHOD;
@@ -542,7 +478,7 @@ public class CodeSnippetConstantPool
if (CharOperation.equals(methodBinding.selector, GET_BYTE_METHOD_NAME)) {
return GET_BYTE_METHOD;
}
- break;
+ break;
case T_short :
if (CharOperation.equals(methodBinding.selector, GET_SHORT_METHOD_NAME)) {
return GET_SHORT_METHOD;
@@ -578,1494 +514,1380 @@ public class CodeSnippetConstantPool
return GET_OBJECT_METHOD;
}
}
- }
- break;
- case 'i' :
- if (methodBinding.declaringClass.id == T_JavaLangInteger
- && methodBinding.parameters.length == 0
- && CharOperation.equals(methodBinding.selector, INTVALUE_INTEGER_METHOD_NAME)) {
+ }
+ break;
+ case 'i':
+ if (methodBinding.declaringClass.id == T_JavaLangInteger
+ && methodBinding.parameters.length == 0
+ && CharOperation.equals(methodBinding.selector, INTVALUE_INTEGER_METHOD_NAME)) {
return INTVALUE_INTEGER_METHOD;
- }
- if (CharOperation
- .equals(methodBinding.declaringClass.compoundName, JAVA_LANG_REFLECT_METHOD)
- && methodBinding.parameters.length == 2
- && methodBinding.parameters[0].id == T_JavaLangObject
- && methodBinding.parameters[1].isArrayType()
- && ((ArrayBinding) methodBinding.parameters[1]).leafComponentType.id
- == T_JavaLangObject
- && CharOperation.equals(methodBinding.selector, INVOKE_METHOD_METHOD_NAME)) {
+ }
+ if (CharOperation.equals(methodBinding.declaringClass.compoundName, JAVA_LANG_REFLECT_METHOD)
+ && methodBinding.parameters.length == 2
+ && methodBinding.parameters[0].id == T_JavaLangObject
+ && methodBinding.parameters[1].isArrayType()
+ && ((ArrayBinding) methodBinding.parameters[1]).leafComponentType.id == T_JavaLangObject
+ && CharOperation.equals(methodBinding.selector, INVOKE_METHOD_METHOD_NAME)) {
return INVOKE_METHOD_METHOD;
- }
- break;
- case 'b' :
- if (methodBinding.declaringClass.id == T_JavaLangByte
- && methodBinding.parameters.length == 0
- && CharOperation.equals(methodBinding.selector, BYTEVALUE_BYTE_METHOD_NAME)) {
+ }
+ break;
+ case 'b':
+ if (methodBinding.declaringClass.id == T_JavaLangByte
+ && methodBinding.parameters.length == 0
+ && CharOperation.equals(methodBinding.selector, BYTEVALUE_BYTE_METHOD_NAME)) {
return BYTEVALUE_BYTE_METHOD;
- }
- if (methodBinding.declaringClass.id == T_JavaLangBoolean
- && methodBinding.parameters.length == 0
- && CharOperation.equals(
- methodBinding.selector,
- BOOLEANVALUE_BOOLEAN_METHOD_NAME)) {
+ }
+ if (methodBinding.declaringClass.id == T_JavaLangBoolean
+ && methodBinding.parameters.length == 0
+ && CharOperation.equals(methodBinding.selector, BOOLEANVALUE_BOOLEAN_METHOD_NAME)) {
return BOOLEANVALUE_BOOLEAN_METHOD;
- }
- break;
- case 's' :
- if (methodBinding.declaringClass.id == T_JavaLangShort
- && methodBinding.parameters.length == 0
- && CharOperation.equals(methodBinding.selector, SHORTVALUE_SHORT_METHOD_NAME)) {
+ }
+ break;
+ case 's':
+ if (methodBinding.declaringClass.id == T_JavaLangShort
+ && methodBinding.parameters.length == 0
+ && CharOperation.equals(methodBinding.selector, SHORTVALUE_SHORT_METHOD_NAME)) {
return SHORTVALUE_SHORT_METHOD;
- }
- if (CharOperation
- .equals(
- methodBinding.declaringClass.compoundName,
- JAVA_LANG_REFLECT_ACCESSIBLEOBJECT)
- && methodBinding.parameters.length == 1
- && methodBinding.parameters[0].id == T_boolean
- && methodBinding.selector.length == 13
- && CharOperation.equals(methodBinding.selector, SETACCESSIBLE_NAME)) {
+ }
+ if (CharOperation.equals(methodBinding.declaringClass.compoundName, JAVA_LANG_REFLECT_ACCESSIBLEOBJECT)
+ && methodBinding.parameters.length == 1
+ && methodBinding.parameters[0].id == T_boolean
+ && methodBinding.selector.length == 13
+ && CharOperation.equals(methodBinding.selector, SETACCESSIBLE_NAME)) {
return SETACCESSIBLE_ACCESSIBLEOBJECT_METHOD;
- }
- if (CharOperation
- .equals(methodBinding.declaringClass.compoundName, JAVA_LANG_REFLECT_FIELD)
- && methodBinding.returnType.id == T_void
- && methodBinding.parameters.length == 2
- && methodBinding.parameters[0].id == T_Object) {
- switch (methodBinding.returnType.id) {
+ }
+ if (CharOperation.equals(methodBinding.declaringClass.compoundName, JAVA_LANG_REFLECT_FIELD)
+ && methodBinding.returnType.id == T_void
+ && methodBinding.parameters.length == 2
+ && methodBinding.parameters[0].id == T_Object) {
+ switch(methodBinding.returnType.id) {
case T_int :
- if (methodBinding.parameters[1].id == T_int
- && CharOperation.equals(methodBinding.selector, SET_INT_METHOD_NAME)) {
+ if (methodBinding.parameters[1].id == T_int && CharOperation.equals(methodBinding.selector, SET_INT_METHOD_NAME)) {
return SET_INT_METHOD;
}
break;
case T_byte :
- if (methodBinding.parameters[1].id == T_byte
- && CharOperation.equals(methodBinding.selector, SET_BYTE_METHOD_NAME)) {
+ if (methodBinding.parameters[1].id == T_byte && CharOperation.equals(methodBinding.selector, SET_BYTE_METHOD_NAME)) {
return SET_BYTE_METHOD;
}
- break;
+ break;
case T_short :
- if (methodBinding.parameters[1].id == T_short
- && CharOperation.equals(methodBinding.selector, SET_SHORT_METHOD_NAME)) {
+ if (methodBinding.parameters[1].id == T_short && CharOperation.equals(methodBinding.selector, SET_SHORT_METHOD_NAME)) {
return SET_SHORT_METHOD;
}
break;
case T_char :
- if (methodBinding.parameters[1].id == T_char
- && CharOperation.equals(methodBinding.selector, SET_CHAR_METHOD_NAME)) {
+ if (methodBinding.parameters[1].id == T_char && CharOperation.equals(methodBinding.selector, SET_CHAR_METHOD_NAME)) {
return SET_CHAR_METHOD;
}
break;
case T_double :
- if (methodBinding.parameters[1].id == T_double
- && CharOperation.equals(methodBinding.selector, SET_DOUBLE_METHOD_NAME)) {
+ if (methodBinding.parameters[1].id == T_double && CharOperation.equals(methodBinding.selector, SET_DOUBLE_METHOD_NAME)) {
return SET_DOUBLE_METHOD;
}
break;
case T_float :
- if (methodBinding.parameters[1].id == T_float
- && CharOperation.equals(methodBinding.selector, SET_FLOAT_METHOD_NAME)) {
+ if (methodBinding.parameters[1].id == T_float && CharOperation.equals(methodBinding.selector, SET_FLOAT_METHOD_NAME)) {
return SET_FLOAT_METHOD;
}
break;
case T_long :
- if (methodBinding.parameters[1].id == T_long
- && CharOperation.equals(methodBinding.selector, SET_LONG_METHOD_NAME)) {
+ if (methodBinding.parameters[1].id == T_long && CharOperation.equals(methodBinding.selector, SET_LONG_METHOD_NAME)) {
return SET_LONG_METHOD;
}
break;
case T_boolean :
- if (methodBinding.parameters[1].id == T_boolean
- && CharOperation.equals(methodBinding.selector, SET_BOOLEAN_METHOD_NAME)) {
+ if (methodBinding.parameters[1].id == T_boolean && CharOperation.equals(methodBinding.selector, SET_BOOLEAN_METHOD_NAME)) {
return SET_BOOLEAN_METHOD;
}
break;
case T_Object :
- if (methodBinding.parameters[1].id == T_Object
- && CharOperation.equals(methodBinding.selector, SET_OBJECT_METHOD_NAME)) {
+ if (methodBinding.parameters[1].id == T_Object && CharOperation.equals(methodBinding.selector, SET_OBJECT_METHOD_NAME)) {
return SET_OBJECT_METHOD;
}
}
- }
- break;
- case 'f' :
- if (methodBinding.declaringClass.id == T_JavaLangFloat
- && methodBinding.parameters.length == 0
- && CharOperation.equals(methodBinding.selector, FLOATVALUE_FLOAT_METHOD_NAME)) {
+ }
+ break;
+ case 'f':
+ if (methodBinding.declaringClass.id == T_JavaLangFloat
+ && methodBinding.parameters.length == 0
+ && CharOperation.equals(methodBinding.selector, FLOATVALUE_FLOAT_METHOD_NAME)) {
return FLOATVALUE_FLOAT_METHOD;
- }
- break;
- case 'd' :
- if (methodBinding.declaringClass.id == T_JavaLangDouble
- && methodBinding.parameters.length == 0
- && CharOperation.equals(methodBinding.selector, DOUBLEVALUE_DOUBLE_METHOD_NAME)) {
+ }
+ break;
+ case 'd':
+ if (methodBinding.declaringClass.id == T_JavaLangDouble
+ && methodBinding.parameters.length == 0
+ && CharOperation.equals(methodBinding.selector, DOUBLEVALUE_DOUBLE_METHOD_NAME)) {
return DOUBLEVALUE_DOUBLE_METHOD;
- }
- break;
- case 'c' :
- if (methodBinding.declaringClass.id == T_JavaLangCharacter
- && methodBinding.parameters.length == 0
- && CharOperation.equals(
- methodBinding.selector,
- CHARVALUE_CHARACTER_METHOD_NAME)) {
+ }
+ break;
+ case 'c':
+ if (methodBinding.declaringClass.id == T_JavaLangCharacter
+ && methodBinding.parameters.length == 0
+ && CharOperation.equals(methodBinding.selector, CHARVALUE_CHARACTER_METHOD_NAME)) {
return CHARVALUE_CHARACTER_METHOD;
- }
- break;
- case 'l' :
- if (methodBinding.declaringClass.id == T_JavaLangLong
- && methodBinding.parameters.length == 0
- && CharOperation.equals(methodBinding.selector, LONGVALUE_LONG_METHOD_NAME)) {
+ }
+ break;
+ case 'l':
+ if (methodBinding.declaringClass.id == T_JavaLangLong
+ && methodBinding.parameters.length == 0
+ && CharOperation.equals(methodBinding.selector, LONGVALUE_LONG_METHOD_NAME)) {
return LONGVALUE_LONG_METHOD;
- }
- break;
- case 'n' :
- if (CharOperation
- .equals(methodBinding.declaringClass.compoundName, JAVA_LANG_REFLECT_ARRAY)
- && methodBinding.parameters.length == 2
- && methodBinding.parameters[0].id == T_JavaLangClass
- && methodBinding.parameters[1].isArrayType()
- && ((ArrayBinding) methodBinding.parameters[1]).leafComponentType.id == T_int
- && CharOperation.equals(methodBinding.selector, ARRAY_NEWINSTANCE_NAME)) {
+ }
+ break;
+ case 'n':
+ if (CharOperation.equals(methodBinding.declaringClass.compoundName, JAVA_LANG_REFLECT_ARRAY)
+ && methodBinding.parameters.length == 2
+ && methodBinding.parameters[0].id == T_JavaLangClass
+ && methodBinding.parameters[1].isArrayType()
+ && ((ArrayBinding) methodBinding.parameters[1]).leafComponentType.id == T_int
+ && CharOperation.equals(methodBinding.selector, ARRAY_NEWINSTANCE_NAME)) {
return NEWINSTANCE_ARRAY_METHOD;
- }
- break;
- }
- }
- return index;
- }
-
- /**
- * Return the index of the @typeBinding
- *
- * Returns -1 if the @typeBinding is not a predefined binding, the right index
- * otherwise.
- *
- * @param typeBinding com.ibm.compiler.namelookup.TypeBinding
- * @return <CODE>int</CODE>
- */
- public int indexOfWellKnownTypes(TypeBinding typeBinding) {
- int index = super.indexOfWellKnownTypes(typeBinding);
- if (index == -1) {
- if (!typeBinding.isBaseType() && !typeBinding.isArrayType()) {
- ReferenceBinding type = (ReferenceBinding) typeBinding;
- if (type.compoundName.length == 4) {
- if (CharOperation.equals(JAVA_LANG_REFLECT_FIELD, type.compoundName)) {
- return JAVA_LANG_REFLECT_FIELD_TYPE;
- }
- if (CharOperation.equals(JAVA_LANG_REFLECT_METHOD, type.compoundName)) {
- return JAVA_LANG_REFLECT_METHOD_TYPE;
- }
- if (CharOperation.equals(JAVA_LANG_REFLECT_ARRAY, type.compoundName)) {
- return JAVA_LANG_REFLECT_ARRAY_TYPE;
- }
- if (CharOperation
- .equals(JAVA_LANG_REFLECT_ACCESSIBLEOBJECT, type.compoundName)) {
- return JAVA_LANG_REFLECT_ACCESSIBLEOBJECT_TYPE;
- }
}
- }
+ break;
}
- return index;
}
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @param MethodBinding aMethodBinding
- * @return <CODE>int</CODE>
- */
- public int literalIndex(MethodBinding aMethodBinding) {
- int index;
- int nameAndTypeIndex;
- int classIndex;
- int nameIndex;
- int indexWellKnownMethod;
- if ((indexWellKnownMethod = super.indexOfWellKnownMethods(aMethodBinding))
- == -1) {
- if ((indexWellKnownMethod = indexOfWellKnownMethods(aMethodBinding)) == -1) {
- if (aMethodBinding.declaringClass.isInterface()) {
- // Lookinf into the interface method ref table
- if ((index = interfaceMethodCache.get(aMethodBinding)) < 0) {
- classIndex = literalIndex(aMethodBinding.declaringClass);
- nameAndTypeIndex =
- literalIndexForMethods(
- literalIndex(aMethodBinding.constantPoolName()),
- literalIndex(aMethodBinding.signature()),
- aMethodBinding);
- index = interfaceMethodCache.put(aMethodBinding, currentIndex++);
- // Write the interface method ref constant into the constant pool
- // First add the tag
- writeU1(InterfaceMethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
- }
- } else {
- // Lookinf into the method ref table
- if ((index = methodCache.get(aMethodBinding)) < 0) {
- classIndex = literalIndex(aMethodBinding.declaringClass);
- nameAndTypeIndex =
- literalIndexForMethods(
- literalIndex(aMethodBinding.constantPoolName()),
- literalIndex(aMethodBinding.signature()),
- aMethodBinding);
- index = methodCache.put(aMethodBinding, currentIndex++);
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
- }
+ return index;
+}
+/**
+ * Return the index of the @typeBinding
+ *
+ * Returns -1 if the @typeBinding is not a predefined binding, the right index
+ * otherwise.
+ *
+ * @param typeBinding com.ibm.compiler.namelookup.TypeBinding
+ * @return <CODE>int</CODE>
+ */
+public int indexOfWellKnownTypes(TypeBinding typeBinding) {
+ int index = super.indexOfWellKnownTypes(typeBinding);
+ if (index == -1) {
+ if (!typeBinding.isBaseType() && !typeBinding.isArrayType()) {
+ ReferenceBinding type = (ReferenceBinding) typeBinding;
+ if (type.compoundName.length == 4) {
+ if (CharOperation.equals(JAVA_LANG_REFLECT_FIELD, type.compoundName)) {
+ return JAVA_LANG_REFLECT_FIELD_TYPE;
}
- } else {
- // This is a well known method
- if ((index = wellKnownMethods[indexWellKnownMethod]) == 0) {
- // this methods was not inserted yet
- if (aMethodBinding.declaringClass.isInterface()) {
- // Lookinf into the interface method ref table
- classIndex = literalIndex(aMethodBinding.declaringClass);
- nameAndTypeIndex =
- literalIndexForMethods(
- literalIndex(aMethodBinding.constantPoolName()),
- literalIndex(aMethodBinding.signature()),
- aMethodBinding);
- index = wellKnownMethods[indexWellKnownMethod] = currentIndex++;
- // Write the interface method ref constant into the constant pool
- // First add the tag
- writeU1(InterfaceMethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
- } else {
- // Lookinf into the method ref table
- classIndex = literalIndex(aMethodBinding.declaringClass);
- nameAndTypeIndex =
- literalIndexForMethods(
- literalIndex(aMethodBinding.constantPoolName()),
- literalIndex(aMethodBinding.signature()),
- aMethodBinding);
- index = wellKnownMethods[indexWellKnownMethod] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
- }
+ if (CharOperation.equals(JAVA_LANG_REFLECT_METHOD, type.compoundName)) {
+ return JAVA_LANG_REFLECT_METHOD_TYPE;
+ }
+ if (CharOperation.equals(JAVA_LANG_REFLECT_ARRAY, type.compoundName)) {
+ return JAVA_LANG_REFLECT_ARRAY_TYPE;
+ }
+ if (CharOperation.equals(JAVA_LANG_REFLECT_ACCESSIBLEOBJECT, type.compoundName)) {
+ return JAVA_LANG_REFLECT_ACCESSIBLEOBJECT_TYPE;
}
}
- } else {
- index = super.literalIndex(aMethodBinding);
}
- return index;
}
-
- /**
- * This method returns the index into the constantPool corresponding to the type descriptor.
- *
- * @param TypeBinding aTypeBinding
- * @return <CODE>int</CODE>
- */
- public int literalIndex(TypeBinding aTypeBinding) {
- int index;
- int nameIndex;
- int indexWellKnownType;
- if ((indexWellKnownType = super.indexOfWellKnownTypes(aTypeBinding)) == -1) {
- if ((indexWellKnownType = indexOfWellKnownTypes(aTypeBinding)) == -1) {
- if ((index = classCache.get(aTypeBinding)) < 0) {
- // The entry doesn't exit yet
- nameIndex = literalIndex(aTypeBinding.constantPoolName());
- index = classCache.put(aTypeBinding, currentIndex++);
- writeU1(ClassTag);
- // Then add the 8 bytes representing the long
- writeU2(nameIndex);
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @param MethodBinding aMethodBinding
+ * @return <CODE>int</CODE>
+ */
+public int literalIndex(MethodBinding aMethodBinding) {
+ int index;
+ int nameAndTypeIndex;
+ int classIndex;
+ int nameIndex;
+ int indexWellKnownMethod;
+ if ((indexWellKnownMethod = super.indexOfWellKnownMethods(aMethodBinding)) == -1) {
+ if ((indexWellKnownMethod = indexOfWellKnownMethods(aMethodBinding)) == -1) {
+ if (aMethodBinding.declaringClass.isInterface()) {
+ // Lookinf into the interface method ref table
+ if ((index = interfaceMethodCache.get(aMethodBinding)) < 0) {
+ classIndex = literalIndex(aMethodBinding.declaringClass);
+ nameAndTypeIndex =
+ literalIndexForMethods(
+ literalIndex(aMethodBinding.constantPoolName()),
+ literalIndex(aMethodBinding.signature()),
+ aMethodBinding);
+ index = interfaceMethodCache.put(aMethodBinding, currentIndex++);
+ // Write the interface method ref constant into the constant pool
+ // First add the tag
+ writeU1(InterfaceMethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
}
} else {
- if ((index = wellKnownTypes[indexWellKnownType]) == 0) {
- // Need to insert that binding
- nameIndex = literalIndex(aTypeBinding.constantPoolName());
- index = wellKnownTypes[indexWellKnownType] = currentIndex++;
- writeU1(ClassTag);
- // Then add the 8 bytes representing the long
- writeU2(nameIndex);
+ // Lookinf into the method ref table
+ if ((index = methodCache.get(aMethodBinding)) < 0) {
+ classIndex = literalIndex(aMethodBinding.declaringClass);
+ nameAndTypeIndex =
+ literalIndexForMethods(
+ literalIndex(aMethodBinding.constantPoolName()),
+ literalIndex(aMethodBinding.signature()),
+ aMethodBinding);
+ index = methodCache.put(aMethodBinding, currentIndex++);
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
}
}
} else {
- index = super.literalIndex(aTypeBinding);
+ // This is a well known method
+ if ((index = wellKnownMethods[indexWellKnownMethod]) == 0) {
+ // this methods was not inserted yet
+ if (aMethodBinding.declaringClass.isInterface()) {
+ // Lookinf into the interface method ref table
+ classIndex = literalIndex(aMethodBinding.declaringClass);
+ nameAndTypeIndex =
+ literalIndexForMethods(
+ literalIndex(aMethodBinding.constantPoolName()),
+ literalIndex(aMethodBinding.signature()),
+ aMethodBinding);
+ index = wellKnownMethods[indexWellKnownMethod] = currentIndex++;
+ // Write the interface method ref constant into the constant pool
+ // First add the tag
+ writeU1(InterfaceMethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
+ } else {
+ // Lookinf into the method ref table
+ classIndex = literalIndex(aMethodBinding.declaringClass);
+ nameAndTypeIndex =
+ literalIndexForMethods(
+ literalIndex(aMethodBinding.constantPoolName()),
+ literalIndex(aMethodBinding.signature()),
+ aMethodBinding);
+ index = wellKnownMethods[indexWellKnownMethod] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
+ }
+ }
}
- return index;
+ } else {
+ index = super.literalIndex(aMethodBinding);
}
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexForJavaLangBooleanBooleanValue() {
- int index;
- int nameAndTypeIndex;
- int classIndex;
- // Looking into the method ref table
- if ((index = wellKnownMethods[BOOLEANVALUE_BOOLEAN_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangBoolean();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[BOOLEANVALUE_BOOLEAN_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(BOOLEANVALUE_BOOLEAN_METHOD_NAME);
- int typeIndex = literalIndex(BOOLEANVALUE_BOOLEAN_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[BOOLEANVALUE_BOOLEAN_METHOD_NAME_AND_TYPE] =
- currentIndex++;
- writeU1(NameAndTypeTag);
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the type descriptor.
+ *
+ * @param TypeBinding aTypeBinding
+ * @return <CODE>int</CODE>
+ */
+public int literalIndex(TypeBinding aTypeBinding) {
+ int index;
+ int nameIndex;
+ int indexWellKnownType;
+ if ((indexWellKnownType = super.indexOfWellKnownTypes(aTypeBinding)) == -1) {
+ if ((indexWellKnownType = indexOfWellKnownTypes(aTypeBinding)) == -1) {
+ if ((index = classCache.get(aTypeBinding)) < 0) {
+ // The entry doesn't exit yet
+ nameIndex = literalIndex(aTypeBinding.constantPoolName());
+ index = classCache.put(aTypeBinding, currentIndex++);
+ writeU1(ClassTag);
+ // Then add the 8 bytes representing the long
writeU2(nameIndex);
- writeU2(typeIndex);
}
- index =
- wellKnownMethods[BOOLEANVALUE_BOOLEAN_METHOD_NAME_AND_TYPE] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
- }
- return index;
- }
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexForJavaLangByteByteValue() {
- int index;
- int nameAndTypeIndex;
- int classIndex;
- // Looking into the method ref table
- if ((index = wellKnownMethods[BYTEVALUE_BYTE_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangByte();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[BYTEVALUE_BYTE_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(BYTEVALUE_BYTE_METHOD_NAME);
- int typeIndex = literalIndex(BYTEVALUE_BYTE_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[BYTEVALUE_BYTE_METHOD_NAME_AND_TYPE] =
- currentIndex++;
- writeU1(NameAndTypeTag);
+ } else {
+ if ((index = wellKnownTypes[indexWellKnownType]) == 0) {
+ // Need to insert that binding
+ nameIndex = literalIndex(aTypeBinding.constantPoolName());
+ index = wellKnownTypes[indexWellKnownType] = currentIndex++;
+ writeU1(ClassTag);
+ // Then add the 8 bytes representing the long
writeU2(nameIndex);
- writeU2(typeIndex);
}
- index = wellKnownMethods[BYTEVALUE_BYTE_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
}
- return index;
+ } else {
+ index = super.literalIndex(aTypeBinding);
}
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexForJavaLangCharacterCharValue() {
- int index;
- int nameAndTypeIndex;
- int classIndex;
- // Looking into the method ref table
- if ((index = wellKnownMethods[CHARVALUE_CHARACTER_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangCharacter();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[CHARVALUE_CHARACTER_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(CHARVALUE_CHARACTER_METHOD_NAME);
- int typeIndex = literalIndex(CHARVALUE_CHARACTER_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[CHARVALUE_CHARACTER_METHOD_NAME_AND_TYPE] =
- currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[CHARVALUE_CHARACTER_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexForJavaLangBooleanBooleanValue() {
+ int index;
+ int nameAndTypeIndex;
+ int classIndex;
+ // Looking into the method ref table
+ if ((index = wellKnownMethods[BOOLEANVALUE_BOOLEAN_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangBoolean();
+ if ((nameAndTypeIndex = wellKnownMethodNameAndTypes[BOOLEANVALUE_BOOLEAN_METHOD_NAME_AND_TYPE]) == 0) {
+ int nameIndex = literalIndex(BOOLEANVALUE_BOOLEAN_METHOD_NAME);
+ int typeIndex = literalIndex(BOOLEANVALUE_BOOLEAN_METHOD_SIGNATURE);
+ nameAndTypeIndex = wellKnownMethodNameAndTypes[BOOLEANVALUE_BOOLEAN_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- return index;
+ index = wellKnownMethods[BOOLEANVALUE_BOOLEAN_METHOD_NAME_AND_TYPE] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
}
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexForJavaLangClassGetDeclaredConstructor() {
- int index;
- int nameAndTypeIndex;
- int classIndex;
- // Looking into the method ref table
- if ((index = wellKnownMethods[GETDECLAREDCONSTRUCTOR_CLASS_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangClass();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GETDECLAREDCONSTRUCTOR_CLASS_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(GETDECLAREDCONSTRUCTOR_NAME);
- int typeIndex = literalIndex(GETDECLAREDCONSTRUCTOR_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GETDECLAREDCONSTRUCTOR_CLASS_METHOD_NAME_AND_TYPE] =
- currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[GETDECLAREDCONSTRUCTOR_CLASS_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexForJavaLangByteByteValue() {
+ int index;
+ int nameAndTypeIndex;
+ int classIndex;
+ // Looking into the method ref table
+ if ((index = wellKnownMethods[BYTEVALUE_BYTE_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangByte();
+ if ((nameAndTypeIndex = wellKnownMethodNameAndTypes[BYTEVALUE_BYTE_METHOD_NAME_AND_TYPE]) == 0) {
+ int nameIndex = literalIndex(BYTEVALUE_BYTE_METHOD_NAME);
+ int typeIndex = literalIndex(BYTEVALUE_BYTE_METHOD_SIGNATURE);
+ nameAndTypeIndex = wellKnownMethodNameAndTypes[BYTEVALUE_BYTE_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- return index;
+ index = wellKnownMethods[BYTEVALUE_BYTE_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
}
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexForJavaLangClassGetDeclaredField() {
- int index;
- int nameAndTypeIndex;
- int classIndex;
- // Looking into the method ref table
- if ((index = wellKnownMethods[GETDECLAREDFIELD_CLASS_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangClass();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GETDECLAREDFIELD_CLASS_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(GETDECLAREDFIELD_NAME);
- int typeIndex = literalIndex(GETDECLAREDFIELD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GETDECLAREDFIELD_CLASS_METHOD_NAME_AND_TYPE] =
- currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[GETDECLAREDFIELD_CLASS_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexForJavaLangCharacterCharValue() {
+ int index;
+ int nameAndTypeIndex;
+ int classIndex;
+ // Looking into the method ref table
+ if ((index = wellKnownMethods[CHARVALUE_CHARACTER_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangCharacter();
+ if ((nameAndTypeIndex = wellKnownMethodNameAndTypes[CHARVALUE_CHARACTER_METHOD_NAME_AND_TYPE]) == 0) {
+ int nameIndex = literalIndex(CHARVALUE_CHARACTER_METHOD_NAME);
+ int typeIndex = literalIndex(CHARVALUE_CHARACTER_METHOD_SIGNATURE);
+ nameAndTypeIndex = wellKnownMethodNameAndTypes[CHARVALUE_CHARACTER_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- return index;
+ index = wellKnownMethods[CHARVALUE_CHARACTER_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
}
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexForJavaLangClassGetDeclaredMethod() {
- int index;
- int nameAndTypeIndex;
- int classIndex;
- // Looking into the method ref table
- if ((index = wellKnownMethods[GETDECLAREDMETHOD_CLASS_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangClass();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GETDECLAREDMETHOD_CLASS_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(GETDECLAREDMETHOD_NAME);
- int typeIndex = literalIndex(GETDECLAREDMETHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GETDECLAREDMETHOD_CLASS_METHOD_NAME_AND_TYPE] =
- currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[GETDECLAREDMETHOD_CLASS_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexForJavaLangClassGetDeclaredConstructor() {
+ int index;
+ int nameAndTypeIndex;
+ int classIndex;
+ // Looking into the method ref table
+ if ((index = wellKnownMethods[GETDECLAREDCONSTRUCTOR_CLASS_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangClass();
+ if ((nameAndTypeIndex = wellKnownMethodNameAndTypes[GETDECLAREDCONSTRUCTOR_CLASS_METHOD_NAME_AND_TYPE]) == 0) {
+ int nameIndex = literalIndex(GETDECLAREDCONSTRUCTOR_NAME);
+ int typeIndex = literalIndex(GETDECLAREDCONSTRUCTOR_SIGNATURE);
+ nameAndTypeIndex = wellKnownMethodNameAndTypes[GETDECLAREDCONSTRUCTOR_CLASS_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- return index;
+ index = wellKnownMethods[GETDECLAREDCONSTRUCTOR_CLASS_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
}
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexForJavaLangDoubleDoubleValue() {
- int index;
- int nameAndTypeIndex;
- int classIndex;
- // Looking into the method ref table
- if ((index = wellKnownMethods[DOUBLEVALUE_DOUBLE_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangDouble();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[DOUBLEVALUE_DOUBLE_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(DOUBLEVALUE_DOUBLE_METHOD_NAME);
- int typeIndex = literalIndex(DOUBLEVALUE_DOUBLE_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[DOUBLEVALUE_DOUBLE_METHOD_NAME_AND_TYPE] =
- currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[DOUBLEVALUE_DOUBLE_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexForJavaLangClassGetDeclaredField() {
+ int index;
+ int nameAndTypeIndex;
+ int classIndex;
+ // Looking into the method ref table
+ if ((index = wellKnownMethods[GETDECLAREDFIELD_CLASS_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangClass();
+ if ((nameAndTypeIndex = wellKnownMethodNameAndTypes[GETDECLAREDFIELD_CLASS_METHOD_NAME_AND_TYPE]) == 0) {
+ int nameIndex = literalIndex(GETDECLAREDFIELD_NAME);
+ int typeIndex = literalIndex(GETDECLAREDFIELD_SIGNATURE);
+ nameAndTypeIndex = wellKnownMethodNameAndTypes[GETDECLAREDFIELD_CLASS_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- return index;
+ index = wellKnownMethods[GETDECLAREDFIELD_CLASS_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
}
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexForJavaLangFloatFloatValue() {
- int index;
- int nameAndTypeIndex;
- int classIndex;
- // Looking into the method ref table
- if ((index = wellKnownMethods[FLOATVALUE_FLOAT_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangFloat();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[FLOATVALUE_FLOAT_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(FLOATVALUE_FLOAT_METHOD_NAME);
- int typeIndex = literalIndex(FLOATVALUE_FLOAT_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[FLOATVALUE_FLOAT_METHOD_NAME_AND_TYPE] =
- currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[FLOATVALUE_FLOAT_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexForJavaLangClassGetDeclaredMethod() {
+ int index;
+ int nameAndTypeIndex;
+ int classIndex;
+ // Looking into the method ref table
+ if ((index = wellKnownMethods[GETDECLAREDMETHOD_CLASS_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangClass();
+ if ((nameAndTypeIndex = wellKnownMethodNameAndTypes[GETDECLAREDMETHOD_CLASS_METHOD_NAME_AND_TYPE]) == 0) {
+ int nameIndex = literalIndex(GETDECLAREDMETHOD_NAME);
+ int typeIndex = literalIndex(GETDECLAREDMETHOD_SIGNATURE);
+ nameAndTypeIndex = wellKnownMethodNameAndTypes[GETDECLAREDMETHOD_CLASS_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- return index;
+ index = wellKnownMethods[GETDECLAREDMETHOD_CLASS_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
}
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexForJavaLangIntegerIntValue() {
- int index;
- int nameAndTypeIndex;
- int classIndex;
- // Looking into the method ref table
- if ((index = wellKnownMethods[INTVALUE_INTEGER_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangInteger();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[INTVALUE_INTEGER_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(INTVALUE_INTEGER_METHOD_NAME);
- int typeIndex = literalIndex(INTVALUE_INTEGER_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[INTVALUE_INTEGER_METHOD_NAME_AND_TYPE] =
- currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[INTVALUE_INTEGER_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexForJavaLangDoubleDoubleValue() {
+ int index;
+ int nameAndTypeIndex;
+ int classIndex;
+ // Looking into the method ref table
+ if ((index = wellKnownMethods[DOUBLEVALUE_DOUBLE_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangDouble();
+ if ((nameAndTypeIndex = wellKnownMethodNameAndTypes[DOUBLEVALUE_DOUBLE_METHOD_NAME_AND_TYPE]) == 0) {
+ int nameIndex = literalIndex(DOUBLEVALUE_DOUBLE_METHOD_NAME);
+ int typeIndex = literalIndex(DOUBLEVALUE_DOUBLE_METHOD_SIGNATURE);
+ nameAndTypeIndex = wellKnownMethodNameAndTypes[DOUBLEVALUE_DOUBLE_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- return index;
+ index = wellKnownMethods[DOUBLEVALUE_DOUBLE_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
}
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexForJavaLangLongLongValue() {
- int index;
- int nameAndTypeIndex;
- int classIndex;
- // Looking into the method ref table
- if ((index = wellKnownMethods[LONGVALUE_LONG_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangLong();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[LONGVALUE_LONG_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(LONGVALUE_LONG_METHOD_NAME);
- int typeIndex = literalIndex(LONGVALUE_LONG_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[LONGVALUE_LONG_METHOD_NAME_AND_TYPE] =
- currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[LONGVALUE_LONG_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexForJavaLangFloatFloatValue() {
+ int index;
+ int nameAndTypeIndex;
+ int classIndex;
+ // Looking into the method ref table
+ if ((index = wellKnownMethods[FLOATVALUE_FLOAT_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangFloat();
+ if ((nameAndTypeIndex = wellKnownMethodNameAndTypes[FLOATVALUE_FLOAT_METHOD_NAME_AND_TYPE]) == 0) {
+ int nameIndex = literalIndex(FLOATVALUE_FLOAT_METHOD_NAME);
+ int typeIndex = literalIndex(FLOATVALUE_FLOAT_METHOD_SIGNATURE);
+ nameAndTypeIndex = wellKnownMethodNameAndTypes[FLOATVALUE_FLOAT_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- return index;
+ index = wellKnownMethods[FLOATVALUE_FLOAT_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
}
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexForJavaLangObjectGetClass() {
- int index;
- int nameAndTypeIndex;
- int classIndex;
- // Looking into the method ref table
- if ((index = wellKnownMethods[GETCLASS_OBJECT_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangObject();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GETCLASS_OBJECT_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(GETCLASS_OBJECT_METHOD_NAME);
- int typeIndex = literalIndex(GETCLASS_OBJECT_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GETCLASS_OBJECT_METHOD_NAME_AND_TYPE] =
- currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[GETCLASS_OBJECT_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexForJavaLangIntegerIntValue() {
+ int index;
+ int nameAndTypeIndex;
+ int classIndex;
+ // Looking into the method ref table
+ if ((index = wellKnownMethods[INTVALUE_INTEGER_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangInteger();
+ if ((nameAndTypeIndex = wellKnownMethodNameAndTypes[INTVALUE_INTEGER_METHOD_NAME_AND_TYPE]) == 0) {
+ int nameIndex = literalIndex(INTVALUE_INTEGER_METHOD_NAME);
+ int typeIndex = literalIndex(INTVALUE_INTEGER_METHOD_SIGNATURE);
+ nameAndTypeIndex = wellKnownMethodNameAndTypes[INTVALUE_INTEGER_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- return index;
+ index = wellKnownMethods[INTVALUE_INTEGER_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
}
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexForJavaLangReflectAccessibleObject() {
- int index;
- if ((index = wellKnownTypes[JAVA_LANG_REFLECT_ACCESSIBLEOBJECT_TYPE]) == 0) {
- int nameIndex;
- // The entry doesn't exit yet
- nameIndex = literalIndex(JAVALANGREFLECTACCESSIBLEOBJECT_CONSTANTPOOLNAME);
- index =
- wellKnownTypes[JAVA_LANG_REFLECT_ACCESSIBLEOBJECT_TYPE] = currentIndex++;
- writeU1(ClassTag);
- // Then add the 8 bytes representing the long
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexForJavaLangLongLongValue() {
+ int index;
+ int nameAndTypeIndex;
+ int classIndex;
+ // Looking into the method ref table
+ if ((index = wellKnownMethods[LONGVALUE_LONG_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangLong();
+ if ((nameAndTypeIndex = wellKnownMethodNameAndTypes[LONGVALUE_LONG_METHOD_NAME_AND_TYPE]) == 0) {
+ int nameIndex = literalIndex(LONGVALUE_LONG_METHOD_NAME);
+ int typeIndex = literalIndex(LONGVALUE_LONG_METHOD_SIGNATURE);
+ nameAndTypeIndex = wellKnownMethodNameAndTypes[LONGVALUE_LONG_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
writeU2(nameIndex);
+ writeU2(typeIndex);
}
- return index;
+ index = wellKnownMethods[LONGVALUE_LONG_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
}
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexForJavaLangReflectAccessibleObjectSetAccessible() {
- int index;
- int nameAndTypeIndex;
- int classIndex;
- // Looking into the method ref table
- if ((index = wellKnownMethods[SETACCESSIBLE_ACCESSIBLEOBJECT_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectAccessibleObject();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SETACCESSIBLE_ACCESSIBLEOBJECT_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(SETACCESSIBLE_NAME);
- int typeIndex = literalIndex(SETACCESSIBLE_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SETACCESSIBLE_ACCESSIBLEOBJECT_METHOD_NAME_AND_TYPE] =
- currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index =
- wellKnownMethods[SETACCESSIBLE_ACCESSIBLEOBJECT_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexForJavaLangObjectGetClass() {
+ int index;
+ int nameAndTypeIndex;
+ int classIndex;
+ // Looking into the method ref table
+ if ((index = wellKnownMethods[GETCLASS_OBJECT_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangObject();
+ if ((nameAndTypeIndex = wellKnownMethodNameAndTypes[GETCLASS_OBJECT_METHOD_NAME_AND_TYPE]) == 0) {
+ int nameIndex = literalIndex(GETCLASS_OBJECT_METHOD_NAME);
+ int typeIndex = literalIndex(GETCLASS_OBJECT_METHOD_SIGNATURE);
+ nameAndTypeIndex = wellKnownMethodNameAndTypes[GETCLASS_OBJECT_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- return index;
+ index = wellKnownMethods[GETCLASS_OBJECT_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
}
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexForJavaLangReflectArray() {
- int index;
- if ((index = wellKnownTypes[JAVA_LANG_REFLECT_ARRAY_TYPE]) == 0) {
- int nameIndex;
- // The entry doesn't exit yet
- nameIndex = literalIndex(JAVALANGREFLECTARRAY_CONSTANTPOOLNAME);
- index = wellKnownTypes[JAVA_LANG_REFLECT_ARRAY_TYPE] = currentIndex++;
- writeU1(ClassTag);
- // Then add the 8 bytes representing the long
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexForJavaLangReflectAccessibleObject() {
+ int index;
+ if ((index = wellKnownTypes[JAVA_LANG_REFLECT_ACCESSIBLEOBJECT_TYPE]) == 0) {
+ int nameIndex;
+ // The entry doesn't exit yet
+ nameIndex = literalIndex(JAVALANGREFLECTACCESSIBLEOBJECT_CONSTANTPOOLNAME);
+ index = wellKnownTypes[JAVA_LANG_REFLECT_ACCESSIBLEOBJECT_TYPE] = currentIndex++;
+ writeU1(ClassTag);
+ // Then add the 8 bytes representing the long
+ writeU2(nameIndex);
+ }
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexForJavaLangReflectAccessibleObjectSetAccessible() {
+ int index;
+ int nameAndTypeIndex;
+ int classIndex;
+ // Looking into the method ref table
+ if ((index = wellKnownMethods[SETACCESSIBLE_ACCESSIBLEOBJECT_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectAccessibleObject();
+ if ((nameAndTypeIndex = wellKnownMethodNameAndTypes[SETACCESSIBLE_ACCESSIBLEOBJECT_METHOD_NAME_AND_TYPE]) == 0) {
+ int nameIndex = literalIndex(SETACCESSIBLE_NAME);
+ int typeIndex = literalIndex(SETACCESSIBLE_SIGNATURE);
+ nameAndTypeIndex = wellKnownMethodNameAndTypes[SETACCESSIBLE_ACCESSIBLEOBJECT_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
writeU2(nameIndex);
+ writeU2(typeIndex);
}
- return index;
+ index = wellKnownMethods[SETACCESSIBLE_ACCESSIBLEOBJECT_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
}
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexForJavaLangReflectArrayNewInstance() {
- int index;
- int nameAndTypeIndex;
- int classIndex;
- // Looking into the method ref table
- if ((index = wellKnownMethods[NEWINSTANCE_ARRAY_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectArray();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[ARRAY_NEWINSTANCE_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(ARRAY_NEWINSTANCE_NAME);
- int typeIndex = literalIndex(ARRAY_NEWINSTANCE_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[ARRAY_NEWINSTANCE_METHOD_NAME_AND_TYPE] =
- currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[NEWINSTANCE_ARRAY_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexForJavaLangReflectArray() {
+ int index;
+ if ((index = wellKnownTypes[JAVA_LANG_REFLECT_ARRAY_TYPE]) == 0) {
+ int nameIndex;
+ // The entry doesn't exit yet
+ nameIndex = literalIndex(JAVALANGREFLECTARRAY_CONSTANTPOOLNAME);
+ index = wellKnownTypes[JAVA_LANG_REFLECT_ARRAY_TYPE] = currentIndex++;
+ writeU1(ClassTag);
+ // Then add the 8 bytes representing the long
+ writeU2(nameIndex);
+ }
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexForJavaLangReflectArrayNewInstance() {
+ int index;
+ int nameAndTypeIndex;
+ int classIndex;
+ // Looking into the method ref table
+ if ((index = wellKnownMethods[NEWINSTANCE_ARRAY_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectArray();
+ if ((nameAndTypeIndex = wellKnownMethodNameAndTypes[ARRAY_NEWINSTANCE_METHOD_NAME_AND_TYPE]) == 0) {
+ int nameIndex = literalIndex(ARRAY_NEWINSTANCE_NAME);
+ int typeIndex = literalIndex(ARRAY_NEWINSTANCE_SIGNATURE);
+ nameAndTypeIndex = wellKnownMethodNameAndTypes[ARRAY_NEWINSTANCE_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- return index;
+ index = wellKnownMethods[NEWINSTANCE_ARRAY_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
}
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexForJavaLangReflectField() {
- int index;
- if ((index = wellKnownTypes[JAVA_LANG_REFLECT_FIELD_TYPE]) == 0) {
- int nameIndex;
- // The entry doesn't exit yet
- nameIndex = literalIndex(JAVALANGREFLECTFIELD_CONSTANTPOOLNAME);
- index = wellKnownTypes[JAVA_LANG_REFLECT_FIELD_TYPE] = currentIndex++;
- writeU1(ClassTag);
- // Then add the 8 bytes representing the long
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexForJavaLangReflectField() {
+ int index;
+ if ((index = wellKnownTypes[JAVA_LANG_REFLECT_FIELD_TYPE]) == 0) {
+ int nameIndex;
+ // The entry doesn't exit yet
+ nameIndex = literalIndex(JAVALANGREFLECTFIELD_CONSTANTPOOLNAME);
+ index = wellKnownTypes[JAVA_LANG_REFLECT_FIELD_TYPE] = currentIndex++;
+ writeU1(ClassTag);
+ // Then add the 8 bytes representing the long
+ writeU2(nameIndex);
+ }
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexForJavaLangReflectMethod() {
+ int index;
+ if ((index = wellKnownTypes[JAVA_LANG_REFLECT_METHOD_TYPE]) == 0) {
+ int nameIndex;
+ // The entry doesn't exit yet
+ nameIndex = literalIndex(JAVALANGREFLECTMETHOD_CONSTANTPOOLNAME);
+ index = wellKnownTypes[JAVA_LANG_REFLECT_METHOD_TYPE] = currentIndex++;
+ writeU1(ClassTag);
+ // Then add the 8 bytes representing the long
+ writeU2(nameIndex);
+ }
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexForJavaLangReflectMethodInvoke() {
+ int index;
+ int nameAndTypeIndex;
+ int classIndex;
+ // Looking into the method ref table
+ if ((index = wellKnownMethods[INVOKE_METHOD_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectMethod();
+ if ((nameAndTypeIndex = wellKnownMethodNameAndTypes[INVOKE_METHOD_METHOD_NAME_AND_TYPE]) == 0) {
+ int nameIndex = literalIndex(INVOKE_METHOD_METHOD_NAME);
+ int typeIndex = literalIndex(INVOKE_METHOD_METHOD_SIGNATURE);
+ nameAndTypeIndex = wellKnownMethodNameAndTypes[INVOKE_METHOD_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
writeU2(nameIndex);
+ writeU2(typeIndex);
}
- return index;
+ index = wellKnownMethods[INVOKE_METHOD_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
}
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexForJavaLangReflectMethod() {
- int index;
- if ((index = wellKnownTypes[JAVA_LANG_REFLECT_METHOD_TYPE]) == 0) {
- int nameIndex;
- // The entry doesn't exit yet
- nameIndex = literalIndex(JAVALANGREFLECTMETHOD_CONSTANTPOOLNAME);
- index = wellKnownTypes[JAVA_LANG_REFLECT_METHOD_TYPE] = currentIndex++;
- writeU1(ClassTag);
- // Then add the 8 bytes representing the long
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexForJavaLangShortShortValue() {
+ int index;
+ int nameAndTypeIndex;
+ int classIndex;
+ // Looking into the method ref table
+ if ((index = wellKnownMethods[SHORTVALUE_SHORT_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangShort();
+ if ((nameAndTypeIndex = wellKnownMethodNameAndTypes[SHORTVALUE_SHORT_METHOD_NAME_AND_TYPE]) == 0) {
+ int nameIndex = literalIndex(SHORTVALUE_SHORT_METHOD_NAME);
+ int typeIndex = literalIndex(SHORTVALUE_SHORT_METHOD_SIGNATURE);
+ nameAndTypeIndex = wellKnownMethodNameAndTypes[SHORTVALUE_SHORT_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
writeU2(nameIndex);
+ writeU2(typeIndex);
}
- return index;
+ index = wellKnownMethods[SHORTVALUE_SHORT_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
}
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexForJavaLangReflectMethodInvoke() {
- int index;
- int nameAndTypeIndex;
- int classIndex;
- // Looking into the method ref table
- if ((index = wellKnownMethods[INVOKE_METHOD_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectMethod();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[INVOKE_METHOD_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(INVOKE_METHOD_METHOD_NAME);
- int typeIndex = literalIndex(INVOKE_METHOD_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[INVOKE_METHOD_METHOD_NAME_AND_TYPE] =
- currentIndex++;
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding
+ * nameAndType constant with nameIndex, typeIndex.
+ *
+ * @param int nameIndex
+ * @param int nameIndex
+ * @param org.eclipse.jdt.internal.compiler.lookup.MethodBinding a methodBinding
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexForMethods(int nameIndex, int typeIndex, MethodBinding key) {
+ int index;
+ int indexOfWellKnownMethodNameAndType;
+ if ((indexOfWellKnownMethodNameAndType = super.indexOfWellKnownMethodNameAndType(key)) == -1) {
+ if ((indexOfWellKnownMethodNameAndType = indexOfWellKnownMethodNameAndType(key)) == -1) {
+ // check if the entry exists
+ if ((index = nameAndTypeCacheForMethods.get(key)) == -1) {
+ // The entry doesn't exit yet
+ index = nameAndTypeCacheForMethods.put(key, currentIndex++);
writeU1(NameAndTypeTag);
writeU2(nameIndex);
writeU2(typeIndex);
}
- index = wellKnownMethods[INVOKE_METHOD_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
- }
- return index;
- }
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexForJavaLangShortShortValue() {
- int index;
- int nameAndTypeIndex;
- int classIndex;
- // Looking into the method ref table
- if ((index = wellKnownMethods[SHORTVALUE_SHORT_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangShort();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SHORTVALUE_SHORT_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(SHORTVALUE_SHORT_METHOD_NAME);
- int typeIndex = literalIndex(SHORTVALUE_SHORT_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SHORTVALUE_SHORT_METHOD_NAME_AND_TYPE] =
- currentIndex++;
+ } else {
+ if ((index = wellKnownMethodNameAndTypes[indexOfWellKnownMethodNameAndType]) == 0) {
+ index = wellKnownMethodNameAndTypes[indexOfWellKnownMethodNameAndType] = currentIndex++;
writeU1(NameAndTypeTag);
writeU2(nameIndex);
writeU2(typeIndex);
}
- index = wellKnownMethods[SHORTVALUE_SHORT_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
}
- return index;
+ } else {
+ index = super.literalIndexForMethods(nameIndex,typeIndex,key);
}
-
- /**
- * This method returns the index into the constantPool corresponding
- * nameAndType constant with nameIndex, typeIndex.
- *
- * @param int nameIndex
- * @param int nameIndex
- * @param org.eclipse.jdt.internal.compiler.lookup.MethodBinding a methodBinding
- * @return <CODE>int</CODE>
- */
- public int literalIndexForMethods(
- int nameIndex,
- int typeIndex,
- MethodBinding key) {
- int index;
- int indexOfWellKnownMethodNameAndType;
- if ((indexOfWellKnownMethodNameAndType =
- super.indexOfWellKnownMethodNameAndType(key))
- == -1) {
- if ((indexOfWellKnownMethodNameAndType =
- indexOfWellKnownMethodNameAndType(key))
- == -1) {
- // check if the entry exists
- if ((index = nameAndTypeCacheForMethods.get(key)) == -1) {
- // The entry doesn't exit yet
- index = nameAndTypeCacheForMethods.put(key, currentIndex++);
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexJavaLangReflectFieldGetter(int typeID) {
+ int index = 0;
+ int nameAndTypeIndex = 0;
+ int classIndex = 0;
+ switch (typeID) {
+ case T_int :
+ if ((index = wellKnownMethods[GET_INT_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectField();
+ if ((nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[GET_INT_METHOD_NAME_AND_TYPE])
+ == 0) {
+ int nameIndex = literalIndex(GET_INT_METHOD_NAME);
+ int typeIndex = literalIndex(GET_INT_METHOD_SIGNATURE);
+ nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[GET_INT_METHOD_NAME_AND_TYPE] = currentIndex++;
writeU1(NameAndTypeTag);
writeU2(nameIndex);
writeU2(typeIndex);
}
- } else {
- if ((index = wellKnownMethodNameAndTypes[indexOfWellKnownMethodNameAndType])
+ index = wellKnownMethods[GET_INT_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
+ }
+ break;
+ case T_byte :
+ if ((index = wellKnownMethods[GET_BYTE_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectField();
+ if ((nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[GET_BYTE_METHOD_NAME_AND_TYPE])
== 0) {
- index =
- wellKnownMethodNameAndTypes[indexOfWellKnownMethodNameAndType] = currentIndex++;
+ int nameIndex = literalIndex(GET_BYTE_METHOD_NAME);
+ int typeIndex = literalIndex(GET_BYTE_METHOD_SIGNATURE);
+ nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[GET_BYTE_METHOD_NAME_AND_TYPE] = currentIndex++;
writeU1(NameAndTypeTag);
writeU2(nameIndex);
writeU2(typeIndex);
}
+ index = wellKnownMethods[GET_BYTE_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
}
- } else {
- index = super.literalIndexForMethods(nameIndex, typeIndex, key);
- }
- return index;
- }
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexJavaLangReflectFieldGetter(int typeID) {
- int index = 0;
- int nameAndTypeIndex = 0;
- int classIndex = 0;
- switch (typeID) {
- case T_int :
- if ((index = wellKnownMethods[GET_INT_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectField();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GET_INT_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(GET_INT_METHOD_NAME);
- int typeIndex = literalIndex(GET_INT_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GET_INT_METHOD_NAME_AND_TYPE] = currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[GET_INT_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
- }
- break;
- case T_byte :
- if ((index = wellKnownMethods[GET_BYTE_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectField();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GET_BYTE_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(GET_BYTE_METHOD_NAME);
- int typeIndex = literalIndex(GET_BYTE_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GET_BYTE_METHOD_NAME_AND_TYPE] = currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[GET_BYTE_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
- }
- break;
- case T_short :
- if ((index = wellKnownMethods[GET_SHORT_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectField();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GET_SHORT_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(GET_SHORT_METHOD_NAME);
- int typeIndex = literalIndex(GET_SHORT_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GET_SHORT_METHOD_NAME_AND_TYPE] = currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[GET_SHORT_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ break;
+ case T_short :
+ if ((index = wellKnownMethods[GET_SHORT_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectField();
+ if ((nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[GET_SHORT_METHOD_NAME_AND_TYPE])
+ == 0) {
+ int nameIndex = literalIndex(GET_SHORT_METHOD_NAME);
+ int typeIndex = literalIndex(GET_SHORT_METHOD_SIGNATURE);
+ nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[GET_SHORT_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- break;
- case T_long :
- if ((index = wellKnownMethods[GET_LONG_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectField();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GET_LONG_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(GET_LONG_METHOD_NAME);
- int typeIndex = literalIndex(GET_LONG_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GET_LONG_METHOD_NAME_AND_TYPE] = currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[GET_LONG_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ index = wellKnownMethods[GET_SHORT_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
+ }
+ break;
+ case T_long :
+ if ((index = wellKnownMethods[GET_LONG_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectField();
+ if ((nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[GET_LONG_METHOD_NAME_AND_TYPE])
+ == 0) {
+ int nameIndex = literalIndex(GET_LONG_METHOD_NAME);
+ int typeIndex = literalIndex(GET_LONG_METHOD_SIGNATURE);
+ nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[GET_LONG_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- break;
- case T_float :
- if ((index = wellKnownMethods[GET_FLOAT_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectField();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GET_FLOAT_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(GET_FLOAT_METHOD_NAME);
- int typeIndex = literalIndex(GET_FLOAT_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GET_FLOAT_METHOD_NAME_AND_TYPE] = currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[GET_FLOAT_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ index = wellKnownMethods[GET_LONG_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
+ }
+ break;
+ case T_float :
+ if ((index = wellKnownMethods[GET_FLOAT_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectField();
+ if ((nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[GET_FLOAT_METHOD_NAME_AND_TYPE])
+ == 0) {
+ int nameIndex = literalIndex(GET_FLOAT_METHOD_NAME);
+ int typeIndex = literalIndex(GET_FLOAT_METHOD_SIGNATURE);
+ nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[GET_FLOAT_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- break;
- case T_double :
- if ((index = wellKnownMethods[GET_DOUBLE_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectField();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GET_DOUBLE_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(GET_DOUBLE_METHOD_NAME);
- int typeIndex = literalIndex(GET_DOUBLE_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GET_DOUBLE_METHOD_NAME_AND_TYPE] = currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[GET_DOUBLE_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ index = wellKnownMethods[GET_FLOAT_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
+ }
+ break;
+ case T_double :
+ if ((index = wellKnownMethods[GET_DOUBLE_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectField();
+ if ((nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[GET_DOUBLE_METHOD_NAME_AND_TYPE])
+ == 0) {
+ int nameIndex = literalIndex(GET_DOUBLE_METHOD_NAME);
+ int typeIndex = literalIndex(GET_DOUBLE_METHOD_SIGNATURE);
+ nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[GET_DOUBLE_METHOD_NAME_AND_TYPE] =
+ currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- break;
- case T_char :
- if ((index = wellKnownMethods[GET_CHAR_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectField();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GET_CHAR_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(GET_CHAR_METHOD_NAME);
- int typeIndex = literalIndex(GET_CHAR_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GET_CHAR_METHOD_NAME_AND_TYPE] = currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[GET_CHAR_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ index = wellKnownMethods[GET_DOUBLE_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
+ }
+ break;
+ case T_char :
+ if ((index = wellKnownMethods[GET_CHAR_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectField();
+ if ((nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[GET_CHAR_METHOD_NAME_AND_TYPE])
+ == 0) {
+ int nameIndex = literalIndex(GET_CHAR_METHOD_NAME);
+ int typeIndex = literalIndex(GET_CHAR_METHOD_SIGNATURE);
+ nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[GET_CHAR_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- break;
- case T_boolean :
- if ((index = wellKnownMethods[GET_BOOLEAN_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectField();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GET_BOOLEAN_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(GET_BOOLEAN_METHOD_NAME);
- int typeIndex = literalIndex(GET_BOOLEAN_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GET_BOOLEAN_METHOD_NAME_AND_TYPE] = currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[GET_BOOLEAN_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ index = wellKnownMethods[GET_CHAR_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
+ }
+ break;
+ case T_boolean :
+ if ((index = wellKnownMethods[GET_BOOLEAN_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectField();
+ if ((nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[GET_BOOLEAN_METHOD_NAME_AND_TYPE])
+ == 0) {
+ int nameIndex = literalIndex(GET_BOOLEAN_METHOD_NAME);
+ int typeIndex = literalIndex(GET_BOOLEAN_METHOD_SIGNATURE);
+ nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[GET_BOOLEAN_METHOD_NAME_AND_TYPE] =
+ currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- break;
- default :
- if ((index = wellKnownMethods[GET_OBJECT_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectField();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GET_OBJECT_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(GET_OBJECT_METHOD_NAME);
- int typeIndex = literalIndex(GET_OBJECT_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[GET_OBJECT_METHOD_NAME_AND_TYPE] = currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[GET_OBJECT_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ index = wellKnownMethods[GET_BOOLEAN_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
+ }
+ break;
+ default :
+ if ((index = wellKnownMethods[GET_OBJECT_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectField();
+ if ((nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[GET_OBJECT_METHOD_NAME_AND_TYPE])
+ == 0) {
+ int nameIndex = literalIndex(GET_OBJECT_METHOD_NAME);
+ int typeIndex = literalIndex(GET_OBJECT_METHOD_SIGNATURE);
+ nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[GET_OBJECT_METHOD_NAME_AND_TYPE] =
+ currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
+ index = wellKnownMethods[GET_OBJECT_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
+ }
}
- return index;
- }
-
- /**
- * This method returns the index into the constantPool corresponding to the
- * method descriptor. It can be either an interface method reference constant
- * or a method reference constant.
- *
- * @return <CODE>int</CODE>
- */
- public int literalIndexJavaLangReflectFieldSetter(int typeID) {
- int index = 0;
- int nameAndTypeIndex = 0;
- int classIndex = 0;
- switch (typeID) {
- case T_int :
- if ((index = wellKnownMethods[SET_INT_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectField();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SET_INT_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(SET_INT_METHOD_NAME);
- int typeIndex = literalIndex(SET_INT_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SET_INT_METHOD_NAME_AND_TYPE] = currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[SET_INT_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ return index;
+}
+/**
+ * This method returns the index into the constantPool corresponding to the
+ * method descriptor. It can be either an interface method reference constant
+ * or a method reference constant.
+ *
+ * @return <CODE>int</CODE>
+ */
+public int literalIndexJavaLangReflectFieldSetter(int typeID) {
+ int index = 0;
+ int nameAndTypeIndex = 0;
+ int classIndex = 0;
+ switch (typeID) {
+ case T_int :
+ if ((index = wellKnownMethods[SET_INT_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectField();
+ if ((nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[SET_INT_METHOD_NAME_AND_TYPE])
+ == 0) {
+ int nameIndex = literalIndex(SET_INT_METHOD_NAME);
+ int typeIndex = literalIndex(SET_INT_METHOD_SIGNATURE);
+ nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[SET_INT_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- break;
- case T_byte :
- if ((index = wellKnownMethods[SET_BYTE_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectField();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SET_BYTE_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(SET_BYTE_METHOD_NAME);
- int typeIndex = literalIndex(SET_BYTE_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SET_BYTE_METHOD_NAME_AND_TYPE] = currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[SET_BYTE_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ index = wellKnownMethods[SET_INT_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
+ }
+ break;
+ case T_byte :
+ if ((index = wellKnownMethods[SET_BYTE_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectField();
+ if ((nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[SET_BYTE_METHOD_NAME_AND_TYPE])
+ == 0) {
+ int nameIndex = literalIndex(SET_BYTE_METHOD_NAME);
+ int typeIndex = literalIndex(SET_BYTE_METHOD_SIGNATURE);
+ nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[SET_BYTE_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- break;
- case T_short :
- if ((index = wellKnownMethods[SET_SHORT_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectField();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SET_SHORT_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(SET_SHORT_METHOD_NAME);
- int typeIndex = literalIndex(SET_SHORT_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SET_SHORT_METHOD_NAME_AND_TYPE] = currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[SET_SHORT_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ index = wellKnownMethods[SET_BYTE_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
+ }
+ break;
+ case T_short :
+ if ((index = wellKnownMethods[SET_SHORT_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectField();
+ if ((nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[SET_SHORT_METHOD_NAME_AND_TYPE])
+ == 0) {
+ int nameIndex = literalIndex(SET_SHORT_METHOD_NAME);
+ int typeIndex = literalIndex(SET_SHORT_METHOD_SIGNATURE);
+ nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[SET_SHORT_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- break;
- case T_long :
- if ((index = wellKnownMethods[SET_LONG_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectField();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SET_LONG_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(SET_LONG_METHOD_NAME);
- int typeIndex = literalIndex(SET_LONG_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SET_LONG_METHOD_NAME_AND_TYPE] = currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[SET_LONG_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ index = wellKnownMethods[SET_SHORT_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
+ }
+ break;
+ case T_long :
+ if ((index = wellKnownMethods[SET_LONG_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectField();
+ if ((nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[SET_LONG_METHOD_NAME_AND_TYPE])
+ == 0) {
+ int nameIndex = literalIndex(SET_LONG_METHOD_NAME);
+ int typeIndex = literalIndex(SET_LONG_METHOD_SIGNATURE);
+ nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[SET_LONG_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- break;
- case T_float :
- if ((index = wellKnownMethods[SET_FLOAT_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectField();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SET_FLOAT_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(SET_FLOAT_METHOD_NAME);
- int typeIndex = literalIndex(SET_FLOAT_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SET_FLOAT_METHOD_NAME_AND_TYPE] = currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[SET_FLOAT_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ index = wellKnownMethods[SET_LONG_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
+ }
+ break;
+ case T_float :
+ if ((index = wellKnownMethods[SET_FLOAT_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectField();
+ if ((nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[SET_FLOAT_METHOD_NAME_AND_TYPE])
+ == 0) {
+ int nameIndex = literalIndex(SET_FLOAT_METHOD_NAME);
+ int typeIndex = literalIndex(SET_FLOAT_METHOD_SIGNATURE);
+ nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[SET_FLOAT_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- break;
- case T_double :
- if ((index = wellKnownMethods[SET_DOUBLE_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectField();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SET_DOUBLE_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(SET_DOUBLE_METHOD_NAME);
- int typeIndex = literalIndex(SET_DOUBLE_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SET_DOUBLE_METHOD_NAME_AND_TYPE] = currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[SET_DOUBLE_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ index = wellKnownMethods[SET_FLOAT_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
+ }
+ break;
+ case T_double :
+ if ((index = wellKnownMethods[SET_DOUBLE_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectField();
+ if ((nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[SET_DOUBLE_METHOD_NAME_AND_TYPE])
+ == 0) {
+ int nameIndex = literalIndex(SET_DOUBLE_METHOD_NAME);
+ int typeIndex = literalIndex(SET_DOUBLE_METHOD_SIGNATURE);
+ nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[SET_DOUBLE_METHOD_NAME_AND_TYPE] =
+ currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- break;
- case T_char :
- if ((index = wellKnownMethods[SET_CHAR_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectField();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SET_CHAR_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(SET_CHAR_METHOD_NAME);
- int typeIndex = literalIndex(SET_CHAR_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SET_CHAR_METHOD_NAME_AND_TYPE] = currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[SET_CHAR_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ index = wellKnownMethods[SET_DOUBLE_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
+ }
+ break;
+ case T_char :
+ if ((index = wellKnownMethods[SET_CHAR_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectField();
+ if ((nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[SET_CHAR_METHOD_NAME_AND_TYPE])
+ == 0) {
+ int nameIndex = literalIndex(SET_CHAR_METHOD_NAME);
+ int typeIndex = literalIndex(SET_CHAR_METHOD_SIGNATURE);
+ nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[SET_CHAR_METHOD_NAME_AND_TYPE] = currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- break;
- case T_boolean :
- if ((index = wellKnownMethods[SET_BOOLEAN_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectField();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SET_BOOLEAN_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(SET_BOOLEAN_METHOD_NAME);
- int typeIndex = literalIndex(SET_BOOLEAN_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SET_BOOLEAN_METHOD_NAME_AND_TYPE] = currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[SET_BOOLEAN_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ index = wellKnownMethods[SET_CHAR_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
+ }
+ break;
+ case T_boolean :
+ if ((index = wellKnownMethods[SET_BOOLEAN_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectField();
+ if ((nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[SET_BOOLEAN_METHOD_NAME_AND_TYPE])
+ == 0) {
+ int nameIndex = literalIndex(SET_BOOLEAN_METHOD_NAME);
+ int typeIndex = literalIndex(SET_BOOLEAN_METHOD_SIGNATURE);
+ nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[SET_BOOLEAN_METHOD_NAME_AND_TYPE] =
+ currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
- break;
- default :
- if ((index = wellKnownMethods[SET_OBJECT_METHOD]) == 0) {
- classIndex = literalIndexForJavaLangReflectField();
- if ((nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SET_OBJECT_METHOD_NAME_AND_TYPE])
- == 0) {
- int nameIndex = literalIndex(SET_OBJECT_METHOD_NAME);
- int typeIndex = literalIndex(SET_OBJECT_METHOD_SIGNATURE);
- nameAndTypeIndex =
- wellKnownMethodNameAndTypes[SET_OBJECT_METHOD_NAME_AND_TYPE] = currentIndex++;
- writeU1(NameAndTypeTag);
- writeU2(nameIndex);
- writeU2(typeIndex);
- }
- index = wellKnownMethods[SET_OBJECT_METHOD] = currentIndex++;
- // Write the method ref constant into the constant pool
- // First add the tag
- writeU1(MethodRefTag);
- // Then write the class index
- writeU2(classIndex);
- // The write the nameAndType index
- writeU2(nameAndTypeIndex);
+ index = wellKnownMethods[SET_BOOLEAN_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
+ }
+ break;
+ default :
+ if ((index = wellKnownMethods[SET_OBJECT_METHOD]) == 0) {
+ classIndex = literalIndexForJavaLangReflectField();
+ if ((nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[SET_OBJECT_METHOD_NAME_AND_TYPE])
+ == 0) {
+ int nameIndex = literalIndex(SET_OBJECT_METHOD_NAME);
+ int typeIndex = literalIndex(SET_OBJECT_METHOD_SIGNATURE);
+ nameAndTypeIndex =
+ wellKnownMethodNameAndTypes[SET_OBJECT_METHOD_NAME_AND_TYPE] =
+ currentIndex++;
+ writeU1(NameAndTypeTag);
+ writeU2(nameIndex);
+ writeU2(typeIndex);
}
+ index = wellKnownMethods[SET_OBJECT_METHOD] = currentIndex++;
+ // Write the method ref constant into the constant pool
+ // First add the tag
+ writeU1(MethodRefTag);
+ // Then write the class index
+ writeU2(classIndex);
+ // The write the nameAndType index
+ writeU2(nameAndTypeIndex);
+ }
}
- return index;
- }
-
+ return index;
+}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetEnvironment.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetEnvironment.java
index d6d91cc794..40dfffb068 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetEnvironment.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetEnvironment.java
@@ -15,70 +15,63 @@ import org.eclipse.jdt.internal.compiler.util.*;
* not found, it search in the code snippet support. This includes the super class
* org.eclipse.jdt.internal.eval.target.CodeSnippet as well as the global variable classes.
*/
-public class CodeSnippetEnvironment
- implements INameEnvironment, EvaluationConstants {
+public class CodeSnippetEnvironment implements INameEnvironment, EvaluationConstants {
INameEnvironment env;
EvaluationContext context;
- /**
- * Creates a new wrapper for the given environment.
- */
- public CodeSnippetEnvironment(
- INameEnvironment env,
- EvaluationContext context) {
- this.env = env;
- this.context = context;
+/**
+ * Creates a new wrapper for the given environment.
+ */
+public CodeSnippetEnvironment(INameEnvironment env, EvaluationContext context) {
+ this.env = env;
+ this.context = context;
+}
+/**
+ * @see INameEnvironment
+ */
+public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
+ NameEnvironmentAnswer result = this.env.findType(compoundTypeName);
+ if (result != null) {
+ return result;
}
-
- /**
- * @see INameEnvironment
- */
- public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
- NameEnvironmentAnswer result = this.env.findType(compoundTypeName);
- if (result != null) {
- return result;
+ if (CharOperation.equals(compoundTypeName, ROOT_COMPOUND_NAME)) {
+ IBinaryType binary = this.context.getRootCodeSnippetBinary();
+ if (binary == null) {
+ return null;
+ } else {
+ return new NameEnvironmentAnswer(binary);
}
- if (CharOperation.equals(compoundTypeName, ROOT_COMPOUND_NAME)) {
- IBinaryType binary = this.context.getRootCodeSnippetBinary();
- if (binary == null) {
+ }
+ VariablesInfo installedVars = this.context.installedVars;
+ ClassFile[] classFiles = installedVars.classFiles;
+ for (int i = 0; i < classFiles.length; i++) {
+ ClassFile classFile = classFiles[i];
+ if (CharOperation.equals(compoundTypeName, classFile.getCompoundName())) {
+ ClassFileReader binary = null;
+ try {
+ binary = new ClassFileReader(classFile.getBytes(), null);
+ } catch (ClassFormatException e) {
+ e.printStackTrace(); // Should never happen since we compiled this type
return null;
- } else {
- return new NameEnvironmentAnswer(binary);
- }
- }
- VariablesInfo installedVars = this.context.installedVars;
- ClassFile[] classFiles = installedVars.classFiles;
- for (int i = 0; i < classFiles.length; i++) {
- ClassFile classFile = classFiles[i];
- if (CharOperation.equals(compoundTypeName, classFile.getCompoundName())) {
- ClassFileReader binary = null;
- try {
- binary = new ClassFileReader(classFile.getBytes(), null);
- } catch (ClassFormatException e) {
- e.printStackTrace(); // Should never happen since we compiled this type
- return null;
- }
- return new NameEnvironmentAnswer(binary);
}
+ return new NameEnvironmentAnswer(binary);
}
- return null;
}
-
- /**
- * @see INameEnvironment.
- */
- public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
- NameEnvironmentAnswer result = this.env.findType(typeName, packageName);
- if (result != null) {
- return result;
- }
- return findType(CharOperation.arrayConcat(packageName, typeName));
- }
-
- /**
- * @see INameEnvironment.
- */
- public boolean isPackage(char[][] parentPackageName, char[] packageName) {
- return this.env.isPackage(parentPackageName, packageName);
+ return null;
+}
+/**
+ * @see INameEnvironment.
+ */
+public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
+ NameEnvironmentAnswer result = this.env.findType(typeName, packageName);
+ if (result != null) {
+ return result;
}
-
+ return findType(CharOperation.arrayConcat(packageName, typeName));
+}
+/**
+ * @see INameEnvironment.
+ */
+public boolean isPackage(char[][] parentPackageName, char[] packageName) {
+ return this.env.isPackage(parentPackageName, packageName);
+}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetEvaluator.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetEvaluator.java
index 41f916b692..dcdcffadfa 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetEvaluator.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetEvaluator.java
@@ -15,9 +15,7 @@ import java.util.*;
* A code snippet evaluator compiles and returns class file for a code snippet.
* Or it reports problems against the code snippet.
*/
-public class CodeSnippetEvaluator
- extends Evaluator
- implements EvaluationConstants {
+public class CodeSnippetEvaluator extends Evaluator implements EvaluationConstants {
/**
* Whether the code snippet support classes should be found in the provided name environment
* or on disk.
@@ -33,183 +31,161 @@ public class CodeSnippetEvaluator
* The code snippet to generated compilation unit mapper
*/
CodeSnippetToCuMapper mapper;
- /**
- * Creates a new code snippet evaluator.
- */
- CodeSnippetEvaluator(
- char[] codeSnippet,
- EvaluationContext context,
- INameEnvironment environment,
- ConfigurableOption[] options,
- IRequestor requestor,
- IProblemFactory problemFactory) {
- super(context, environment, options, requestor, problemFactory);
- this.codeSnippet = codeSnippet;
- }
-
- /**
- * @see org.eclipse.jdt.internal.eval.Evaluator
- */
- protected void addEvaluationResultForCompilationProblem(
- Hashtable resultsByIDs,
- IProblem problem,
- char[] cuSource) {
- CodeSnippetToCuMapper mapper = getMapper();
- int pbLineNumber = problem.getSourceLineNumber();
- int evaluationType = mapper.getEvaluationType(pbLineNumber);
-
- char[] evaluationID = null;
- switch (evaluationType) {
- case EvaluationResult.T_PACKAGE :
- evaluationID = this.context.packageName;
-
- // shift line number, source start and source end
- problem.setSourceLineNumber(1);
- problem.setSourceStart(0);
- problem.setSourceEnd(evaluationID.length - 1);
- break;
-
- case EvaluationResult.T_IMPORT :
- evaluationID = mapper.getImport(pbLineNumber);
-
- // shift line number, source start and source end
- problem.setSourceLineNumber(1);
- problem.setSourceStart(0);
- problem.setSourceEnd(evaluationID.length - 1);
- break;
-
- case EvaluationResult.T_CODE_SNIPPET :
- evaluationID = this.codeSnippet;
-
- // shift line number, source start and source end
- problem.setSourceLineNumber(pbLineNumber - this.mapper.lineNumberOffset);
- problem.setSourceStart(problem.getSourceStart() - this.mapper.startPosOffset);
- problem.setSourceEnd(problem.getSourceEnd() - this.mapper.startPosOffset);
- break;
-
- case EvaluationResult.T_INTERNAL :
- evaluationID = cuSource;
- break;
- }
-
- EvaluationResult result = (EvaluationResult) resultsByIDs.get(evaluationID);
- if (result == null) {
- resultsByIDs.put(
- evaluationID,
- new EvaluationResult(evaluationID, evaluationType, new IProblem[] { problem }));
- } else {
- result.addProblem(problem);
- }
+/**
+ * Creates a new code snippet evaluator.
+ */
+CodeSnippetEvaluator(char[] codeSnippet, EvaluationContext context, INameEnvironment environment, ConfigurableOption[] options, IRequestor requestor, IProblemFactory problemFactory) {
+ super(context, environment, options, requestor, problemFactory);
+ this.codeSnippet = codeSnippet;
+}
+/**
+ * @see org.eclipse.jdt.internal.eval.Evaluator
+ */
+protected void addEvaluationResultForCompilationProblem(Hashtable resultsByIDs, IProblem problem, char[] cuSource) {
+ CodeSnippetToCuMapper mapper = getMapper();
+ int pbLineNumber = problem.getSourceLineNumber();
+ int evaluationType = mapper.getEvaluationType(pbLineNumber);
+
+ char[] evaluationID = null;
+ switch(evaluationType) {
+ case EvaluationResult.T_PACKAGE:
+ evaluationID = this.context.packageName;
+
+ // shift line number, source start and source end
+ problem.setSourceLineNumber(1);
+ problem.setSourceStart(0);
+ problem.setSourceEnd(evaluationID.length - 1);
+ break;
+
+ case EvaluationResult.T_IMPORT:
+ evaluationID = mapper.getImport(pbLineNumber);
+
+ // shift line number, source start and source end
+ problem.setSourceLineNumber(1);
+ problem.setSourceStart(0);
+ problem.setSourceEnd(evaluationID.length - 1);
+ break;
+
+ case EvaluationResult.T_CODE_SNIPPET:
+ evaluationID = this.codeSnippet;
+
+ // shift line number, source start and source end
+ problem.setSourceLineNumber(pbLineNumber - this.mapper.lineNumberOffset);
+ problem.setSourceStart(problem.getSourceStart() - this.mapper.startPosOffset);
+ problem.setSourceEnd(problem.getSourceEnd() - this.mapper.startPosOffset);
+ break;
+
+ case EvaluationResult.T_INTERNAL:
+ evaluationID = cuSource;
+ break;
}
- /**
- * @see org.eclipse.jdt.internal.eval.Evaluator
- */
- protected char[] getClassName() {
- return CharOperation.concat(
- CODE_SNIPPET_CLASS_NAME_PREFIX,
- Integer.toString(this.context.CODE_SNIPPET_COUNTER + 1).toCharArray());
+ EvaluationResult result = (EvaluationResult)resultsByIDs.get(evaluationID);
+ if (result == null) {
+ resultsByIDs.put(evaluationID, new EvaluationResult(evaluationID, evaluationType, new IProblem[] {problem}));
+ } else {
+ result.addProblem(problem);
}
-
- /**
- * @see Evaluator.
- */
- Compiler getCompiler(ICompilerRequestor requestor) {
- Compiler compiler = null;
- if (!DEVELOPMENT_MODE) {
- // If we are not developping the code snippet support classes,
- // use a regular compiler and feed its lookup environment with
- // the code snippet support classes
-
- compiler =
- new CodeSnippetCompiler(
- this.environment,
- DefaultErrorHandlingPolicies.exitAfterAllProblems(),
- this.options,
- requestor,
- this.problemFactory,
- this.context,
- getMapper().startPosOffset,
- getMapper().startPosOffset + codeSnippet.length - 1);
- // Initialize the compiler's lookup environment with the already compiled super classes
- IBinaryType binary = this.context.getRootCodeSnippetBinary();
- if (binary != null) {
- compiler.lookupEnvironment.cacheBinaryType(binary);
- }
- VariablesInfo installedVars = this.context.installedVars;
- if (installedVars != null) {
- ClassFile[] globalClassFiles = installedVars.classFiles;
- for (int i = 0; i < globalClassFiles.length; i++) {
- ClassFileReader binaryType = null;
- try {
- binaryType = new ClassFileReader(globalClassFiles[i].getBytes(), null);
- } catch (ClassFormatException e) {
- e.printStackTrace(); // Should never happen since we compiled this type
- }
- compiler.lookupEnvironment.cacheBinaryType(binaryType);
+}
+/**
+ * @see org.eclipse.jdt.internal.eval.Evaluator
+ */
+protected char[] getClassName() {
+ return CharOperation.concat(CODE_SNIPPET_CLASS_NAME_PREFIX, Integer.toString(this.context.CODE_SNIPPET_COUNTER + 1).toCharArray());
+}
+/**
+ * @see Evaluator.
+ */
+Compiler getCompiler(ICompilerRequestor requestor) {
+ Compiler compiler = null;
+ if (!DEVELOPMENT_MODE) {
+ // If we are not developping the code snippet support classes,
+ // use a regular compiler and feed its lookup environment with
+ // the code snippet support classes
+
+ compiler =
+ new CodeSnippetCompiler(
+ this.environment,
+ DefaultErrorHandlingPolicies.exitAfterAllProblems(),
+ this.options,
+ requestor,
+ this.problemFactory,
+ this.context,
+ getMapper().startPosOffset,
+ getMapper().startPosOffset + codeSnippet.length - 1);
+ // Initialize the compiler's lookup environment with the already compiled super classes
+ IBinaryType binary = this.context.getRootCodeSnippetBinary();
+ if (binary != null) {
+ compiler.lookupEnvironment.cacheBinaryType(binary);
+ }
+ VariablesInfo installedVars = this.context.installedVars;
+ if (installedVars != null) {
+ ClassFile[] globalClassFiles = installedVars.classFiles;
+ for (int i = 0; i < globalClassFiles.length; i++) {
+ ClassFileReader binaryType = null;
+ try {
+ binaryType = new ClassFileReader(globalClassFiles[i].getBytes(), null);
+ } catch (ClassFormatException e) {
+ e.printStackTrace(); // Should never happen since we compiled this type
}
+ compiler.lookupEnvironment.cacheBinaryType(binaryType);
}
- } else {
- // If we are developping the code snippet support classes,
- // use a wrapped environment so that if the code snippet classes are not found
- // then a default implementation is provided.
-
- compiler =
- new Compiler(
- getWrapperEnvironment(),
- DefaultErrorHandlingPolicies.exitAfterAllProblems(),
- this.options,
- requestor,
- this.problemFactory);
}
- return compiler;
+ } else {
+ // If we are developping the code snippet support classes,
+ // use a wrapped environment so that if the code snippet classes are not found
+ // then a default implementation is provided.
+
+ compiler = new Compiler(
+ getWrapperEnvironment(),
+ DefaultErrorHandlingPolicies.exitAfterAllProblems(),
+ this.options,
+ requestor,
+ this.problemFactory);
}
-
- private CodeSnippetToCuMapper getMapper() {
- if (this.mapper == null) {
- char[] varClassName = null;
- VariablesInfo installedVars = this.context.installedVars;
- if (installedVars != null) {
- char[] superPackageName = installedVars.packageName;
- if (superPackageName != null && superPackageName.length != 0) {
- varClassName =
- CharOperation.concat(superPackageName, installedVars.className, '.');
- } else {
- varClassName = installedVars.className;
- }
-
+ return compiler;
+}
+private CodeSnippetToCuMapper getMapper() {
+ if (this.mapper == null) {
+ char[] varClassName = null;
+ VariablesInfo installedVars = this.context.installedVars;
+ if (installedVars != null) {
+ char[] superPackageName = installedVars.packageName;
+ if (superPackageName != null && superPackageName.length != 0) {
+ varClassName = CharOperation.concat(superPackageName, installedVars.className, '.');
+ } else {
+ varClassName = installedVars.className;
}
- this.mapper =
- new CodeSnippetToCuMapper(
- this.codeSnippet,
- this.context.packageName,
- this.context.imports,
- getClassName(),
- varClassName,
- this.context.localVariableNames,
- this.context.localVariableTypeNames,
- this.context.localVariableModifiers,
- this.context.declaringTypeName);
-
+
}
- return this.mapper;
- }
+ this.mapper = new CodeSnippetToCuMapper(
+ this.codeSnippet,
+ this.context.packageName,
+ this.context.imports,
+ getClassName(),
+ varClassName,
+ this.context.localVariableNames,
+ this.context.localVariableTypeNames,
+ this.context.localVariableModifiers,
+ this.context.declaringTypeName
+ );
- /**
- * @see org.eclipse.jdt.internal.eval.Evaluator
- */
- protected char[] getSource() {
- return getMapper().cuSource;
}
-
- /**
- * Returns an environment that wraps the client's name environment.
- * This wrapper always considers the wrapped environment then if the name is
- * not found, it search in the code snippet support. This includes the superclass
- * org.eclipse.jdt.internal.eval.target.CodeSnippet as well as the global variable classes.
- */
- private INameEnvironment getWrapperEnvironment() {
- return new CodeSnippetEnvironment(this.environment, this.context);
- }
-
+ return this.mapper;
+}
+/**
+ * @see org.eclipse.jdt.internal.eval.Evaluator
+ */
+protected char[] getSource() {
+ return getMapper().cuSource;
+}
+/**
+ * Returns an environment that wraps the client's name environment.
+ * This wrapper always considers the wrapped environment then if the name is
+ * not found, it search in the code snippet support. This includes the superclass
+ * org.eclipse.jdt.internal.eval.target.CodeSnippet as well as the global variable classes.
+ */
+private INameEnvironment getWrapperEnvironment() {
+ return new CodeSnippetEnvironment(this.environment, this.context);
+}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetFieldReference.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetFieldReference.java
index fe9170b653..ca49587af3 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetFieldReference.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetFieldReference.java
@@ -4,7 +4,7 @@ package org.eclipse.jdt.internal.eval;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
-
+
import org.eclipse.jdt.internal.compiler.ast.*;
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
@@ -14,342 +14,280 @@ import org.eclipse.jdt.internal.compiler.lookup.ProblemReasons;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
-public class CodeSnippetFieldReference
- extends FieldReference
- implements ProblemReasons, EvaluationConstants {
+public class CodeSnippetFieldReference extends FieldReference implements ProblemReasons, EvaluationConstants {
EvaluationContext evaluationContext;
FieldBinding delegateThis;
- TypeBinding receiverType;
- /**
- * CodeSnippetFieldReference constructor comment.
- * @param source char[]
- * @param pos long
- */
- public CodeSnippetFieldReference(
- char[] source,
- long pos,
- EvaluationContext evaluationContext) {
- super(source, pos);
- this.evaluationContext = evaluationContext;
- }
-
- public void generateAssignment(
- BlockScope currentScope,
- CodeStream codeStream,
- Assignment assignment,
- boolean valueRequired) {
+/**
+ * CodeSnippetFieldReference constructor comment.
+ * @param source char[]
+ * @param pos long
+ */
+public CodeSnippetFieldReference(char[] source, long pos, EvaluationContext evaluationContext) {
+ super(source, pos);
+ this.evaluationContext = evaluationContext;
+}
+public void generateAssignment(BlockScope currentScope, CodeStream codeStream, Assignment assignment, boolean valueRequired) {
- if (binding.canBeSeenBy(receiverType, this, currentScope)) {
- receiver.generateCode(currentScope, codeStream, !binding.isStatic());
- assignment.expression.generateCode(currentScope, codeStream, true);
- fieldStore(codeStream, binding, null, valueRequired);
- } else {
- ((CodeSnippetCodeStream) codeStream).generateEmulationForField(binding);
- receiver.generateCode(currentScope, codeStream, !binding.isStatic());
- if (binding.isStatic()) { // need a receiver?
- codeStream.aconst_null();
- }
- assignment.expression.generateCode(currentScope, codeStream, true);
- if (valueRequired) {
- if ((binding.type == LongBinding) || (binding.type == DoubleBinding)) {
- codeStream.dup2_x2();
- } else {
- codeStream.dup_x2();
- }
- }
- ((CodeSnippetCodeStream) codeStream).generateEmulatedWriteAccessForField(
- binding);
+ if (binding.canBeSeenBy(receiverType, this, currentScope)) {
+ receiver.generateCode(currentScope, codeStream, !binding.isStatic());
+ assignment.expression.generateCode(currentScope, codeStream, true);
+ fieldStore(codeStream, binding, null, valueRequired);
+ } else {
+ ((CodeSnippetCodeStream) codeStream).generateEmulationForField(binding);
+ receiver.generateCode(currentScope, codeStream, !binding.isStatic());
+ if (binding.isStatic()) { // need a receiver?
+ codeStream.aconst_null();
}
+ assignment.expression.generateCode(currentScope, codeStream, true);
if (valueRequired) {
- codeStream.generateImplicitConversion(assignment.implicitConversion);
+ if ((binding.type == LongBinding) || (binding.type == DoubleBinding)) {
+ codeStream.dup2_x2();
+ } else {
+ codeStream.dup_x2();
+ }
}
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedWriteAccessForField(binding);
}
-
- /**
- * Field reference code generation
- *
- * @param currentScope org.eclipse.jdt.internal.compiler.lookup.BlockScope
- * @param codeStream org.eclipse.jdt.internal.compiler.codegen.CodeStream
- * @param valueRequired boolean
- */
- public void generateCode(
- BlockScope currentScope,
- CodeStream codeStream,
- boolean valueRequired) {
- int pc = codeStream.position;
- if (constant != NotAConstant) {
- if (valueRequired) {
- codeStream.generateConstant(constant, implicitConversion);
- }
- } else {
- boolean isStatic = binding.isStatic();
- receiver.generateCode(
- currentScope,
- codeStream,
- valueRequired && (!isStatic) && (binding.constant == NotAConstant));
- if (valueRequired) {
- if (binding.constant == NotAConstant) {
- if (binding.declaringClass == null) { // array length
- codeStream.arraylength();
- } else {
- if (binding.canBeSeenBy(receiverType, this, currentScope)) {
- if (isStatic) {
- codeStream.getstatic(binding);
- } else {
- codeStream.getfield(binding);
- }
+ if (valueRequired){
+ codeStream.generateImplicitConversion(assignment.implicitConversion);
+ }
+}
+/**
+ * Field reference code generation
+ *
+ * @param currentScope org.eclipse.jdt.internal.compiler.lookup.BlockScope
+ * @param codeStream org.eclipse.jdt.internal.compiler.codegen.CodeStream
+ * @param valueRequired boolean
+ */
+public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) {
+ int pc = codeStream.position;
+ if (constant != NotAConstant) {
+ if (valueRequired) {
+ codeStream.generateConstant(constant, implicitConversion);
+ }
+ } else {
+ boolean isStatic = binding.isStatic();
+ receiver.generateCode(currentScope, codeStream, valueRequired && (!isStatic) && (binding.constant == NotAConstant));
+ if (valueRequired) {
+ if (binding.constant == NotAConstant) {
+ if (binding.declaringClass == null) { // array length
+ codeStream.arraylength();
+ } else {
+ if (binding.canBeSeenBy(receiverType, this, currentScope)) {
+ if (isStatic) {
+ codeStream.getstatic(binding);
} else {
- if (isStatic) {
- // we need a null on the stack to use the reflect emulation
- codeStream.aconst_null();
- }
- ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(
- binding);
+ codeStream.getfield(binding);
}
+ } else {
+ if (isStatic) {
+ // we need a null on the stack to use the reflect emulation
+ codeStream.aconst_null();
+ }
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(binding);
}
- codeStream.generateImplicitConversion(implicitConversion);
- } else {
- codeStream.generateConstant(binding.constant, implicitConversion);
}
+ codeStream.generateImplicitConversion(implicitConversion);
+ } else {
+ codeStream.generateConstant(binding.constant, implicitConversion);
}
}
- codeStream.recordPositionsFrom(pc, this);
}
-
- public void generateCompoundAssignment(
- BlockScope currentScope,
- CodeStream codeStream,
- Expression expression,
- int operator,
- int assignmentImplicitConversion,
- boolean valueRequired) {
-
- boolean isStatic;
- if (binding.canBeSeenBy(receiverType, this, currentScope)) {
- receiver.generateCode(
- currentScope,
- codeStream,
- !(isStatic = binding.isStatic()));
- if (isStatic) {
- codeStream.getstatic(binding);
- } else {
- codeStream.dup();
- codeStream.getfield(binding);
- }
- int operationTypeID;
- if ((operationTypeID = implicitConversion >> 4) == T_String) {
- codeStream.generateStringAppend(currentScope, null, expression);
- } else {
- // promote the array reference to the suitable operation type
- codeStream.generateImplicitConversion(implicitConversion);
- // generate the increment value (will by itself be promoted to the operation value)
- if (expression == IntLiteral.One) { // prefix operation
- codeStream.generateConstant(expression.constant, implicitConversion);
- } else {
- expression.generateCode(currentScope, codeStream, true);
- }
- // perform the operation
- codeStream.sendOperator(operator, operationTypeID);
- // cast the value back to the array reference type
- codeStream.generateImplicitConversion(assignmentImplicitConversion);
- }
- fieldStore(codeStream, binding, null, valueRequired);
+ codeStream.recordPositionsFrom(pc, this);
+}
+public void generateCompoundAssignment(BlockScope currentScope, CodeStream codeStream, Expression expression, int operator, int assignmentImplicitConversion, boolean valueRequired) {
+
+ boolean isStatic;
+ if (binding.canBeSeenBy(receiverType, this, currentScope)) {
+ receiver.generateCode(currentScope, codeStream, !(isStatic = binding.isStatic()));
+ if (isStatic) {
+ codeStream.getstatic(binding);
} else {
- receiver.generateCode(
- currentScope,
- codeStream,
- !(isStatic = binding.isStatic()));
- if (isStatic) {
- // used to store the value
- ((CodeSnippetCodeStream) codeStream).generateEmulationForField(binding);
- codeStream.aconst_null();
-
- // used to retrieve the actual value
- codeStream.aconst_null();
- ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(
- binding);
+ codeStream.dup();
+ codeStream.getfield(binding);
+ }
+ int operationTypeID;
+ if ((operationTypeID = implicitConversion >> 4) == T_String) {
+ codeStream.generateStringAppend(currentScope, null, expression);
+ } else {
+ // promote the array reference to the suitable operation type
+ codeStream.generateImplicitConversion(implicitConversion);
+ // generate the increment value (will by itself be promoted to the operation value)
+ if (expression == IntLiteral.One){ // prefix operation
+ codeStream.generateConstant(expression.constant, implicitConversion);
} else {
- // used to store the value
- ((CodeSnippetCodeStream) codeStream).generateEmulationForField(binding);
- receiver.generateCode(
- currentScope,
- codeStream,
- !(isStatic = binding.isStatic()));
+ expression.generateCode(currentScope, codeStream, true);
+ }
+ // perform the operation
+ codeStream.sendOperator(operator, operationTypeID);
+ // cast the value back to the array reference type
+ codeStream.generateImplicitConversion(assignmentImplicitConversion);
+ }
+ fieldStore(codeStream, binding, null, valueRequired);
+ } else {
+ receiver.generateCode(currentScope, codeStream, !(isStatic = binding.isStatic()));
+ if (isStatic) {
+ // used to store the value
+ ((CodeSnippetCodeStream) codeStream).generateEmulationForField(binding);
+ codeStream.aconst_null();
- // used to retrieve the actual value
- codeStream.dup();
- ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(
- binding);
+ // used to retrieve the actual value
+ codeStream.aconst_null();
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(binding);
+ } else {
+ // used to store the value
+ ((CodeSnippetCodeStream) codeStream).generateEmulationForField(binding);
+ receiver.generateCode(currentScope, codeStream, !(isStatic = binding.isStatic()));
- }
- int operationTypeID;
- if ((operationTypeID = implicitConversion >> 4) == T_String) {
- codeStream.generateStringAppend(currentScope, null, expression);
+ // used to retrieve the actual value
+ codeStream.dup();
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(binding);
+
+ }
+ int operationTypeID;
+ if ((operationTypeID = implicitConversion >> 4) == T_String) {
+ codeStream.generateStringAppend(currentScope, null, expression);
+ } else {
+ // promote the array reference to the suitable operation type
+ codeStream.generateImplicitConversion(implicitConversion);
+ // generate the increment value (will by itself be promoted to the operation value)
+ if (expression == IntLiteral.One){ // prefix operation
+ codeStream.generateConstant(expression.constant, implicitConversion);
} else {
- // promote the array reference to the suitable operation type
- codeStream.generateImplicitConversion(implicitConversion);
- // generate the increment value (will by itself be promoted to the operation value)
- if (expression == IntLiteral.One) { // prefix operation
- codeStream.generateConstant(expression.constant, implicitConversion);
- } else {
- expression.generateCode(currentScope, codeStream, true);
- }
- // perform the operation
- codeStream.sendOperator(operator, operationTypeID);
- // cast the value back to the array reference type
- codeStream.generateImplicitConversion(assignmentImplicitConversion);
- }
- // current stack is:
- // field receiver value
- if (valueRequired) {
- if ((binding.type == LongBinding) || (binding.type == DoubleBinding)) {
- codeStream.dup2_x2();
- } else {
- codeStream.dup_x2();
- }
- }
- // current stack is:
- // value field receiver value
- ((CodeSnippetCodeStream) codeStream).generateEmulatedWriteAccessForField(
- binding);
+ expression.generateCode(currentScope, codeStream, true);
+ }
+ // perform the operation
+ codeStream.sendOperator(operator, operationTypeID);
+ // cast the value back to the array reference type
+ codeStream.generateImplicitConversion(assignmentImplicitConversion);
}
- }
-
- public void generatePostIncrement(
- BlockScope currentScope,
- CodeStream codeStream,
- CompoundAssignment postIncrement,
- boolean valueRequired) {
- boolean isStatic;
- if (binding.canBeSeenBy(receiverType, this, currentScope)) {
- receiver.generateCode(
- currentScope,
- codeStream,
- !(isStatic = binding.isStatic()));
- if (isStatic) {
- codeStream.getstatic(binding);
+ // current stack is:
+ // field receiver value
+ if (valueRequired) {
+ if ((binding.type == LongBinding) || (binding.type == DoubleBinding)) {
+ codeStream.dup2_x2();
} else {
- codeStream.dup();
- codeStream.getfield(binding);
- }
- if (valueRequired) {
- if (isStatic) {
- if ((binding.type == LongBinding) || (binding.type == DoubleBinding)) {
- codeStream.dup2();
- } else {
- codeStream.dup();
- }
- } else { // Stack: [owner][old field value] ---> [old field value][owner][old field value]
- if ((binding.type == LongBinding) || (binding.type == DoubleBinding)) {
- codeStream.dup2_x1();
- } else {
- codeStream.dup_x1();
- }
- }
+ codeStream.dup_x2();
}
- codeStream.generateConstant(
- postIncrement.expression.constant,
- implicitConversion);
- codeStream.sendOperator(postIncrement.operator, binding.type.id);
- codeStream.generateImplicitConversion(
- postIncrement.assignmentImplicitConversion);
- fieldStore(codeStream, binding, null, false);
+ }
+ // current stack is:
+ // value field receiver value
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedWriteAccessForField(binding);
+ }
+}
+public void generatePostIncrement(BlockScope currentScope, CodeStream codeStream, CompoundAssignment postIncrement, boolean valueRequired) {
+ boolean isStatic;
+ if (binding.canBeSeenBy(receiverType, this, currentScope)) {
+ receiver.generateCode(currentScope, codeStream, !(isStatic = binding.isStatic()));
+ if (isStatic) {
+ codeStream.getstatic(binding);
} else {
- receiver.generateCode(
- currentScope,
- codeStream,
- !(isStatic = binding.isStatic()));
- if (binding.isStatic()) {
- codeStream.aconst_null();
- }
- // the actual stack is: receiver
codeStream.dup();
- // the actual stack is: receiver receiver
- ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(
- binding);
- // the actual stack is: receiver value
- // receiver value
- // value receiver value dup_x1 or dup2_x1 if value required
- // value value receiver value dup_x1 or dup2_x1
- // value value receiver pop or pop2
- // value value receiver field generateEmulationForField
- // value value field receiver swap
- // value field receiver value field receiver dup2_x1 or dup2_x2
- // value field receiver value pop2
- // value field receiver newvalue generate constant + op
- // value store
- if (valueRequired) {
+ codeStream.getfield(binding);
+ }
+ if (valueRequired) {
+ if (isStatic) {
+ if ((binding.type == LongBinding) || (binding.type == DoubleBinding)) {
+ codeStream.dup2();
+ } else {
+ codeStream.dup();
+ }
+ } else { // Stack: [owner][old field value] ---> [old field value][owner][old field value]
if ((binding.type == LongBinding) || (binding.type == DoubleBinding)) {
codeStream.dup2_x1();
} else {
codeStream.dup_x1();
}
}
+ }
+ codeStream.generateConstant(postIncrement.expression.constant, implicitConversion);
+ codeStream.sendOperator(postIncrement.operator, binding.type.id);
+ codeStream.generateImplicitConversion(postIncrement.assignmentImplicitConversion);
+ fieldStore(codeStream, binding, null, false);
+ } else {
+ receiver.generateCode(currentScope, codeStream, !(isStatic = binding.isStatic()));
+ if (binding.isStatic()) {
+ codeStream.aconst_null();
+ }
+ // the actual stack is: receiver
+ codeStream.dup();
+ // the actual stack is: receiver receiver
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(binding);
+ // the actual stack is: receiver value
+ // receiver value
+ // value receiver value dup_x1 or dup2_x1 if value required
+ // value value receiver value dup_x1 or dup2_x1
+ // value value receiver pop or pop2
+ // value value receiver field generateEmulationForField
+ // value value field receiver swap
+ // value field receiver value field receiver dup2_x1 or dup2_x2
+ // value field receiver value pop2
+ // value field receiver newvalue generate constant + op
+ // value store
+ if (valueRequired) {
if ((binding.type == LongBinding) || (binding.type == DoubleBinding)) {
codeStream.dup2_x1();
- codeStream.pop2();
} else {
codeStream.dup_x1();
- codeStream.pop();
- }
- ((CodeSnippetCodeStream) codeStream).generateEmulationForField(binding);
- codeStream.swap();
-
- if ((binding.type == LongBinding) || (binding.type == DoubleBinding)) {
- codeStream.dup2_x2();
- } else {
- codeStream.dup2_x1();
}
+ }
+ if ((binding.type == LongBinding) || (binding.type == DoubleBinding)) {
+ codeStream.dup2_x1();
codeStream.pop2();
-
- codeStream.generateConstant(
- postIncrement.expression.constant,
- implicitConversion);
- codeStream.sendOperator(postIncrement.operator, binding.type.id);
- codeStream.generateImplicitConversion(
- postIncrement.assignmentImplicitConversion);
- ((CodeSnippetCodeStream) codeStream).generateEmulatedWriteAccessForField(
- binding);
+ } else {
+ codeStream.dup_x1();
+ codeStream.pop();
}
- }
+ ((CodeSnippetCodeStream) codeStream).generateEmulationForField(binding);
+ codeStream.swap();
+
+ if ((binding.type == LongBinding) || (binding.type == DoubleBinding)) {
+ codeStream.dup2_x2();
+ } else {
+ codeStream.dup2_x1();
+ }
+ codeStream.pop2();
- /*
- * No need to emulate access to protected fields since not implicitly accessed
- */
- public void manageSyntheticReadAccessIfNecessary(BlockScope currentScope) {
- // nothing to do. The private access will be managed through the code generation
+ codeStream.generateConstant(postIncrement.expression.constant, implicitConversion);
+ codeStream.sendOperator(postIncrement.operator, binding.type.id);
+ codeStream.generateImplicitConversion(postIncrement.assignmentImplicitConversion);
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedWriteAccessForField(binding);
}
+}
+/*
+ * No need to emulate access to protected fields since not implicitly accessed
+ */
+public void manageSyntheticReadAccessIfNecessary(BlockScope currentScope){
+ // nothing to do. The private access will be managed through the code generation
+}
+/*
+ * No need to emulate access to protected fields since not implicitly accessed
+ */
+public void manageSyntheticWriteAccessIfNecessary(BlockScope currentScope){
+ // nothing to do. The private access will be managed through the code generation
+}
+public TypeBinding resolveType(BlockScope scope) {
+ // Answer the signature type of the field.
+ // constants are propaged when the field is final
+ // and initialized with a (compile time) constant
- /*
- * No need to emulate access to protected fields since not implicitly accessed
- */
- public void manageSyntheticWriteAccessIfNecessary(BlockScope currentScope) {
- // nothing to do. The private access will be managed through the code generation
+ // regular receiver reference
+ receiverType = receiver.resolveType(scope);
+ if (receiverType == null){
+ constant = NotAConstant;
+ return null;
}
-
- public TypeBinding resolveType(BlockScope scope) {
- // Answer the signature type of the field.
- // constants are propaged when the field is final
- // and initialized with a (compile time) constant
-
- // regular receiver reference
- receiverType = receiver.resolveType(scope);
- if (receiverType == null) {
- constant = NotAConstant;
- return null;
- }
- // the case receiverType.isArrayType and token = 'length' is handled by the scope API
- binding = scope.getField(receiverType, token, this);
- FieldBinding firstAttempt = binding;
- boolean isNotVisible = false;
- if (!binding.isValidBinding()) {
- if (binding instanceof ProblemFieldBinding
- && ((ProblemFieldBinding) binding).problemId() == NotVisible) {
+ // the case receiverType.isArrayType and token = 'length' is handled by the scope API
+ binding = scope.getField(receiverType, token, this);
+ FieldBinding firstAttempt = binding;
+ boolean isNotVisible = false;
+ if (!binding.isValidBinding()) {
+ if (binding instanceof ProblemFieldBinding
+ && ((ProblemFieldBinding) binding).problemId() == NotVisible) {
isNotVisible = true;
if (this.evaluationContext.declaringTypeName != null) {
delegateThis = scope.getField(scope.enclosingSourceType(), DELEGATE_THIS, this);
- if (delegateThis == null) {
- ; // if not found then internal error, field should have been found
+ if (delegateThis == null){ ; // if not found then internal error, field should have been found
constant = NotAConstant;
scope.problemReporter().invalidField(this, receiverType);
return null;
@@ -359,41 +297,35 @@ public class CodeSnippetFieldReference
scope.problemReporter().invalidField(this, receiverType);
return null;
}
- CodeSnippetScope localScope = new CodeSnippetScope(scope);
- binding = localScope.getFieldForCodeSnippet(delegateThis.type, token, this);
- }
+ CodeSnippetScope localScope = new CodeSnippetScope(scope);
+ binding = localScope.getFieldForCodeSnippet(delegateThis.type, token, this);
}
+ }
- if (!binding.isValidBinding()) {
- constant = NotAConstant;
- if (isNotVisible) {
- binding = firstAttempt;
- }
- scope.problemReporter().invalidField(this, receiverType);
- return null;
+ if (!binding.isValidBinding()) {
+ constant = NotAConstant;
+ if (isNotVisible) {
+ binding = firstAttempt;
}
+ scope.problemReporter().invalidField(this, receiverType);
+ return null;
+ }
- if (isFieldUseDeprecated(binding, scope))
- scope.problemReporter().deprecatedField(binding, this);
+ if (isFieldUseDeprecated(binding, scope))
+ scope.problemReporter().deprecatedField(binding, this);
- // check for this.x in static is done in the resolution of the receiver
- constant =
- FieldReference.getConstantFor(
- binding,
- receiver == ThisReference.ThisImplicit,
- this,
- 0);
- if (!receiver.isThis())
- constant = NotAConstant;
+ // check for this.x in static is done in the resolution of the receiver
+ constant = FieldReference.getConstantFor(binding, receiver == ThisReference.ThisImplicit, this, 0);
+ if (!receiver.isThis())
+ constant = NotAConstant;
- // if the binding declaring class is not visible, need special action
- // for runtime compatibility on 1.2 VMs : change the declaring class of the binding
- if (binding.declaringClass != receiverType
- && binding.declaringClass != null // array.length
- && binding.constant == NotAConstant
- && !binding.declaringClass.canBeSeenBy(scope))
+ // if the binding declaring class is not visible, need special action
+ // for runtime compatibility on 1.2 VMs : change the declaring class of the binding
+ if (binding.declaringClass != receiverType
+ && binding.declaringClass != null // array.length
+ && binding.constant == NotAConstant
+ && !binding.declaringClass.canBeSeenBy(scope))
binding = new FieldBinding(binding, (ReferenceBinding) receiverType);
- return binding.type;
- }
-
+ return binding.type;
+}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetMessageSend.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetMessageSend.java
index 1d69b8b042..98a865a1b7 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetMessageSend.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetMessageSend.java
@@ -9,227 +9,194 @@ import org.eclipse.jdt.internal.compiler.lookup.*;
import org.eclipse.jdt.internal.compiler.ast.*;
import org.eclipse.jdt.internal.compiler.codegen.CodeStream;
-public class CodeSnippetMessageSend
- extends MessageSend
- implements ProblemReasons, EvaluationConstants {
+public class CodeSnippetMessageSend extends MessageSend implements ProblemReasons, EvaluationConstants {
EvaluationContext evaluationContext;
FieldBinding delegateThis;
- TypeBinding receiverType;
- /**
- * CodeSnippetMessageSend constructor comment.
- */
- public CodeSnippetMessageSend(EvaluationContext evaluationContext) {
- this.evaluationContext = evaluationContext;
- }
-
- /**
- * MessageSend code generation
- *
- * @param currentScope org.eclipse.jdt.internal.compiler.lookup.BlockScope
- * @param codeStream org.eclipse.jdt.internal.compiler.codegen.CodeStream
- * @param valueRequired boolean
- */
- public void generateCode(
- BlockScope currentScope,
- CodeStream codeStream,
- boolean valueRequired) {
+/**
+ * CodeSnippetMessageSend constructor comment.
+ */
+public CodeSnippetMessageSend(EvaluationContext evaluationContext) {
+ this.evaluationContext = evaluationContext;
+}
+/**
+ * MessageSend code generation
+ *
+ * @param currentScope org.eclipse.jdt.internal.compiler.lookup.BlockScope
+ * @param codeStream org.eclipse.jdt.internal.compiler.codegen.CodeStream
+ * @param valueRequired boolean
+ */
+public void generateCode(
+ BlockScope currentScope,
+ CodeStream codeStream,
+ boolean valueRequired) {
- int pc = codeStream.position;
+ int pc = codeStream.position;
- if (binding.canBeSeenBy(receiverType, this, currentScope)) {
- // generate receiver/enclosing instance access
- boolean isStatic = binding.isStatic();
- // outer access ?
- if (!isStatic && ((bits & DepthMASK) != 0)) {
- // outer method can be reached through emulation
- Object[] path =
- currentScope.getExactEmulationPath(
- currentScope.enclosingSourceType().enclosingTypeAt(
- (bits & DepthMASK) >> DepthSHIFT));
- if (path == null) {
- // emulation was not possible (should not happen per construction)
- currentScope.problemReporter().needImplementation();
- } else {
- codeStream.generateOuterAccess(path, this, currentScope);
- }
+ if (binding.canBeSeenBy(receiverType, this, currentScope)) {
+ // generate receiver/enclosing instance access
+ boolean isStatic = binding.isStatic();
+ // outer access ?
+ if (!isStatic && ((bits & DepthMASK) != 0)) {
+ // outer method can be reached through emulation
+ Object[] path =
+ currentScope.getExactEmulationPath(
+ currentScope.enclosingSourceType().enclosingTypeAt(
+ (bits & DepthMASK) >> DepthSHIFT));
+ if (path == null) {
+ // emulation was not possible (should not happen per construction)
+ currentScope.problemReporter().needImplementation();
} else {
- receiver.generateCode(currentScope, codeStream, !isStatic);
+ codeStream.generateOuterAccess(path, this, currentScope);
}
- // generate arguments
- if (arguments != null) {
- for (int i = 0, max = arguments.length; i < max; i++) {
- arguments[i].generateCode(currentScope, codeStream, true);
- }
+ } else {
+ receiver.generateCode(currentScope, codeStream, !isStatic);
+ }
+ // generate arguments
+ if (arguments != null) {
+ for (int i = 0, max = arguments.length; i < max; i++) {
+ arguments[i].generateCode(currentScope, codeStream, true);
}
- // actual message invocation
- if (isStatic) {
- codeStream.invokestatic(binding);
+ }
+ // actual message invocation
+ if (isStatic) {
+ codeStream.invokestatic(binding);
+ } else {
+ if (receiver.isSuper()) {
+ codeStream.invokespecial(binding);
} else {
- if (receiver.isSuper()) {
- codeStream.invokespecial(binding);
+ if (binding.declaringClass.isInterface()) {
+ codeStream.invokeinterface(binding);
} else {
- if (binding.declaringClass.isInterface()) {
- codeStream.invokeinterface(binding);
- } else {
- codeStream.invokevirtual(binding);
- }
+ codeStream.invokevirtual(binding);
}
}
+ }
+ } else {
+ ((CodeSnippetCodeStream) codeStream).generateEmulationForMethod(currentScope, binding);
+ // generate receiver/enclosing instance access
+ boolean isStatic = binding.isStatic();
+ // outer access ?
+ if (!isStatic && ((bits & DepthMASK) != 0)) {
+ // not supported yet
+ currentScope.problemReporter().needImplementation();
} else {
- ((CodeSnippetCodeStream) codeStream).generateEmulationForMethod(
- currentScope,
- binding);
- // generate receiver/enclosing instance access
- boolean isStatic = binding.isStatic();
- // outer access ?
- if (!isStatic && ((bits & DepthMASK) != 0)) {
- // not supported yet
- currentScope.problemReporter().needImplementation();
- } else {
- receiver.generateCode(currentScope, codeStream, !isStatic);
- }
- if (isStatic) {
- // we need an object on the stack which is ignored for the method invocation
- codeStream.aconst_null();
- }
- // generate arguments
- if (arguments != null) {
- int argsLength = arguments.length;
- codeStream.generateInlinedValue(argsLength);
- codeStream.newArray(
- currentScope,
- new ArrayBinding(currentScope.getType(TypeBinding.JAVA_LANG_OBJECT), 1));
- codeStream.dup();
- for (int i = 0; i < argsLength; i++) {
- codeStream.generateInlinedValue(i);
- arguments[i].generateCode(currentScope, codeStream, true);
- if (binding.parameters[i].isBaseType()) {
- codeStream.generateObjectWrapperForType(binding.parameters[i]);
- }
- codeStream.aastore();
- if (i < argsLength - 1) {
- codeStream.dup();
- }
+ receiver.generateCode(currentScope, codeStream, !isStatic);
+ }
+ if (isStatic) {
+ // we need an object on the stack which is ignored for the method invocation
+ codeStream.aconst_null();
+ }
+ // generate arguments
+ if (arguments != null) {
+ int argsLength = arguments.length;
+ codeStream.generateInlinedValue(argsLength);
+ codeStream.newArray(currentScope, new ArrayBinding(currentScope.getType(TypeBinding.JAVA_LANG_OBJECT), 1));
+ codeStream.dup();
+ for (int i = 0; i < argsLength; i++) {
+ codeStream.generateInlinedValue(i);
+ arguments[i].generateCode(currentScope, codeStream, true);
+ if (binding.parameters[i].isBaseType()) {
+ codeStream.generateObjectWrapperForType(binding.parameters[i]);
}
- } else {
- codeStream.generateInlinedValue(0);
- codeStream.newArray(
- currentScope,
- new ArrayBinding(currentScope.getType(TypeBinding.JAVA_LANG_OBJECT), 1));
+ codeStream.aastore();
+ if (i < argsLength - 1) {
+ codeStream.dup();
+ }
}
- ((CodeSnippetCodeStream) codeStream).invokeJavaLangReflectMethodInvoke();
+ } else {
+ codeStream.generateInlinedValue(0);
+ codeStream.newArray(currentScope, new ArrayBinding(currentScope.getType(TypeBinding.JAVA_LANG_OBJECT), 1));
+ }
+ ((CodeSnippetCodeStream) codeStream).invokeJavaLangReflectMethodInvoke();
- // convert the return value to the appropriate type for primitive types
- if (binding.returnType.isBaseType()) {
- int typeID = binding.returnType.id;
- if (typeID == T_void) {
- // remove the null from the stack
- codeStream.pop();
- }
- ((CodeSnippetCodeStream) codeStream).checkcast(typeID);
- ((CodeSnippetCodeStream) codeStream).getBaseTypeValue(typeID);
- } else {
- codeStream.checkcast(binding.returnType);
+ // convert the return value to the appropriate type for primitive types
+ if (binding.returnType.isBaseType()) {
+ int typeID = binding.returnType.id;
+ if (typeID == T_void) {
+ // remove the null from the stack
+ codeStream.pop();
}
- }
- // operation on the returned value
- if (valueRequired) {
- // implicit conversion if necessary
- codeStream.generateImplicitConversion(implicitConversion);
+ ((CodeSnippetCodeStream) codeStream).checkcast(typeID);
+ ((CodeSnippetCodeStream) codeStream).getBaseTypeValue(typeID);
} else {
- // pop return value if any
- switch (binding.returnType.id) {
- case T_long :
- case T_double :
- codeStream.pop2();
- break;
- case T_void :
- break;
- default :
- codeStream.pop();
- }
+ codeStream.checkcast(binding.returnType);
}
- codeStream.recordPositionsFrom(pc, this);
- }
-
- public void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope) {
}
-
- public void manageSyntheticAccessIfNecessary(BlockScope currentScope) {
+ // operation on the returned value
+ if (valueRequired) {
+ // implicit conversion if necessary
+ codeStream.generateImplicitConversion(implicitConversion);
+ } else {
+ // pop return value if any
+ switch (binding.returnType.id) {
+ case T_long :
+ case T_double :
+ codeStream.pop2();
+ break;
+ case T_void :
+ break;
+ default :
+ codeStream.pop();
+ }
}
+ codeStream.recordPositionsFrom(pc, this);
+}
+public void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope) {
+}
+public void manageSyntheticAccessIfNecessary(BlockScope currentScope) {
+}
+public TypeBinding resolveType(BlockScope scope) {
+ // Answer the signature return type
+ // Base type promotion
- public TypeBinding resolveType(BlockScope scope) {
- // Answer the signature return type
- // Base type promotion
-
- constant = NotAConstant;
- receiverType = receiver.resolveType(scope);
- // will check for null after args are resolved
- TypeBinding[] argumentTypes = NoParameters;
- if (arguments != null) {
- boolean argHasError = false; // typeChecks all arguments
- int length = arguments.length;
- argumentTypes = new TypeBinding[length];
- for (int i = 0; i < length; i++)
- if ((argumentTypes[i] = arguments[i].resolveType(scope)) == null)
- argHasError = true;
- if (argHasError)
- return null;
- }
- if (receiverType == null)
+ constant = NotAConstant;
+ receiverType = receiver.resolveType(scope);
+ // will check for null after args are resolved
+ TypeBinding[] argumentTypes = NoParameters;
+ if (arguments != null) {
+ boolean argHasError = false; // typeChecks all arguments
+ int length = arguments.length;
+ argumentTypes = new TypeBinding[length];
+ for (int i = 0; i < length; i++)
+ if ((argumentTypes[i] = arguments[i].resolveType(scope)) == null)
+ argHasError = true;
+ if (argHasError)
return null;
+ }
+ if (receiverType == null)
+ return null;
- // base type cannot receive any message
- if (receiverType.isBaseType()) {
- scope.problemReporter().errorNoMethodFor(this, receiverType, argumentTypes);
- return null;
- }
+ // base type cannot receive any message
+ if (receiverType.isBaseType()) {
+ scope.problemReporter().errorNoMethodFor(this, receiverType, argumentTypes);
+ return null;
+ }
- binding =
- receiver == ThisReference.ThisImplicit
- ? scope.getImplicitMethod(selector, argumentTypes, this)
- : scope.getMethod(receiverType, selector, argumentTypes, this);
- if (!binding.isValidBinding()) {
- if (binding instanceof ProblemMethodBinding
- && ((ProblemMethodBinding) binding).problemId() == NotVisible) {
- if (this.evaluationContext.declaringTypeName != null) {
- delegateThis = scope.getField(scope.enclosingSourceType(), DELEGATE_THIS, this);
- if (delegateThis == null) {
- ; // if not found then internal error, field should have been found
- constant = NotAConstant;
- scope.problemReporter().invalidMethod(this, binding);
- return null;
- }
- } else {
+ binding =
+ receiver == ThisReference.ThisImplicit
+ ? scope.getImplicitMethod(selector, argumentTypes, this)
+ : scope.getMethod(receiverType, selector, argumentTypes, this);
+ if (!binding.isValidBinding()) {
+ if (binding instanceof ProblemMethodBinding
+ && ((ProblemMethodBinding) binding).problemId() == NotVisible) {
+ if (this.evaluationContext.declaringTypeName != null) {
+ delegateThis = scope.getField(scope.enclosingSourceType(), DELEGATE_THIS, this);
+ if (delegateThis == null){ ; // if not found then internal error, field should have been found
constant = NotAConstant;
scope.problemReporter().invalidMethod(this, binding);
return null;
}
- CodeSnippetScope localScope = new CodeSnippetScope(scope);
- MethodBinding privateBinding =
- receiver instanceof CodeSnippetThisReference
- && ((CodeSnippetThisReference) receiver).isImplicit
- ? localScope.getImplicitMethod(
- (ReferenceBinding) delegateThis.type,
- selector,
- argumentTypes,
- this)
- : localScope.getMethod(delegateThis.type, selector, argumentTypes, this);
- if (!privateBinding.isValidBinding()) {
- if (binding.declaringClass == null) {
- if (receiverType instanceof ReferenceBinding) {
- binding.declaringClass = (ReferenceBinding) receiverType;
- } else { // really bad error ....
- scope.problemReporter().errorNoMethodFor(this, receiverType, argumentTypes);
- return null;
- }
- }
- scope.problemReporter().invalidMethod(this, binding);
- return null;
- } else {
- binding = privateBinding;
- }
} else {
+ constant = NotAConstant;
+ scope.problemReporter().invalidMethod(this, binding);
+ return null;
+ }
+ CodeSnippetScope localScope = new CodeSnippetScope(scope);
+ MethodBinding privateBinding =
+ receiver instanceof CodeSnippetThisReference && ((CodeSnippetThisReference) receiver).isImplicit
+ ? localScope.getImplicitMethod((ReferenceBinding)delegateThis.type, selector, argumentTypes, this)
+ : localScope.getMethod(delegateThis.type, selector, argumentTypes, this);
+ if (!privateBinding.isValidBinding()) {
if (binding.declaringClass == null) {
if (receiverType instanceof ReferenceBinding) {
binding.declaringClass = (ReferenceBinding) receiverType;
@@ -240,37 +207,50 @@ public class CodeSnippetMessageSend
}
scope.problemReporter().invalidMethod(this, binding);
return null;
+ } else {
+ binding = privateBinding;
}
- }
- if (!binding.isStatic()) {
- // the "receiver" must not be a type, i.e. a NameReference that the TC has bound to a Type
- if (receiver instanceof NameReference) {
- if ((((NameReference) receiver).bits & BindingIds.TYPE) != 0) {
- scope.problemReporter().mustUseAStaticMethod(this, binding);
+ } else {
+ if (binding.declaringClass == null) {
+ if (receiverType instanceof ReferenceBinding) {
+ binding.declaringClass = (ReferenceBinding) receiverType;
+ } else { // really bad error ....
+ scope.problemReporter().errorNoMethodFor(this, receiverType, argumentTypes);
return null;
}
}
+ scope.problemReporter().invalidMethod(this, binding);
+ return null;
}
- if (arguments != null)
- for (int i = 0; i < arguments.length; i++)
- arguments[i].implicitWidening(binding.parameters[i], argumentTypes[i]);
-
- //-------message send that are known to fail at compile time-----------
- if (binding.isAbstract()) {
- if (receiver.isSuper()) {
- scope.problemReporter().cannotDireclyInvokeAbstractMethod(this, binding);
+ }
+ if (!binding.isStatic()) {
+ // the "receiver" must not be a type, i.e. a NameReference that the TC has bound to a Type
+ if (receiver instanceof NameReference) {
+ if ((((NameReference) receiver).bits & BindingIds.TYPE) != 0) {
+ scope.problemReporter().mustUseAStaticMethod(this, binding);
return null;
}
- // abstract private methods cannot occur nor abstract static............
}
- if (isMethodUseDeprecated(binding, scope))
- scope.problemReporter().deprecatedMethod(binding, this);
- // if the binding declaring class is not visible, need special action
- // for runtime compatibility on 1.2 VMs : change the declaring class of the binding
- if (binding.declaringClass != receiverType
- && !binding.declaringClass.canBeSeenBy(scope))
- binding = new MethodBinding(binding, (ReferenceBinding) receiverType);
- return binding.returnType;
}
+ if (arguments != null)
+ for (int i = 0; i < arguments.length; i++)
+ arguments[i].implicitWidening(binding.parameters[i], argumentTypes[i]);
+ //-------message send that are known to fail at compile time-----------
+ if (binding.isAbstract()) {
+ if (receiver.isSuper()) {
+ scope.problemReporter().cannotDireclyInvokeAbstractMethod(this, binding);
+ return null;
+ }
+ // abstract private methods cannot occur nor abstract static............
+ }
+ if (isMethodUseDeprecated(binding, scope))
+ scope.problemReporter().deprecatedMethod(binding, this);
+ // if the binding declaring class is not visible, need special action
+ // for runtime compatibility on 1.2 VMs : change the declaring class of the binding
+ if (binding.declaringClass != receiverType
+ && !binding.declaringClass.canBeSeenBy(scope))
+ binding = new MethodBinding(binding, (ReferenceBinding) receiverType);
+ return binding.returnType;
+}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetParser.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetParser.java
index a03f677395..4d43bb9eb7 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetParser.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetParser.java
@@ -20,726 +20,633 @@ public class CodeSnippetParser extends Parser implements EvaluationConstants {
int lastStatement = -1; // end of last top level statement
EvaluationContext evaluationContext;
- /**
- * Creates a new code snippet parser.
- */
- public CodeSnippetParser(
- ProblemReporter problemReporter,
- EvaluationContext evaluationContext,
- boolean optimizeStringLiterals,
- int codeSnippetStart,
- int codeSnippetEnd) {
- super(problemReporter, optimizeStringLiterals);
- this.codeSnippetStart = codeSnippetStart;
- this.codeSnippetEnd = codeSnippetEnd;
- this.evaluationContext = evaluationContext;
- }
-
- protected void classInstanceCreation(boolean alwaysQualified) {
- // ClassInstanceCreationExpression ::= 'new' ClassType '(' ArgumentListopt ')' ClassBodyopt
-
- // ClassBodyopt produces a null item on the astStak if it produces NO class body
- // An empty class body produces a 0 on the length stack.....
-
- AllocationExpression alloc;
- int length;
- if (((length = astLengthStack[astLengthPtr--]) == 1)
- && (astStack[astPtr] == null)) {
- //NO ClassBody
- astPtr--;
- if (alwaysQualified) {
- alloc = new QualifiedAllocationExpression();
- } else {
- alloc = new CodeSnippetAllocationExpression(evaluationContext);
- }
- alloc.sourceEnd = endPosition; //the position has been stored explicitly
-
- if ((length = expressionLengthStack[expressionLengthPtr--]) != 0) {
- expressionPtr -= length;
- System.arraycopy(
- expressionStack,
- expressionPtr + 1,
- alloc.arguments = new Expression[length],
- 0,
- length);
- }
- alloc.type = getTypeReference(0);
- //the default constructor with the correct number of argument
- //will be created and added by the TC (see createsInternalConstructorWithBinding)
- alloc.sourceStart = intStack[intPtr--];
- pushOnExpressionStack(alloc);
+/**
+ * Creates a new code snippet parser.
+ */
+public CodeSnippetParser(ProblemReporter problemReporter, EvaluationContext evaluationContext, boolean optimizeStringLiterals, int codeSnippetStart, int codeSnippetEnd) {
+ super(problemReporter, optimizeStringLiterals);
+ this.codeSnippetStart = codeSnippetStart;
+ this.codeSnippetEnd = codeSnippetEnd;
+ this.evaluationContext = evaluationContext;
+}
+protected void classInstanceCreation(boolean alwaysQualified) {
+ // ClassInstanceCreationExpression ::= 'new' ClassType '(' ArgumentListopt ')' ClassBodyopt
+
+ // ClassBodyopt produces a null item on the astStak if it produces NO class body
+ // An empty class body produces a 0 on the length stack.....
+
+ AllocationExpression alloc;
+ int length;
+ if (((length = astLengthStack[astLengthPtr--]) == 1)
+ && (astStack[astPtr] == null)) {
+ //NO ClassBody
+ astPtr--;
+ if (alwaysQualified) {
+ alloc = new QualifiedAllocationExpression();
} else {
- dispatchDeclarationInto(length);
- AnonymousLocalTypeDeclaration anonymousTypeDeclaration =
- (AnonymousLocalTypeDeclaration) astStack[astPtr];
- anonymousTypeDeclaration.declarationSourceEnd = endStatementPosition;
- astPtr--;
- astLengthPtr--;
+ alloc = new CodeSnippetAllocationExpression(evaluationContext);
}
- }
+ alloc.sourceEnd = endPosition; //the position has been stored explicitly
- protected void consumeClassDeclaration() {
- super.consumeClassDeclaration();
- /* recovery */
- recordLastStatementIfNeeded();
+ if ((length = expressionLengthStack[expressionLengthPtr--]) != 0) {
+ expressionPtr -= length;
+ System.arraycopy(
+ expressionStack,
+ expressionPtr + 1,
+ alloc.arguments = new Expression[length],
+ 0,
+ length);
+ }
+ alloc.type = getTypeReference(0);
+ //the default constructor with the correct number of argument
+ //will be created and added by the TC (see createsInternalConstructorWithBinding)
+ alloc.sourceStart = intStack[intPtr--];
+ pushOnExpressionStack(alloc);
+ } else {
+ dispatchDeclarationInto(length);
+ AnonymousLocalTypeDeclaration anonymousTypeDeclaration = (AnonymousLocalTypeDeclaration) astStack[astPtr];
+ anonymousTypeDeclaration.declarationSourceEnd = endStatementPosition;
+ astPtr--;
+ astLengthPtr--;
}
-
- protected void consumeClassHeaderName() {
- // ClassHeaderName ::= Modifiersopt 'class' 'Identifier'
- TypeDeclaration typeDecl;
- int length;
- if (nestedMethod[nestedType] == 0) {
- if (nestedType != 0) {
- typeDecl = new MemberTypeDeclaration();
- } else {
- typeDecl = new CodeSnippetTypeDeclaration();
- }
+}
+protected void consumeClassDeclaration() {
+ super.consumeClassDeclaration();
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+protected void consumeClassHeaderName() {
+ // ClassHeaderName ::= Modifiersopt 'class' 'Identifier'
+ TypeDeclaration typeDecl;
+ int length;
+ if (nestedMethod[nestedType] == 0) {
+ if (nestedType != 0) {
+ typeDecl = new MemberTypeDeclaration();
} else {
- // Record that the block has a declaration for local types
- typeDecl = new LocalTypeDeclaration();
- blockReal();
- }
-
- //highlight the name of the type
- long pos = identifierPositionStack[identifierPtr];
- typeDecl.sourceEnd = (int) pos;
- typeDecl.sourceStart = (int) (pos >>> 32);
- typeDecl.name = identifierStack[identifierPtr--];
- identifierLengthPtr--;
-
- //compute the declaration source too
- typeDecl.declarationSourceStart = intStack[intPtr--];
- // 'class' and 'interface' push an int position
- typeDecl.modifiersSourceStart = intStack[intPtr--];
- typeDecl.modifiers = intStack[intPtr--];
- if (typeDecl.modifiersSourceStart >= 0) {
- typeDecl.declarationSourceStart = typeDecl.modifiersSourceStart;
- }
- typeDecl.bodyStart = typeDecl.sourceEnd + 1;
- pushOnAstStack(typeDecl);
-
- listLength = 0; // will be updated when reading super-interfaces
- // recovery
- if (currentElement != null) {
- lastCheckPoint = typeDecl.bodyStart;
- currentElement = currentElement.add(typeDecl, 0);
- lastIgnoredToken = -1;
+ typeDecl = new CodeSnippetTypeDeclaration();
}
+ } else {
+ // Record that the block has a declaration for local types
+ typeDecl = new LocalTypeDeclaration();
+ blockReal();
+ }
+
+ //highlight the name of the type
+ long pos = identifierPositionStack[identifierPtr];
+ typeDecl.sourceEnd = (int) pos;
+ typeDecl.sourceStart = (int) (pos >>> 32);
+ typeDecl.name = identifierStack[identifierPtr--];
+ identifierLengthPtr--;
+
+ //compute the declaration source too
+ typeDecl.declarationSourceStart = intStack[intPtr--];
+ // 'class' and 'interface' push an int position
+ typeDecl.modifiersSourceStart = intStack[intPtr--];
+ typeDecl.modifiers = intStack[intPtr--];
+ if (typeDecl.modifiersSourceStart >= 0) {
+ typeDecl.declarationSourceStart = typeDecl.modifiersSourceStart;
+ }
+ typeDecl.bodyStart = typeDecl.sourceEnd + 1;
+ pushOnAstStack(typeDecl);
+
+ listLength = 0; // will be updated when reading super-interfaces
+ // recovery
+ if (currentElement != null){
+ lastCheckPoint = typeDecl.bodyStart;
+ currentElement = currentElement.add(typeDecl, 0);
+ lastIgnoredToken = -1;
}
-
- protected void consumeEmptyStatement() {
- super.consumeEmptyStatement();
- /* recovery */
- recordLastStatementIfNeeded();
- }
-
- protected void consumeExpressionStatement() {
- super.consumeExpressionStatement();
- /* recovery */
- recordLastStatementIfNeeded();
- }
-
- protected void consumeFieldAccess(boolean isSuperAccess) {
- // FieldAccess ::= Primary '.' 'Identifier'
- // FieldAccess ::= 'super' '.' 'Identifier'
-
- FieldReference fr =
- new CodeSnippetFieldReference(
- identifierStack[identifierPtr],
- identifierPositionStack[identifierPtr--],
- evaluationContext);
- identifierLengthPtr--;
- if (isSuperAccess) {
- //considerates the fieldReference beginning at the 'super' ....
- fr.sourceStart = intStack[intPtr--];
- fr.receiver = new SuperReference(fr.sourceStart, endPosition);
- pushOnExpressionStack(fr);
- } else {
- //optimize push/pop
- if ((fr.receiver = expressionStack[expressionPtr]).isThis()) {
- //fieldreference begins at the this
- fr.sourceStart = fr.receiver.sourceStart;
- }
- expressionStack[expressionPtr] = fr;
+}
+protected void consumeEmptyStatement() {
+ super.consumeEmptyStatement();
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+protected void consumeExpressionStatement() {
+ super.consumeExpressionStatement();
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+protected void consumeFieldAccess(boolean isSuperAccess) {
+ // FieldAccess ::= Primary '.' 'Identifier'
+ // FieldAccess ::= 'super' '.' 'Identifier'
+
+ FieldReference fr =
+ new CodeSnippetFieldReference(
+ identifierStack[identifierPtr],
+ identifierPositionStack[identifierPtr--],
+ evaluationContext);
+ identifierLengthPtr--;
+ if (isSuperAccess) {
+ //considerates the fieldReference beginning at the 'super' ....
+ fr.sourceStart = intStack[intPtr--];
+ fr.receiver = new SuperReference(fr.sourceStart, endPosition);
+ pushOnExpressionStack(fr);
+ } else {
+ //optimize push/pop
+ if ((fr.receiver = expressionStack[expressionPtr]).isThis()) {
+ //fieldreference begins at the this
+ fr.sourceStart = fr.receiver.sourceStart;
}
+ expressionStack[expressionPtr] = fr;
}
-
- protected void consumeInterfaceHeaderName() {
- // InterfaceHeaderName ::= Modifiersopt 'interface' 'Identifier'
- TypeDeclaration typeDecl;
- int length;
- if (nestedMethod[nestedType] == 0) {
- if (nestedType != 0) {
- typeDecl = new MemberTypeDeclaration();
- } else {
- typeDecl = new CodeSnippetTypeDeclaration();
- }
+}
+protected void consumeInterfaceHeaderName() {
+ // InterfaceHeaderName ::= Modifiersopt 'interface' 'Identifier'
+ TypeDeclaration typeDecl;
+ int length;
+ if (nestedMethod[nestedType] == 0) {
+ if (nestedType != 0) {
+ typeDecl = new MemberTypeDeclaration();
} else {
- // Record that the block has a declaration for local types
- typeDecl = new LocalTypeDeclaration();
- blockReal();
- }
-
- //highlight the name of the type
- long pos = identifierPositionStack[identifierPtr];
- typeDecl.sourceEnd = (int) pos;
- typeDecl.sourceStart = (int) (pos >>> 32);
- typeDecl.name = identifierStack[identifierPtr--];
- identifierLengthPtr--;
-
- //compute the declaration source too
- typeDecl.declarationSourceStart = intStack[intPtr--];
- // 'class' and 'interface' push an int position
- typeDecl.modifiersSourceStart = intStack[intPtr--];
- typeDecl.modifiers = intStack[intPtr--];
- if (typeDecl.modifiersSourceStart >= 0) {
- typeDecl.declarationSourceStart = typeDecl.modifiersSourceStart;
- }
- typeDecl.bodyStart = typeDecl.sourceEnd + 1;
- pushOnAstStack(typeDecl);
- listLength = 0; // will be updated when reading super-interfaces
- // recovery
- if (currentElement != null) { // is recovering
- lastCheckPoint = typeDecl.bodyStart;
- currentElement = currentElement.add(typeDecl, 0);
- lastIgnoredToken = -1;
+ typeDecl = new CodeSnippetTypeDeclaration();
}
+ } else {
+ // Record that the block has a declaration for local types
+ typeDecl = new LocalTypeDeclaration();
+ blockReal();
+ }
+
+ //highlight the name of the type
+ long pos = identifierPositionStack[identifierPtr];
+ typeDecl.sourceEnd = (int) pos;
+ typeDecl.sourceStart = (int) (pos >>> 32);
+ typeDecl.name = identifierStack[identifierPtr--];
+ identifierLengthPtr--;
+
+ //compute the declaration source too
+ typeDecl.declarationSourceStart = intStack[intPtr--];
+ // 'class' and 'interface' push an int position
+ typeDecl.modifiersSourceStart = intStack[intPtr--];
+ typeDecl.modifiers = intStack[intPtr--];
+ if (typeDecl.modifiersSourceStart >= 0) {
+ typeDecl.declarationSourceStart = typeDecl.modifiersSourceStart;
+ }
+ typeDecl.bodyStart = typeDecl.sourceEnd + 1;
+ pushOnAstStack(typeDecl);
+ listLength = 0; // will be updated when reading super-interfaces
+ // recovery
+ if (currentElement != null){ // is recovering
+ lastCheckPoint = typeDecl.bodyStart;
+ currentElement = currentElement.add(typeDecl, 0);
+ lastIgnoredToken = -1;
}
-
- protected void consumeLocalVariableDeclarationStatement() {
- super.consumeLocalVariableDeclarationStatement();
- /* recovery */
- recordLastStatementIfNeeded();
- }
-
- /**
- * In case emulating local variables, wrap the (recovered) statements inside a
- * try statement so as to achieve local state commiting (copy local vars back to fields).
- * The CSToCuMapper could not be used, since it could have interfered with
- * the syntax recovery specific to code snippets.
- */
- protected void consumeMethodDeclaration(boolean isNotAbstract) {
- // MethodDeclaration ::= MethodHeader MethodBody
- // AbstractMethodDeclaration ::= MethodHeader ';'
-
- super.consumeMethodDeclaration(isNotAbstract);
-
- // now we know that we have a method declaration at the top of the ast stack
- MethodDeclaration methodDecl = (MethodDeclaration) astStack[astPtr];
-
- // automatically wrap the last statement inside a return statement, if it is an expression
- // support have to be defined at toplevel only
- if (this.isTopLevelType()) {
- int last =
- methodDecl.statements == null ? -1 : methodDecl.statements.length - 1;
- if (last >= 0 && methodDecl.statements[last] instanceof Expression) {
- Expression lastExpression = (Expression) methodDecl.statements[last];
- methodDecl.statements[last] =
- new CodeSnippetReturnStatement(
- lastExpression,
- lastExpression.sourceStart(),
- lastExpression.sourceEnd(),
- evaluationContext);
- }
- }
-
- int start = methodDecl.bodyStart - 1, end = start;
- long position = (start << 32) + end;
- long[] positions = new long[] { position };
- if (this.evaluationContext.localVariableNames != null) {
-
- int varCount = this.evaluationContext.localVariableNames.length;
- // n local decls+ try statement
-
- // generate n local variable declarations: [type] [name] = val$[name];
- Statement[] newStatements = new Statement[varCount + 1];
- for (int i = 0; i < varCount; i++) {
- char[] trimmedTypeName = this.evaluationContext.localVariableTypeNames[i];
- int nameEnd = CharOperation.indexOf('[', trimmedTypeName);
- if (nameEnd >= 0)
- trimmedTypeName = CharOperation.subarray(trimmedTypeName, 0, nameEnd);
- nameEnd = CharOperation.indexOf(' ', trimmedTypeName);
- if (nameEnd >= 0)
- trimmedTypeName = CharOperation.subarray(trimmedTypeName, 0, nameEnd);
-
- TypeReference typeReference =
- new QualifiedTypeReference(
- CharOperation.splitOn('.', trimmedTypeName),
- positions);
- int dimCount =
- CharOperation.occurencesOf(
- '[',
- this.evaluationContext.localVariableTypeNames[i]);
- if (dimCount > 0) {
- typeReference = typeReference.copyDims(dimCount);
- }
- NameReference init =
- new SingleNameReference(
- CharOperation.concat(
- LOCAL_VAR_PREFIX,
- this.evaluationContext.localVariableNames[i]),
- position);
- LocalDeclaration declaration =
- new LocalDeclaration(
- init,
- this.evaluationContext.localVariableNames[i],
- start,
- end);
- declaration.type = typeReference;
- declaration.modifiers = this.evaluationContext.localVariableModifiers[i];
- newStatements[i] = declaration;
- }
-
- // generate try { [snippet] } finally { [save locals to fields] }
- // try block
- TryStatement tryStatement = new TryStatement();
- Block tryBlock = new Block(methodDecl.explicitDeclarations);
- tryBlock.sourceStart = start;
- tryBlock.sourceEnd = end;
- tryBlock.statements = methodDecl.statements; // snippet statements
- tryStatement.tryBlock = tryBlock;
- // finally block
- Block finallyBlock = new Block(0);
- finallyBlock.sourceStart = start;
- finallyBlock.sourceEnd = end;
- finallyBlock.statements = new Statement[varCount];
- for (int i = 0; i < varCount; i++) {
- finallyBlock.statements[i] =
- new Assignment(
- new SingleNameReference(
- CharOperation.concat(
- LOCAL_VAR_PREFIX,
- this.evaluationContext.localVariableNames[i]),
- position),
- new SingleNameReference(
- this.evaluationContext.localVariableNames[i],
- position));
- }
- tryStatement.finallyBlock = finallyBlock;
-
- newStatements[varCount] = tryStatement;
- methodDecl.statements = newStatements;
+}
+protected void consumeLocalVariableDeclarationStatement() {
+ super.consumeLocalVariableDeclarationStatement();
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+/**
+ * In case emulating local variables, wrap the (recovered) statements inside a
+ * try statement so as to achieve local state commiting (copy local vars back to fields).
+ * The CSToCuMapper could not be used, since it could have interfered with
+ * the syntax recovery specific to code snippets.
+ */
+protected void consumeMethodDeclaration(boolean isNotAbstract) {
+ // MethodDeclaration ::= MethodHeader MethodBody
+ // AbstractMethodDeclaration ::= MethodHeader ';'
+
+ super.consumeMethodDeclaration(isNotAbstract);
+
+ // now we know that we have a method declaration at the top of the ast stack
+ MethodDeclaration methodDecl = (MethodDeclaration) astStack[astPtr];
+
+ // automatically wrap the last statement inside a return statement, if it is an expression
+ // support have to be defined at toplevel only
+ if (this.isTopLevelType()) {
+ int last = methodDecl.statements == null ? -1 : methodDecl.statements.length - 1;
+ if (last >= 0 && methodDecl.statements[last] instanceof Expression){
+ Expression lastExpression = (Expression) methodDecl.statements[last];
+ methodDecl.statements[last] = new CodeSnippetReturnStatement(
+ lastExpression,
+ lastExpression.sourceStart(),
+ lastExpression.sourceEnd(),
+ evaluationContext);
}
}
-
- protected void consumeMethodInvocationName() {
- // MethodInvocation ::= Name '(' ArgumentListopt ')'
-
- if (scanner.startPosition >= codeSnippetStart
- && scanner.startPosition <= codeSnippetEnd + 1
- && isTopLevelType()) {
-
- // when the name is only an identifier...we have a message send to "this" (implicit)
-
- MessageSend m = newMessageSend();
- m.sourceEnd = rParenPos;
- m.sourceStart =
- (int) ((m.nameSourcePosition = identifierPositionStack[identifierPtr]) >>> 32);
- m.selector = identifierStack[identifierPtr--];
- if (identifierLengthStack[identifierLengthPtr] == 1) {
- m.receiver = new CodeSnippetThisReference(0, 0, evaluationContext, true);
- identifierLengthPtr--;
- } else {
- identifierLengthStack[identifierLengthPtr]--;
- m.receiver = getUnspecifiedReference();
- m.sourceStart = m.receiver.sourceStart;
+
+ int start = methodDecl.bodyStart-1, end = start;
+ long position = (start << 32) + end;
+ long[] positions = new long[]{position};
+ if (this.evaluationContext.localVariableNames != null) {
+
+ int varCount = this.evaluationContext.localVariableNames.length; // n local decls+ try statement
+
+ // generate n local variable declarations: [type] [name] = val$[name];
+ Statement[] newStatements = new Statement[varCount+1];
+ for (int i = 0; i < varCount; i++){
+ char[] trimmedTypeName = this.evaluationContext.localVariableTypeNames[i];
+ int nameEnd = CharOperation.indexOf('[', trimmedTypeName);
+ if (nameEnd >= 0) trimmedTypeName = CharOperation.subarray(trimmedTypeName, 0, nameEnd);
+ nameEnd = CharOperation.indexOf(' ', trimmedTypeName);
+ if (nameEnd >= 0) trimmedTypeName = CharOperation.subarray(trimmedTypeName, 0, nameEnd);
+
+ TypeReference typeReference = new QualifiedTypeReference(
+ CharOperation.splitOn('.', trimmedTypeName),
+ positions);
+ int dimCount = CharOperation.occurencesOf('[', this.evaluationContext.localVariableTypeNames[i]);
+ if (dimCount > 0) {
+ typeReference = typeReference.copyDims(dimCount);
}
- pushOnExpressionStack(m);
- } else {
- super.consumeMethodInvocationName();
+ NameReference init = new SingleNameReference(
+ CharOperation.concat(LOCAL_VAR_PREFIX, this.evaluationContext.localVariableNames[i]), position);
+ LocalDeclaration declaration = new LocalDeclaration(init, this.evaluationContext.localVariableNames[i], start, end);
+ declaration.type = typeReference;
+ declaration.modifiers = this.evaluationContext.localVariableModifiers[i];
+ newStatements[i] = declaration;
}
- }
- protected void consumePrimaryNoNewArrayThis() {
- // PrimaryNoNewArray ::= 'this'
-
- if (scanner.startPosition >= codeSnippetStart
- && scanner.startPosition <= codeSnippetEnd + 1
- && isTopLevelType()) {
- pushOnExpressionStack(
- new CodeSnippetThisReference(
- intStack[intPtr--],
- endPosition,
- evaluationContext,
- false));
- } else {
- super.consumePrimaryNoNewArrayThis();
+ // generate try { [snippet] } finally { [save locals to fields] }
+ // try block
+ TryStatement tryStatement = new TryStatement();
+ Block tryBlock = new Block(methodDecl.explicitDeclarations);
+ tryBlock.sourceStart = start;
+ tryBlock.sourceEnd = end;
+ tryBlock.statements = methodDecl.statements; // snippet statements
+ tryStatement.tryBlock = tryBlock;
+ // finally block
+ Block finallyBlock = new Block(0);
+ finallyBlock.sourceStart = start;
+ finallyBlock.sourceEnd = end;
+ finallyBlock.statements = new Statement[varCount];
+ for (int i = 0; i < varCount; i++){
+ finallyBlock.statements[i] = new Assignment(
+ new SingleNameReference(CharOperation.concat(LOCAL_VAR_PREFIX, this.evaluationContext.localVariableNames[i]), position),
+ new SingleNameReference(this.evaluationContext.localVariableNames[i], position));
}
- }
-
- protected void consumeStatementBreak() {
- super.consumeStatementBreak();
- /* recovery */
- recordLastStatementIfNeeded();
- }
+ tryStatement.finallyBlock = finallyBlock;
- protected void consumeStatementBreakWithLabel() {
- super.consumeStatementBreakWithLabel();
- /* recovery */
- recordLastStatementIfNeeded();
+ newStatements[varCount] = tryStatement;
+ methodDecl.statements = newStatements;
}
-
- protected void consumeStatementCatch() {
- super.consumeStatementCatch();
- /* recovery */
- recordLastStatementIfNeeded();
- }
-
- protected void consumeStatementContinue() {
- super.consumeStatementContinue();
- /* recovery */
- recordLastStatementIfNeeded();
- }
-
- protected void consumeStatementContinueWithLabel() {
- super.consumeStatementContinueWithLabel();
- /* recovery */
- recordLastStatementIfNeeded();
- }
-
- protected void consumeStatementDo() {
- super.consumeStatementDo();
- /* recovery */
- recordLastStatementIfNeeded();
- }
-
- protected void consumeStatementFor() {
- super.consumeStatementFor();
- /* recovery */
- recordLastStatementIfNeeded();
- }
-
- protected void consumeStatementIfNoElse() {
- super.consumeStatementIfNoElse();
- /* recovery */
- recordLastStatementIfNeeded();
- }
-
- protected void consumeStatementIfWithElse() {
- super.consumeStatementIfWithElse();
- /* recovery */
- recordLastStatementIfNeeded();
- }
-
- protected void consumeStatementLabel() {
- super.consumeStatementLabel();
- /* recovery */
- recordLastStatementIfNeeded();
- }
-
- protected void consumeStatementReturn() {
- // ReturnStatement ::= 'return' Expressionopt ';'
-
- // returned value intercepted by code snippet
- // support have to be defined at toplevel only
- if ((this.hasRecoveredOnExpression
- || (scanner.startPosition >= codeSnippetStart
- && scanner.startPosition <= codeSnippetEnd + 1))
- && this.expressionLengthStack[this.expressionLengthPtr] != 0
- && isTopLevelType()) {
- this.expressionLengthPtr--;
- Expression expression = this.expressionStack[this.expressionPtr--];
- pushOnAstStack(
- new CodeSnippetReturnStatement(
- expression,
- expression.sourceStart(),
- expression.sourceEnd(),
- evaluationContext));
+}
+protected void consumeMethodInvocationName() {
+ // MethodInvocation ::= Name '(' ArgumentListopt ')'
+
+ if (scanner.startPosition >= codeSnippetStart
+ && scanner.startPosition <= codeSnippetEnd + 1
+ && isTopLevelType()) {
+
+ // when the name is only an identifier...we have a message send to "this" (implicit)
+
+ MessageSend m = newMessageSend();
+ m.sourceEnd = rParenPos;
+ m.sourceStart =
+ (int) ((m.nameSourcePosition = identifierPositionStack[identifierPtr]) >>> 32);
+ m.selector = identifierStack[identifierPtr--];
+ if (identifierLengthStack[identifierLengthPtr] == 1) {
+ m.receiver = new CodeSnippetThisReference(0,0,evaluationContext, true);
+ identifierLengthPtr--;
} else {
- super.consumeStatementReturn();
+ identifierLengthStack[identifierLengthPtr]--;
+ m.receiver = getUnspecifiedReference();
+ m.sourceStart = m.receiver.sourceStart;
}
- /* recovery */
- recordLastStatementIfNeeded();
- }
-
- protected void consumeStatementSwitch() {
- super.consumeStatementSwitch();
- /* recovery */
- recordLastStatementIfNeeded();
- }
-
- protected void consumeStatementSynchronized() {
- super.consumeStatementSynchronized();
- /* recovery */
- recordLastStatementIfNeeded();
- }
-
- protected void consumeStatementThrow() {
- super.consumeStatementThrow();
- /* recovery */
- recordLastStatementIfNeeded();
- }
-
- protected void consumeStatementTry(boolean arg_0) {
- super.consumeStatementTry(arg_0);
- /* recovery */
- recordLastStatementIfNeeded();
+ pushOnExpressionStack(m);
+ } else {
+ super.consumeMethodInvocationName();
}
+}
+protected void consumePrimaryNoNewArrayThis() {
+ // PrimaryNoNewArray ::= 'this'
- protected void consumeStatementWhile() {
- super.consumeStatementWhile();
- /* recovery */
- recordLastStatementIfNeeded();
+ if (scanner.startPosition >= codeSnippetStart
+ && scanner.startPosition <= codeSnippetEnd + 1
+ && isTopLevelType()) {
+ pushOnExpressionStack(
+ new CodeSnippetThisReference(intStack[intPtr--], endPosition, evaluationContext, false));
+ } else {
+ super.consumePrimaryNoNewArrayThis();
}
+}
+protected void consumeStatementBreak() {
+ super.consumeStatementBreak();
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+protected void consumeStatementBreakWithLabel() {
+ super.consumeStatementBreakWithLabel();
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+protected void consumeStatementCatch() {
+ super.consumeStatementCatch();
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+protected void consumeStatementContinue() {
+ super.consumeStatementContinue();
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+protected void consumeStatementContinueWithLabel() {
+ super.consumeStatementContinueWithLabel();
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+protected void consumeStatementDo() {
+ super.consumeStatementDo();
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+protected void consumeStatementFor() {
+ super.consumeStatementFor();
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+protected void consumeStatementIfNoElse() {
+ super.consumeStatementIfNoElse();
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+protected void consumeStatementIfWithElse() {
+ super.consumeStatementIfWithElse();
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+protected void consumeStatementLabel() {
+ super.consumeStatementLabel();
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+protected void consumeStatementReturn() {
+ // ReturnStatement ::= 'return' Expressionopt ';'
+
+ // returned value intercepted by code snippet
+ // support have to be defined at toplevel only
+ if ((this.hasRecoveredOnExpression
+ || (scanner.startPosition >= codeSnippetStart && scanner.startPosition <= codeSnippetEnd+1))
+ && this.expressionLengthStack[this.expressionLengthPtr] != 0
+ && isTopLevelType()) {
+ this.expressionLengthPtr--;
+ Expression expression = this.expressionStack[this.expressionPtr--];
+ pushOnAstStack(
+ new CodeSnippetReturnStatement(
+ expression,
+ expression.sourceStart(),
+ expression.sourceEnd(),
+ evaluationContext));
+ } else {
+ super.consumeStatementReturn();
+ }
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+protected void consumeStatementSwitch() {
+ super.consumeStatementSwitch();
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+protected void consumeStatementSynchronized() {
+ super.consumeStatementSynchronized();
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+protected void consumeStatementThrow() {
+ super.consumeStatementThrow();
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+protected void consumeStatementTry(boolean arg_0) {
+ super.consumeStatementTry(arg_0);
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+protected void consumeStatementWhile() {
+ super.consumeStatementWhile();
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+protected CompilationUnitDeclaration endParse(int act) {
+ if (this.hasRecoveredOnExpression) {
+ CompilationResult unitResult = this.compilationUnit.compilationResult;
+ if (act != ERROR_ACTION) { // expression recovery worked
+ // flush previously recorded problems
+ for (int i = 0; i < unitResult.problemCount; i++) {
+ unitResult.problems[i] = null; // discard problem
+ }
+ unitResult.problemCount = 0;
+ if (this.referenceContext instanceof AbstractMethodDeclaration) {
+ ((AbstractMethodDeclaration)this.referenceContext).ignoreFurtherInvestigation = false;
+ }
+ if (this.referenceContext instanceof CompilationUnitDeclaration) {
+ ((CompilationUnitDeclaration)this.referenceContext).ignoreFurtherInvestigation = false;
+ }
- protected CompilationUnitDeclaration endParse(int act) {
- if (this.hasRecoveredOnExpression) {
- CompilationResult unitResult = this.compilationUnit.compilationResult;
- if (act != ERROR_ACTION) { // expression recovery worked
- // flush previously recorded problems
- for (int i = 0; i < unitResult.problemCount; i++) {
- unitResult.problems[i] = null; // discard problem
- }
- unitResult.problemCount = 0;
- if (this.referenceContext instanceof AbstractMethodDeclaration) {
- ((AbstractMethodDeclaration) this.referenceContext).ignoreFurtherInvestigation =
- false;
- }
- if (this.referenceContext instanceof CompilationUnitDeclaration) {
- ((CompilationUnitDeclaration) this.referenceContext).ignoreFurtherInvestigation =
- false;
- }
-
- // consume expresion as a return statement
- consumeStatementReturn();
- int fieldsCount =
- (this.evaluationContext.localVariableNames == null
- ? 0
- : this.evaluationContext.localVariableNames.length)
- + (this.evaluationContext.declaringTypeName == null ? 0 : 1);
- if (this.astPtr > (this.diet ? 0 : 2 + fieldsCount)) {
+ // consume expresion as a return statement
+ consumeStatementReturn();
+ int fieldsCount =
+ (this.evaluationContext.localVariableNames == null ? 0 : this.evaluationContext.localVariableNames.length)
+ + (this.evaluationContext.declaringTypeName == null ? 0 : 1);
+ if (this.astPtr > (this.diet ? 0 : 2 + fieldsCount)) {
// in diet mode, the ast stack was empty when we went for method body
// otherwise it contained the type, the generated fields for local variables,
// the generated field for 'this' and the method
- consumeBlockStatements();
- }
- consumeMethodBody();
- if (!this.diet) {
- consumeMethodDeclaration(true);
- if (fieldsCount > 0) {
- consumeClassBodyDeclarations();
- }
- consumeClassBodyDeclarationsopt();
- consumeClassDeclaration();
- consumeTypeDeclarationsopt();
- consumeCompilationUnit();
- }
- this.lastAct = ACCEPT_ACTION;
- } else {
- // might have more than one error recorded:
- // 1. during regular parse
- // 2. during expression recovery
- // -> must filter out one of them, the earliest one is less accurate
- int maxRegularPos = 0, problemCount = unitResult.problemCount;
- for (int i = 0; i < this.problemCountBeforeRecovery; i++) {
- // skip unmatched bracket problems
- if (unitResult.problems[i].getID() == ProblemIrritants.UnmatchedBracket)
- continue;
-
- int start = unitResult.problems[i].getSourceStart();
- if (start > maxRegularPos && start <= this.codeSnippetEnd) {
- maxRegularPos = start;
- }
- }
- int maxRecoveryPos = 0;
- for (int i = this.problemCountBeforeRecovery; i < problemCount; i++) {
- // skip unmatched bracket problems
- if (unitResult.problems[i].getID() == ProblemIrritants.UnmatchedBracket)
- continue;
-
- int start = unitResult.problems[i].getSourceStart();
- if (start > maxRecoveryPos && start <= this.codeSnippetEnd) {
- maxRecoveryPos = start;
- }
+ consumeBlockStatements();
+ }
+ consumeMethodBody();
+ if (!this.diet) {
+ consumeMethodDeclaration(true);
+ if (fieldsCount > 0) {
+ consumeClassBodyDeclarations();
}
- if (maxRecoveryPos > maxRegularPos) {
- System.arraycopy(
- unitResult.problems,
- this.problemCountBeforeRecovery,
- unitResult.problems,
- 0,
- problemCount - this.problemCountBeforeRecovery);
- unitResult.problemCount -= this.problemCountBeforeRecovery;
- } else {
- unitResult.problemCount -= (problemCount - this.problemCountBeforeRecovery);
+ consumeClassBodyDeclarationsopt();
+ consumeClassDeclaration();
+ consumeTypeDeclarationsopt();
+ consumeCompilationUnit();
+ }
+ this.lastAct = ACCEPT_ACTION;
+ } else {
+ // might have more than one error recorded:
+ // 1. during regular parse
+ // 2. during expression recovery
+ // -> must filter out one of them, the earliest one is less accurate
+ int maxRegularPos = 0, problemCount = unitResult.problemCount;
+ for (int i = 0; i < this.problemCountBeforeRecovery; i++) {
+ // skip unmatched bracket problems
+ if (unitResult.problems[i].getID() == ProblemIrritants.UnmatchedBracket) continue;
+
+ int start = unitResult.problems[i].getSourceStart();
+ if (start > maxRegularPos && start <= this.codeSnippetEnd) {
+ maxRegularPos = start;
}
- for (int i = unitResult.problemCount; i < problemCount; i++) {
- unitResult.problems[i] = null; // discard problem
+ }
+ int maxRecoveryPos = 0;
+ for (int i = this.problemCountBeforeRecovery; i < problemCount; i++) {
+ // skip unmatched bracket problems
+ if (unitResult.problems[i].getID() == ProblemIrritants.UnmatchedBracket) continue;
+
+ int start = unitResult.problems[i].getSourceStart();
+ if (start > maxRecoveryPos && start <= this.codeSnippetEnd) {
+ maxRecoveryPos = start;
}
-
}
- }
- return super.endParse(act);
- }
+ if (maxRecoveryPos > maxRegularPos) {
+ System.arraycopy(unitResult.problems, this.problemCountBeforeRecovery, unitResult.problems, 0, problemCount - this.problemCountBeforeRecovery);
+ unitResult.problemCount -= this.problemCountBeforeRecovery;
+ } else {
+ unitResult.problemCount -= (problemCount - this.problemCountBeforeRecovery);
+ }
+ for (int i = unitResult.problemCount; i < problemCount; i++) {
+ unitResult.problems[i] = null; // discard problem
+ }
- protected NameReference getUnspecifiedReference() {
- /* build a (unspecified) NameReference which may be qualified*/
-
- if (scanner.startPosition >= codeSnippetStart
- && scanner.startPosition <= codeSnippetEnd + 1) {
- int length;
- NameReference ref;
- if ((length = identifierLengthStack[identifierLengthPtr--]) == 1)
- // single variable reference
- ref =
- new CodeSnippetSingleNameReference(
- identifierStack[identifierPtr],
- identifierPositionStack[identifierPtr--],
- this.evaluationContext);
- else
- //Qualified variable reference
- {
- char[][] tokens = new char[length][];
- identifierPtr -= length;
- System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length);
- ref =
- new CodeSnippetQualifiedNameReference(
- tokens,
- (int) (identifierPositionStack[identifierPtr + 1] >> 32),
- // sourceStart
- (int) identifierPositionStack[identifierPtr + length], evaluationContext);
- // sourceEnd
- };
- return ref;
- } else {
- return super.getUnspecifiedReference();
}
}
+ return super.endParse(act);
+}
+protected NameReference getUnspecifiedReference() {
+ /* build a (unspecified) NameReference which may be qualified*/
- protected NameReference getUnspecifiedReferenceOptimized() {
- /* build a (unspecified) NameReference which may be qualified
- The optimization occurs for qualified reference while we are
- certain in this case the last item of the qualified name is
- a field access. This optimization is IMPORTANT while it results
- that when a NameReference is build, the type checker should always
- look for that it is not a type reference */
-
- if (scanner.startPosition >= codeSnippetStart
- && scanner.startPosition <= codeSnippetEnd + 1) {
- int length;
- NameReference ref;
- if ((length = identifierLengthStack[identifierLengthPtr--]) == 1) {
- // single variable reference
- ref =
- new CodeSnippetSingleNameReference(
- identifierStack[identifierPtr],
- identifierPositionStack[identifierPtr--],
- this.evaluationContext);
- ref.bits &= ~NameReference.RestrictiveFlagMASK;
- ref.bits |= LOCAL | FIELD;
- return ref;
- }
-
- //Qualified-variable-reference
- //In fact it is variable-reference DOT field-ref , but it would result in a type
- //conflict tha can be only reduce by making a superclass (or inetrface ) between
- //nameReference and FiledReference or putting FieldReference under NameReference
- //or else..........This optimisation is not really relevant so just leave as it is
-
+ if (scanner.startPosition >= codeSnippetStart
+ && scanner.startPosition <= codeSnippetEnd+1){
+ int length;
+ NameReference ref;
+ if ((length = identifierLengthStack[identifierLengthPtr--]) == 1)
+ // single variable reference
+ ref =
+ new CodeSnippetSingleNameReference(
+ identifierStack[identifierPtr],
+ identifierPositionStack[identifierPtr--],
+ this.evaluationContext);
+ else
+ //Qualified variable reference
+ {
char[][] tokens = new char[length][];
identifierPtr -= length;
System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length);
- ref =
- new CodeSnippetQualifiedNameReference(
- tokens,
- (int) (identifierPositionStack[identifierPtr + 1] >> 32),
- // sourceStart
- (int) identifierPositionStack[identifierPtr + length], evaluationContext);
- // sourceEnd
+ ref =
+ new CodeSnippetQualifiedNameReference(tokens,
+ (int) (identifierPositionStack[identifierPtr + 1] >> 32), // sourceStart
+ (int) identifierPositionStack[identifierPtr + length],
+ evaluationContext); // sourceEnd
+ };
+ return ref;
+ } else {
+ return super.getUnspecifiedReference();
+ }
+}
+protected NameReference getUnspecifiedReferenceOptimized() {
+ /* build a (unspecified) NameReference which may be qualified
+ The optimization occurs for qualified reference while we are
+ certain in this case the last item of the qualified name is
+ a field access. This optimization is IMPORTANT while it results
+ that when a NameReference is build, the type checker should always
+ look for that it is not a type reference */
+
+ if (scanner.startPosition >= codeSnippetStart
+ && scanner.startPosition <= codeSnippetEnd+1){
+ int length;
+ NameReference ref;
+ if ((length = identifierLengthStack[identifierLengthPtr--]) == 1) {
+ // single variable reference
+ ref =
+ new CodeSnippetSingleNameReference(
+ identifierStack[identifierPtr],
+ identifierPositionStack[identifierPtr--],
+ this.evaluationContext);
ref.bits &= ~NameReference.RestrictiveFlagMASK;
ref.bits |= LOCAL | FIELD;
return ref;
- } else {
- return super.getUnspecifiedReferenceOptimized();
}
- }
- protected void ignoreExpressionAssignment() {
- super.ignoreExpressionAssignment();
- /* recovery */
- recordLastStatementIfNeeded();
+ //Qualified-variable-reference
+ //In fact it is variable-reference DOT field-ref , but it would result in a type
+ //conflict tha can be only reduce by making a superclass (or inetrface ) between
+ //nameReference and FiledReference or putting FieldReference under NameReference
+ //or else..........This optimisation is not really relevant so just leave as it is
+
+ char[][] tokens = new char[length][];
+ identifierPtr -= length;
+ System.arraycopy(identifierStack, identifierPtr + 1, tokens, 0, length);
+ ref = new CodeSnippetQualifiedNameReference(
+ tokens,
+ (int) (identifierPositionStack[identifierPtr + 1] >> 32), // sourceStart
+ (int) identifierPositionStack[identifierPtr + length],
+ evaluationContext); // sourceEnd
+ ref.bits &= ~NameReference.RestrictiveFlagMASK;
+ ref.bits |= LOCAL | FIELD;
+ return ref;
+ } else {
+ return super.getUnspecifiedReferenceOptimized();
}
-
- /**
- * Returns whether we are parsing a top level type or not.
- */
- private boolean isTopLevelType() {
- return this.nestedType == (this.diet ? 0 : 1);
- }
-
- protected MessageSend newMessageSend() {
- // '(' ArgumentListopt ')'
- // the arguments are on the expression stack
-
- CodeSnippetMessageSend m = new CodeSnippetMessageSend(evaluationContext);
- int length;
- if ((length = expressionLengthStack[expressionLengthPtr--]) != 0) {
- expressionPtr -= length;
- System.arraycopy(
- expressionStack,
- expressionPtr + 1,
- m.arguments = new Expression[length],
- 0,
- length);
- };
- return m;
- }
-
- /**
- * Records the scanner position if we're parsing a top level type.
- */
- private void recordLastStatementIfNeeded() {
- if ((isTopLevelType())
- && (this.scanner.startPosition <= this.codeSnippetEnd)) {
- this.lastStatement = this.scanner.startPosition;
- }
- }
-
- protected void reportSyntaxError(int act, int currentKind, int stateStackTop) {
- if (!this.diet) {
- this.scanner.initialPosition = this.codeSnippetStart;
- // for correct bracket match diagnosis
- this.scanner.eofPosition = this.codeSnippetEnd + 1; // stop after expression
- }
- super.reportSyntaxError(act, currentKind, stateStackTop);
+}
+protected void ignoreExpressionAssignment() {
+ super.ignoreExpressionAssignment();
+ /* recovery */
+ recordLastStatementIfNeeded();
+}
+/**
+ * Returns whether we are parsing a top level type or not.
+ */
+private boolean isTopLevelType() {
+ return this.nestedType == (this.diet ? 0 : 1);
+}
+protected MessageSend newMessageSend() {
+ // '(' ArgumentListopt ')'
+ // the arguments are on the expression stack
+
+ CodeSnippetMessageSend m = new CodeSnippetMessageSend(evaluationContext);
+ int length;
+ if ((length = expressionLengthStack[expressionLengthPtr--]) != 0) {
+ expressionPtr -= length;
+ System.arraycopy(
+ expressionStack,
+ expressionPtr + 1,
+ m.arguments = new Expression[length],
+ 0,
+ length);
+ };
+ return m;
+}
+/**
+ * Records the scanner position if we're parsing a top level type.
+ */
+private void recordLastStatementIfNeeded() {
+ if ((isTopLevelType()) && (this.scanner.startPosition <= this.codeSnippetEnd)) {
+ this.lastStatement = this.scanner.startPosition;
}
-
- /*
- * A syntax error was detected. If a method is being parsed, records the number of errors and
- * attempts to restart from the last statement by going for an expression.
- */
- protected boolean resumeOnSyntaxError() {
- if (this.diet
- || this.hasRecoveredOnExpression) { // no reentering inside expression recovery
- return super.resumeOnSyntaxError();
- }
-
- // record previous error, in case more accurate than potential one in expression recovery
- // e.g. "return foo(a a); 1+3"
- this.problemCountBeforeRecovery =
- this.compilationUnit.compilationResult.problemCount;
-
- // reposition for expression parsing
- if (this.lastStatement < 0) {
- this.lastStatement = this.codeSnippetStart;
- // no statement reduced prior to error point
- }
- this.scanner.initialPosition = this.lastStatement;
- this.scanner.startPosition = this.lastStatement;
- this.scanner.currentPosition = this.lastStatement;
+}
+protected void reportSyntaxError(int act, int currentKind, int stateStackTop) {
+ if (!this.diet) {
+ this.scanner.initialPosition = this.codeSnippetStart; // for correct bracket match diagnosis
this.scanner.eofPosition = this.codeSnippetEnd + 1; // stop after expression
- this.scanner.commentPtr = -1;
-
- // reset stacks in consistent state
- this.expressionPtr = -1;
- this.identifierPtr = -1;
- this.identifierLengthPtr = -1;
-
- // go for the exprssion
- goForExpression();
- this.hasRecoveredOnExpression = true;
- this.hasReportedError = false;
- return true;
}
-
+ super.reportSyntaxError(act, currentKind, stateStackTop);
+}
+/*
+ * A syntax error was detected. If a method is being parsed, records the number of errors and
+ * attempts to restart from the last statement by going for an expression.
+ */
+protected boolean resumeOnSyntaxError() {
+ if (this.diet || this.hasRecoveredOnExpression) { // no reentering inside expression recovery
+ return super.resumeOnSyntaxError();
+ }
+
+ // record previous error, in case more accurate than potential one in expression recovery
+ // e.g. "return foo(a a); 1+3"
+ this.problemCountBeforeRecovery = this.compilationUnit.compilationResult.problemCount;
+
+ // reposition for expression parsing
+ if (this.lastStatement < 0) {
+ this.lastStatement = this.codeSnippetStart; // no statement reduced prior to error point
+ }
+ this.scanner.initialPosition = this.lastStatement;
+ this.scanner.startPosition = this.lastStatement;
+ this.scanner.currentPosition = this.lastStatement;
+ this.scanner.eofPosition = this.codeSnippetEnd + 1; // stop after expression
+ this.scanner.commentPtr = -1;
+
+ // reset stacks in consistent state
+ this.expressionPtr = -1;
+ this.identifierPtr = -1;
+ this.identifierLengthPtr = -1;
+
+ // go for the exprssion
+ goForExpression();
+ this.hasRecoveredOnExpression = true;
+ this.hasReportedError = false;
+ return true;
+}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetQualifiedNameReference.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetQualifiedNameReference.java
index 0d12775794..94ae42059e 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetQualifiedNameReference.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetQualifiedNameReference.java
@@ -10,650 +10,538 @@ import org.eclipse.jdt.internal.compiler.codegen.*;
import org.eclipse.jdt.internal.compiler.lookup.*;
import org.eclipse.jdt.internal.compiler.util.CharOperation;
-public class CodeSnippetQualifiedNameReference
- extends QualifiedNameReference
- implements EvaluationConstants, InvocationSite, ProblemReasons {
+public class CodeSnippetQualifiedNameReference extends QualifiedNameReference implements EvaluationConstants, InvocationSite, ProblemReasons {
EvaluationContext evaluationContext;
FieldBinding delegateThis;
- TypeBinding receiverType;
- /**
- * CodeSnippetQualifiedNameReference constructor comment.
- * @param sources char[][]
- * @param sourceStart int
- * @param sourceEnd int
- */
- public CodeSnippetQualifiedNameReference(
- char[][] sources,
- int sourceStart,
- int sourceEnd,
- EvaluationContext evaluationContext) {
- super(sources, sourceStart, sourceEnd);
- this.evaluationContext = evaluationContext;
- }
-
- /**
- * Check and/or redirect the field access to the delegate receiver if any
- */
- public TypeBinding checkFieldAccess(BlockScope scope) {
- // check for forward references
- bits &= ~RestrictiveFlagMASK; // clear bits
- bits |= FIELD;
- return getOtherFieldBindings(scope);
- }
-
- public void generateAssignment(
- BlockScope currentScope,
- CodeStream codeStream,
- Assignment assignment,
- boolean valueRequired) {
- generateReadSequence(currentScope, codeStream, true);
- if (lastFieldBinding
- .canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
- // the last field access is a write access
- assignment.expression.generateCode(currentScope, codeStream, true);
- fieldStore(codeStream, lastFieldBinding, null, valueRequired);
- } else {
- ((CodeSnippetCodeStream) codeStream).generateEmulationForField(
- lastFieldBinding);
- codeStream.swap();
- assignment.expression.generateCode(currentScope, codeStream, true);
- if (valueRequired) {
- if ((lastFieldBinding.type == LongBinding)
- || (lastFieldBinding.type == DoubleBinding)) {
- codeStream.dup2_x2();
- } else {
- codeStream.dup_x2();
- }
+/**
+ * CodeSnippetQualifiedNameReference constructor comment.
+ * @param sources char[][]
+ * @param sourceStart int
+ * @param sourceEnd int
+ */
+public CodeSnippetQualifiedNameReference(char[][] sources, int sourceStart, int sourceEnd, EvaluationContext evaluationContext) {
+ super(sources, sourceStart, sourceEnd);
+ this.evaluationContext = evaluationContext;
+}
+/**
+ * Check and/or redirect the field access to the delegate receiver if any
+ */
+public TypeBinding checkFieldAccess(BlockScope scope) {
+ // check for forward references
+ bits &= ~RestrictiveFlagMASK; // clear bits
+ bits |= FIELD;
+ return getOtherFieldBindings(scope);
+}
+public void generateAssignment(BlockScope currentScope, CodeStream codeStream, Assignment assignment, boolean valueRequired) {
+ generateReadSequence(currentScope, codeStream, true);
+ if (lastFieldBinding.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
+ // the last field access is a write access
+ assignment.expression.generateCode(currentScope, codeStream, true);
+ fieldStore(codeStream, lastFieldBinding, null, valueRequired);
+ } else {
+ ((CodeSnippetCodeStream) codeStream).generateEmulationForField(lastFieldBinding);
+ codeStream.swap();
+ assignment.expression.generateCode(currentScope, codeStream, true);
+ if (valueRequired) {
+ if ((lastFieldBinding.type == LongBinding) || (lastFieldBinding.type == DoubleBinding)) {
+ codeStream.dup2_x2();
+ } else {
+ codeStream.dup_x2();
}
- ((CodeSnippetCodeStream) codeStream).generateEmulatedWriteAccessForField(
- lastFieldBinding);
}
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedWriteAccessForField(lastFieldBinding);
+ }
+ if (valueRequired) {
+ codeStream.generateImplicitConversion(assignment.implicitConversion);
+ }
+}
+public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) {
+ int pc = codeStream.position;
+ if (constant != NotAConstant) {
if (valueRequired) {
- codeStream.generateImplicitConversion(assignment.implicitConversion);
+ codeStream.generateConstant(constant, implicitConversion);
}
- }
-
- public void generateCode(
- BlockScope currentScope,
- CodeStream codeStream,
- boolean valueRequired) {
- int pc = codeStream.position;
- if (constant != NotAConstant) {
- if (valueRequired) {
- codeStream.generateConstant(constant, implicitConversion);
- }
- } else {
- generateReadSequence(currentScope, codeStream, valueRequired);
- if (valueRequired) {
- if (lastFieldBinding.declaringClass == null) { // array length
- codeStream.arraylength();
- codeStream.generateImplicitConversion(implicitConversion);
- } else {
- if (lastFieldBinding.constant != NotAConstant) {
- // inline the last field constant
- codeStream.generateConstant(lastFieldBinding.constant, implicitConversion);
- } else {
- if (lastFieldBinding
- .canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
- if (lastFieldBinding.isStatic()) {
- codeStream.getstatic(lastFieldBinding);
- } else {
- codeStream.getfield(lastFieldBinding);
- }
+ } else {
+ generateReadSequence(currentScope, codeStream, valueRequired);
+ if (valueRequired) {
+ if (lastFieldBinding.declaringClass == null) { // array length
+ codeStream.arraylength();
+ codeStream.generateImplicitConversion(implicitConversion);
+ } else {
+ if (lastFieldBinding.constant != NotAConstant) {
+ // inline the last field constant
+ codeStream.generateConstant(lastFieldBinding.constant, implicitConversion);
+ } else {
+ if (lastFieldBinding.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
+ if (lastFieldBinding.isStatic()) {
+ codeStream.getstatic(lastFieldBinding);
} else {
- ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(
- lastFieldBinding);
+ codeStream.getfield(lastFieldBinding);
}
- codeStream.generateImplicitConversion(implicitConversion);
- }
+ } else {
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(lastFieldBinding);
+ }
+ codeStream.generateImplicitConversion(implicitConversion);
}
}
}
- codeStream.recordPositionsFrom(pc, this);
}
-
- public void generateCompoundAssignment(
- BlockScope currentScope,
- CodeStream codeStream,
- Expression expression,
- int operator,
- int assignmentImplicitConversion,
- boolean valueRequired) {
-
- generateReadSequence(currentScope, codeStream, true);
- if (lastFieldBinding
- .canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
- if (lastFieldBinding.isStatic()) {
- codeStream.getstatic(lastFieldBinding);
- } else {
- codeStream.dup();
- codeStream.getfield(lastFieldBinding);
- }
- // the last field access is a write access
- // perform the actual compound operation
- int operationTypeID;
- if ((operationTypeID = implicitConversion >> 4) == T_String) {
- codeStream.generateStringAppend(currentScope, null, expression);
+ codeStream.recordPositionsFrom(pc, this);
+}
+public void generateCompoundAssignment(BlockScope currentScope, CodeStream codeStream, Expression expression, int operator, int assignmentImplicitConversion, boolean valueRequired) {
+
+ generateReadSequence(currentScope, codeStream, true);
+ if (lastFieldBinding.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
+ if (lastFieldBinding.isStatic()){
+ codeStream.getstatic(lastFieldBinding);
+ } else {
+ codeStream.dup();
+ codeStream.getfield(lastFieldBinding);
+ }
+ // the last field access is a write access
+ // perform the actual compound operation
+ int operationTypeID;
+ if ((operationTypeID = implicitConversion >> 4) == T_String) {
+ codeStream.generateStringAppend(currentScope, null, expression);
+ } else {
+ // promote the array reference to the suitable operation type
+ codeStream.generateImplicitConversion(implicitConversion);
+ // generate the increment value (will by itself be promoted to the operation value)
+ if (expression == IntLiteral.One){ // prefix operation
+ codeStream.generateConstant(expression.constant, implicitConversion);
} else {
- // promote the array reference to the suitable operation type
- codeStream.generateImplicitConversion(implicitConversion);
- // generate the increment value (will by itself be promoted to the operation value)
- if (expression == IntLiteral.One) { // prefix operation
- codeStream.generateConstant(expression.constant, implicitConversion);
- } else {
- expression.generateCode(currentScope, codeStream, true);
- }
- // perform the operation
- codeStream.sendOperator(operator, operationTypeID);
- // cast the value back to the array reference type
- codeStream.generateImplicitConversion(assignmentImplicitConversion);
+ expression.generateCode(currentScope, codeStream, true);
}
- // actual assignment
- fieldStore(codeStream, lastFieldBinding, null, valueRequired);
- } else {
- if (lastFieldBinding.isStatic()) {
- ((CodeSnippetCodeStream) codeStream).generateEmulationForField(
- lastFieldBinding);
- codeStream.swap();
- codeStream.aconst_null();
- codeStream.swap();
+ // perform the operation
+ codeStream.sendOperator(operator, operationTypeID);
+ // cast the value back to the array reference type
+ codeStream.generateImplicitConversion(assignmentImplicitConversion);
+ }
+ // actual assignment
+ fieldStore(codeStream, lastFieldBinding, null, valueRequired);
+ } else {
+ if (lastFieldBinding.isStatic()){
+ ((CodeSnippetCodeStream) codeStream).generateEmulationForField(lastFieldBinding);
+ codeStream.swap();
+ codeStream.aconst_null();
+ codeStream.swap();
- ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(
- lastFieldBinding);
- } else {
- ((CodeSnippetCodeStream) codeStream).generateEmulationForField(
- lastFieldBinding);
- codeStream.swap();
- codeStream.dup();
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(lastFieldBinding);
+ } else {
+ ((CodeSnippetCodeStream) codeStream).generateEmulationForField(lastFieldBinding);
+ codeStream.swap();
+ codeStream.dup();
- ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(
- lastFieldBinding);
- }
- // the last field access is a write access
- // perform the actual compound operation
- int operationTypeID;
- if ((operationTypeID = implicitConversion >> 4) == T_String) {
- codeStream.generateStringAppend(currentScope, null, expression);
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(lastFieldBinding);
+ }
+ // the last field access is a write access
+ // perform the actual compound operation
+ int operationTypeID;
+ if ((operationTypeID = implicitConversion >> 4) == T_String) {
+ codeStream.generateStringAppend(currentScope, null, expression);
+ } else {
+ // promote the array reference to the suitable operation type
+ codeStream.generateImplicitConversion(implicitConversion);
+ // generate the increment value (will by itself be promoted to the operation value)
+ if (expression == IntLiteral.One){ // prefix operation
+ codeStream.generateConstant(expression.constant, implicitConversion);
} else {
- // promote the array reference to the suitable operation type
- codeStream.generateImplicitConversion(implicitConversion);
- // generate the increment value (will by itself be promoted to the operation value)
- if (expression == IntLiteral.One) { // prefix operation
- codeStream.generateConstant(expression.constant, implicitConversion);
- } else {
- expression.generateCode(currentScope, codeStream, true);
- }
- // perform the operation
- codeStream.sendOperator(operator, operationTypeID);
- // cast the value back to the array reference type
- codeStream.generateImplicitConversion(assignmentImplicitConversion);
+ expression.generateCode(currentScope, codeStream, true);
}
- // actual assignment
-
- // current stack is:
- // field receiver value
- if (valueRequired) {
- if ((lastFieldBinding.type == LongBinding)
- || (lastFieldBinding.type == DoubleBinding)) {
- codeStream.dup2_x2();
- } else {
- codeStream.dup_x2();
- }
- }
- // current stack is:
- // value field receiver value
- ((CodeSnippetCodeStream) codeStream).generateEmulatedWriteAccessForField(
- lastFieldBinding);
+ // perform the operation
+ codeStream.sendOperator(operator, operationTypeID);
+ // cast the value back to the array reference type
+ codeStream.generateImplicitConversion(assignmentImplicitConversion);
}
- }
-
- public void generatePostIncrement(
- BlockScope currentScope,
- CodeStream codeStream,
- CompoundAssignment postIncrement,
- boolean valueRequired) {
- generateReadSequence(currentScope, codeStream, true);
+ // actual assignment
- if (lastFieldBinding
- .canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
- if (lastFieldBinding.isStatic()) {
- codeStream.getstatic(lastFieldBinding);
+ // current stack is:
+ // field receiver value
+ if (valueRequired) {
+ if ((lastFieldBinding.type == LongBinding) || (lastFieldBinding.type == DoubleBinding)) {
+ codeStream.dup2_x2();
} else {
- codeStream.dup();
- codeStream.getfield(lastFieldBinding);
- }
- // duplicate the old field value
- if (valueRequired) {
- if (lastFieldBinding.isStatic()) {
- if ((lastFieldBinding.type == LongBinding)
- || (lastFieldBinding.type == DoubleBinding)) {
- codeStream.dup2();
- } else {
- codeStream.dup();
- }
- } else { // Stack: [owner][old field value] ---> [old field value][owner][old field value]
- if ((lastFieldBinding.type == LongBinding)
- || (lastFieldBinding.type == DoubleBinding)) {
- codeStream.dup2_x1();
- } else {
- codeStream.dup_x1();
- }
- }
+ codeStream.dup_x2();
}
- codeStream.generateConstant(
- postIncrement.expression.constant,
- implicitConversion);
- codeStream.sendOperator(postIncrement.operator, lastFieldBinding.type.id);
- codeStream.generateImplicitConversion(
- postIncrement.assignmentImplicitConversion);
+ }
+ // current stack is:
+ // value field receiver value
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedWriteAccessForField(lastFieldBinding);
+ }
+}
+public void generatePostIncrement(BlockScope currentScope, CodeStream codeStream, CompoundAssignment postIncrement, boolean valueRequired) {
+ generateReadSequence(currentScope, codeStream, true);
- fieldStore(codeStream, lastFieldBinding, null, false);
+ if (lastFieldBinding.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
+ if (lastFieldBinding.isStatic()){
+ codeStream.getstatic(lastFieldBinding);
} else {
- ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(
- lastFieldBinding);
- if (valueRequired) {
- if ((lastFieldBinding.type == LongBinding)
- || (lastFieldBinding.type == DoubleBinding)) {
+ codeStream.dup();
+ codeStream.getfield(lastFieldBinding);
+ }
+ // duplicate the old field value
+ if (valueRequired) {
+ if (lastFieldBinding.isStatic()) {
+ if ((lastFieldBinding.type == LongBinding) || (lastFieldBinding.type == DoubleBinding)) {
codeStream.dup2();
} else {
codeStream.dup();
}
- }
- ((CodeSnippetCodeStream) codeStream).generateEmulationForField(
- lastFieldBinding);
- if ((lastFieldBinding.type == LongBinding)
- || (lastFieldBinding.type == DoubleBinding)) {
- codeStream.dup_x2();
- codeStream.pop();
- if (lastFieldBinding.isStatic()) {
- codeStream.aconst_null();
- } else {
- generateReadSequence(currentScope, codeStream, true);
- }
- codeStream.dup_x2();
- codeStream.pop();
- } else {
- codeStream.dup_x1();
- codeStream.pop();
- if (lastFieldBinding.isStatic()) {
- codeStream.aconst_null();
+ } else { // Stack: [owner][old field value] ---> [old field value][owner][old field value]
+ if ((lastFieldBinding.type == LongBinding) || (lastFieldBinding.type == DoubleBinding)) {
+ codeStream.dup2_x1();
} else {
- generateReadSequence(currentScope, codeStream, true);
+ codeStream.dup_x1();
}
- codeStream.dup_x1();
- codeStream.pop();
}
- codeStream.generateConstant(
- postIncrement.expression.constant,
- implicitConversion);
- codeStream.sendOperator(postIncrement.operator, lastFieldBinding.type.id);
- codeStream.generateImplicitConversion(
- postIncrement.assignmentImplicitConversion);
- ((CodeSnippetCodeStream) codeStream).generateEmulatedWriteAccessForField(
- lastFieldBinding);
}
- }
-
- /*
- * Generate code for all bindings (local and fields) excluding the last one, which may then be generated code
- * for a read or write access.
- */
- public void generateReadSequence(
- BlockScope currentScope,
- CodeStream codeStream,
- boolean valueRequired) {
-
- // determine the rank until which we now we do not need any actual value for the field access
- int otherBindingsCount = otherBindings == null ? 0 : otherBindings.length;
- int indexOfFirstValueRequired;
+ codeStream.generateConstant(postIncrement.expression.constant, implicitConversion);
+ codeStream.sendOperator(postIncrement.operator, lastFieldBinding.type.id);
+ codeStream.generateImplicitConversion(postIncrement.assignmentImplicitConversion);
+
+ fieldStore(codeStream, lastFieldBinding, null, false);
+ } else {
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(lastFieldBinding);
if (valueRequired) {
- indexOfFirstValueRequired = otherBindingsCount;
- while (indexOfFirstValueRequired > 0) {
- FieldBinding otherBinding = otherBindings[indexOfFirstValueRequired - 1];
- if (otherBinding.isStatic() || otherBinding.constant != NotAConstant)
- break; // no longer need any value before this point
- indexOfFirstValueRequired--;
+ if ((lastFieldBinding.type == LongBinding) || (lastFieldBinding.type == DoubleBinding)) {
+ codeStream.dup2();
+ } else {
+ codeStream.dup();
+ }
+ }
+ ((CodeSnippetCodeStream) codeStream).generateEmulationForField(lastFieldBinding);
+ if ((lastFieldBinding.type == LongBinding) || (lastFieldBinding.type == DoubleBinding)) {
+ codeStream.dup_x2();
+ codeStream.pop();
+ if (lastFieldBinding.isStatic()) {
+ codeStream.aconst_null();
+ } else {
+ generateReadSequence(currentScope, codeStream, true);
}
+ codeStream.dup_x2();
+ codeStream.pop();
} else {
- indexOfFirstValueRequired = otherBindingsCount + 1;
+ codeStream.dup_x1();
+ codeStream.pop();
+ if (lastFieldBinding.isStatic()) {
+ codeStream.aconst_null();
+ } else {
+ generateReadSequence(currentScope, codeStream, true);
+ }
+ codeStream.dup_x1();
+ codeStream.pop();
}
- if (indexOfFirstValueRequired == 0) {
- switch (bits & RestrictiveFlagMASK) {
- case FIELD :
- lastFieldBinding = (FieldBinding) binding;
- // if first field is actually constant, we can inline it
- if (lastFieldBinding.constant != NotAConstant) {
- codeStream.generateConstant(lastFieldBinding.constant, 0);
- // no implicit conversion
- lastFieldBinding = null; // will not generate it again
- break;
- }
- if (lastFieldBinding
- .canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
- if (!lastFieldBinding.isStatic()) {
- if ((bits & DepthMASK) != 0) {
- Object[] emulationPath =
- currentScope.getExactEmulationPath(
- currentScope.enclosingSourceType().enclosingTypeAt(
- (bits & DepthMASK) >> DepthSHIFT));
- if (emulationPath == null) {
- // internal error, per construction we should have found it
- currentScope.problemReporter().needImplementation();
- } else {
- codeStream.generateOuterAccess(emulationPath, this, currentScope);
- }
- } else {
- generateReceiver(codeStream);
- }
- }
- } else {
- if (!lastFieldBinding.isStatic()) {
- if ((bits & DepthMASK) != 0) {
+ codeStream.generateConstant(postIncrement.expression.constant, implicitConversion);
+ codeStream.sendOperator(postIncrement.operator, lastFieldBinding.type.id);
+ codeStream.generateImplicitConversion(postIncrement.assignmentImplicitConversion);
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedWriteAccessForField(lastFieldBinding);
+ }
+}
+/*
+ * Generate code for all bindings (local and fields) excluding the last one, which may then be generated code
+ * for a read or write access.
+ */
+public void generateReadSequence(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) {
+
+ // determine the rank until which we now we do not need any actual value for the field access
+ int otherBindingsCount = otherBindings == null ? 0 : otherBindings.length;
+ int indexOfFirstValueRequired;
+ if (valueRequired) {
+ indexOfFirstValueRequired = otherBindingsCount;
+ while (indexOfFirstValueRequired > 0) {
+ FieldBinding otherBinding = otherBindings[indexOfFirstValueRequired - 1];
+ if (otherBinding.isStatic() || otherBinding.constant != NotAConstant)
+ break; // no longer need any value before this point
+ indexOfFirstValueRequired--;
+ }
+ } else {
+ indexOfFirstValueRequired = otherBindingsCount + 1;
+ }
+ if (indexOfFirstValueRequired == 0) {
+ switch (bits & RestrictiveFlagMASK) {
+ case FIELD :
+ lastFieldBinding = (FieldBinding) binding;
+ // if first field is actually constant, we can inline it
+ if (lastFieldBinding.constant != NotAConstant) {
+ codeStream.generateConstant(lastFieldBinding.constant, 0); // no implicit conversion
+ lastFieldBinding = null; // will not generate it again
+ break;
+ }
+ if (lastFieldBinding.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
+ if (!lastFieldBinding.isStatic()) {
+ if ((bits & DepthMASK) != 0) {
+ Object[] emulationPath = currentScope.getExactEmulationPath(currentScope.enclosingSourceType().enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT));
+ if (emulationPath == null) {
// internal error, per construction we should have found it
- // not yet supported
currentScope.problemReporter().needImplementation();
} else {
- generateReceiver(codeStream);
+ codeStream.generateOuterAccess(emulationPath, this, currentScope);
}
} else {
- codeStream.aconst_null();
+ generateReceiver(codeStream);
}
}
- break;
- case LOCAL : // reading the first local variable
- lastFieldBinding = null;
- LocalVariableBinding localBinding = (LocalVariableBinding) binding;
-
- // regular local variable read
- if (localBinding.constant != NotAConstant) {
- codeStream.generateConstant(localBinding.constant, 0);
- // no implicit conversion
- } else {
- // outer local?
+ } else {
+ if (!lastFieldBinding.isStatic()) {
if ((bits & DepthMASK) != 0) {
- // outer local can be reached either through a synthetic arg or a synthetic field
- VariableBinding[] path = currentScope.getEmulationPath(localBinding);
- if (path == null) {
- // emulation was not possible (should not happen per construction)
- currentScope.problemReporter().needImplementation();
- } else {
- codeStream.generateOuterAccess(path, this, currentScope);
- }
+ // internal error, per construction we should have found it
+ // not yet supported
+ currentScope.problemReporter().needImplementation();
} else {
- codeStream.load(localBinding);
+ generateReceiver(codeStream);
}
- }
- }
- } else {
- lastFieldBinding = null;
- }
- // all intermediate field accesses are read accesses
- // only the last field binding is a write access
- if (otherBindings != null) {
- int start = indexOfFirstValueRequired == 0 ? 0 : indexOfFirstValueRequired - 1;
- for (int i = start; i < otherBindingsCount; i++) {
- if (lastFieldBinding != null) {
- if (lastFieldBinding
- .canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
- if (lastFieldBinding.isStatic())
- codeStream.getstatic(lastFieldBinding);
- else
- codeStream.getfield(lastFieldBinding);
} else {
- ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(
- lastFieldBinding);
+ codeStream.aconst_null();
}
}
-
- lastFieldBinding = otherBindings[i];
- if (lastFieldBinding != null
- && !lastFieldBinding.canBeSeenBy(
- getReceiverType(currentScope),
- this,
- currentScope)) {
- if (lastFieldBinding.isStatic()) {
- codeStream.aconst_null();
+ break;
+ case LOCAL : // reading the first local variable
+ lastFieldBinding = null;
+ LocalVariableBinding localBinding = (LocalVariableBinding) binding;
+
+ // regular local variable read
+ if (localBinding.constant != NotAConstant) {
+ codeStream.generateConstant(localBinding.constant, 0); // no implicit conversion
+ } else {
+ // outer local?
+ if ((bits & DepthMASK) != 0) {
+ // outer local can be reached either through a synthetic arg or a synthetic field
+ VariableBinding[] path = currentScope.getEmulationPath(localBinding);
+ if (path == null) {
+ // emulation was not possible (should not happen per construction)
+ currentScope.problemReporter().needImplementation();
+ } else {
+ codeStream.generateOuterAccess(path, this, currentScope);
+ }
+ } else {
+ codeStream.load(localBinding);
}
}
- }
}
+ } else {
+ lastFieldBinding = null;
}
+ // all intermediate field accesses are read accesses
+ // only the last field binding is a write access
+ if (otherBindings != null) {
+ int start = indexOfFirstValueRequired == 0 ? 0 : indexOfFirstValueRequired - 1;
+ for (int i = start; i < otherBindingsCount; i++) {
+ if (lastFieldBinding != null) {
+ if (lastFieldBinding.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
+ if (lastFieldBinding.isStatic())
+ codeStream.getstatic(lastFieldBinding);
+ else
+ codeStream.getfield(lastFieldBinding);
+ } else {
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(lastFieldBinding);
+ }
+ }
- public void generateReceiver(CodeStream codeStream) {
- codeStream.aload_0();
- if (delegateThis != null)
- codeStream.getfield(delegateThis); // delegated field access
+ lastFieldBinding = otherBindings[i];
+ if (lastFieldBinding != null && !lastFieldBinding.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
+ if (lastFieldBinding.isStatic()) {
+ codeStream.aconst_null();
+ }
+ }
+ }
}
-
- public TypeBinding getOtherFieldBindings(BlockScope scope) {
- // At this point restrictiveFlag may ONLY have two potential value : FIELD LOCAL (i.e cast <<(VariableBinding) binding>> is valid)
-
- if ((bits & FIELD) != 0) {
- if (!((FieldBinding) binding).isStatic()) {
- //must check for the static status....
- if (indexOfFirstFieldBinding == 1) {
- //the field is the first token of the qualified reference....
- if (scope.methodScope().isStatic) {
- scope.problemReporter().staticFieldAccessToNonStaticVariable(
- this,
- (FieldBinding) binding);
- return null;
- }
- } else { //accessing to a field using a type as "receiver" is allowed only with static field
- scope.problemReporter().staticFieldAccessToNonStaticVariable(
- this,
- (FieldBinding) binding);
+}
+public void generateReceiver(CodeStream codeStream) {
+ codeStream.aload_0();
+ if (delegateThis != null) codeStream.getfield(delegateThis); // delegated field access
+}
+public TypeBinding getOtherFieldBindings(BlockScope scope) {
+ // At this point restrictiveFlag may ONLY have two potential value : FIELD LOCAL (i.e cast <<(VariableBinding) binding>> is valid)
+
+ if ((bits & FIELD) != 0) {
+ if (!((FieldBinding) binding).isStatic()) { //must check for the static status....
+ if (indexOfFirstFieldBinding == 1) {
+ //the field is the first token of the qualified reference....
+ if (scope.methodScope().isStatic) {
+ scope.problemReporter().staticFieldAccessToNonStaticVariable(this, (FieldBinding) binding);
return null;
}
+ } else { //accessing to a field using a type as "receiver" is allowed only with static field
+ scope.problemReporter().staticFieldAccessToNonStaticVariable(this, (FieldBinding) binding);
+ return null;
}
- if (isFieldUseDeprecated((FieldBinding) binding, scope))
- scope.problemReporter().deprecatedField((FieldBinding) binding, this);
-
- // if the binding declaring class is not visible, need special action
- // for runtime compatibility on 1.2 VMs : change the declaring class of the binding
- FieldBinding fieldBinding = (FieldBinding) binding;
- if (delegateThis == null) {
- if (fieldBinding.declaringClass != null
- && fieldBinding.constant == NotAConstant
- && !fieldBinding.declaringClass.canBeSeenBy(scope))
+ }
+ if (isFieldUseDeprecated((FieldBinding) binding, scope))
+ scope.problemReporter().deprecatedField((FieldBinding) binding, this);
+
+ // if the binding declaring class is not visible, need special action
+ // for runtime compatibility on 1.2 VMs : change the declaring class of the binding
+ FieldBinding fieldBinding = (FieldBinding)binding;
+ if (delegateThis == null) {
+ if (fieldBinding.declaringClass != null
+ && fieldBinding.constant == NotAConstant
+ && !fieldBinding.declaringClass.canBeSeenBy(scope))
binding = new FieldBinding(fieldBinding, (ReferenceBinding) delegateThis.type);
- } else {
- CodeSnippetScope localScope = new CodeSnippetScope(scope);
- if (fieldBinding.declaringClass != null
- && fieldBinding.constant == NotAConstant
- && !localScope.canBeSeenByForCodeSnippet(
- fieldBinding.declaringClass,
- (ReferenceBinding) delegateThis.type))
+ } else {
+ CodeSnippetScope localScope = new CodeSnippetScope(scope);
+ if (fieldBinding.declaringClass != null
+ && fieldBinding.constant == NotAConstant
+ && !localScope.canBeSeenByForCodeSnippet(fieldBinding.declaringClass, (ReferenceBinding) delegateThis.type))
binding = new FieldBinding(fieldBinding, (ReferenceBinding) delegateThis.type);
- }
- }
-
- TypeBinding type = ((VariableBinding) binding).type;
- int index = indexOfFirstFieldBinding;
- int length = tokens.length;
- if (index == length) { // restrictiveFlag == FIELD
- constant =
- FieldReference.getConstantFor((FieldBinding) binding, false, this, index - 1);
- return type;
}
+ }
- // allocation of the fieldBindings array and its respective constants
- int otherBindingsLength = length - index;
- otherBindings = new FieldBinding[otherBindingsLength];
-
- // fill the first constant (the one of the binding)
- constant =
- ((bits & FIELD) != 0)
- ? FieldReference.getConstantFor((FieldBinding) binding, false, this, index - 1)
- : ((VariableBinding) binding).constant;
+ TypeBinding type = ((VariableBinding) binding).type;
+ int index = indexOfFirstFieldBinding;
+ int length = tokens.length;
+ if (index == length) { // restrictiveFlag == FIELD
+ constant = FieldReference.getConstantFor((FieldBinding) binding, false, this, index - 1);
+ return type;
+ }
- // iteration on each field
- while (index < length) {
- char[] token = tokens[index];
- if (type == null)
- return null; // could not resolve type prior to this point
- FieldBinding field = scope.getField(type, token, this);
- int place = index - indexOfFirstFieldBinding;
- otherBindings[place] = field;
- if (!field.isValidBinding()) {
- // try to retrieve the field as private field
- CodeSnippetScope localScope = new CodeSnippetScope(scope);
- if (delegateThis == null) {
- if (this.evaluationContext.declaringTypeName != null) {
- delegateThis = scope.getField(scope.enclosingSourceType(), DELEGATE_THIS, this);
- if (delegateThis == null) {
- ; // if not found then internal error, field should have been found
- return super.reportError(scope);
- }
- } else {
+ // allocation of the fieldBindings array and its respective constants
+ int otherBindingsLength = length - index;
+ otherBindings = new FieldBinding[otherBindingsLength];
+
+ // fill the first constant (the one of the binding)
+ constant =
+ ((bits & FIELD) != 0)
+ ? FieldReference.getConstantFor((FieldBinding) binding, false, this, index - 1)
+ : ((VariableBinding) binding).constant;
+
+ // iteration on each field
+ while (index < length) {
+ char[] token = tokens[index];
+ if (type == null) return null; // could not resolve type prior to this point
+ FieldBinding field = scope.getField(type, token, this);
+ int place = index - indexOfFirstFieldBinding;
+ otherBindings[place] = field;
+ if (!field.isValidBinding()) {
+ // try to retrieve the field as private field
+ CodeSnippetScope localScope = new CodeSnippetScope(scope);
+ if (delegateThis == null) {
+ if (this.evaluationContext.declaringTypeName != null) {
+ delegateThis = scope.getField(scope.enclosingSourceType(), DELEGATE_THIS, this);
+ if (delegateThis == null){ ; // if not found then internal error, field should have been found
return super.reportError(scope);
}
- }
- field = localScope.getFieldForCodeSnippet(delegateThis.type, token, this);
- otherBindings[place] = field;
- }
- if (field.isValidBinding()) {
- if (isFieldUseDeprecated(field, scope))
- scope.problemReporter().deprecatedField(field, this);
- Constant someConstant =
- FieldReference.getConstantFor(field, false, this, place);
- // constant propagation can only be performed as long as the previous one is a constant too.
- if (constant != NotAConstant) {
- constant = someConstant;
- }
- // if the binding declaring class is not visible, need special action
- // for runtime compatibility on 1.2 VMs : change the declaring class of the binding
- if (delegateThis == null) {
- CodeSnippetScope localScope = new CodeSnippetScope(scope);
- if (field.declaringClass != type
- && field.declaringClass != null // array.length
- && field.constant == NotAConstant
- && !field.declaringClass.canBeSeenBy(scope))
- otherBindings[place] = new FieldBinding(field, (ReferenceBinding) type);
} else {
- CodeSnippetScope localScope = new CodeSnippetScope(scope);
- if (field.declaringClass != type
- && field.declaringClass != null // array.length
- && field.constant == NotAConstant
- && !localScope.canBeSeenByForCodeSnippet(
- field.declaringClass,
- (ReferenceBinding) delegateThis.type))
- otherBindings[place] = new FieldBinding(field, (ReferenceBinding) type);
+ return super.reportError(scope);
}
- type = field.type;
- index++;
+ }
+ field = localScope.getFieldForCodeSnippet(delegateThis.type, token, this);
+ otherBindings[place] = field;
+ }
+ if (field.isValidBinding()) {
+ if (isFieldUseDeprecated(field, scope))
+ scope.problemReporter().deprecatedField(field, this);
+ Constant someConstant = FieldReference.getConstantFor(field, false, this, place);
+ // constant propagation can only be performed as long as the previous one is a constant too.
+ if (constant != NotAConstant){
+ constant = someConstant;
+ }
+ // if the binding declaring class is not visible, need special action
+ // for runtime compatibility on 1.2 VMs : change the declaring class of the binding
+ if (delegateThis == null) {
+ CodeSnippetScope localScope = new CodeSnippetScope(scope);
+ if (field.declaringClass != type
+ && field.declaringClass != null // array.length
+ && field.constant == NotAConstant
+ && !field.declaringClass.canBeSeenBy(scope))
+ otherBindings[place] = new FieldBinding(field, (ReferenceBinding)type);
} else {
- constant = NotAConstant; //don't fill other constants slots...
- scope.problemReporter().invalidField(this, field, index, type);
- return null;
+ CodeSnippetScope localScope = new CodeSnippetScope(scope);
+ if (field.declaringClass != type
+ && field.declaringClass != null // array.length
+ && field.constant == NotAConstant
+ && !localScope.canBeSeenByForCodeSnippet(field.declaringClass, (ReferenceBinding) delegateThis.type))
+ otherBindings[place] = new FieldBinding(field, (ReferenceBinding)type);
}
+ type = field.type;
+ index++;
+ } else {
+ constant = NotAConstant; //don't fill other constants slots...
+ scope.problemReporter().invalidField(this, field, index, type);
+ return null;
}
- return (otherBindings[otherBindingsLength - 1]).type;
}
-
- /**
- * Check and/or redirect the field access to the delegate receiver if any
- */
- public TypeBinding getReceiverType(BlockScope currentScope) {
- if (receiverType != null)
- return receiverType;
- Scope scope = currentScope.parent;
- while (true) {
+ return (otherBindings[otherBindingsLength - 1]).type;
+}
+/**
+ * Check and/or redirect the field access to the delegate receiver if any
+ */
+public TypeBinding getReceiverType(BlockScope currentScope) {
+ if (receiverType != null) return receiverType;
+ Scope scope = currentScope.parent;
+ while (true) {
switch (scope.kind) {
case Scope.CLASS_SCOPE :
return receiverType = ((ClassScope) scope).referenceContext.binding;
- default :
+ default:
scope = scope.parent;
}
- }
}
+}
+public void manageSyntheticReadAccessIfNecessary(BlockScope currentScope, FieldBinding fieldBinding, int index) {
+ // nothing to do the code generation will take care of private access
+}
+/*
+ * No need to emulate access to protected fields since not implicitly accessed
+ */
+public void manageSyntheticWriteAccessIfNecessary(BlockScope currentScope, FieldBinding fieldBinding) {
+ // nothing to do the code generation will take care of private access
+}
+/**
+ * Normal field binding did not work, try to bind to a field of the delegate receiver.
+ */
+public TypeBinding reportError(BlockScope scope) {
- public void manageSyntheticReadAccessIfNecessary(
- BlockScope currentScope,
- FieldBinding fieldBinding,
- int index) {
- // nothing to do the code generation will take care of private access
+ if (this.evaluationContext.declaringTypeName != null) {
+ delegateThis = scope.getField(scope.enclosingSourceType(), DELEGATE_THIS, this);
+ if (delegateThis == null){ ; // if not found then internal error, field should have been found
+ return super.reportError(scope);
+ }
+ } else {
+ return super.reportError(scope);
}
- /*
- * No need to emulate access to protected fields since not implicitly accessed
- */
- public void manageSyntheticWriteAccessIfNecessary(
- BlockScope currentScope,
- FieldBinding fieldBinding) {
- // nothing to do the code generation will take care of private access
+ if (binding instanceof ProblemFieldBinding && ((ProblemFieldBinding) binding).problemId() == NotFound){
+ // will not support innerclass emulation inside delegate
+ binding = scope.getField(delegateThis.type, this.tokens[0], this);
+ if (!binding.isValidBinding()) return super.reportError(scope);
+ return checkFieldAccess(scope);
}
- /**
- * Normal field binding did not work, try to bind to a field of the delegate receiver.
- */
- public TypeBinding reportError(BlockScope scope) {
+ if (binding instanceof ProblemBinding && ((ProblemBinding) binding).problemId() == NotFound){
+ // will not support innerclass emulation inside delegate
+ FieldBinding fieldBinding = scope.getField(delegateThis.type, this.tokens[0], this);
+ if (!fieldBinding.isValidBinding()) return super.reportError(scope);
+ binding = fieldBinding;
+ return checkFieldAccess(scope);
+ }
- if (this.evaluationContext.declaringTypeName != null) {
- delegateThis = scope.getField(scope.enclosingSourceType(), DELEGATE_THIS, this);
- if (delegateThis == null) {
- ; // if not found then internal error, field should have been found
- return super.reportError(scope);
- }
- } else {
+ TypeBinding result;
+ if (binding instanceof ProblemFieldBinding
+ && ((ProblemFieldBinding) binding).problemId() == NotVisible) {
+ result = resolveTypeVisibility(scope);
+ if (result == null)
return super.reportError(scope);
+ if (result.isValidBinding()) {
+ return result;
}
-
- if (binding instanceof ProblemFieldBinding
- && ((ProblemFieldBinding) binding).problemId() == NotFound) {
- // will not support innerclass emulation inside delegate
- binding = scope.getField(delegateThis.type, this.tokens[0], this);
- if (!binding.isValidBinding())
- return super.reportError(scope);
- return checkFieldAccess(scope);
- }
-
- if (binding instanceof ProblemBinding
- && ((ProblemBinding) binding).problemId() == NotFound) {
- // will not support innerclass emulation inside delegate
- FieldBinding fieldBinding =
- scope.getField(delegateThis.type, this.tokens[0], this);
- if (!fieldBinding.isValidBinding())
- return super.reportError(scope);
- binding = fieldBinding;
- return checkFieldAccess(scope);
- }
-
- TypeBinding result;
- if (binding instanceof ProblemFieldBinding
- && ((ProblemFieldBinding) binding).problemId() == NotVisible) {
- result = resolveTypeVisibility(scope);
- if (result == null)
- return super.reportError(scope);
- if (result.isValidBinding()) {
- return result;
- }
- }
-
- return super.reportError(scope);
}
- public TypeBinding resolveTypeVisibility(BlockScope scope) {
- // field and/or local are done before type lookups
+ return super.reportError(scope);
+}
+public TypeBinding resolveTypeVisibility(BlockScope scope) {
+ // field and/or local are done before type lookups
- // the only available value for the restrictiveFlag BEFORE
- // the TC is Flag_Type Flag_LocalField and Flag_TypeLocalField
+ // the only available value for the restrictiveFlag BEFORE
+ // the TC is Flag_Type Flag_LocalField and Flag_TypeLocalField
- CodeSnippetScope localScope = new CodeSnippetScope(scope);
- if ((binding =
- localScope.getBinding(
- tokens,
- bits & RestrictiveFlagMASK,
- this,
- (ReferenceBinding) delegateThis.type))
- .isValidBinding()) {
- bits &= ~RestrictiveFlagMASK; // clear bits
- bits |= FIELD;
- return getOtherFieldBindings(scope);
- }
- //========error cases===============
- return super.reportError(scope);
+ CodeSnippetScope localScope = new CodeSnippetScope(scope);
+ if ((binding = localScope.getBinding(tokens, bits & RestrictiveFlagMASK, this, (ReferenceBinding) delegateThis.type)).isValidBinding()) {
+ bits &= ~RestrictiveFlagMASK; // clear bits
+ bits |= FIELD;
+ return getOtherFieldBindings(scope);
}
-
+ //========error cases===============
+ return super.reportError(scope);
+}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetReturnStatement.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetReturnStatement.java
index 928e62e171..6c761f6fba 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetReturnStatement.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetReturnStatement.java
@@ -16,131 +16,96 @@ import org.eclipse.jdt.internal.compiler.impl.NullConstant;
* it uses a macro to set the result of the code snippet instead
* of returning it.
*/
-public class CodeSnippetReturnStatement
- extends ReturnStatement
- implements InvocationSite, EvaluationConstants {
+public class CodeSnippetReturnStatement extends ReturnStatement implements InvocationSite, EvaluationConstants {
MethodBinding setResultMethod;
- public CodeSnippetReturnStatement(
- Expression expr,
- int s,
- int e,
- EvaluationContext evaluationContext) {
- super(expr, s, e);
- }
-
- /**
- * Dump the suitable return bytecode for a return statement
- *
- */
- public void generateReturnBytecode(
- BlockScope currentScope,
- CodeStream codeStream) {
-
- // output the return bytecode
- codeStream.return_();
- }
-
- public void generateStoreSaveValueIfNecessary(
- BlockScope currentScope,
- CodeStream codeStream) {
-
- // push receiver
- codeStream.aload_0();
-
- // push the 2 parameters of "setResult(Object, Class)"
- if (this.expression == null
- || this.expressionType == VoidBinding) {
- // expressionType == VoidBinding if code snippet is the expression "System.out.println()"
- // push null
- codeStream.aconst_null();
-
- // void.class
- codeStream.generateClassLiteralAccessForType(VoidBinding, null);
+public CodeSnippetReturnStatement(Expression expr, int s, int e, EvaluationContext evaluationContext) {
+ super(expr, s, e);
+}
+/**
+ * Dump the suitable return bytecode for a return statement
+ *
+ */
+public void generateReturnBytecode(BlockScope currentScope, CodeStream codeStream) {
+
+ // output the return bytecode
+ codeStream.return_();
+}
+public void generateStoreSaveValueIfNecessary(BlockScope currentScope, CodeStream codeStream){
+
+ // push receiver
+ codeStream.aload_0();
+
+ // push the 2 parameters of "setResult(Object, Class)"
+ if (this.expression == null || this.expressionType == VoidBinding) { // expressionType == VoidBinding if code snippet is the expression "System.out.println()"
+ // push null
+ codeStream.aconst_null();
+
+ // void.class
+ codeStream.generateClassLiteralAccessForType(VoidBinding, null);
+ } else {
+ // swap with expression
+ int valueTypeID = this.expressionType.id;
+ if (valueTypeID == T_long || valueTypeID == T_double) {
+ codeStream.dup_x2();
+ codeStream.pop();
} else {
- // swap with expression
- int valueTypeID = this.expressionType.id;
- if (valueTypeID == T_long || valueTypeID == T_double) {
- codeStream.dup_x2();
- codeStream.pop();
- } else {
- codeStream.swap();
- }
-
- // generate wrapper if needed
- if (this.expressionType.isBaseType()) {
- codeStream.generateObjectWrapperForType(this.expressionType);
- }
-
- // generate the expression type
- codeStream.generateClassLiteralAccessForType(this.expressionType, null);
+ codeStream.swap();
}
- // generate the invoke virtual to "setResult(Object,Class)"
- codeStream.invokevirtual(this.setResultMethod);
- }
-
- public boolean isSuperAccess() {
- return false;
- }
-
- public boolean isTypeAccess() {
- return false;
- }
-
- public boolean needValue() {
- return true;
- }
-
- public void prepareSaveValueLocation(BlockScope currentScope) {
+ // generate wrapper if needed
+ if (this.expressionType.isBaseType()) {
+ codeStream.generateObjectWrapperForType(this.expressionType);
+ }
- // do nothing: no storage is necessary for snippets
+ // generate the expression type
+ codeStream.generateClassLiteralAccessForType(this.expressionType, null);
}
- public void resolve(BlockScope scope) {
- if (this.expression != null) {
- if ((this.expressionType = this.expression.resolveType(scope)) != null) {
- TypeBinding javaLangClass = scope.getJavaLangClass();
- if (!javaLangClass.isValidBinding()) {
- scope.problemReporter().codeSnippetMissingClass(
- "java.lang.Class",
- this.sourceStart,
- this.sourceEnd);
- return;
- }
- TypeBinding javaLangObject = scope.getJavaLangObject();
- if (!javaLangObject.isValidBinding()) {
- scope.problemReporter().codeSnippetMissingClass(
- "java.lang.Object",
- this.sourceStart,
- this.sourceEnd);
- return;
- }
- TypeBinding[] argumentTypes =
- new TypeBinding[] { javaLangObject, javaLangClass };
- this.setResultMethod =
- scope.getImplicitMethod(SETRESULT_SELECTOR, argumentTypes, this);
- if (!this.setResultMethod.isValidBinding()) {
- scope.problemReporter().codeSnippetMissingMethod(
- ROOT_FULL_CLASS_NAME,
- new String(SETRESULT_SELECTOR),
- new String(SETRESULT_ARGUMENTS),
- this.sourceStart,
- this.sourceEnd);
- return;
- }
- // in constant case, the implicit conversion cannot be left uninitialized
- if (this.expression.constant != NotAConstant) {
- // fake 'no implicit conversion' (the return type is always void)
- this.expression.implicitConversion = this.expression.constant.typeID() << 4;
- }
+ // generate the invoke virtual to "setResult(Object,Class)"
+ codeStream.invokevirtual(this.setResultMethod);
+}
+public boolean isSuperAccess() {
+ return false;
+}
+public boolean isTypeAccess() {
+ return false;
+}
+public boolean needValue(){
+ return true;
+}
+public void prepareSaveValueLocation(BlockScope currentScope){
+
+ // do nothing: no storage is necessary for snippets
+}
+public void resolve(BlockScope scope) {
+ if (this.expression != null) {
+ if ((this.expressionType = this.expression.resolveType(scope)) != null) {
+ TypeBinding javaLangClass = scope.getJavaLangClass();
+ if (!javaLangClass.isValidBinding()) {
+ scope.problemReporter().codeSnippetMissingClass("java.lang.Class", this.sourceStart, this.sourceEnd);
+ return;
+ }
+ TypeBinding javaLangObject = scope.getJavaLangObject();
+ if (!javaLangObject.isValidBinding()) {
+ scope.problemReporter().codeSnippetMissingClass("java.lang.Object", this.sourceStart, this.sourceEnd);
+ return;
+ }
+ TypeBinding[] argumentTypes = new TypeBinding[] {javaLangObject, javaLangClass};
+ this.setResultMethod = scope.getImplicitMethod(SETRESULT_SELECTOR, argumentTypes, this);
+ if (!this.setResultMethod.isValidBinding()) {
+ scope.problemReporter().codeSnippetMissingMethod(ROOT_FULL_CLASS_NAME, new String(SETRESULT_SELECTOR), new String(SETRESULT_ARGUMENTS), this.sourceStart, this.sourceEnd);
+ return;
+ }
+ // in constant case, the implicit conversion cannot be left uninitialized
+ if (this.expression.constant != NotAConstant) {
+ // fake 'no implicit conversion' (the return type is always void)
+ this.expression.implicitConversion = this.expression.constant.typeID() << 4;
}
}
}
-
- public void setDepth(int depth) {
- }
-
- public void setFieldIndex(int depth) {
- }
-
+}
+public void setDepth(int depth) {
+}
+public void setFieldIndex(int depth) {
+}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetScope.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetScope.java
index ef59e5abc1..38466f6d2f 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetScope.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetScope.java
@@ -4,7 +4,7 @@ package org.eclipse.jdt.internal.eval;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
-
+
import org.eclipse.jdt.internal.compiler.lookup.*;
import org.eclipse.jdt.internal.compiler.util.CharOperation;
import org.eclipse.jdt.internal.compiler.util.ObjectVector;
@@ -15,376 +15,382 @@ import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration;
* These accesses inside inner classes are not managed yet.
*/
public class CodeSnippetScope extends BlockScope {
- /**
- * CodeSnippetScope constructor comment.
- * @param kind int
- * @param parent org.eclipse.jdt.internal.compiler.lookup.Scope
- */
- protected CodeSnippetScope(int kind, Scope parent) {
- super(kind, parent);
- }
-
- /**
- * CodeSnippetScope constructor comment.
- * @param parent org.eclipse.jdt.internal.compiler.lookup.BlockScope
- */
- public CodeSnippetScope(BlockScope parent) {
- super(parent);
- }
-
- /**
- * CodeSnippetScope constructor comment.
- * @param parent org.eclipse.jdt.internal.compiler.lookup.BlockScope
- * @param variableCount int
- */
- public CodeSnippetScope(BlockScope parent, int variableCount) {
- super(parent, variableCount);
- }
-
- /* Answer true if the receiver is visible to the type provided by the scope.
- * InvocationSite implements isSuperAccess() to provide additional information
- * if the receiver is protected.
- *
- * NOTE: Cannot invoke this method with a compilation unit scope.
- */
-
- public final boolean canBeSeenByForCodeSnippet(
- FieldBinding fieldBinding,
- TypeBinding receiverType,
- InvocationSite invocationSite,
- Scope scope) {
- if (fieldBinding.isPublic())
- return true;
-
- ReferenceBinding invocationType = (ReferenceBinding) receiverType;
- if (invocationType == fieldBinding.declaringClass)
- return true;
-
- if (fieldBinding.isProtected()) {
- // answer true if the invocationType is the declaringClass or they are in the same package
- // OR the invocationType is a subclass of the declaringClass
- // AND the receiverType is the invocationType or its subclass
- // OR the field is a static field accessed directly through a type
- if (invocationType == fieldBinding.declaringClass)
- return true;
- if (invocationType.fPackage == fieldBinding.declaringClass.fPackage)
+/**
+ * CodeSnippetScope constructor comment.
+ * @param kind int
+ * @param parent org.eclipse.jdt.internal.compiler.lookup.Scope
+ */
+protected CodeSnippetScope(int kind, Scope parent) {
+ super(kind, parent);
+}
+/**
+ * CodeSnippetScope constructor comment.
+ * @param parent org.eclipse.jdt.internal.compiler.lookup.BlockScope
+ */
+public CodeSnippetScope(BlockScope parent) {
+ super(parent);
+}
+/**
+ * CodeSnippetScope constructor comment.
+ * @param parent org.eclipse.jdt.internal.compiler.lookup.BlockScope
+ * @param variableCount int
+ */
+public CodeSnippetScope(BlockScope parent, int variableCount) {
+ super(parent, variableCount);
+}
+/* Answer true if the receiver is visible to the type provided by the scope.
+* InvocationSite implements isSuperAccess() to provide additional information
+* if the receiver is protected.
+*
+* NOTE: Cannot invoke this method with a compilation unit scope.
+*/
+
+public final boolean canBeSeenByForCodeSnippet(FieldBinding fieldBinding, TypeBinding receiverType, InvocationSite invocationSite, Scope scope) {
+ if (fieldBinding.isPublic()) return true;
+
+ ReferenceBinding invocationType = (ReferenceBinding) receiverType;
+ if (invocationType == fieldBinding.declaringClass) return true;
+
+ if (fieldBinding.isProtected()) {
+ // answer true if the invocationType is the declaringClass or they are in the same package
+ // OR the invocationType is a subclass of the declaringClass
+ // AND the receiverType is the invocationType or its subclass
+ // OR the field is a static field accessed directly through a type
+ if (invocationType == fieldBinding.declaringClass) return true;
+ if (invocationType.fPackage == fieldBinding.declaringClass.fPackage) return true;
+ if (fieldBinding.declaringClass.isSuperclassOf(invocationType)) {
+ if (invocationSite.isSuperAccess()) return true;
+ // receiverType can be an array binding in one case... see if you can change it
+ if (receiverType instanceof ArrayBinding)
+ return false;
+ if (invocationType == receiverType || invocationType.isSuperclassOf((ReferenceBinding) receiverType))
return true;
- if (fieldBinding.declaringClass.isSuperclassOf(invocationType)) {
- if (invocationSite.isSuperAccess())
- return true;
- // receiverType can be an array binding in one case... see if you can change it
- if (receiverType instanceof ArrayBinding)
- return false;
- if (invocationType == receiverType
- || invocationType.isSuperclassOf((ReferenceBinding) receiverType))
- return true;
- if (fieldBinding.isStatic())
- return true; // see 1FMEPDL - return invocationSite.isTypeAccess();
- }
- return false;
+ if (fieldBinding.isStatic())
+ return true; // see 1FMEPDL - return invocationSite.isTypeAccess();
}
+ return false;
+ }
- if (fieldBinding.isPrivate()) {
- // answer true if the receiverType is the declaringClass
- // AND the invocationType and the declaringClass have a common enclosingType
- if (receiverType != fieldBinding.declaringClass)
- return false;
+ if (fieldBinding.isPrivate()) {
+ // answer true if the receiverType is the declaringClass
+ // AND the invocationType and the declaringClass have a common enclosingType
+ if (receiverType != fieldBinding.declaringClass) return false;
- if (invocationType != fieldBinding.declaringClass) {
- ReferenceBinding outerInvocationType = invocationType;
- ReferenceBinding temp = outerInvocationType.enclosingType();
- while (temp != null) {
- outerInvocationType = temp;
- temp = temp.enclosingType();
- }
+ if (invocationType != fieldBinding.declaringClass) {
+ ReferenceBinding outerInvocationType = invocationType;
+ ReferenceBinding temp = outerInvocationType.enclosingType();
+ while (temp != null) {
+ outerInvocationType = temp;
+ temp = temp.enclosingType();
+ }
- ReferenceBinding outerDeclaringClass = fieldBinding.declaringClass;
- temp = outerDeclaringClass.enclosingType();
- while (temp != null) {
- outerDeclaringClass = temp;
- temp = temp.enclosingType();
- }
- if (outerInvocationType != outerDeclaringClass)
- return false;
+ ReferenceBinding outerDeclaringClass = fieldBinding.declaringClass;
+ temp = outerDeclaringClass.enclosingType();
+ while (temp != null) {
+ outerDeclaringClass = temp;
+ temp = temp.enclosingType();
}
- return true;
+ if (outerInvocationType != outerDeclaringClass) return false;
}
-
- // isDefault()
- if (invocationType.fPackage != fieldBinding.declaringClass.fPackage)
- return false;
-
- // receiverType can be an array binding in one case... see if you can change it
- if (receiverType instanceof ArrayBinding)
- return false;
- ReferenceBinding type = (ReferenceBinding) receiverType;
- PackageBinding declaringPackage = fieldBinding.declaringClass.fPackage;
- do {
- if (fieldBinding.declaringClass == type)
- return true;
- if (declaringPackage != type.fPackage)
- return false;
- } while ((type = type.superclass()) != null);
- return false;
+ return true;
}
- /* Answer true if the receiver is visible to the type provided by the scope.
- * InvocationSite implements isSuperAccess() to provide additional information
- * if the receiver is protected.
- *
- * NOTE: Cannot invoke this method with a compilation unit scope.
- */
- public final boolean canBeSeenByForCodeSnippet(
- MethodBinding methodBinding,
- TypeBinding receiverType,
- InvocationSite invocationSite,
- Scope scope) {
- if (methodBinding.isPublic())
- return true;
-
- ReferenceBinding invocationType = (ReferenceBinding) receiverType;
- if (invocationType == methodBinding.declaringClass
- && invocationType == receiverType)
- return true;
-
- if (methodBinding.isProtected()) {
- // answer true if the invocationType is the declaringClass or they are in the same package
- // OR the invocationType is a subclass of the declaringClass
- // AND the receiverType is the invocationType or its subclass
- // OR the method is a static method accessed directly through a type
- if (invocationType == methodBinding.declaringClass)
- return true;
- if (invocationType.fPackage == methodBinding.declaringClass.fPackage)
- return true;
- if (methodBinding.declaringClass.isSuperclassOf(invocationType)) {
- if (invocationSite.isSuperAccess())
- return true;
- // receiverType can be an array binding in one case... see if you can change it
- if (receiverType instanceof ArrayBinding)
- return false;
- if (invocationType == receiverType
- || invocationType.isSuperclassOf((ReferenceBinding) receiverType))
- return true;
- if (methodBinding.isStatic())
- return true; // see 1FMEPDL - return invocationSite.isTypeAccess();
- }
- return false;
- }
+ // isDefault()
+ if (invocationType.fPackage != fieldBinding.declaringClass.fPackage) return false;
- if (methodBinding.isPrivate()) {
- // answer true if the receiverType is the declaringClass
- // AND the invocationType and the declaringClass have a common enclosingType
- if (receiverType != methodBinding.declaringClass)
+ // receiverType can be an array binding in one case... see if you can change it
+ if (receiverType instanceof ArrayBinding)
+ return false;
+ ReferenceBinding type = (ReferenceBinding) receiverType;
+ PackageBinding declaringPackage = fieldBinding.declaringClass.fPackage;
+ do {
+ if (fieldBinding.declaringClass == type) return true;
+ if (declaringPackage != type.fPackage) return false;
+ } while ((type = type.superclass()) != null);
+ return false;
+}
+/* Answer true if the receiver is visible to the type provided by the scope.
+* InvocationSite implements isSuperAccess() to provide additional information
+* if the receiver is protected.
+*
+* NOTE: Cannot invoke this method with a compilation unit scope.
+*/
+public final boolean canBeSeenByForCodeSnippet(MethodBinding methodBinding, TypeBinding receiverType, InvocationSite invocationSite, Scope scope) {
+ if (methodBinding.isPublic()) return true;
+
+ ReferenceBinding invocationType = (ReferenceBinding) receiverType;
+ if (invocationType == methodBinding.declaringClass && invocationType == receiverType) return true;
+
+ if (methodBinding.isProtected()) {
+ // answer true if the invocationType is the declaringClass or they are in the same package
+ // OR the invocationType is a subclass of the declaringClass
+ // AND the receiverType is the invocationType or its subclass
+ // OR the method is a static method accessed directly through a type
+ if (invocationType == methodBinding.declaringClass) return true;
+ if (invocationType.fPackage == methodBinding.declaringClass.fPackage) return true;
+ if (methodBinding.declaringClass.isSuperclassOf(invocationType)) {
+ if (invocationSite.isSuperAccess()) return true;
+ // receiverType can be an array binding in one case... see if you can change it
+ if (receiverType instanceof ArrayBinding)
return false;
-
- if (invocationType != methodBinding.declaringClass) {
- ReferenceBinding outerInvocationType = invocationType;
- ReferenceBinding temp = outerInvocationType.enclosingType();
- while (temp != null) {
- outerInvocationType = temp;
- temp = temp.enclosingType();
- }
-
- ReferenceBinding outerDeclaringClass = methodBinding.declaringClass;
- temp = outerDeclaringClass.enclosingType();
- while (temp != null) {
- outerDeclaringClass = temp;
- temp = temp.enclosingType();
- }
- if (outerInvocationType != outerDeclaringClass)
- return false;
- }
- return true;
- }
-
- // isDefault()
- if (invocationType.fPackage != methodBinding.declaringClass.fPackage)
- return false;
-
- // receiverType can be an array binding in one case... see if you can change it
- if (receiverType instanceof ArrayBinding)
- return false;
- ReferenceBinding type = (ReferenceBinding) receiverType;
- PackageBinding declaringPackage = methodBinding.declaringClass.fPackage;
- do {
- if (methodBinding.declaringClass == type)
+ if (invocationType == receiverType || invocationType.isSuperclassOf((ReferenceBinding) receiverType))
return true;
- if (declaringPackage != type.fPackage)
- return false;
- } while ((type = type.superclass()) != null);
+ if (methodBinding.isStatic())
+ return true; // see 1FMEPDL - return invocationSite.isTypeAccess();
+ }
return false;
}
- /* Answer true if the receiver is visible to the type provided by the scope.
- * InvocationSite implements isSuperAccess() to provide additional information
- * if the receiver is protected.
- *
- * NOTE: Cannot invoke this method with a compilation unit scope.
- */
-
- public final boolean canBeSeenByForCodeSnippet(
- ReferenceBinding referenceBinding,
- ReferenceBinding receiverType) {
- if (referenceBinding.isPublic())
- return true;
-
- if (receiverType == referenceBinding)
- return true;
-
- if (referenceBinding.isProtected()) {
- // answer true if the receiver (or its enclosing type) is the superclass
- // of the receiverType or in the same package
- return receiverType.fPackage == referenceBinding.fPackage
- || referenceBinding.isSuperclassOf(receiverType)
- || referenceBinding.enclosingType().isSuperclassOf(receiverType);
- // protected types always have an enclosing one
- }
+ if (methodBinding.isPrivate()) {
+ // answer true if the receiverType is the declaringClass
+ // AND the invocationType and the declaringClass have a common enclosingType
+ if (receiverType != methodBinding.declaringClass) return false;
- if (referenceBinding.isPrivate()) {
- // answer true if the receiver and the receiverType have a common enclosingType
- // already know they are not the identical type
- ReferenceBinding outerInvocationType = receiverType;
+ if (invocationType != methodBinding.declaringClass) {
+ ReferenceBinding outerInvocationType = invocationType;
ReferenceBinding temp = outerInvocationType.enclosingType();
while (temp != null) {
outerInvocationType = temp;
temp = temp.enclosingType();
}
- ReferenceBinding outerDeclaringClass = referenceBinding;
+ ReferenceBinding outerDeclaringClass = methodBinding.declaringClass;
temp = outerDeclaringClass.enclosingType();
while (temp != null) {
outerDeclaringClass = temp;
temp = temp.enclosingType();
}
- return outerInvocationType == outerDeclaringClass;
+ if (outerInvocationType != outerDeclaringClass) return false;
}
+ return true;
+ }
+
+ // isDefault()
+ if (invocationType.fPackage != methodBinding.declaringClass.fPackage) return false;
- // isDefault()
- return receiverType.fPackage == referenceBinding.fPackage;
+ // receiverType can be an array binding in one case... see if you can change it
+ if (receiverType instanceof ArrayBinding)
+ return false;
+ ReferenceBinding type = (ReferenceBinding) receiverType;
+ PackageBinding declaringPackage = methodBinding.declaringClass.fPackage;
+ do {
+ if (methodBinding.declaringClass == type) return true;
+ if (declaringPackage != type.fPackage) return false;
+ } while ((type = type.superclass()) != null);
+ return false;
+}
+/* Answer true if the receiver is visible to the type provided by the scope.
+* InvocationSite implements isSuperAccess() to provide additional information
+* if the receiver is protected.
+*
+* NOTE: Cannot invoke this method with a compilation unit scope.
+*/
+
+public final boolean canBeSeenByForCodeSnippet(ReferenceBinding referenceBinding, ReferenceBinding receiverType) {
+ if (referenceBinding.isPublic()) return true;
+
+ if (receiverType == referenceBinding) return true;
+
+ if (referenceBinding.isProtected()) {
+ // answer true if the receiver (or its enclosing type) is the superclass
+ // of the receiverType or in the same package
+ return receiverType.fPackage == referenceBinding.fPackage
+ || referenceBinding.isSuperclassOf(receiverType)
+ || referenceBinding.enclosingType().isSuperclassOf(receiverType); // protected types always have an enclosing one
}
- // Internal use only
- public MethodBinding findExactMethod(
- ReferenceBinding receiverType,
- char[] selector,
- TypeBinding[] argumentTypes,
- InvocationSite invocationSite) {
- compilationUnitScope().addTypeReference(receiverType);
- MethodBinding exactMethod =
- receiverType.getExactMethod(selector, argumentTypes);
- if (exactMethod != null) {
- compilationUnitScope().addTypeReferences(exactMethod.thrownExceptions);
- if (receiverType.isInterface()
- || canBeSeenByForCodeSnippet(exactMethod, receiverType, invocationSite, this))
- return exactMethod;
+ if (referenceBinding.isPrivate()) {
+ // answer true if the receiver and the receiverType have a common enclosingType
+ // already know they are not the identical type
+ ReferenceBinding outerInvocationType = receiverType;
+ ReferenceBinding temp = outerInvocationType.enclosingType();
+ while (temp != null) {
+ outerInvocationType = temp;
+ temp = temp.enclosingType();
}
- return null;
+
+ ReferenceBinding outerDeclaringClass = referenceBinding;
+ temp = outerDeclaringClass.enclosingType();
+ while (temp != null) {
+ outerDeclaringClass = temp;
+ temp = temp.enclosingType();
+ }
+ return outerInvocationType == outerDeclaringClass;
}
- // Internal use only
+ // isDefault()
+ return receiverType.fPackage == referenceBinding.fPackage;
+}
+// Internal use only
+public MethodBinding findExactMethod(ReferenceBinding receiverType, char[] selector, TypeBinding[] argumentTypes, InvocationSite invocationSite) {
+ compilationUnitScope().addTypeReference(receiverType);
+ MethodBinding exactMethod = receiverType.getExactMethod(selector, argumentTypes);
+ if (exactMethod != null){
+ compilationUnitScope().addTypeReferences(exactMethod.thrownExceptions);
+ if (receiverType.isInterface() || canBeSeenByForCodeSnippet(exactMethod, receiverType, invocationSite, this))
+ return exactMethod;
+ }
+ return null;
+}
+// Internal use only
- /* Answer the field binding that corresponds to fieldName.
- Start the lookup at the receiverType.
- InvocationSite implements
- isSuperAccess(); this is used to determine if the discovered field is visible.
- Only fields defined by the receiverType or its supertypes are answered;
- a field of an enclosing type will not be found using this API.
-
- If no visible field is discovered, null is answered.
- */
-
- public FieldBinding findFieldForCodeSnippet(
- TypeBinding receiverType,
- char[] fieldName,
- InvocationSite invocationSite) {
- if (receiverType.isBaseType())
- return null;
- if (receiverType.isArrayType()) {
- if (CharOperation.equals(fieldName, LENGTH))
- return ArrayBinding.LengthField;
- return null;
- }
+/* Answer the field binding that corresponds to fieldName.
+ Start the lookup at the receiverType.
+ InvocationSite implements
+ isSuperAccess(); this is used to determine if the discovered field is visible.
+ Only fields defined by the receiverType or its supertypes are answered;
+ a field of an enclosing type will not be found using this API.
+
+ If no visible field is discovered, null is answered.
+*/
+
+public FieldBinding findFieldForCodeSnippet(TypeBinding receiverType, char[] fieldName, InvocationSite invocationSite) {
+ if (receiverType.isBaseType())
+ return null;
+ if (receiverType.isArrayType()) {
+ if (CharOperation.equals(fieldName, LENGTH))
+ return ArrayBinding.LengthField;
+ return null;
+ }
- ReferenceBinding currentType = (ReferenceBinding) receiverType;
- if (!currentType.canBeSeenBy(this))
+ ReferenceBinding currentType = (ReferenceBinding) receiverType;
+ if (!currentType.canBeSeenBy(this))
+ return new ProblemFieldBinding(fieldName, NotVisible); // *** Need a new problem id - TypeNotVisible?
+
+ compilationUnitScope().addTypeReference(currentType);
+ FieldBinding field = currentType.getField(fieldName);
+ if (field != null) {
+ if (canBeSeenByForCodeSnippet(field, currentType, invocationSite, this))
+ return field;
+ else
return new ProblemFieldBinding(fieldName, NotVisible);
- // *** Need a new problem id - TypeNotVisible?
+ }
- compilationUnitScope().addTypeReference(currentType);
- FieldBinding field = currentType.getField(fieldName);
- if (field != null) {
- if (canBeSeenByForCodeSnippet(field, currentType, invocationSite, this))
- return field;
- else
- return new ProblemFieldBinding(fieldName, NotVisible);
+ // collect all superinterfaces of receiverType until the field is found in a supertype
+ ReferenceBinding[][] interfacesToVisit = null;
+ int lastPosition = -1;
+ FieldBinding visibleField = null;
+ boolean keepLooking = true;
+ boolean notVisible = false; // we could hold onto the not visible field for extra error reporting
+ while (keepLooking) {
+ ReferenceBinding[] itsInterfaces = currentType.superInterfaces();
+ if (itsInterfaces != NoSuperInterfaces) {
+ if (interfacesToVisit == null)
+ interfacesToVisit = new ReferenceBinding[5][];
+ if (++lastPosition == interfacesToVisit.length)
+ System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition);
+ interfacesToVisit[lastPosition] = itsInterfaces;
}
-
- // collect all superinterfaces of receiverType until the field is found in a supertype
- ReferenceBinding[][] interfacesToVisit = null;
- int lastPosition = -1;
- FieldBinding visibleField = null;
- boolean keepLooking = true;
- boolean notVisible = false;
- // we could hold onto the not visible field for extra error reporting
- while (keepLooking) {
- ReferenceBinding[] itsInterfaces = currentType.superInterfaces();
- if (itsInterfaces != NoSuperInterfaces) {
- if (interfacesToVisit == null)
- interfacesToVisit = new ReferenceBinding[5][];
- if (++lastPosition == interfacesToVisit.length)
- System.arraycopy(
- interfacesToVisit,
- 0,
- interfacesToVisit = new ReferenceBinding[lastPosition * 2][],
- 0,
- lastPosition);
- interfacesToVisit[lastPosition] = itsInterfaces;
+ if ((currentType = currentType.superclass()) == null)
+ break;
+
+ if ((field = currentType.getField(fieldName)) != null) {
+ keepLooking = false;
+ if (canBeSeenByForCodeSnippet(field, receiverType, invocationSite, this)) {
+ if (visibleField == null)
+ visibleField = field;
+ else
+ return new ProblemFieldBinding(fieldName, Ambiguous);
+ } else {
+ notVisible = true;
}
- if ((currentType = currentType.superclass()) == null)
- break;
-
- if ((field = currentType.getField(fieldName)) != null) {
- keepLooking = false;
- if (canBeSeenByForCodeSnippet(field, receiverType, invocationSite, this)) {
- if (visibleField == null)
- visibleField = field;
- else
- return new ProblemFieldBinding(fieldName, Ambiguous);
- } else {
- notVisible = true;
+ }
+ }
+
+ // walk all visible interfaces to find ambiguous references
+ if (interfacesToVisit != null) {
+ ProblemFieldBinding ambiguous = null;
+ done : for (int i = 0; i <= lastPosition; i++) {
+ ReferenceBinding[] interfaces = interfacesToVisit[i];
+ for (int j = 0, length = interfaces.length; j < length; j++) {
+ ReferenceBinding anInterface = interfaces[j];
+ if ((anInterface.tagBits & InterfaceVisited) == 0) { // if interface as not already been visited
+ anInterface.tagBits |= InterfaceVisited;
+ if ((field = anInterface.getField(fieldName)) != null) {
+ if (visibleField == null) {
+ visibleField = field;
+ } else {
+ ambiguous = new ProblemFieldBinding(fieldName, Ambiguous);
+ break done;
+ }
+ } else {
+ ReferenceBinding[] itsInterfaces = anInterface.superInterfaces();
+ if (itsInterfaces != NoSuperInterfaces) {
+ if (++lastPosition == interfacesToVisit.length)
+ System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition);
+ interfacesToVisit[lastPosition] = itsInterfaces;
+ }
+ }
}
}
}
- // walk all visible interfaces to find ambiguous references
- if (interfacesToVisit != null) {
- ProblemFieldBinding ambiguous = null;
- done : for (int i = 0; i <= lastPosition; i++) {
+ // bit reinitialization
+ for (int i = 0; i <= lastPosition; i++) {
+ ReferenceBinding[] interfaces = interfacesToVisit[i];
+ for (int j = 0, length = interfaces.length; j < length; j++)
+ interfaces[j].tagBits &= ~InterfaceVisited;
+ }
+ if (ambiguous != null) return ambiguous;
+ }
+
+ if (visibleField != null)
+ return visibleField;
+ if (notVisible)
+ return new ProblemFieldBinding(fieldName, NotVisible);
+ return null;
+}
+// Internal use only
+public MethodBinding findMethod(ReferenceBinding receiverType, char[] selector, TypeBinding[] argumentTypes, InvocationSite invocationSite) {
+ ReferenceBinding currentType = receiverType;
+ MethodBinding matchingMethod = null;
+ ObjectVector found = null;
+
+ compilationUnitScope().addTypeReference(currentType);
+ if (currentType.isInterface()) {
+ MethodBinding[] currentMethods = currentType.getMethods(selector);
+ int currentLength = currentMethods.length;
+ if (currentLength == 1) {
+ matchingMethod = currentMethods[0];
+ } else if (currentLength > 1) {
+ found = new ObjectVector();
+ for (int f = 0; f < currentLength; f++)
+ found.add(currentMethods[f]);
+ }
+
+ ReferenceBinding[] itsInterfaces = currentType.superInterfaces();
+ if (itsInterfaces != NoSuperInterfaces) {
+ ReferenceBinding[][] interfacesToVisit = new ReferenceBinding[5][];
+ int lastPosition = -1;
+ if (++lastPosition == interfacesToVisit.length)
+ System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition);
+ interfacesToVisit[lastPosition] = itsInterfaces;
+
+ for (int i = 0; i <= lastPosition; i++) {
ReferenceBinding[] interfaces = interfacesToVisit[i];
for (int j = 0, length = interfaces.length; j < length; j++) {
- ReferenceBinding anInterface = interfaces[j];
- if ((anInterface.tagBits & InterfaceVisited) == 0) {
- // if interface as not already been visited
- anInterface.tagBits |= InterfaceVisited;
- if ((field = anInterface.getField(fieldName)) != null) {
- if (visibleField == null) {
- visibleField = field;
- } else {
- ambiguous = new ProblemFieldBinding(fieldName, Ambiguous);
- break done;
- }
- } else {
- ReferenceBinding[] itsInterfaces = anInterface.superInterfaces();
- if (itsInterfaces != NoSuperInterfaces) {
- if (++lastPosition == interfacesToVisit.length)
- System.arraycopy(
- interfacesToVisit,
- 0,
- interfacesToVisit = new ReferenceBinding[lastPosition * 2][],
- 0,
- lastPosition);
- interfacesToVisit[lastPosition] = itsInterfaces;
+ currentType = interfaces[j];
+ if ((currentType.tagBits & InterfaceVisited) == 0) { // if interface as not already been visited
+ currentType.tagBits |= InterfaceVisited;
+
+ currentMethods = currentType.getMethods(selector);
+ if ((currentLength = currentMethods.length) == 1 && matchingMethod == null && found == null) {
+ matchingMethod = currentMethods[0];
+ } else if (currentLength > 0) {
+ if (found == null) {
+ found = new ObjectVector();
+ if (matchingMethod != null)
+ found.add(matchingMethod);
}
+ for (int f = 0; f < currentLength; f++)
+ found.add(currentMethods[f]);
+ }
+
+ itsInterfaces = currentType.superInterfaces();
+ if (itsInterfaces != NoSuperInterfaces) {
+ if (++lastPosition == interfacesToVisit.length)
+ System.arraycopy(interfacesToVisit, 0, interfacesToVisit = new ReferenceBinding[lastPosition * 2][], 0, lastPosition);
+ interfacesToVisit[lastPosition] = itsInterfaces;
}
}
}
@@ -396,573 +402,346 @@ public class CodeSnippetScope extends BlockScope {
for (int j = 0, length = interfaces.length; j < length; j++)
interfaces[j].tagBits &= ~InterfaceVisited;
}
- if (ambiguous != null)
- return ambiguous;
}
-
- if (visibleField != null)
- return visibleField;
- if (notVisible)
- return new ProblemFieldBinding(fieldName, NotVisible);
- return null;
+ currentType = (matchingMethod == null && found == null) ? getJavaLangObject() : null;
}
- // Internal use only
- public MethodBinding findMethod(
- ReferenceBinding receiverType,
- char[] selector,
- TypeBinding[] argumentTypes,
- InvocationSite invocationSite) {
- ReferenceBinding currentType = receiverType;
- MethodBinding matchingMethod = null;
- ObjectVector found = null;
-
- compilationUnitScope().addTypeReference(currentType);
- if (currentType.isInterface()) {
- MethodBinding[] currentMethods = currentType.getMethods(selector);
- int currentLength = currentMethods.length;
- if (currentLength == 1) {
- matchingMethod = currentMethods[0];
- } else
- if (currentLength > 1) {
- found = new ObjectVector();
- for (int f = 0; f < currentLength; f++)
- found.add(currentMethods[f]);
- }
-
- ReferenceBinding[] itsInterfaces = currentType.superInterfaces();
- if (itsInterfaces != NoSuperInterfaces) {
- ReferenceBinding[][] interfacesToVisit = new ReferenceBinding[5][];
- int lastPosition = -1;
- if (++lastPosition == interfacesToVisit.length)
- System.arraycopy(
- interfacesToVisit,
- 0,
- interfacesToVisit = new ReferenceBinding[lastPosition * 2][],
- 0,
- lastPosition);
- interfacesToVisit[lastPosition] = itsInterfaces;
-
- for (int i = 0; i <= lastPosition; i++) {
- ReferenceBinding[] interfaces = interfacesToVisit[i];
- for (int j = 0, length = interfaces.length; j < length; j++) {
- currentType = interfaces[j];
- if ((currentType.tagBits & InterfaceVisited) == 0) {
- // if interface as not already been visited
- currentType.tagBits |= InterfaceVisited;
-
- currentMethods = currentType.getMethods(selector);
- if ((currentLength = currentMethods.length) == 1
- && matchingMethod == null
- && found == null) {
- matchingMethod = currentMethods[0];
- } else
- if (currentLength > 0) {
- if (found == null) {
- found = new ObjectVector();
- if (matchingMethod != null)
- found.add(matchingMethod);
- }
- for (int f = 0; f < currentLength; f++)
- found.add(currentMethods[f]);
- }
-
- itsInterfaces = currentType.superInterfaces();
- if (itsInterfaces != NoSuperInterfaces) {
- if (++lastPosition == interfacesToVisit.length)
- System.arraycopy(
- interfacesToVisit,
- 0,
- interfacesToVisit = new ReferenceBinding[lastPosition * 2][],
- 0,
- lastPosition);
- interfacesToVisit[lastPosition] = itsInterfaces;
- }
- }
- }
- }
-
- // bit reinitialization
- for (int i = 0; i <= lastPosition; i++) {
- ReferenceBinding[] interfaces = interfacesToVisit[i];
- for (int j = 0, length = interfaces.length; j < length; j++)
- interfaces[j].tagBits &= ~InterfaceVisited;
- }
+ while (currentType != null) {
+ MethodBinding[] currentMethods = currentType.getMethods(selector);
+ int currentLength = currentMethods.length;
+ if (currentLength == 1 && matchingMethod == null && found == null) {
+ matchingMethod = currentMethods[0];
+ } else if (currentLength > 0) {
+ if (found == null) {
+ found = new ObjectVector();
+ if (matchingMethod != null)
+ found.add(matchingMethod);
}
- currentType =
- (matchingMethod == null && found == null) ? getJavaLangObject() : null;
+ for (int f = 0; f < currentLength; f++)
+ found.add(currentMethods[f]);
}
+ currentType = currentType.superclass();
+ }
- while (currentType != null) {
- MethodBinding[] currentMethods = currentType.getMethods(selector);
- int currentLength = currentMethods.length;
- if (currentLength == 1 && matchingMethod == null && found == null) {
- matchingMethod = currentMethods[0];
- } else
- if (currentLength > 0) {
- if (found == null) {
- found = new ObjectVector();
- if (matchingMethod != null)
- found.add(matchingMethod);
- }
- for (int f = 0; f < currentLength; f++)
- found.add(currentMethods[f]);
- }
- currentType = currentType.superclass();
- }
+ if (found == null)
+ return matchingMethod; // may be null - have not checked arg types or visibility
- if (found == null)
- return matchingMethod;
- // may be null - have not checked arg types or visibility
-
- int foundSize = found.size;
- MethodBinding[] compatible = new MethodBinding[foundSize];
- int compatibleIndex = 0;
- for (int i = 0; i < foundSize; i++) {
- MethodBinding methodBinding = (MethodBinding) found.elementAt(i);
- if (areParametersAssignable(methodBinding.parameters, argumentTypes))
- compatible[compatibleIndex++] = methodBinding;
- }
- if (compatibleIndex == 1)
- return compatible[0]; // have not checked visibility
- if (compatibleIndex == 0)
- return (MethodBinding) found.elementAt(0);
- // no good match so just use the first one found
-
- MethodBinding[] visible = new MethodBinding[compatibleIndex];
- int visibleIndex = 0;
- for (int i = 0; i < compatibleIndex; i++) {
- MethodBinding methodBinding = compatible[i];
- if (canBeSeenByForCodeSnippet(methodBinding,
- receiverType,
- invocationSite,
- this))
- visible[visibleIndex++] = methodBinding;
- }
- if (visibleIndex == 1) {
- compilationUnitScope().addTypeReferences(visible[0].thrownExceptions);
- return visible[0];
- }
- if (visibleIndex == 0)
- return new ProblemMethodBinding(
- compatible[0].selector,
- argumentTypes,
- compatible[0].declaringClass,
- NotVisible);
- if (visible[0].declaringClass.isClass())
- return mostSpecificClassMethodBinding(visible, visibleIndex);
- else
- return mostSpecificInterfaceMethodBinding(visible, visibleIndex);
+ int foundSize = found.size;
+ MethodBinding[] compatible = new MethodBinding[foundSize];
+ int compatibleIndex = 0;
+ for (int i = 0; i < foundSize; i++) {
+ MethodBinding methodBinding = (MethodBinding) found.elementAt(i);
+ if (areParametersAssignable(methodBinding.parameters, argumentTypes))
+ compatible[compatibleIndex++] = methodBinding;
+ }
+ if (compatibleIndex == 1)
+ return compatible[0]; // have not checked visibility
+ if (compatibleIndex == 0)
+ return (MethodBinding) found.elementAt(0); // no good match so just use the first one found
+
+ MethodBinding[] visible = new MethodBinding[compatibleIndex];
+ int visibleIndex = 0;
+ for (int i = 0; i < compatibleIndex; i++) {
+ MethodBinding methodBinding = compatible[i];
+ if (canBeSeenByForCodeSnippet(methodBinding, receiverType, invocationSite, this))
+ visible[visibleIndex++] = methodBinding;
+ }
+ if (visibleIndex == 1){
+ compilationUnitScope().addTypeReferences(visible[0].thrownExceptions);
+ return visible[0];
+ }
+ if (visibleIndex == 0)
+ return new ProblemMethodBinding(compatible[0].selector, argumentTypes, compatible[0].declaringClass, NotVisible);
+ if (visible[0].declaringClass.isClass())
+ return mostSpecificClassMethodBinding(visible, visibleIndex);
+ else
+ return mostSpecificInterfaceMethodBinding(visible, visibleIndex);
+}
+// Internal use only
+public MethodBinding findMethodForArray(ArrayBinding receiverType, char[] selector, TypeBinding[] argumentTypes, InvocationSite invocationSite) {
+ ReferenceBinding object = getJavaLangObject();
+ MethodBinding methodBinding = object.getExactMethod(selector, argumentTypes);
+ if (methodBinding != null) {
+ // handle the method clone() specially... cannot be protected or throw exceptions
+ if (argumentTypes == NoParameters && CharOperation.equals(selector, CLONE))
+ return new MethodBinding((methodBinding.modifiers ^ AccProtected) | AccPublic, CLONE, methodBinding.returnType, argumentTypes, null, object);
+ if (canBeSeenByForCodeSnippet(methodBinding, receiverType, invocationSite, this))
+ return methodBinding;
}
- // Internal use only
- public MethodBinding findMethodForArray(
- ArrayBinding receiverType,
- char[] selector,
- TypeBinding[] argumentTypes,
- InvocationSite invocationSite) {
- ReferenceBinding object = getJavaLangObject();
- MethodBinding methodBinding = object.getExactMethod(selector, argumentTypes);
- if (methodBinding != null) {
- // handle the method clone() specially... cannot be protected or throw exceptions
- if (argumentTypes == NoParameters && CharOperation.equals(selector, CLONE))
- return new MethodBinding(
- (methodBinding.modifiers ^ AccProtected) | AccPublic,
- CLONE,
- methodBinding.returnType,
- argumentTypes,
- null,
- object);
- if (canBeSeenByForCodeSnippet(methodBinding,
- receiverType,
- invocationSite,
- this))
- return methodBinding;
- }
-
- // answers closest approximation, may not check argumentTypes or visibility
- methodBinding = findMethod(object, selector, argumentTypes, invocationSite);
- if (methodBinding == null)
- return new ProblemMethodBinding(selector, argumentTypes, NotFound);
- if (methodBinding.isValidBinding()) {
- if (!areParametersAssignable(methodBinding.parameters, argumentTypes))
- return new ProblemMethodBinding(
- methodBinding,
- selector,
- argumentTypes,
- NotFound);
- if (!canBeSeenByForCodeSnippet(methodBinding,
- receiverType,
- invocationSite,
- this))
- return new ProblemMethodBinding(
- selector,
- argumentTypes,
- methodBinding.declaringClass,
- NotVisible);
- }
- return methodBinding;
+ // answers closest approximation, may not check argumentTypes or visibility
+ methodBinding = findMethod(object, selector, argumentTypes, invocationSite);
+ if (methodBinding == null)
+ return new ProblemMethodBinding(selector, argumentTypes, NotFound);
+ if (methodBinding.isValidBinding()) {
+ if (!areParametersAssignable(methodBinding.parameters, argumentTypes))
+ return new ProblemMethodBinding(methodBinding, selector, argumentTypes, NotFound);
+ if (!canBeSeenByForCodeSnippet(methodBinding, receiverType, invocationSite, this))
+ return new ProblemMethodBinding(selector, argumentTypes, methodBinding.declaringClass, NotVisible);
}
+ return methodBinding;
+}
+/* API
+ flag is a mask of the following values VARIABLE (= FIELD or LOCAL), TYPE.
+ Only bindings corresponding to the mask will be answered.
- /* API
- flag is a mask of the following values VARIABLE (= FIELD or LOCAL), TYPE.
- Only bindings corresponding to the mask will be answered.
-
- if the VARIABLE mask is set then
- If the first name provided is a field (or local) then the field (or local) is answered
- Otherwise, package names and type names are consumed until a field is found.
- In this case, the field is answered.
-
- if the TYPE mask is set,
- package names and type names are consumed until the end of the input.
- Only if all of the input is consumed is the type answered
-
- All other conditions are errors, and a problem binding is returned.
-
- NOTE: If a problem binding is returned, senders should extract the compound name
- from the binding & not assume the problem applies to the entire compoundName.
-
- The VARIABLE mask has precedence over the TYPE mask.
-
- InvocationSite implements
- isSuperAccess(); this is used to determine if the discovered field is visible.
- setFieldIndex(int); this is used to record the number of names that were consumed.
-
- For example, getBinding({"foo","y","q", VARIABLE, site) will answer
- the binding for the field or local named "foo" (or an error binding if none exists).
- In addition, setFieldIndex(1) will be sent to the invocation site.
- If a type named "foo" exists, it will not be detected (and an error binding will be answered)
+ if the VARIABLE mask is set then
+ If the first name provided is a field (or local) then the field (or local) is answered
+ Otherwise, package names and type names are consumed until a field is found.
+ In this case, the field is answered.
+
+ if the TYPE mask is set,
+ package names and type names are consumed until the end of the input.
+ Only if all of the input is consumed is the type answered
+
+ All other conditions are errors, and a problem binding is returned.
- IMPORTANT NOTE: This method is written under the assumption that compoundName is longer than length 1.
- */
-
- public Binding getBinding(
- char[][] compoundName,
- int mask,
- InvocationSite invocationSite,
- ReferenceBinding receiverType) {
- Binding binding =
- getBinding(compoundName[0], mask | TYPE | PACKAGE, invocationSite);
- invocationSite.setFieldIndex(1);
- if (!binding.isValidBinding() || binding instanceof VariableBinding)
- return binding;
-
- int length = compoundName.length;
- int currentIndex = 1;
- foundType : if (binding instanceof PackageBinding) {
- PackageBinding packageBinding = (PackageBinding) binding;
- compilationUnitScope().addNamespaceReference(packageBinding);
+ NOTE: If a problem binding is returned, senders should extract the compound name
+ from the binding & not assume the problem applies to the entire compoundName.
- while (currentIndex < length) {
- binding = packageBinding.getTypeOrPackage(compoundName[currentIndex++]);
- invocationSite.setFieldIndex(currentIndex);
- if (binding == null) {
- if (currentIndex == length)
- // must be a type if its the last name, otherwise we have no idea if its a package or type
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- NotFound);
- else
- return new ProblemBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- NotFound);
- }
- if (binding instanceof ReferenceBinding) {
- if (!binding.isValidBinding())
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- binding.problemId());
- compilationUnitScope().addTypeReference((ReferenceBinding) binding);
- if (!this.canBeSeenByForCodeSnippet((ReferenceBinding) binding, receiverType))
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- NotVisible);
- break foundType;
- }
- packageBinding = (PackageBinding) binding;
- compilationUnitScope().addNamespaceReference(packageBinding);
- }
+ The VARIABLE mask has precedence over the TYPE mask.
- // It is illegal to request a PACKAGE from this method.
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- NotFound);
- }
+ InvocationSite implements
+ isSuperAccess(); this is used to determine if the discovered field is visible.
+ setFieldIndex(int); this is used to record the number of names that were consumed.
+
+ For example, getBinding({"foo","y","q", VARIABLE, site) will answer
+ the binding for the field or local named "foo" (or an error binding if none exists).
+ In addition, setFieldIndex(1) will be sent to the invocation site.
+ If a type named "foo" exists, it will not be detected (and an error binding will be answered)
+
+ IMPORTANT NOTE: This method is written under the assumption that compoundName is longer than length 1.
+*/
+
+public Binding getBinding(char[][] compoundName, int mask, InvocationSite invocationSite, ReferenceBinding receiverType) {
+ Binding binding = getBinding(compoundName[0], mask | TYPE | PACKAGE, invocationSite);
+ invocationSite.setFieldIndex(1);
+ if (!binding.isValidBinding() || binding instanceof VariableBinding)
+ return binding;
+
+ int length = compoundName.length;
+ int currentIndex = 1;
+ foundType: if (binding instanceof PackageBinding) {
+ PackageBinding packageBinding = (PackageBinding) binding;
+ compilationUnitScope().addNamespaceReference(packageBinding);
- // know binding is now a ReferenceBinding
while (currentIndex < length) {
- ReferenceBinding typeBinding = (ReferenceBinding) binding;
- char[] nextName = compoundName[currentIndex++];
+ binding = packageBinding.getTypeOrPackage(compoundName[currentIndex++]);
invocationSite.setFieldIndex(currentIndex);
- if ((binding = findFieldForCodeSnippet(typeBinding, nextName, invocationSite))
- != null) {
- if (!binding.isValidBinding())
- return new ProblemFieldBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- binding.problemId());
- break; // binding is now a field
- }
- if ((binding = findMemberType(nextName, typeBinding)) == null)
- return new ProblemBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- typeBinding,
- NotFound);
- if (!binding.isValidBinding())
- return new ProblemReferenceBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- binding.problemId());
- }
-
- if ((mask & FIELD) != 0
- && (binding instanceof FieldBinding)) {
- // was looking for a field and found a field
- FieldBinding field = (FieldBinding) binding;
- if (!field.isStatic())
- return new ProblemFieldBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- NonStaticReferenceInStaticContext);
- return binding;
- }
- if ((mask & TYPE) != 0
- && (binding instanceof ReferenceBinding)) {
- // was looking for a type and found a type
- return binding;
+ if (binding == null) {
+ if (currentIndex == length) // must be a type if its the last name, otherwise we have no idea if its a package or type
+ return new ProblemReferenceBinding(CharOperation.subarray(compoundName, 0, currentIndex), NotFound);
+ else
+ return new ProblemBinding(CharOperation.subarray(compoundName, 0, currentIndex), NotFound);
+ }
+ if (binding instanceof ReferenceBinding) {
+ if (!binding.isValidBinding())
+ return new ProblemReferenceBinding(CharOperation.subarray(compoundName, 0, currentIndex), binding.problemId());
+ compilationUnitScope().addTypeReference((ReferenceBinding) binding);
+ if (!this.canBeSeenByForCodeSnippet((ReferenceBinding) binding, receiverType))
+ return new ProblemReferenceBinding(CharOperation.subarray(compoundName, 0, currentIndex), NotVisible);
+ break foundType;
+ }
+ packageBinding = (PackageBinding) binding;
+ compilationUnitScope().addNamespaceReference(packageBinding);
}
- // handle the case when a field or type was asked for but we resolved the compoundName to a type or field
- return new ProblemBinding(
- CharOperation.subarray(compoundName, 0, currentIndex),
- NotFound);
+ // It is illegal to request a PACKAGE from this method.
+ return new ProblemReferenceBinding(CharOperation.subarray(compoundName, 0, currentIndex), NotFound);
}
- /* API
-
- Answer the constructor binding that corresponds to receiverType, argumentTypes.
-
- InvocationSite implements
- isSuperAccess(); this is used to determine if the discovered constructor is visible.
-
- If no visible constructor is discovered, an error binding is answered.
- */
-
- public MethodBinding getConstructor(
- ReferenceBinding receiverType,
- TypeBinding[] argumentTypes,
- InvocationSite invocationSite) {
- MethodBinding methodBinding = receiverType.getExactConstructor(argumentTypes);
- if (methodBinding != null)
- if (canBeSeenByForCodeSnippet(methodBinding,
- receiverType,
- invocationSite,
- this))
- return methodBinding;
-
- MethodBinding[] methods =
- receiverType.getMethods(ConstructorDeclaration.ConstantPoolName);
- if (methods == NoMethods)
- return new ProblemMethodBinding(
- ConstructorDeclaration.ConstantPoolName,
- argumentTypes,
- NotFound);
-
- MethodBinding[] compatible = new MethodBinding[methods.length];
- int compatibleIndex = 0;
- for (int i = 0, length = methods.length; i < length; i++)
- if (areParametersAssignable(methods[i].parameters, argumentTypes))
- compatible[compatibleIndex++] = methods[i];
- if (compatibleIndex == 0)
- return new ProblemMethodBinding(
- ConstructorDeclaration.ConstantPoolName,
- argumentTypes,
- NotFound);
- // need a more descriptive error... cannot convert from X to Y
-
- MethodBinding[] visible = new MethodBinding[compatibleIndex];
- int visibleIndex = 0;
- for (int i = 0; i < compatibleIndex; i++) {
- MethodBinding method = compatible[i];
- if (canBeSeenByForCodeSnippet(method, receiverType, invocationSite, this))
- visible[visibleIndex++] = method;
+ // know binding is now a ReferenceBinding
+ while (currentIndex < length) {
+ ReferenceBinding typeBinding = (ReferenceBinding) binding;
+ char[] nextName = compoundName[currentIndex++];
+ invocationSite.setFieldIndex(currentIndex);
+ if ((binding = findFieldForCodeSnippet(typeBinding, nextName, invocationSite)) != null) {
+ if (!binding.isValidBinding())
+ return new ProblemFieldBinding(CharOperation.subarray(compoundName, 0, currentIndex), binding.problemId());
+ break; // binding is now a field
}
- if (visibleIndex == 1)
- return visible[0];
- if (visibleIndex == 0)
- return new ProblemMethodBinding(
- ConstructorDeclaration.ConstantPoolName,
- argumentTypes,
- NotVisible);
- return mostSpecificClassMethodBinding(visible, visibleIndex);
+ if ((binding = findMemberType(nextName, typeBinding)) == null)
+ return new ProblemBinding(CharOperation.subarray(compoundName, 0, currentIndex), typeBinding, NotFound);
+ if (!binding.isValidBinding())
+ return new ProblemReferenceBinding(CharOperation.subarray(compoundName, 0, currentIndex), binding.problemId());
}
- /* API
-
- Answer the field binding that corresponds to fieldName.
- Start the lookup at the receiverType.
- InvocationSite implements
- isSuperAccess(); this is used to determine if the discovered field is visible.
- Only fields defined by the receiverType or its supertypes are answered;
- a field of an enclosing type will not be found using this API.
-
- If no visible field is discovered, an error binding is answered.
- */
-
- public FieldBinding getFieldForCodeSnippet(
- TypeBinding receiverType,
- char[] fieldName,
- InvocationSite invocationSite) {
- FieldBinding field =
- findFieldForCodeSnippet(receiverType, fieldName, invocationSite);
- if (field == null)
- return new ProblemFieldBinding(fieldName, NotFound);
- else
- return field;
+ if ((mask & FIELD) != 0 && (binding instanceof FieldBinding)) { // was looking for a field and found a field
+ FieldBinding field = (FieldBinding) binding;
+ if (!field.isStatic())
+ return new ProblemFieldBinding(CharOperation.subarray(compoundName, 0, currentIndex), NonStaticReferenceInStaticContext);
+ return binding;
+ }
+ if ((mask & TYPE) != 0 && (binding instanceof ReferenceBinding)) { // was looking for a type and found a type
+ return binding;
}
- /* API
-
- Answer the method binding that corresponds to selector, argumentTypes.
- Start the lookup at the enclosing type of the receiver.
- InvocationSite implements
- isSuperAccess(); this is used to determine if the discovered method is visible.
- setDepth(int); this is used to record the depth of the discovered method
- relative to the enclosing type of the receiver. (If the method is defined
- in the enclosing type of the receiver, the depth is 0; in the next enclosing
- type, the depth is 1; and so on
-
- If no visible method is discovered, an error binding is answered.
- */
-
- public MethodBinding getImplicitMethod(
- ReferenceBinding receiverType,
- char[] selector,
- TypeBinding[] argumentTypes,
- InvocationSite invocationSite) {
- boolean insideStaticContext = false;
- boolean insideConstructorCall = false;
- MethodBinding foundMethod = null;
- ProblemMethodBinding foundFuzzyProblem = null;
- // the weird method lookup case (matches method name in scope, then arg types, then visibility)
- ProblemMethodBinding foundInsideProblem = null;
- // inside Constructor call or inside static context
- Scope scope = this;
- boolean isExactMatch = true;
- // retrieve an exact visible match (if possible)
- MethodBinding methodBinding =
- (foundMethod == null)
- ? findExactMethod(receiverType, selector, argumentTypes, invocationSite)
- : findExactMethod(
- receiverType,
- foundMethod.selector,
- foundMethod.parameters,
- invocationSite);
- // ? findExactMethod(receiverType, selector, argumentTypes, invocationSite)
- // : findExactMethod(receiverType, foundMethod.selector, foundMethod.parameters, invocationSite);
- if (methodBinding == null && foundMethod == null) {
- // answers closest approximation, may not check argumentTypes or visibility
- isExactMatch = false;
- methodBinding =
- findMethod(receiverType, selector, argumentTypes, invocationSite);
- // methodBinding = findMethod(receiverType, selector, argumentTypes, invocationSite);
+ // handle the case when a field or type was asked for but we resolved the compoundName to a type or field
+ return new ProblemBinding(CharOperation.subarray(compoundName, 0, currentIndex), NotFound);
+}
+/* API
+
+ Answer the constructor binding that corresponds to receiverType, argumentTypes.
+
+ InvocationSite implements
+ isSuperAccess(); this is used to determine if the discovered constructor is visible.
+
+ If no visible constructor is discovered, an error binding is answered.
+*/
+
+public MethodBinding getConstructor(ReferenceBinding receiverType, TypeBinding[] argumentTypes, InvocationSite invocationSite) {
+ MethodBinding methodBinding = receiverType.getExactConstructor(argumentTypes);
+ if (methodBinding != null)
+ if (canBeSeenByForCodeSnippet(methodBinding, receiverType, invocationSite, this))
+ return methodBinding;
+
+ MethodBinding[] methods = receiverType.getMethods(ConstructorDeclaration.ConstantPoolName);
+ if (methods == NoMethods)
+ return new ProblemMethodBinding(ConstructorDeclaration.ConstantPoolName, argumentTypes, NotFound);
+
+ MethodBinding[] compatible = new MethodBinding[methods.length];
+ int compatibleIndex = 0;
+ for (int i = 0, length = methods.length; i < length; i++)
+ if (areParametersAssignable(methods[i].parameters, argumentTypes))
+ compatible[compatibleIndex++] = methods[i];
+ if (compatibleIndex == 0)
+ return new ProblemMethodBinding(ConstructorDeclaration.ConstantPoolName, argumentTypes, NotFound); // need a more descriptive error... cannot convert from X to Y
+
+ MethodBinding[] visible = new MethodBinding[compatibleIndex];
+ int visibleIndex = 0;
+ for (int i = 0; i < compatibleIndex; i++) {
+ MethodBinding method = compatible[i];
+ if (canBeSeenByForCodeSnippet(method, receiverType, invocationSite, this))
+ visible[visibleIndex++] = method;
+ }
+ if (visibleIndex == 1)
+ return visible[0];
+ if (visibleIndex == 0)
+ return new ProblemMethodBinding(ConstructorDeclaration.ConstantPoolName, argumentTypes, NotVisible);
+ return mostSpecificClassMethodBinding(visible, visibleIndex);
+}
+/* API
+
+ Answer the field binding that corresponds to fieldName.
+ Start the lookup at the receiverType.
+ InvocationSite implements
+ isSuperAccess(); this is used to determine if the discovered field is visible.
+ Only fields defined by the receiverType or its supertypes are answered;
+ a field of an enclosing type will not be found using this API.
+
+ If no visible field is discovered, an error binding is answered.
+*/
+
+public FieldBinding getFieldForCodeSnippet(TypeBinding receiverType, char[] fieldName, InvocationSite invocationSite) {
+ FieldBinding field = findFieldForCodeSnippet(receiverType, fieldName, invocationSite);
+ if (field == null)
+ return new ProblemFieldBinding(fieldName, NotFound);
+ else
+ return field;
+}
+/* API
+
+ Answer the method binding that corresponds to selector, argumentTypes.
+ Start the lookup at the enclosing type of the receiver.
+ InvocationSite implements
+ isSuperAccess(); this is used to determine if the discovered method is visible.
+ setDepth(int); this is used to record the depth of the discovered method
+ relative to the enclosing type of the receiver. (If the method is defined
+ in the enclosing type of the receiver, the depth is 0; in the next enclosing
+ type, the depth is 1; and so on
+
+ If no visible method is discovered, an error binding is answered.
+*/
+
+public MethodBinding getImplicitMethod(ReferenceBinding receiverType, char[] selector, TypeBinding[] argumentTypes, InvocationSite invocationSite) {
+ boolean insideStaticContext = false;
+ boolean insideConstructorCall = false;
+ MethodBinding foundMethod = null;
+ ProblemMethodBinding foundFuzzyProblem = null; // the weird method lookup case (matches method name in scope, then arg types, then visibility)
+ ProblemMethodBinding foundInsideProblem = null; // inside Constructor call or inside static context
+ Scope scope = this;
+ boolean isExactMatch = true;
+ // retrieve an exact visible match (if possible)
+ MethodBinding methodBinding =
+ (foundMethod == null)
+ ? findExactMethod(receiverType, selector, argumentTypes, invocationSite)
+ : findExactMethod(receiverType, foundMethod.selector, foundMethod.parameters, invocationSite);
+// ? findExactMethod(receiverType, selector, argumentTypes, invocationSite)
+// : findExactMethod(receiverType, foundMethod.selector, foundMethod.parameters, invocationSite);
+ if (methodBinding == null && foundMethod == null) {
+ // answers closest approximation, may not check argumentTypes or visibility
+ isExactMatch = false;
+ methodBinding = findMethod(receiverType, selector, argumentTypes, invocationSite);
+// methodBinding = findMethod(receiverType, selector, argumentTypes, invocationSite);
+ }
+ if (methodBinding != null) { // skip it if we did not find anything
+ if (methodBinding.problemId() == Ambiguous) {
+ if (foundMethod == null || foundMethod.problemId() == NotVisible)
+ // supercedes any potential InheritedNameHidesEnclosingName problem
+ return methodBinding;
+ else
+ // make the user qualify the method, likely wants the first inherited method (javac generates an ambiguous error instead)
+ return new ProblemMethodBinding(selector, argumentTypes, InheritedNameHidesEnclosingName);
}
- if (methodBinding != null) { // skip it if we did not find anything
- if (methodBinding.problemId() == Ambiguous) {
- if (foundMethod == null || foundMethod.problemId() == NotVisible)
- // supercedes any potential InheritedNameHidesEnclosingName problem
- return methodBinding;
- else
- // make the user qualify the method, likely wants the first inherited method (javac generates an ambiguous error instead)
- return new ProblemMethodBinding(
- selector,
- argumentTypes,
- InheritedNameHidesEnclosingName);
- }
- ProblemMethodBinding fuzzyProblem = null;
- ProblemMethodBinding insideProblem = null;
- if (methodBinding.isValidBinding()) {
- if (!isExactMatch) {
- if (!areParametersAssignable(methodBinding.parameters, argumentTypes)) {
- fuzzyProblem =
- new ProblemMethodBinding(methodBinding, selector, argumentTypes, NotFound);
- } else
- if (!canBeSeenByForCodeSnippet(methodBinding,
- receiverType,
- invocationSite,
- this)) {
- // using <classScope> instead of <this> for visibility check does grant all access to innerclass
- fuzzyProblem =
- new ProblemMethodBinding(
- selector,
- argumentTypes,
- methodBinding.declaringClass,
- NotVisible);
- }
+ ProblemMethodBinding fuzzyProblem = null;
+ ProblemMethodBinding insideProblem = null;
+ if (methodBinding.isValidBinding()) {
+ if (!isExactMatch) {
+ if (!areParametersAssignable(methodBinding.parameters, argumentTypes)) {
+ fuzzyProblem = new ProblemMethodBinding(methodBinding, selector, argumentTypes, NotFound);
+ } else if (!canBeSeenByForCodeSnippet(methodBinding, receiverType, invocationSite, this)) {
+ // using <classScope> instead of <this> for visibility check does grant all access to innerclass
+ fuzzyProblem = new ProblemMethodBinding(selector, argumentTypes, methodBinding.declaringClass, NotVisible);
}
- if (fuzzyProblem == null && !methodBinding.isStatic()) {
- if (insideConstructorCall) {
- insideProblem =
- new ProblemMethodBinding(
- methodBinding.selector,
- methodBinding.parameters,
- NonStaticReferenceInConstructorInvocation);
- } else
- if (insideStaticContext) {
- insideProblem =
- new ProblemMethodBinding(
- methodBinding.selector,
- methodBinding.parameters,
- NonStaticReferenceInStaticContext);
- }
+ }
+ if (fuzzyProblem == null && !methodBinding.isStatic()) {
+ if (insideConstructorCall) {
+ insideProblem = new ProblemMethodBinding(methodBinding.selector, methodBinding.parameters, NonStaticReferenceInConstructorInvocation);
+ } else if (insideStaticContext) {
+ insideProblem = new ProblemMethodBinding(methodBinding.selector, methodBinding.parameters, NonStaticReferenceInStaticContext);
}
- if (receiverType == methodBinding.declaringClass
- || (receiverType.getMethods(selector)) != NoMethods) {
- // found a valid method in the 'immediate' scope (ie. not inherited)
- // OR the receiverType implemented a method with the correct name
- if (foundMethod == null) {
- // return the methodBinding if it is not declared in a superclass of the scope's binding (i.e. "inherited")
- if (fuzzyProblem != null)
- return fuzzyProblem;
- if (insideProblem != null)
- return insideProblem;
- return methodBinding;
- }
- // if a method was found, complain when another is found in an 'immediate' enclosing type (ie. not inherited)
- // NOTE: Unlike fields, a non visible method hides a visible method
- if (foundMethod.declaringClass != methodBinding.declaringClass)
- // ie. have we found the same method - do not trust field identity yet
- return new ProblemMethodBinding(
- methodBinding.selector,
- methodBinding.parameters,
- InheritedNameHidesEnclosingName);
+ }
+ if (receiverType == methodBinding.declaringClass || (receiverType.getMethods(selector)) != NoMethods) {
+ // found a valid method in the 'immediate' scope (ie. not inherited)
+ // OR the receiverType implemented a method with the correct name
+ if (foundMethod == null) {
+ // return the methodBinding if it is not declared in a superclass of the scope's binding (i.e. "inherited")
+ if (fuzzyProblem != null)
+ return fuzzyProblem;
+ if (insideProblem != null)
+ return insideProblem;
+ return methodBinding;
}
+ // if a method was found, complain when another is found in an 'immediate' enclosing type (ie. not inherited)
+ // NOTE: Unlike fields, a non visible method hides a visible method
+ if (foundMethod.declaringClass != methodBinding.declaringClass) // ie. have we found the same method - do not trust field identity yet
+ return new ProblemMethodBinding(methodBinding.selector, methodBinding.parameters, InheritedNameHidesEnclosingName);
}
+ }
- if (foundMethod == null
- || (foundMethod.problemId() == NotVisible
- && methodBinding.problemId() != NotVisible)) {
- // only remember the methodBinding if its the first one found or the previous one was not visible & methodBinding is...
- // remember that private methods are visible if defined directly by an enclosing class
- foundFuzzyProblem = fuzzyProblem;
- foundInsideProblem = insideProblem;
- if (fuzzyProblem == null)
- foundMethod = methodBinding; // only keep it if no error was found
- }
+ if (foundMethod == null || (foundMethod.problemId() == NotVisible && methodBinding.problemId() != NotVisible)) {
+ // only remember the methodBinding if its the first one found or the previous one was not visible & methodBinding is...
+ // remember that private methods are visible if defined directly by an enclosing class
+ foundFuzzyProblem = fuzzyProblem;
+ foundInsideProblem = insideProblem;
+ if (fuzzyProblem == null)
+ foundMethod = methodBinding; // only keep it if no error was found
}
- insideStaticContext |= receiverType.isStatic();
- // 1EX5I8Z - accessing outer fields within a constructor call is permitted
- // in order to do so, we change the flag as we exit from the type, not the method
- // itself, because the class scope is used to retrieve the fields.
- MethodScope enclosingMethodScope = scope.methodScope();
- insideConstructorCall =
- enclosingMethodScope == null ? false : enclosingMethodScope.isConstructorCall;
-
- if (foundFuzzyProblem != null)
- return foundFuzzyProblem;
- if (foundInsideProblem != null)
- return foundInsideProblem;
- if (foundMethod != null)
- return foundMethod;
- return new ProblemMethodBinding(selector, argumentTypes, NotFound);
}
-
+ insideStaticContext |= receiverType.isStatic();
+ // 1EX5I8Z - accessing outer fields within a constructor call is permitted
+ // in order to do so, we change the flag as we exit from the type, not the method
+ // itself, because the class scope is used to retrieve the fields.
+ MethodScope enclosingMethodScope = scope.methodScope();
+ insideConstructorCall = enclosingMethodScope == null ? false : enclosingMethodScope.isConstructorCall;
+
+ if (foundFuzzyProblem != null)
+ return foundFuzzyProblem;
+ if (foundInsideProblem != null)
+ return foundInsideProblem;
+ if (foundMethod != null)
+ return foundMethod;
+ return new ProblemMethodBinding(selector, argumentTypes, NotFound);
+}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetSingleNameReference.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetSingleNameReference.java
index 54896650ad..655d987592 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetSingleNameReference.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetSingleNameReference.java
@@ -14,684 +14,564 @@ import org.eclipse.jdt.internal.compiler.lookup.*;
* A single name reference inside a code snippet can denote a field of a remote
* receiver object (i.e. the one of the context in the stack frame)
*/
-public class CodeSnippetSingleNameReference
- extends SingleNameReference
- implements EvaluationConstants, InvocationSite, ProblemReasons {
+public class CodeSnippetSingleNameReference extends SingleNameReference implements EvaluationConstants, InvocationSite, ProblemReasons {
EvaluationContext evaluationContext;
FieldBinding delegateThis;
- TypeBinding receiverType;
- public CodeSnippetSingleNameReference(
- char[] source,
- long pos,
- EvaluationContext evaluationContext) {
- super(source, pos);
- this.evaluationContext = evaluationContext;
+public CodeSnippetSingleNameReference(char[] source, long pos, EvaluationContext evaluationContext) {
+ super(source, pos);
+ this.evaluationContext = evaluationContext;
+}
+public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo, boolean valueRequired) {
+ switch (bits & RestrictiveFlagMASK) {
+ case FIELD : // reading a field
+ // check if reading a final blank field
+ FieldBinding fieldBinding;
+ if ((fieldBinding = (FieldBinding) binding).isFinal() && currentScope.allowBlankFinalFieldAssignment(fieldBinding)) {
+ if (!flowInfo.isDefinitelyAssigned(fieldBinding)) {
+ currentScope.problemReporter().uninitializedBlankFinalField(fieldBinding, this);
+ }
+ }
+ break;
+ case LOCAL : // reading a local variable
+ LocalVariableBinding localBinding;
+ if (!flowInfo.isDefinitelyAssigned(localBinding = (LocalVariableBinding) binding)) {
+ currentScope.problemReporter().uninitializedLocalVariable(localBinding, this);
+ }
+ if (!flowInfo.isFakeReachable()) localBinding.used = true;
}
+ return flowInfo;
+}
+/**
+ * Check and/or redirect the field access to the delegate receiver if any
+ */
+public TypeBinding checkFieldAccess(BlockScope scope) {
- public FlowInfo analyseCode(
- BlockScope currentScope,
- FlowContext flowContext,
- FlowInfo flowInfo,
- boolean valueRequired) {
- switch (bits & RestrictiveFlagMASK) {
- case FIELD : // reading a field
- // check if reading a final blank field
- FieldBinding fieldBinding;
- if ((fieldBinding = (FieldBinding) binding).isFinal()
- && currentScope.allowBlankFinalFieldAssignment(fieldBinding)) {
- if (!flowInfo.isDefinitelyAssigned(fieldBinding)) {
- currentScope.problemReporter().uninitializedBlankFinalField(fieldBinding, this);
- }
- }
- break;
- case LOCAL : // reading a local variable
- LocalVariableBinding localBinding;
- if (!flowInfo
- .isDefinitelyAssigned(localBinding = (LocalVariableBinding) binding)) {
- currentScope.problemReporter().uninitializedLocalVariable(localBinding, this);
- }
- if (!flowInfo.isFakeReachable())
- localBinding.used = true;
+ if (delegateThis == null) return super.checkFieldAccess(scope);
+
+ FieldBinding fieldBinding = (FieldBinding) binding;
+ bits &= ~RestrictiveFlagMASK; // clear bits
+ bits |= FIELD;
+ if (!fieldBinding.isStatic()) {
+ // must check for the static status....
+ if (this.evaluationContext.isStatic) {
+ scope.problemReporter().staticFieldAccessToNonStaticVariable(
+ this,
+ fieldBinding);
+ constant = NotAConstant;
+ return null;
}
- return flowInfo;
}
+ constant = FieldReference.getConstantFor(fieldBinding, true, this, 0);
+ if (isFieldUseDeprecated(fieldBinding, scope))
+ scope.problemReporter().deprecatedField(fieldBinding, this);
+ // if the binding declaring class is not visible, need special action
+ // for runtime compatibility on 1.2 VMs : change the declaring class of the binding
+ if (fieldBinding.declaringClass != null
+ && fieldBinding.constant == NotAConstant
+ && !fieldBinding.declaringClass.canBeSeenBy(scope)) {
+ binding = new FieldBinding(fieldBinding, scope.enclosingSourceType());
+ }
+ return fieldBinding.type;
- /**
- * Check and/or redirect the field access to the delegate receiver if any
- */
- public TypeBinding checkFieldAccess(BlockScope scope) {
-
- if (delegateThis == null)
- return super.checkFieldAccess(scope);
+}
+public void generateAssignment(BlockScope currentScope, CodeStream codeStream, Assignment assignment, boolean valueRequired) {
- FieldBinding fieldBinding = (FieldBinding) binding;
- bits &= ~RestrictiveFlagMASK; // clear bits
- bits |= FIELD;
- if (!fieldBinding.isStatic()) {
- // must check for the static status....
- if (this.evaluationContext.isStatic) {
- scope.problemReporter().staticFieldAccessToNonStaticVariable(
- this,
- fieldBinding);
- constant = NotAConstant;
- return null;
- }
+ // optimizing assignment like: i = i + 1 or i = 1 + i
+ if (assignment.expression.isCompactableOperation()) {
+ BinaryExpression operation = (BinaryExpression) assignment.expression;
+ SingleNameReference variableReference;
+ if ((operation.left instanceof SingleNameReference) && ((variableReference = (SingleNameReference) operation.left).binding == binding)) {
+ // i = i + value, then use the variable on the right hand side, since it has the correct implicit conversion
+ variableReference.generateCompoundAssignment(currentScope, codeStream, syntheticAccessors == null ? null : syntheticAccessors[WRITE], operation.right, (operation.bits & OperatorMASK) >> OperatorSHIFT, operation.left.implicitConversion /*should be equivalent to no conversion*/, valueRequired);
+ return;
}
- constant = FieldReference.getConstantFor(fieldBinding, true, this, 0);
- if (isFieldUseDeprecated(fieldBinding, scope))
- scope.problemReporter().deprecatedField(fieldBinding, this);
- // if the binding declaring class is not visible, need special action
- // for runtime compatibility on 1.2 VMs : change the declaring class of the binding
- if (fieldBinding.declaringClass != null
- && fieldBinding.constant == NotAConstant
- && !fieldBinding.declaringClass.canBeSeenBy(scope)) {
- binding = new FieldBinding(fieldBinding, scope.enclosingSourceType());
+ int operator = (operation.bits & OperatorMASK) >> OperatorSHIFT;
+ if ((operation.right instanceof SingleNameReference)
+ && ((operator == PLUS) || (operator == MULTIPLY)) // only commutative operations
+ && ((variableReference = (SingleNameReference) operation.right).binding == binding)
+ && (operation.left.constant != NotAConstant) // exclude non constant expressions, since could have side-effect
+ && ((operation.implicitConversion >> 4) != T_String)) { // exclude string concatenation which would occur backwards
+ // i = value + i, then use the variable on the right hand side, since it has the correct implicit conversion
+ variableReference.generateCompoundAssignment(currentScope, codeStream, syntheticAccessors == null ? null : syntheticAccessors[WRITE], operation.left, operator, operation.right.implicitConversion /*should be equivalent to no conversion*/, valueRequired);
+ return;
}
- return fieldBinding.type;
-
}
-
- public void generateAssignment(
- BlockScope currentScope,
- CodeStream codeStream,
- Assignment assignment,
- boolean valueRequired) {
-
- // optimizing assignment like: i = i + 1 or i = 1 + i
- if (assignment.expression.isCompactableOperation()) {
- BinaryExpression operation = (BinaryExpression) assignment.expression;
- SingleNameReference variableReference;
- if ((operation.left instanceof SingleNameReference)
- && ((variableReference = (SingleNameReference) operation.left).binding
- == binding)) {
- // i = i + value, then use the variable on the right hand side, since it has the correct implicit conversion
- variableReference.generateCompoundAssignment(
- currentScope,
- codeStream,
- syntheticAccessors == null ? null : syntheticAccessors[WRITE],
- operation.right,
- (operation.bits & OperatorMASK) >> OperatorSHIFT,
- operation.left.implicitConversion /*should be equivalent to no conversion*/,
- valueRequired);
- return;
- }
- int operator = (operation.bits & OperatorMASK) >> OperatorSHIFT;
- if ((operation.right instanceof SingleNameReference)
- && ((operator == PLUS)
- || (operator == MULTIPLY)) // only commutative operations
- && ((variableReference = (SingleNameReference) operation.right).binding
- == binding)
- && (operation.left.constant != NotAConstant)
- // exclude non constant expressions, since could have side-effect
- && ((operation.implicitConversion >> 4) != T_String)) {
- // exclude string concatenation which would occur backwards
- // i = value + i, then use the variable on the right hand side, since it has the correct implicit conversion
- variableReference.generateCompoundAssignment(
- currentScope,
- codeStream,
- syntheticAccessors == null ? null : syntheticAccessors[WRITE],
- operation.left,
- operator,
- operation.right.implicitConversion /*should be equivalent to no conversion*/,
- valueRequired);
- return;
- }
- }
- switch (bits & RestrictiveFlagMASK) {
- case FIELD : // assigning to a field
- FieldBinding fieldBinding = (FieldBinding) binding;
- if (fieldBinding
- .canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
- if (!fieldBinding.isStatic()) { // need a receiver?
- if ((bits & DepthMASK) != 0) {
- Object[] emulationPath =
- currentScope.getExactEmulationPath(
- currentScope.enclosingSourceType().enclosingTypeAt(
- (bits & DepthMASK) >> DepthSHIFT));
- if (emulationPath == null) {
- // internal error, per construction we should have found it
- currentScope.problemReporter().needImplementation();
- } else {
- codeStream.generateOuterAccess(emulationPath, this, currentScope);
- }
- } else {
- this.generateReceiver(codeStream);
- }
- }
- assignment.expression.generateCode(currentScope, codeStream, true);
- fieldStore(codeStream, fieldBinding, null, valueRequired);
- if (valueRequired) {
- codeStream.generateImplicitConversion(assignment.implicitConversion);
- }
- } else {
- ((CodeSnippetCodeStream) codeStream).generateEmulationForField(fieldBinding);
- if (!fieldBinding.isStatic()) { // need a receiver?
- if ((bits & DepthMASK) != 0) {
+ switch (bits & RestrictiveFlagMASK) {
+ case FIELD : // assigning to a field
+ FieldBinding fieldBinding = (FieldBinding) binding;
+ if (fieldBinding.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
+ if (!fieldBinding.isStatic()) { // need a receiver?
+ if ((bits & DepthMASK) != 0) {
+ Object[] emulationPath = currentScope.getExactEmulationPath(currentScope.enclosingSourceType().enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT));
+ if (emulationPath == null) {
// internal error, per construction we should have found it
- // not yet supported
currentScope.problemReporter().needImplementation();
} else {
- this.generateReceiver(codeStream);
+ codeStream.generateOuterAccess(emulationPath, this, currentScope);
}
} else {
- codeStream.aconst_null();
+ this.generateReceiver(codeStream);
}
- assignment.expression.generateCode(currentScope, codeStream, true);
- if (valueRequired) {
- if ((fieldBinding.type == LongBinding)
- || (fieldBinding.type == DoubleBinding)) {
- codeStream.dup2_x2();
- } else {
- codeStream.dup_x2();
- }
+ }
+ assignment.expression.generateCode(currentScope, codeStream, true);
+ fieldStore(codeStream, fieldBinding, null, valueRequired);
+ if (valueRequired) {
+ codeStream.generateImplicitConversion(assignment.implicitConversion);
+ }
+ } else {
+ ((CodeSnippetCodeStream) codeStream).generateEmulationForField(fieldBinding);
+ if (!fieldBinding.isStatic()) { // need a receiver?
+ if ((bits & DepthMASK) != 0) {
+ // internal error, per construction we should have found it
+ // not yet supported
+ currentScope.problemReporter().needImplementation();
+ } else {
+ this.generateReceiver(codeStream);
}
- ((CodeSnippetCodeStream) codeStream).generateEmulatedWriteAccessForField(
- fieldBinding);
- if (valueRequired) {
- codeStream.generateImplicitConversion(assignment.implicitConversion);
+ } else {
+ codeStream.aconst_null();
+ }
+ assignment.expression.generateCode(currentScope, codeStream, true);
+ if (valueRequired) {
+ if ((fieldBinding.type == LongBinding) || (fieldBinding.type == DoubleBinding)) {
+ codeStream.dup2_x2();
+ } else {
+ codeStream.dup_x2();
}
}
- return;
- case LOCAL : // assigning to a local variable
- LocalVariableBinding localBinding = (LocalVariableBinding) binding;
- if (localBinding.resolvedPosition != -1) {
- assignment.expression.generateCode(currentScope, codeStream, true);
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedWriteAccessForField(fieldBinding);
+ if (valueRequired) {
+ codeStream.generateImplicitConversion(assignment.implicitConversion);
+ }
+ }
+ return;
+ case LOCAL : // assigning to a local variable
+ LocalVariableBinding localBinding = (LocalVariableBinding) binding;
+ if (localBinding.resolvedPosition != -1) {
+ assignment.expression.generateCode(currentScope, codeStream, true);
+ } else {
+ if (assignment.expression.constant != NotAConstant) {
+ // assigning an unused local to a constant value = no actual assignment is necessary
+ if (valueRequired) {
+ codeStream.generateConstant(assignment.expression.constant, assignment.implicitConversion);
+ }
} else {
- if (assignment.expression.constant != NotAConstant) {
- // assigning an unused local to a constant value = no actual assignment is necessary
- if (valueRequired) {
- codeStream.generateConstant(
- assignment.expression.constant,
- assignment.implicitConversion);
- }
+ assignment.expression.generateCode(currentScope, codeStream, true);
+ /* Even though the value may not be required, we force it to be produced, and discard it later
+ on if it was actually not necessary, so as to provide the same behavior as JDK1.2beta3. */
+ if (valueRequired) {
+ codeStream.generateImplicitConversion(assignment.implicitConversion); // implicit conversion
} else {
- assignment.expression.generateCode(currentScope, codeStream, true);
- /* Even though the value may not be required, we force it to be produced, and discard it later
- on if it was actually not necessary, so as to provide the same behavior as JDK1.2beta3. */
- if (valueRequired) {
- codeStream.generateImplicitConversion(assignment.implicitConversion);
- // implicit conversion
+ if ((localBinding.type == LongBinding) || (localBinding.type == DoubleBinding)) {
+ codeStream.pop2();
} else {
- if ((localBinding.type == LongBinding)
- || (localBinding.type == DoubleBinding)) {
- codeStream.pop2();
- } else {
- codeStream.pop();
- }
+ codeStream.pop();
}
}
- return;
- }
- // normal local assignment (since cannot store in outer local which are final locations)
- codeStream.store(localBinding, valueRequired);
- if ((bits & FirstAssignmentToLocalMASK) != 0) {
- // for local variable debug attributes
- localBinding.recordInitializationStartPC(codeStream.position);
}
- // implicit conversion
- if (valueRequired) {
- codeStream.generateImplicitConversion(assignment.implicitConversion);
- }
- }
- }
-
- public void generateCode(
- BlockScope currentScope,
- CodeStream codeStream,
- boolean valueRequired) {
- int pc = codeStream.position;
- if (constant != NotAConstant) {
+ return;
+ }
+ // normal local assignment (since cannot store in outer local which are final locations)
+ codeStream.store(localBinding, valueRequired);
+ if ((bits & FirstAssignmentToLocalMASK) != 0) { // for local variable debug attributes
+ localBinding.recordInitializationStartPC(codeStream.position);
+ }
+ // implicit conversion
if (valueRequired) {
- codeStream.generateConstant(constant, implicitConversion);
+ codeStream.generateImplicitConversion(assignment.implicitConversion);
}
- } else {
- switch (bits & RestrictiveFlagMASK) {
- case FIELD : // reading a field
- FieldBinding fieldBinding;
- if (valueRequired) {
- if ((fieldBinding = (FieldBinding) binding).constant == NotAConstant) {
- // directly use inlined value for constant fields
- if (fieldBinding
- .canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
- // directly use inlined value for constant fields
- boolean isStatic;
- if (!(isStatic = fieldBinding.isStatic())) {
- if ((bits & DepthMASK) != 0) {
- Object[] emulationPath =
- currentScope.getExactEmulationPath(
- currentScope.enclosingSourceType().enclosingTypeAt(
- (bits & DepthMASK) >> DepthSHIFT));
- if (emulationPath == null) {
- // internal error, per construction we should have found it
- currentScope.problemReporter().needImplementation();
- } else {
- codeStream.generateOuterAccess(emulationPath, this, currentScope);
- }
- } else {
- generateReceiver(codeStream);
- }
- }
- // managing private access
- if (isStatic) {
- codeStream.getstatic(fieldBinding);
- } else {
- codeStream.getfield(fieldBinding);
- }
- } else {
- // managing private access
- if (!fieldBinding.isStatic()) {
- if ((bits & DepthMASK) != 0) {
+ }
+}
+public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) {
+ int pc = codeStream.position;
+ if (constant != NotAConstant) {
+ if (valueRequired) {
+ codeStream.generateConstant(constant, implicitConversion);
+ }
+ } else {
+ switch (bits & RestrictiveFlagMASK) {
+ case FIELD : // reading a field
+ FieldBinding fieldBinding;
+ if (valueRequired) {
+ if ((fieldBinding = (FieldBinding) binding).constant == NotAConstant) { // directly use inlined value for constant fields
+ if (fieldBinding.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
+ // directly use inlined value for constant fields
+ boolean isStatic;
+ if (!(isStatic = fieldBinding.isStatic())) {
+ if ((bits & DepthMASK) != 0) {
+ Object[] emulationPath = currentScope.getExactEmulationPath(currentScope.enclosingSourceType().enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT));
+ if (emulationPath == null) {
// internal error, per construction we should have found it
- // not yet supported
currentScope.problemReporter().needImplementation();
} else {
- generateReceiver(codeStream);
+ codeStream.generateOuterAccess(emulationPath, this, currentScope);
}
} else {
- codeStream.aconst_null();
+ generateReceiver(codeStream);
}
- ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(
- fieldBinding);
}
- codeStream.generateImplicitConversion(implicitConversion);
- } else { // directly use the inlined value
- codeStream.generateConstant(fieldBinding.constant, implicitConversion);
- }
- }
- break;
- case LOCAL : // reading a local
- LocalVariableBinding localBinding = (LocalVariableBinding) binding;
- if (valueRequired) {
- // outer local?
- if ((bits & DepthMASK) != 0) {
- // outer local can be reached either through a synthetic arg or a synthetic field
- VariableBinding[] path = currentScope.getEmulationPath(localBinding);
- if (path == null) {
- // emulation was not possible (should not happen per construction)
- currentScope.problemReporter().needImplementation();
+ // managing private access
+ if (isStatic) {
+ codeStream.getstatic(fieldBinding);
} else {
- codeStream.generateOuterAccess(path, this, currentScope);
+ codeStream.getfield(fieldBinding);
}
} else {
- // regular local variable read
- codeStream.load(localBinding);
- }
- codeStream.generateImplicitConversion(implicitConversion);
- }
- }
- }
- codeStream.recordPositionsFrom(pc, this);
- }
-
- /*
- * The APIs with an extra argument is used whenever there are two references to the same variable which
- * are optimized in one access: e.g "a = a + 1" optimized into "a++".
- */
- public void generateCompoundAssignment(
- BlockScope currentScope,
- CodeStream codeStream,
- MethodBinding writeAccessor,
- Expression expression,
- int operator,
- int assignmentImplicitConversion,
- boolean valueRequired) {
- switch (bits & RestrictiveFlagMASK) {
- case FIELD : // assigning to a field
- FieldBinding fieldBinding = (FieldBinding) binding;
- if (fieldBinding.isStatic()) {
- if (fieldBinding
- .canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
- codeStream.getstatic(fieldBinding);
- } else {
- // used to store the value
- ((CodeSnippetCodeStream) codeStream).generateEmulationForField(fieldBinding);
- codeStream.aconst_null();
-
- // used to retrieve the actual value
- codeStream.aconst_null();
- ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(
- fieldBinding);
- }
- } else {
- if (fieldBinding
- .canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
- if ((bits & DepthMASK) != 0) {
- Object[] emulationPath =
- currentScope.getExactEmulationPath(
- currentScope.enclosingSourceType().enclosingTypeAt(
- (bits & DepthMASK) >> DepthSHIFT));
- if (emulationPath == null) {
- // internal error, per construction we should have found it
- currentScope.problemReporter().needImplementation();
+ // managing private access
+ if (!fieldBinding.isStatic()) {
+ if ((bits & DepthMASK) != 0) {
+ // internal error, per construction we should have found it
+ // not yet supported
+ currentScope.problemReporter().needImplementation();
+ } else {
+ generateReceiver(codeStream);
+ }
} else {
- codeStream.generateOuterAccess(emulationPath, this, currentScope);
+ codeStream.aconst_null();
}
- } else {
- generateReceiver(codeStream);
+ ((CodeSnippetCodeStream)codeStream).generateEmulatedReadAccessForField(fieldBinding);
}
- codeStream.dup();
- codeStream.getfield(fieldBinding);
- } else {
- if ((bits & DepthMASK) != 0) {
- // internal error, per construction we should have found it
- // not yet supported
- currentScope.problemReporter().needImplementation();
- }
- // used to store the value
- ((CodeSnippetCodeStream) codeStream).generateEmulationForField(fieldBinding);
- generateReceiver(codeStream);
-
- // used to retrieve the actual value
- codeStream.dup();
- ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(
- fieldBinding);
+ codeStream.generateImplicitConversion(implicitConversion);
+ } else { // directly use the inlined value
+ codeStream.generateConstant(fieldBinding.constant, implicitConversion);
}
}
break;
- case LOCAL : // assigning to a local variable (cannot assign to outer local)
+ case LOCAL : // reading a local
LocalVariableBinding localBinding = (LocalVariableBinding) binding;
- Constant assignConstant;
- int increment;
- // using incr bytecode if possible
- switch (localBinding.type.id) {
- case T_String :
- codeStream.generateStringAppend(currentScope, this, expression);
- if (valueRequired) {
- codeStream.dup();
- }
- codeStream.store(localBinding, false);
- return;
- case T_int :
- if (((assignConstant = expression.constant) != NotAConstant)
- && ((increment = assignConstant.intValue()) == (short) increment)) {
- // 16 bits value
- switch (operator) {
- case PLUS :
- codeStream.iinc(localBinding.resolvedPosition, increment);
- if (valueRequired) {
- codeStream.load(localBinding);
- }
- return;
- case MINUS :
- codeStream.iinc(localBinding.resolvedPosition, -increment);
- if (valueRequired) {
- codeStream.load(localBinding);
- }
- return;
- }
- }
- default :
- codeStream.load(localBinding);
- }
- }
- // perform the actual compound operation
- int operationTypeID;
- if ((operationTypeID = implicitConversion >> 4) == T_String) {
- codeStream.generateStringAppend(currentScope, null, expression);
- } else {
- // promote the array reference to the suitable operation type
- codeStream.generateImplicitConversion(implicitConversion);
- // generate the increment value (will by itself be promoted to the operation value)
- if (expression == IntLiteral.One) { // prefix operation
- codeStream.generateConstant(expression.constant, implicitConversion);
- } else {
- expression.generateCode(currentScope, codeStream, true);
- }
- // perform the operation
- codeStream.sendOperator(operator, operationTypeID);
- // cast the value back to the array reference type
- codeStream.generateImplicitConversion(assignmentImplicitConversion);
- }
- // store the result back into the variable
- switch (bits & RestrictiveFlagMASK) {
- case FIELD : // assigning to a field
- FieldBinding fieldBinding = (FieldBinding) binding;
- if (fieldBinding
- .canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
- fieldStore(codeStream, (FieldBinding) binding, writeAccessor, valueRequired);
- } else {
- // current stack is:
- // field receiver value
- if (valueRequired) {
- if ((fieldBinding.type == LongBinding)
- || (fieldBinding.type == DoubleBinding)) {
- codeStream.dup2_x2();
+ if (valueRequired) {
+ // outer local?
+ if ((bits & DepthMASK) != 0) {
+ // outer local can be reached either through a synthetic arg or a synthetic field
+ VariableBinding[] path = currentScope.getEmulationPath(localBinding);
+ if (path == null) {
+ // emulation was not possible (should not happen per construction)
+ currentScope.problemReporter().needImplementation();
} else {
- codeStream.dup_x2();
+ codeStream.generateOuterAccess(path, this, currentScope);
}
- }
- // current stack is:
- // value field receiver value
- ((CodeSnippetCodeStream) codeStream).generateEmulatedWriteAccessForField(
- fieldBinding);
- }
- return;
- case LOCAL : // assigning to a local variable
- LocalVariableBinding localBinding = (LocalVariableBinding) binding;
- if (valueRequired) {
- if ((localBinding.type == LongBinding)
- || (localBinding.type == DoubleBinding)) {
- codeStream.dup2();
} else {
- codeStream.dup();
+ // regular local variable read
+ codeStream.load(localBinding);
}
+ codeStream.generateImplicitConversion(implicitConversion);
}
- codeStream.store(localBinding, false);
}
}
+ codeStream.recordPositionsFrom(pc, this);
+}
+/*
+ * The APIs with an extra argument is used whenever there are two references to the same variable which
+ * are optimized in one access: e.g "a = a + 1" optimized into "a++".
+ */
+public void generateCompoundAssignment(BlockScope currentScope, CodeStream codeStream, MethodBinding writeAccessor, Expression expression, int operator, int assignmentImplicitConversion, boolean valueRequired) {
+ switch (bits & RestrictiveFlagMASK) {
+ case FIELD : // assigning to a field
+ FieldBinding fieldBinding = (FieldBinding) binding;
+ if (fieldBinding.isStatic()) {
+ if (fieldBinding.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
+ codeStream.getstatic(fieldBinding);
+ } else {
+ // used to store the value
+ ((CodeSnippetCodeStream) codeStream).generateEmulationForField(fieldBinding);
+ codeStream.aconst_null();
- public void generatePostIncrement(
- BlockScope currentScope,
- CodeStream codeStream,
- CompoundAssignment postIncrement,
- boolean valueRequired) {
- switch (bits & RestrictiveFlagMASK) {
- case FIELD : // assigning to a field
- FieldBinding fieldBinding = (FieldBinding) binding;
- if (fieldBinding
- .canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
- if (fieldBinding.isStatic()) {
- codeStream.getstatic(fieldBinding);
- } else {
- if ((bits & DepthMASK) != 0) {
- Object[] emulationPath =
- currentScope.getExactEmulationPath(
- currentScope.enclosingSourceType().enclosingTypeAt(
- (bits & DepthMASK) >> DepthSHIFT));
- if (emulationPath == null) {
- // internal error, per construction we should have found it
- currentScope.problemReporter().needImplementation();
- } else {
- codeStream.generateOuterAccess(emulationPath, this, currentScope);
- }
+ // used to retrieve the actual value
+ codeStream.aconst_null();
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(fieldBinding);
+ }
+ } else {
+ if (fieldBinding.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
+ if ((bits & DepthMASK) != 0) {
+ Object[] emulationPath = currentScope.getExactEmulationPath(currentScope.enclosingSourceType().enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT));
+ if (emulationPath == null) {
+ // internal error, per construction we should have found it
+ currentScope.problemReporter().needImplementation();
} else {
- generateReceiver(codeStream);
+ codeStream.generateOuterAccess(emulationPath, this, currentScope);
}
- codeStream.dup();
- codeStream.getfield(fieldBinding);
+ } else {
+ generateReceiver(codeStream);
}
+ codeStream.dup();
+ codeStream.getfield(fieldBinding);
+ } else {
+ if ((bits & DepthMASK) != 0) {
+ // internal error, per construction we should have found it
+ // not yet supported
+ currentScope.problemReporter().needImplementation();
+ }
+ // used to store the value
+ ((CodeSnippetCodeStream) codeStream).generateEmulationForField(fieldBinding);
+ generateReceiver(codeStream);
+
+ // used to retrieve the actual value
+ codeStream.dup();
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(fieldBinding);
+ }
+ }
+ break;
+ case LOCAL : // assigning to a local variable (cannot assign to outer local)
+ LocalVariableBinding localBinding = (LocalVariableBinding) binding;
+ Constant assignConstant;
+ int increment;
+ // using incr bytecode if possible
+ switch (localBinding.type.id) {
+ case T_String :
+ codeStream.generateStringAppend(currentScope, this, expression);
if (valueRequired) {
- if (fieldBinding.isStatic()) {
- if ((fieldBinding.type == LongBinding)
- || (fieldBinding.type == DoubleBinding)) {
- codeStream.dup2();
- } else {
- codeStream.dup();
- }
- } else { // Stack: [owner][old field value] ---> [old field value][owner][old field value]
- if ((fieldBinding.type == LongBinding)
- || (fieldBinding.type == DoubleBinding)) {
- codeStream.dup2_x1();
- } else {
- codeStream.dup_x1();
- }
+ codeStream.dup();
+ }
+ codeStream.store(localBinding, false);
+ return;
+ case T_int :
+ if (((assignConstant = expression.constant) != NotAConstant) && ((increment = assignConstant.intValue()) == (short) increment)) { // 16 bits value
+ switch (operator) {
+ case PLUS :
+ codeStream.iinc(localBinding.resolvedPosition, increment);
+ if (valueRequired) {
+ codeStream.load(localBinding);
+ }
+ return;
+ case MINUS :
+ codeStream.iinc(localBinding.resolvedPosition, -increment);
+ if (valueRequired) {
+ codeStream.load(localBinding);
+ }
+ return;
}
}
- codeStream.generateConstant(
- postIncrement.expression.constant,
- implicitConversion);
- codeStream.sendOperator(postIncrement.operator, fieldBinding.type.id);
- codeStream.generateImplicitConversion(
- postIncrement.assignmentImplicitConversion);
- fieldStore(codeStream, fieldBinding, null, false);
- } else {
- if (fieldBinding.isStatic()) {
- codeStream.aconst_null();
+ default :
+ codeStream.load(localBinding);
+ }
+ }
+ // perform the actual compound operation
+ int operationTypeID;
+ if ((operationTypeID = implicitConversion >> 4) == T_String) {
+ codeStream.generateStringAppend(currentScope, null, expression);
+ } else {
+ // promote the array reference to the suitable operation type
+ codeStream.generateImplicitConversion(implicitConversion);
+ // generate the increment value (will by itself be promoted to the operation value)
+ if (expression == IntLiteral.One){ // prefix operation
+ codeStream.generateConstant(expression.constant, implicitConversion);
+ } else {
+ expression.generateCode(currentScope, codeStream, true);
+ }
+ // perform the operation
+ codeStream.sendOperator(operator, operationTypeID);
+ // cast the value back to the array reference type
+ codeStream.generateImplicitConversion(assignmentImplicitConversion);
+ }
+ // store the result back into the variable
+ switch (bits & RestrictiveFlagMASK) {
+ case FIELD : // assigning to a field
+ FieldBinding fieldBinding = (FieldBinding) binding;
+ if (fieldBinding.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
+ fieldStore(codeStream, (FieldBinding) binding, writeAccessor, valueRequired);
+ } else {
+ // current stack is:
+ // field receiver value
+ if (valueRequired) {
+ if ((fieldBinding.type == LongBinding) || (fieldBinding.type == DoubleBinding)) {
+ codeStream.dup2_x2();
} else {
- if ((bits & DepthMASK) != 0) {
+ codeStream.dup_x2();
+ }
+ }
+ // current stack is:
+ // value field receiver value
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedWriteAccessForField(fieldBinding);
+ }
+ return;
+ case LOCAL : // assigning to a local variable
+ LocalVariableBinding localBinding = (LocalVariableBinding) binding;
+ if (valueRequired) {
+ if ((localBinding.type == LongBinding) || (localBinding.type == DoubleBinding)) {
+ codeStream.dup2();
+ } else {
+ codeStream.dup();
+ }
+ }
+ codeStream.store(localBinding, false);
+ }
+}
+public void generatePostIncrement(BlockScope currentScope, CodeStream codeStream, CompoundAssignment postIncrement, boolean valueRequired) {
+ switch (bits & RestrictiveFlagMASK) {
+ case FIELD : // assigning to a field
+ FieldBinding fieldBinding = (FieldBinding) binding;
+ if (fieldBinding.canBeSeenBy(getReceiverType(currentScope), this, currentScope)) {
+ if (fieldBinding.isStatic()) {
+ codeStream.getstatic(fieldBinding);
+ } else {
+ if ((bits & DepthMASK) != 0) {
+ Object[] emulationPath = currentScope.getExactEmulationPath(currentScope.enclosingSourceType().enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT));
+ if (emulationPath == null) {
// internal error, per construction we should have found it
- // not yet supported
currentScope.problemReporter().needImplementation();
} else {
- generateReceiver(codeStream);
+ codeStream.generateOuterAccess(emulationPath, this, currentScope);
}
+ } else {
+ generateReceiver(codeStream);
}
- ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(
- fieldBinding);
- if (valueRequired) {
- if ((fieldBinding.type == LongBinding)
- || (fieldBinding.type == DoubleBinding)) {
+ codeStream.dup();
+ codeStream.getfield(fieldBinding);
+ }
+ if (valueRequired) {
+ if (fieldBinding.isStatic()) {
+ if ((fieldBinding.type == LongBinding) || (fieldBinding.type == DoubleBinding)) {
codeStream.dup2();
} else {
codeStream.dup();
}
- }
- ((CodeSnippetCodeStream) codeStream).generateEmulationForField(fieldBinding);
- if ((fieldBinding.type == LongBinding)
- || (fieldBinding.type == DoubleBinding)) {
- codeStream.dup_x2();
- codeStream.pop();
- if (fieldBinding.isStatic()) {
- codeStream.aconst_null();
+ } else { // Stack: [owner][old field value] ---> [old field value][owner][old field value]
+ if ((fieldBinding.type == LongBinding) || (fieldBinding.type == DoubleBinding)) {
+ codeStream.dup2_x1();
} else {
- generateReceiver(codeStream);
+ codeStream.dup_x1();
}
- codeStream.dup_x2();
- codeStream.pop();
+ }
+ }
+ codeStream.generateConstant(postIncrement.expression.constant, implicitConversion);
+ codeStream.sendOperator(postIncrement.operator, fieldBinding.type.id);
+ codeStream.generateImplicitConversion(postIncrement.assignmentImplicitConversion);
+ fieldStore(codeStream, fieldBinding, null, false);
+ } else {
+ if (fieldBinding.isStatic()) {
+ codeStream.aconst_null();
+ } else {
+ if ((bits & DepthMASK) != 0) {
+ // internal error, per construction we should have found it
+ // not yet supported
+ currentScope.problemReporter().needImplementation();
} else {
- codeStream.dup_x1();
- codeStream.pop();
- if (fieldBinding.isStatic()) {
- codeStream.aconst_null();
- } else {
- generateReceiver(codeStream);
- }
- codeStream.dup_x1();
- codeStream.pop();
+ generateReceiver(codeStream);
}
- codeStream.generateConstant(
- postIncrement.expression.constant,
- implicitConversion);
- codeStream.sendOperator(postIncrement.operator, fieldBinding.type.id);
- codeStream.generateImplicitConversion(
- postIncrement.assignmentImplicitConversion);
- ((CodeSnippetCodeStream) codeStream).generateEmulatedWriteAccessForField(
- fieldBinding);
}
- return;
- case LOCAL : // assigning to a local variable
- LocalVariableBinding localBinding = (LocalVariableBinding) binding;
- // using incr bytecode if possible
- if (localBinding.type == IntBinding) {
- if (valueRequired) {
- codeStream.load(localBinding);
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedReadAccessForField(fieldBinding);
+ if (valueRequired) {
+ if ((fieldBinding.type == LongBinding) || (fieldBinding.type == DoubleBinding)) {
+ codeStream.dup2();
+ } else {
+ codeStream.dup();
}
- if (postIncrement.operator == PLUS) {
- codeStream.iinc(localBinding.resolvedPosition, 1);
+ }
+ ((CodeSnippetCodeStream) codeStream).generateEmulationForField(fieldBinding);
+ if ((fieldBinding.type == LongBinding) || (fieldBinding.type == DoubleBinding)) {
+ codeStream.dup_x2();
+ codeStream.pop();
+ if (fieldBinding.isStatic()) {
+ codeStream.aconst_null();
} else {
- codeStream.iinc(localBinding.resolvedPosition, -1);
+ generateReceiver(codeStream);
}
+ codeStream.dup_x2();
+ codeStream.pop();
} else {
+ codeStream.dup_x1();
+ codeStream.pop();
+ if (fieldBinding.isStatic()) {
+ codeStream.aconst_null();
+ } else {
+ generateReceiver(codeStream);
+ }
+ codeStream.dup_x1();
+ codeStream.pop();
+ }
+ codeStream.generateConstant(postIncrement.expression.constant, implicitConversion);
+ codeStream.sendOperator(postIncrement.operator, fieldBinding.type.id);
+ codeStream.generateImplicitConversion(postIncrement.assignmentImplicitConversion);
+ ((CodeSnippetCodeStream) codeStream).generateEmulatedWriteAccessForField(fieldBinding);
+ }
+ return;
+ case LOCAL : // assigning to a local variable
+ LocalVariableBinding localBinding = (LocalVariableBinding) binding;
+ // using incr bytecode if possible
+ if (localBinding.type == IntBinding) {
+ if (valueRequired) {
codeStream.load(localBinding);
- if (valueRequired) {
- if ((localBinding.type == LongBinding)
- || (localBinding.type == DoubleBinding)) {
- codeStream.dup2();
- } else {
- codeStream.dup();
- }
+ }
+ if (postIncrement.operator == PLUS) {
+ codeStream.iinc(localBinding.resolvedPosition, 1);
+ } else {
+ codeStream.iinc(localBinding.resolvedPosition, -1);
+ }
+ } else {
+ codeStream.load(localBinding);
+ if (valueRequired){
+ if ((localBinding.type == LongBinding) || (localBinding.type == DoubleBinding)) {
+ codeStream.dup2();
+ } else {
+ codeStream.dup();
}
- codeStream.generateConstant(
- postIncrement.expression.constant,
- implicitConversion);
- codeStream.sendOperator(postIncrement.operator, localBinding.type.id);
- codeStream.generateImplicitConversion(
- postIncrement.assignmentImplicitConversion);
-
- codeStream.store(localBinding, false);
}
- }
- }
+ codeStream.generateConstant(postIncrement.expression.constant, implicitConversion);
+ codeStream.sendOperator(postIncrement.operator, localBinding.type.id);
+ codeStream.generateImplicitConversion(postIncrement.assignmentImplicitConversion);
- public void generateReceiver(CodeStream codeStream) {
- codeStream.aload_0();
- if (delegateThis != null)
- codeStream.getfield(delegateThis); // delegated field access
+ codeStream.store(localBinding, false);
+ }
}
-
- /**
- * Check and/or redirect the field access to the delegate receiver if any
- */
- public TypeBinding getReceiverType(BlockScope currentScope) {
- if (receiverType != null)
- return receiverType;
- Scope scope = currentScope.parent;
- while (true) {
+}
+public void generateReceiver(CodeStream codeStream) {
+ codeStream.aload_0();
+ if (delegateThis != null) codeStream.getfield(delegateThis); // delegated field access
+}
+/**
+ * Check and/or redirect the field access to the delegate receiver if any
+ */
+public TypeBinding getReceiverType(BlockScope currentScope) {
+ if (receiverType != null) return receiverType;
+ Scope scope = currentScope.parent;
+ while (true) {
switch (scope.kind) {
case Scope.CLASS_SCOPE :
return receiverType = ((ClassScope) scope).referenceContext.binding;
- default :
+ default:
scope = scope.parent;
}
- }
}
+}
+/**
+ * Normal field binding did not work, try to bind to a field of the delegate receiver.
+ */
+public TypeBinding reportError(BlockScope scope) {
- /**
- * Normal field binding did not work, try to bind to a field of the delegate receiver.
- */
- public TypeBinding reportError(BlockScope scope) {
-
- constant = Constant.NotAConstant;
- if (binding instanceof ProblemFieldBinding
- && ((ProblemFieldBinding) binding).problemId() == NotFound) {
- if (this.evaluationContext.declaringTypeName != null) {
- delegateThis = scope.getField(scope.enclosingSourceType(), DELEGATE_THIS, this);
- if (delegateThis != null) {
- ; // if not found then internal error, field should have been found
- // will not support innerclass emulation inside delegate
- binding = scope.getField(delegateThis.type, this.token, this);
- if (!binding.isValidBinding())
- return super.reportError(scope);
- return checkFieldAccess(scope);
- }
+ constant = Constant.NotAConstant;
+ if (binding instanceof ProblemFieldBinding && ((ProblemFieldBinding) binding).problemId() == NotFound){
+ if (this.evaluationContext.declaringTypeName != null) {
+ delegateThis = scope.getField(scope.enclosingSourceType(), DELEGATE_THIS, this);
+ if (delegateThis != null){ ; // if not found then internal error, field should have been found
+ // will not support innerclass emulation inside delegate
+ binding = scope.getField(delegateThis.type, this.token, this);
+ if (!binding.isValidBinding()) return super.reportError(scope);
+ return checkFieldAccess(scope);
}
}
- if (binding instanceof ProblemBinding
- && ((ProblemBinding) binding).problemId() == NotFound) {
- if (this.evaluationContext.declaringTypeName != null) {
- delegateThis = scope.getField(scope.enclosingSourceType(), DELEGATE_THIS, this);
- if (delegateThis != null) {
- ; // if not found then internal error, field should have been found
- // will not support innerclass emulation inside delegate
- FieldBinding fieldBinding = scope.getField(delegateThis.type, this.token, this);
- if (!fieldBinding.isValidBinding()) {
- if (((ProblemFieldBinding) fieldBinding).problemId() == NotVisible) {
- // manage the access to a private field of the enclosing type
- CodeSnippetScope localScope = new CodeSnippetScope(scope);
- binding =
- localScope.getFieldForCodeSnippet(delegateThis.type, this.token, this);
- return checkFieldAccess(scope);
- } else {
- return super.reportError(scope);
- }
+ }
+ if (binding instanceof ProblemBinding && ((ProblemBinding) binding).problemId() == NotFound){
+ if (this.evaluationContext.declaringTypeName != null) {
+ delegateThis = scope.getField(scope.enclosingSourceType(), DELEGATE_THIS, this);
+ if (delegateThis != null){ ; // if not found then internal error, field should have been found
+ // will not support innerclass emulation inside delegate
+ FieldBinding fieldBinding = scope.getField(delegateThis.type, this.token, this);
+ if (!fieldBinding.isValidBinding()) {
+ if (((ProblemFieldBinding) fieldBinding).problemId() == NotVisible) {
+ // manage the access to a private field of the enclosing type
+ CodeSnippetScope localScope = new CodeSnippetScope(scope);
+ binding = localScope.getFieldForCodeSnippet(delegateThis.type, this.token, this);
+ return checkFieldAccess(scope);
+ } else {
+ return super.reportError(scope);
}
- binding = fieldBinding;
- return checkFieldAccess(scope);
}
+ binding = fieldBinding;
+ return checkFieldAccess(scope);
}
}
- return super.reportError(scope);
}
-
+ return super.reportError(scope);
+}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetSkeleton.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetSkeleton.java
index 0bd225da26..a030283b2a 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetSkeleton.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetSkeleton.java
@@ -4,7 +4,7 @@ package org.eclipse.jdt.internal.eval;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
-
+
import org.eclipse.jdt.internal.compiler.env.*;
import org.eclipse.jdt.internal.compiler.util.CharOperation;
@@ -15,23 +15,25 @@ import org.eclipse.jdt.internal.compiler.util.CharOperation;
* throws checked exceptio without having to catch those.
*/
public class CodeSnippetSkeleton implements IBinaryType, EvaluationConstants {
- IBinaryMethod[] methods =
- new IBinaryMethod[] { new BinaryMethodSkeleton(
+ IBinaryMethod[] methods = new IBinaryMethod[] {
+ new BinaryMethodSkeleton(
"<init>".toCharArray(),
"()V".toCharArray(),
- new char[][] {
- },
- true),
- new BinaryMethodSkeleton(
- "run".toCharArray(),
- "()V".toCharArray(),
- new char[][] { "java/lang/Throwable".toCharArray()},
- false),
- new BinaryMethodSkeleton(
- "setResult".toCharArray(),
- "(Ljava/lang/Object;Ljava/lang/Class;)V".toCharArray(),
- new char[][] {
- }, false)
+ new char[][] {},
+ true
+ ),
+ new BinaryMethodSkeleton(
+ "run".toCharArray(),
+ "()V".toCharArray(),
+ new char[][] {"java/lang/Throwable".toCharArray()},
+ false
+ ),
+ new BinaryMethodSkeleton(
+ "setResult".toCharArray(),
+ "(Ljava/lang/Object;Ljava/lang/Class;)V".toCharArray(),
+ new char[][] {},
+ false
+ )
};
public class BinaryMethodSkeleton implements IBinaryMethod {
@@ -39,96 +41,83 @@ public class CodeSnippetSkeleton implements IBinaryType, EvaluationConstants {
char[] methodDescriptor;
char[] selector;
boolean isConstructor;
-
- public BinaryMethodSkeleton(
- char[] selector,
- char[] methodDescriptor,
- char[][] exceptionTypeNames,
- boolean isConstructor) {
+
+ public BinaryMethodSkeleton(char[] selector, char[] methodDescriptor, char[][] exceptionTypeNames, boolean isConstructor) {
this.selector = selector;
this.methodDescriptor = methodDescriptor;
this.exceptionTypeNames = exceptionTypeNames;
this.isConstructor = this.isConstructor;
}
-
+
public char[][] getExceptionTypeNames() {
return this.exceptionTypeNames;
}
-
+
public char[] getMethodDescriptor() {
return this.methodDescriptor;
}
-
+
public int getModifiers() {
return IConstants.AccPublic;
}
-
+
public char[] getSelector() {
return this.selector;
}
-
+
public boolean isClinit() {
return false;
}
-
+
public boolean isConstructor() {
return this.isConstructor;
}
}
+
+/**
+ * CodeSnippetSkeleton constructor comment.
+ */
+public CodeSnippetSkeleton() {
+ super();
+}
+public char[] getEnclosingTypeName() {
+ return null;
+}
+public IBinaryField[] getFields() {
+ return null;
+}
+public char[] getFileName() {
+ return CharOperation.concat(CODE_SNIPPET_NAME, ".java".toCharArray());
+}
+public char[][] getInterfaceNames() {
+ return null;
+}
+public IBinaryNestedType[] getMemberTypes() {
+ return null;
+}
+public IBinaryMethod[] getMethods() {
+ return this.methods;
+}
+public int getModifiers() {
+ return IConstants.AccPublic;
+}
+public char[] getName() {
+ return CODE_SNIPPET_NAME;
+}
+public char[] getSuperclassName() {
+ return null;
+}
+public boolean isBinaryType() {
+ return true;
+}
+public boolean isClass() {
+ return true;
+}
+public boolean isInterface() {
+ return false;
+}
- /**
- * CodeSnippetSkeleton constructor comment.
- */
- public CodeSnippetSkeleton() {
- super();
- }
-
- public char[] getEnclosingTypeName() {
- return null;
- }
-
- public IBinaryField[] getFields() {
- return null;
- }
-
- public char[] getFileName() {
- return CharOperation.concat(CODE_SNIPPET_NAME, ".java".toCharArray());
- }
-
- public char[][] getInterfaceNames() {
- return null;
- }
-
- public IBinaryNestedType[] getMemberTypes() {
- return null;
- }
-
- public IBinaryMethod[] getMethods() {
- return this.methods;
- }
-
- public int getModifiers() {
- return IConstants.AccPublic;
- }
-
- public char[] getName() {
- return CODE_SNIPPET_NAME;
- }
-
- public char[] getSuperclassName() {
- return null;
- }
-
- public boolean isBinaryType() {
- return true;
- }
-
- public boolean isClass() {
- return true;
- }
-
- public boolean isInterface() {
- return false;
- }
-
+public char[] sourceFileName() {
+ return null;
+}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetThisReference.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetThisReference.java
index c17fbbccb4..ddabe4bcd8 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetThisReference.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetThisReference.java
@@ -13,91 +13,68 @@ import org.eclipse.jdt.internal.compiler.lookup.*;
* receiver object (i.e. the one of the context in the stack
* frame)
*/
-public class CodeSnippetThisReference
- extends ThisReference
- implements EvaluationConstants, InvocationSite {
+public class CodeSnippetThisReference extends ThisReference implements EvaluationConstants, InvocationSite {
EvaluationContext evaluationContext;
FieldBinding delegateThis;
boolean isImplicit;
- /**
- * CodeSnippetThisReference constructor comment.
- * @param s int
- * @param sourceEnd int
- */
- public CodeSnippetThisReference(
- int s,
- int sourceEnd,
- EvaluationContext evaluationContext,
- boolean isImplicit) {
- super(s, sourceEnd);
- this.evaluationContext = evaluationContext;
- this.isImplicit = isImplicit;
- }
-
- protected boolean checkAccess(MethodScope methodScope) {
- // this/super cannot be used in constructor call
- if (evaluationContext.isConstructorCall) {
- methodScope.problemReporter().fieldsOrThisBeforeConstructorInvocation(this);
- return false;
- }
-
- // static may not refer to this/super
- if (this.evaluationContext.declaringTypeName == null
- || evaluationContext.isStatic) {
- methodScope.problemReporter().errorThisSuperInStatic(this);
- return false;
- }
- return true;
- }
-
- public void generateCode(
- BlockScope currentScope,
- CodeStream codeStream,
- boolean valueRequired) {
- int pc = codeStream.position;
- if (valueRequired) {
- codeStream.aload_0();
- codeStream.getfield(delegateThis);
- }
- codeStream.recordPositionsFrom(pc, this);
- }
-
- public boolean isSuperAccess() {
+/**
+ * CodeSnippetThisReference constructor comment.
+ * @param s int
+ * @param sourceEnd int
+ */
+public CodeSnippetThisReference(int s, int sourceEnd, EvaluationContext evaluationContext, boolean isImplicit) {
+ super(s, sourceEnd);
+ this.evaluationContext = evaluationContext;
+ this.isImplicit = isImplicit;
+}
+protected boolean checkAccess(MethodScope methodScope) {
+ // this/super cannot be used in constructor call
+ if (evaluationContext.isConstructorCall) {
+ methodScope.problemReporter().fieldsOrThisBeforeConstructorInvocation(this);
return false;
}
- public boolean isTypeAccess() {
+ // static may not refer to this/super
+ if (this.evaluationContext.declaringTypeName == null || evaluationContext.isStatic) {
+ methodScope.problemReporter().errorThisSuperInStatic(this);
return false;
}
-
- public TypeBinding resolveType(BlockScope scope) {
-
- // implicit this
- constant = NotAConstant;
- TypeBinding snippetType = null;
- if (this.isImplicit || checkAccess(scope.methodScope())) {
- snippetType = scope.enclosingSourceType();
- }
- if (snippetType == null)
- return null;
-
- delegateThis = scope.getField(snippetType, DELEGATE_THIS, this);
- if (delegateThis == null)
- return null; // internal error, field should have been found
- return delegateThis.type;
- }
-
- public void setDepth(int depth) {
- }
-
- public void setFieldIndex(int index) {
+ return true;
+}
+public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) {
+ int pc = codeStream.position;
+ if (valueRequired) {
+ codeStream.aload_0();
+ codeStream.getfield(delegateThis);
}
+ codeStream.recordPositionsFrom(pc, this);
+}
+public boolean isSuperAccess(){
+ return false;
+}
+public boolean isTypeAccess(){
+ return false;
+}
+public TypeBinding resolveType(BlockScope scope) {
- public String toStringExpression() {
- char[] declaringType = this.evaluationContext.declaringTypeName;
- return "("
- + (declaringType == null ? "<NO DECLARING TYPE>" : new String(declaringType))
- + ")this";
+ // implicit this
+ constant = NotAConstant;
+ TypeBinding snippetType = null;
+ if (this.isImplicit || checkAccess(scope.methodScope())){
+ snippetType = scope.enclosingSourceType();
}
-
+ if (snippetType == null) return null;
+
+ delegateThis = scope.getField(snippetType, DELEGATE_THIS, this);
+ if (delegateThis == null) return null; // internal error, field should have been found
+ return delegateThis.type;
+}
+public void setDepth(int depth){
+}
+public void setFieldIndex(int index){
+}
+public String toStringExpression(){
+ char[] declaringType = this.evaluationContext.declaringTypeName;
+ return "("+ (declaringType == null ? "<NO DECLARING TYPE>" : new String(declaringType)) + ")this";
+}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetToCuMapper.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetToCuMapper.java
index 2a24db35d6..099e699d61 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetToCuMapper.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetToCuMapper.java
@@ -26,7 +26,7 @@ class CodeSnippetToCuMapper implements EvaluationConstants {
* The generated compilation unit.
*/
public char[] cuSource;
-
+
/**
* Where the code snippet starts in the generated compilation unit.
*/
@@ -37,8 +37,7 @@ class CodeSnippetToCuMapper implements EvaluationConstants {
private char[] codeSnippet;
private char[] packageName;
private char[][] imports;
- char[] className;
- // NB: Make it package default visibility to optimize access from inner classes
+ char[] className; // NB: Make it package default visibility to optimize access from inner classes
private char[] varClassName;
// Mapping of external local variables
@@ -47,389 +46,231 @@ class CodeSnippetToCuMapper implements EvaluationConstants {
private int[] localVarModifiers;
private char[] declaringTypeName;
- /**
- * Rebuild source in presence of external local variables
- */
- public CodeSnippetToCuMapper(
- char[] codeSnippet,
- char[] packageName,
- char[][] imports,
- char[] className,
- char[] varClassName,
- char[][] localVarNames,
- char[][] localVarTypeNames,
- int[] localVarModifiers,
- char[] declaringTypeName) {
- this.codeSnippet = codeSnippet;
- this.packageName = packageName;
- this.imports = imports;
- this.className = className;
- this.varClassName = varClassName;
- this.localVarNames = localVarNames;
- this.localVarTypeNames = localVarTypeNames;
- this.localVarModifiers = localVarModifiers;
- this.declaringTypeName = declaringTypeName;
- this.buildCUSource();
- }
+/**
+ * Rebuild source in presence of external local variables
+ */
+ public CodeSnippetToCuMapper(char[] codeSnippet, char[] packageName, char[][] imports, char[] className, char[] varClassName, char[][] localVarNames, char[][] localVarTypeNames, int[] localVarModifiers, char[] declaringTypeName) {
+ this.codeSnippet = codeSnippet;
+ this.packageName = packageName;
+ this.imports = imports;
+ this.className = className;
+ this.varClassName = varClassName;
+ this.localVarNames = localVarNames;
+ this.localVarTypeNames = localVarTypeNames;
+ this.localVarModifiers = localVarModifiers;
+ this.declaringTypeName = declaringTypeName;
+ this.buildCUSource();
+}
+private void buildCUSource() {
+ StringBuffer buffer = new StringBuffer();
- private void buildCUSource() {
- StringBuffer buffer = new StringBuffer();
+ // package declaration
+ if (this.packageName != null && this.packageName.length != 0) {
+ buffer.append("package ");
+ buffer.append(this.packageName);
+ buffer.append(";").append(JavaModelManager.LINE_SEPARATOR);
+ this.lineNumberOffset++;
+ }
- // package declaration
- if (this.packageName != null && this.packageName.length != 0) {
- buffer.append("package ");
- buffer.append(this.packageName);
- buffer.append(";").append(JavaModelManager.LINE_SEPARATOR);
- this.lineNumberOffset++;
- }
+ // import declarations
+ char[][] imports = this.imports;
+ for (int i = 0; i < imports.length; i++) {
+ buffer.append("import ");
+ buffer.append(imports[i]);
+ buffer.append(';').append(JavaModelManager.LINE_SEPARATOR);
+ this.lineNumberOffset++;
+ }
- // import declarations
- char[][] imports = this.imports;
- for (int i = 0; i < imports.length; i++) {
- buffer.append("import ");
- buffer.append(imports[i]);
- buffer.append(';').append(JavaModelManager.LINE_SEPARATOR);
- this.lineNumberOffset++;
- }
+ // class declaration
+ buffer.append("public class ");
+ buffer.append(this.className);
- // class declaration
- buffer.append("public class ");
- buffer.append(this.className);
+ // super class is either a global variable class or the CodeSnippet class
+ if (this.varClassName != null) {
+ buffer.append(" extends ");
+ buffer.append(this.varClassName);
+ } else {
+ buffer.append(" extends ");
+ buffer.append(PACKAGE_NAME);
+ buffer.append(".");
+ buffer.append(ROOT_CLASS_NAME);
+ }
+ buffer.append(" {").append(JavaModelManager.LINE_SEPARATOR);
+ this.lineNumberOffset++;
- // super class is either a global variable class or the CodeSnippet class
- if (this.varClassName != null) {
- buffer.append(" extends ");
- buffer.append(this.varClassName);
- } else {
- buffer.append(" extends ");
- buffer.append(PACKAGE_NAME);
- buffer.append(".");
- buffer.append(ROOT_CLASS_NAME);
- }
- buffer.append(" {").append(JavaModelManager.LINE_SEPARATOR);
+ if (this.declaringTypeName != null){
+ buffer.append(" ");
+ buffer.append(this.declaringTypeName);
+ buffer.append(" ");
+ buffer.append(DELEGATE_THIS); // val$this
+ buffer.append(';').append(JavaModelManager.LINE_SEPARATOR);
this.lineNumberOffset++;
-
- if (this.declaringTypeName != null) {
- buffer.append(" ");
- buffer.append(this.declaringTypeName);
+ }
+ // add some storage location for local variable persisted state
+ if (localVarNames != null) {
+ for (int i = 0, max = localVarNames.length; i < max; i++) {
+ buffer.append(" ");
+ buffer.append(localVarTypeNames[i]);
buffer.append(" ");
- buffer.append(DELEGATE_THIS); // val$this
+ buffer.append(LOCAL_VAR_PREFIX); // val$...
+ buffer.append(localVarNames[i]);
buffer.append(';').append(JavaModelManager.LINE_SEPARATOR);
this.lineNumberOffset++;
}
- // add some storage location for local variable persisted state
- if (localVarNames != null) {
- for (int i = 0, max = localVarNames.length; i < max; i++) {
- buffer.append(" ");
- buffer.append(localVarTypeNames[i]);
- buffer.append(" ");
- buffer.append(LOCAL_VAR_PREFIX); // val$...
- buffer.append(localVarNames[i]);
- buffer.append(';').append(JavaModelManager.LINE_SEPARATOR);
- this.lineNumberOffset++;
- }
- }
- // run() method declaration
- buffer.append("public void run() throws Throwable {").append(
- JavaModelManager.LINE_SEPARATOR);
- this.lineNumberOffset++;
- startPosOffset = buffer.length();
- buffer.append(codeSnippet);
- buffer.append('}').append(JavaModelManager.LINE_SEPARATOR);
-
- // end of class declaration
- buffer.append('}').append(JavaModelManager.LINE_SEPARATOR);
-
- // store result
- int length = buffer.length();
- this.cuSource = new char[length];
- buffer.getChars(0, length, this.cuSource, 0);
}
+ // run() method declaration
+ buffer.append("public void run() throws Throwable {").append(JavaModelManager.LINE_SEPARATOR);
+ this.lineNumberOffset++;
+ startPosOffset = buffer.length();
+ buffer.append(codeSnippet);
+ buffer.append('}').append(JavaModelManager.LINE_SEPARATOR);
- /**
- * Returns a completion requestor that wraps the given requestor and shift the results
- * according to the start offset and line number offset of the code snippet in the generated compilation unit.
- */
- public ICompletionRequestor getCompletionRequestor(final ICompletionRequestor originalRequestor) {
- final int startPosOffset = this.startPosOffset;
- final int lineNumberOffset = this.lineNumberOffset;
- return new ICompletionRequestor() {
- public void acceptClass(
- char[] packageName,
- char[] className,
- char[] completionName,
- int modifiers,
- int completionStart,
- int completionEnd) {
- // Remove completion on generated class name or generated global variable class name
- if (CharOperation.equals(packageName, CodeSnippetToCuMapper.this.packageName)
+ // end of class declaration
+ buffer.append('}').append(JavaModelManager.LINE_SEPARATOR);
+
+ // store result
+ int length = buffer.length();
+ this.cuSource = new char[length];
+ buffer.getChars(0, length, this.cuSource, 0);
+}
+/**
+ * Returns a completion requestor that wraps the given requestor and shift the results
+ * according to the start offset and line number offset of the code snippet in the generated compilation unit.
+ */
+public ICompletionRequestor getCompletionRequestor(final ICompletionRequestor originalRequestor) {
+ final int startPosOffset = this.startPosOffset;
+ final int lineNumberOffset = this.lineNumberOffset;
+ return new ICompletionRequestor() {
+ public void acceptClass(char[] packageName, char[] className, char[] completionName, int modifiers, int completionStart, int completionEnd) {
+ // Remove completion on generated class name or generated global variable class name
+ if (CharOperation.equals(packageName, CodeSnippetToCuMapper.this.packageName)
&& (CharOperation.equals(className, CodeSnippetToCuMapper.this.className)
- || CharOperation.equals(className, CodeSnippetToCuMapper.this.varClassName)))
- return;
- originalRequestor.acceptClass(
- packageName,
- className,
- completionName,
- modifiers,
- completionStart - startPosOffset,
- completionEnd - startPosOffset);
- }
- public void acceptError(IProblem error) {
- error.setSourceLineNumber(error.getSourceLineNumber() - lineNumberOffset);
- error.setSourceStart(error.getSourceStart() - startPosOffset);
- error.setSourceEnd(error.getSourceEnd() - startPosOffset);
- originalRequestor.acceptError(error);
- }
- public void acceptField(
- char[] declaringTypePackageName,
- char[] declaringTypeName,
- char[] name,
- char[] typePackageName,
- char[] typeName,
- char[] completionName,
- int modifiers,
- int completionStart,
- int completionEnd) {
- originalRequestor.acceptField(
- declaringTypePackageName,
- declaringTypeName,
- name,
- typePackageName,
- typeName,
- completionName,
- modifiers,
- completionStart - startPosOffset,
- completionEnd - startPosOffset);
- }
- public void acceptInterface(
- char[] packageName,
- char[] interfaceName,
- char[] completionName,
- int modifiers,
- int completionStart,
- int completionEnd) {
- originalRequestor.acceptInterface(
- packageName,
- interfaceName,
- completionName,
- modifiers,
- completionStart - startPosOffset,
- completionEnd - startPosOffset);
- }
- public void acceptKeyword(
- char[] keywordName,
- int completionStart,
- int completionEnd) {
- originalRequestor.acceptKeyword(
- keywordName,
- completionStart - startPosOffset,
- completionEnd - startPosOffset);
- }
- public void acceptLabel(
- char[] labelName,
- int completionStart,
- int completionEnd) {
- originalRequestor.acceptLabel(
- labelName,
- completionStart - startPosOffset,
- completionEnd - startPosOffset);
- }
- public void acceptLocalVariable(
- char[] name,
- char[] typePackageName,
- char[] typeName,
- int modifiers,
- int completionStart,
- int completionEnd) {
- originalRequestor.acceptLocalVariable(
- name,
- typePackageName,
- typeName,
- modifiers,
- completionStart - startPosOffset,
- completionEnd - startPosOffset);
- }
- public void acceptMethod(
- char[] declaringTypePackageName,
- char[] declaringTypeName,
- char[] selector,
- char[][] parameterPackageNames,
- char[][] parameterTypeNames,
- char[] returnTypePackageName,
- char[] returnTypeName,
- char[] completionName,
- int modifiers,
- int completionStart,
- int completionEnd) {
- // Remove completion on generated method
- if (CharOperation
- .equals(declaringTypePackageName, CodeSnippetToCuMapper.this.packageName)
+ || CharOperation.equals(className, CodeSnippetToCuMapper.this.varClassName))) return;
+ originalRequestor.acceptClass(packageName, className, completionName, modifiers, completionStart - startPosOffset, completionEnd - startPosOffset);
+ }
+ public void acceptError(IProblem error) {
+ error.setSourceLineNumber(error.getSourceLineNumber() - lineNumberOffset);
+ error.setSourceStart(error.getSourceStart() - startPosOffset);
+ error.setSourceEnd(error.getSourceEnd() - startPosOffset);
+ originalRequestor.acceptError(error);
+ }
+ public void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[] typePackageName, char[] typeName, char[] completionName, int modifiers, int completionStart, int completionEnd) {
+ originalRequestor.acceptField(declaringTypePackageName, declaringTypeName, name, typePackageName, typeName, completionName, modifiers, completionStart - startPosOffset, completionEnd - startPosOffset);
+ }
+ public void acceptInterface(char[] packageName, char[] interfaceName, char[] completionName, int modifiers, int completionStart, int completionEnd) {
+ originalRequestor.acceptInterface(packageName, interfaceName, completionName, modifiers, completionStart - startPosOffset, completionEnd - startPosOffset);
+ }
+ public void acceptKeyword(char[] keywordName, int completionStart, int completionEnd) {
+ originalRequestor.acceptKeyword(keywordName, completionStart - startPosOffset, completionEnd - startPosOffset);
+ }
+ public void acceptLabel(char[] labelName, int completionStart, int completionEnd) {
+ originalRequestor.acceptLabel(labelName, completionStart - startPosOffset, completionEnd - startPosOffset);
+ }
+ public void acceptLocalVariable(char[] name, char[] typePackageName, char[] typeName, int modifiers, int completionStart, int completionEnd) {
+ originalRequestor.acceptLocalVariable(name, typePackageName, typeName, modifiers, completionStart - startPosOffset, completionEnd - startPosOffset);
+ }
+ public void acceptMethod(char[] declaringTypePackageName, char[] declaringTypeName, char[] selector, char[][] parameterPackageNames, char[][] parameterTypeNames, char[] returnTypePackageName, char[] returnTypeName, char[] completionName, int modifiers, int completionStart, int completionEnd) {
+ // Remove completion on generated method
+ if (CharOperation.equals(declaringTypePackageName, CodeSnippetToCuMapper.this.packageName)
&& CharOperation.equals(declaringTypeName, CodeSnippetToCuMapper.this.className)
- && CharOperation.equals(selector, "run".toCharArray()))
- return;
- originalRequestor.acceptMethod(
- declaringTypePackageName,
- declaringTypeName,
- selector,
- parameterPackageNames,
- parameterTypeNames,
- returnTypePackageName,
- returnTypeName,
- completionName,
- modifiers,
- completionStart - startPosOffset,
- completionEnd - startPosOffset);
- }
- public void acceptModifier(
- char[] modifierName,
- int completionStart,
- int completionEnd) {
- originalRequestor.acceptModifier(
- modifierName,
- completionStart - startPosOffset,
- completionEnd - startPosOffset);
- }
- public void acceptPackage(
- char[] packageName,
- char[] completionName,
- int completionStart,
- int completionEnd) {
- originalRequestor.acceptPackage(
- packageName,
- completionName,
- completionStart - startPosOffset,
- completionEnd - startPosOffset);
- }
- public void acceptType(
- char[] packageName,
- char[] typeName,
- char[] completionName,
- int completionStart,
- int completionEnd) {
- // Remove completion on generated class name or generated global variable class name
- if (CharOperation.equals(packageName, CodeSnippetToCuMapper.this.packageName)
- && (CharOperation.equals(className, CodeSnippetToCuMapper.this.className)
- || CharOperation.equals(className, CodeSnippetToCuMapper.this.varClassName)))
- return;
- originalRequestor.acceptType(
- packageName,
- typeName,
- completionName,
- completionStart - startPosOffset,
- completionEnd - startPosOffset);
- }
- };
- }
-
- public char[] getCUSource() {
- if (this.cuSource == null) {
- buildCUSource();
+ && CharOperation.equals(selector, "run".toCharArray())) return;
+ originalRequestor.acceptMethod(declaringTypePackageName, declaringTypeName, selector, parameterPackageNames, parameterTypeNames, returnTypePackageName, returnTypeName, completionName, modifiers, completionStart - startPosOffset, completionEnd - startPosOffset);
}
- return this.cuSource;
- }
-
- /**
- * Returns the type of evaluation that corresponds to the given line number in the generated compilation unit.
- */
- public int getEvaluationType(int lineNumber) {
- int currentLine = 1;
-
- // check package declaration
- if (this.packageName != null && this.packageName.length != 0) {
- if (lineNumber == 1) {
- return EvaluationResult.T_PACKAGE;
- }
- currentLine++;
+ public void acceptModifier(char[] modifierName, int completionStart, int completionEnd) {
+ originalRequestor.acceptModifier(modifierName, completionStart - startPosOffset, completionEnd - startPosOffset);
}
-
- // check imports
- char[][] imports = this.imports;
- if ((currentLine <= lineNumber)
- && (lineNumber < (currentLine + imports.length))) {
- return EvaluationResult.T_IMPORT;
+ public void acceptPackage(char[] packageName, char[] completionName, int completionStart, int completionEnd) {
+ originalRequestor.acceptPackage(packageName, completionName, completionStart - startPosOffset, completionEnd - startPosOffset);
}
- currentLine += imports.length + 1; // + 1 to skip the class declaration line
-
- // check generated fields
- currentLine += (this.declaringTypeName == null ? 0 : 1)
- + (this.localVarNames == null ? 0 : this.localVarNames.length);
- if (currentLine > lineNumber) {
- return EvaluationResult.T_INTERNAL;
+ public void acceptType(char[] packageName, char[] typeName, char[] completionName, int completionStart, int completionEnd) {
+ // Remove completion on generated class name or generated global variable class name
+ if (CharOperation.equals(packageName, CodeSnippetToCuMapper.this.packageName)
+ && (CharOperation.equals(className, CodeSnippetToCuMapper.this.className)
+ || CharOperation.equals(className, CodeSnippetToCuMapper.this.varClassName))) return;
+ originalRequestor.acceptType(packageName, typeName, completionName, completionStart - startPosOffset, completionEnd - startPosOffset);
}
- currentLine++; // + 1 to skip the method declaration line
+ };
+}
+public char[] getCUSource() {
+ if (this.cuSource == null) {
+ buildCUSource();
+ }
+ return this.cuSource;
+}
+/**
+ * Returns the type of evaluation that corresponds to the given line number in the generated compilation unit.
+ */
+public int getEvaluationType(int lineNumber) {
+ int currentLine = 1;
- // check code snippet
- if (currentLine >= this.lineNumberOffset) {
- return EvaluationResult.T_CODE_SNIPPET;
+ // check package declaration
+ if (this.packageName != null && this.packageName.length != 0) {
+ if (lineNumber == 1) {
+ return EvaluationResult.T_PACKAGE;
}
+ currentLine++;
+ }
- // default
- return EvaluationResult.T_INTERNAL;
+ // check imports
+ char[][] imports = this.imports;
+ if ((currentLine <= lineNumber) && (lineNumber < (currentLine + imports.length))) {
+ return EvaluationResult.T_IMPORT;
}
+ currentLine += imports.length + 1; // + 1 to skip the class declaration line
- /**
- * Returns the import defined at the given line number.
- */
- public char[] getImport(int lineNumber) {
- int importStartLine = this.lineNumberOffset - 2 - this.imports.length;
- return this.imports[lineNumber - importStartLine];
+ // check generated fields
+ currentLine +=
+ (this.declaringTypeName == null ? 0 : 1)
+ + (this.localVarNames == null ? 0 : this.localVarNames.length);
+ if (currentLine > lineNumber) {
+ return EvaluationResult.T_INTERNAL;
}
+ currentLine ++; // + 1 to skip the method declaration line
- /**
- * Returns a selection requestor that wraps the given requestor and shift the problems
- * according to the start offset and line number offset of the code snippet in the generated compilation unit.
- */
- public ISelectionRequestor getSelectionRequestor(final ISelectionRequestor originalRequestor) {
- final int startPosOffset = this.startPosOffset;
- final int lineNumberOffset = this.lineNumberOffset;
- return new ISelectionRequestor() {
- public void acceptClass(
- char[] packageName,
- char[] className,
- boolean needQualification) {
- originalRequestor.acceptClass(packageName, className, needQualification);
- }
- public void acceptError(IProblem error) {
- error.setSourceLineNumber(error.getSourceLineNumber() - lineNumberOffset);
- error.setSourceStart(error.getSourceStart() - startPosOffset);
- error.setSourceEnd(error.getSourceEnd() - startPosOffset);
- originalRequestor.acceptError(error);
- }
- public void acceptField(
- char[] declaringTypePackageName,
- char[] declaringTypeName,
- char[] name) {
- originalRequestor.acceptField(
- declaringTypePackageName,
- declaringTypeName,
- name);
- }
- public void acceptInterface(
- char[] packageName,
- char[] interfaceName,
- boolean needQualification) {
- originalRequestor.acceptInterface(
- packageName,
- interfaceName,
- needQualification);
- }
- public void acceptMethod(
- char[] declaringTypePackageName,
- char[] declaringTypeName,
- char[] selector,
- char[][] parameterPackageNames,
- char[][] parameterTypeNames) {
- originalRequestor.acceptMethod(
- declaringTypePackageName,
- declaringTypeName,
- selector,
- parameterPackageNames,
- parameterTypeNames);
- }
- public void acceptPackage(char[] packageName) {
- originalRequestor.acceptPackage(packageName);
- }
- };
+ // check code snippet
+ if (currentLine >= this.lineNumberOffset) {
+ return EvaluationResult.T_CODE_SNIPPET;
}
+ // default
+ return EvaluationResult.T_INTERNAL;
+}
+/**
+ * Returns the import defined at the given line number.
+ */
+public char[] getImport(int lineNumber) {
+ int importStartLine = this.lineNumberOffset - 2 - this.imports.length;
+ return this.imports[lineNumber - importStartLine];
+}
+/**
+ * Returns a selection requestor that wraps the given requestor and shift the problems
+ * according to the start offset and line number offset of the code snippet in the generated compilation unit.
+ */
+public ISelectionRequestor getSelectionRequestor(final ISelectionRequestor originalRequestor) {
+ final int startPosOffset = this.startPosOffset;
+ final int lineNumberOffset = this.lineNumberOffset;
+ return new ISelectionRequestor() {
+ public void acceptClass(char[] packageName, char[] className, boolean needQualification) {
+ originalRequestor.acceptClass(packageName, className, needQualification);
+ }
+ public void acceptError(IProblem error) {
+ error.setSourceLineNumber(error.getSourceLineNumber() - lineNumberOffset);
+ error.setSourceStart(error.getSourceStart() - startPosOffset);
+ error.setSourceEnd(error.getSourceEnd() - startPosOffset);
+ originalRequestor.acceptError(error);
+ }
+ public void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, char[] name) {
+ originalRequestor.acceptField(declaringTypePackageName, declaringTypeName, name);
+ }
+ public void acceptInterface(char[] packageName, char[] interfaceName, boolean needQualification) {
+ originalRequestor.acceptInterface(packageName, interfaceName, needQualification);
+ }
+ public void acceptMethod(char[] declaringTypePackageName, char[] declaringTypeName, char[] selector, char[][] parameterPackageNames, char[][] parameterTypeNames) {
+ originalRequestor.acceptMethod(declaringTypePackageName, declaringTypeName, selector, parameterPackageNames, parameterTypeNames);
+ }
+ public void acceptPackage(char[] packageName) {
+ originalRequestor.acceptPackage(packageName);
+ }
+ };
+}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetTypeDeclaration.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetTypeDeclaration.java
index 22a88f2722..8637c5ff05 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetTypeDeclaration.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/CodeSnippetTypeDeclaration.java
@@ -10,68 +10,60 @@ import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.problem.AbortType;
public class CodeSnippetTypeDeclaration extends TypeDeclaration {
- /**
- * Generic bytecode generation for type
- */
- public void generateCode(ClassFile enclosingClassFile) {
- if (ignoreFurtherInvestigation) {
- if (binding == null)
- return;
- CodeSnippetClassFile.createProblemType(
- this,
- scope.referenceCompilationUnit().compilationResult);
+/**
+ * Generic bytecode generation for type
+ */
+public void generateCode(ClassFile enclosingClassFile) {
+ if (ignoreFurtherInvestigation) {
+ if (binding == null)
return;
- }
- try {
- // create the result for a compiled type
- ClassFile classFile =
- new CodeSnippetClassFile(binding, enclosingClassFile, false);
- // generate all fiels
- classFile.addFieldInfos();
+ CodeSnippetClassFile.createProblemType(this, scope.referenceCompilationUnit().compilationResult);
+ return;
+ }
+ try {
+ // create the result for a compiled type
+ ClassFile classFile = new CodeSnippetClassFile(binding, enclosingClassFile, false);
+ // generate all fiels
+ classFile.addFieldInfos();
- // record the inner type inside its own .class file to be able
- // to generate inner classes attributes
- if (binding.isMemberType())
- classFile.recordEnclosingTypeAttributes(binding);
- if (binding.isLocalType()) {
- enclosingClassFile.recordNestedLocalAttribute(binding);
- classFile.recordNestedLocalAttribute(binding);
- }
- if (memberTypes != null) {
- for (int i = 0, max = memberTypes.length; i < max; i++) {
- // record the inner type inside its own .class file to be able
- // to generate inner classes attributes
- classFile.recordNestedMemberAttribute(memberTypes[i].binding);
- memberTypes[i].generateCode(scope, classFile);
- }
- }
- // generate all methods
- classFile.setForMethodInfos();
- if (methods != null) {
- for (int i = 0, max = methods.length; i < max; i++) {
- methods[i].generateCode(scope, classFile);
- }
+ // record the inner type inside its own .class file to be able
+ // to generate inner classes attributes
+ if (binding.isMemberType())
+ classFile.recordEnclosingTypeAttributes(binding);
+ if (binding.isLocalType()) {
+ enclosingClassFile.recordNestedLocalAttribute(binding);
+ classFile.recordNestedLocalAttribute(binding);
+ }
+ if (memberTypes != null) {
+ for (int i = 0, max = memberTypes.length; i < max; i++) {
+ // record the inner type inside its own .class file to be able
+ // to generate inner classes attributes
+ classFile.recordNestedMemberAttribute(memberTypes[i].binding);
+ memberTypes[i].generateCode(scope, classFile);
}
-
- // generate all methods
- classFile.addSpecialMethods();
-
- if (ignoreFurtherInvestigation) { // trigger problem type generation for code gen errors
- throw new AbortType(scope.referenceCompilationUnit().compilationResult);
+ }
+ // generate all methods
+ classFile.setForMethodInfos();
+ if (methods != null) {
+ for (int i = 0, max = methods.length; i < max; i++) {
+ methods[i].generateCode(scope, classFile);
}
+ }
+
+ // generate all methods
+ classFile.addSpecialMethods();
- // finalize the compiled type result
- classFile.addAttributes();
- scope.referenceCompilationUnit().compilationResult.record(
- binding.constantPoolName(),
- classFile);
- } catch (AbortType e) {
- if (binding == null)
- return;
- CodeSnippetClassFile.createProblemType(
- this,
- scope.referenceCompilationUnit().compilationResult);
+ if (ignoreFurtherInvestigation){ // trigger problem type generation for code gen errors
+ throw new AbortType(scope.referenceCompilationUnit().compilationResult);
}
- }
+ // finalize the compiled type result
+ classFile.addAttributes();
+ scope.referenceCompilationUnit().compilationResult.record(binding.constantPoolName(), classFile);
+ } catch (AbortType e) {
+ if (binding == null)
+ return;
+ CodeSnippetClassFile.createProblemType(this, scope.referenceCompilationUnit().compilationResult);
+ }
+}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/EvaluationConstants.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/EvaluationConstants.java
index fe91dc0b05..a4a61fa6ce 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/EvaluationConstants.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/EvaluationConstants.java
@@ -7,28 +7,19 @@ package org.eclipse.jdt.internal.eval;
import org.eclipse.jdt.internal.compiler.util.CharOperation;
public interface EvaluationConstants {
- public static final char[] CODE_SNIPPET_CLASS_NAME_PREFIX =
- "CodeSnippet_".toCharArray();
- public static final char[] GLOBAL_VARS_CLASS_NAME_PREFIX =
- "GlobalVariables_".toCharArray();
- public static final char[] PACKAGE_NAME =
- "org.eclipse.jdt.internal.eval.target".toCharArray();
- public static final char[] CODE_SNIPPET_NAME =
- "org/eclipse/jdt/internal/eval/target/CodeSnippet".toCharArray();
+ public static final char[] CODE_SNIPPET_CLASS_NAME_PREFIX = "CodeSnippet_".toCharArray();
+ public static final char[] GLOBAL_VARS_CLASS_NAME_PREFIX = "GlobalVariables_".toCharArray();
+ public static final char[] PACKAGE_NAME = "org.eclipse.jdt.internal.eval.target".toCharArray();
+ public static final char[] CODE_SNIPPET_NAME = "org/eclipse/jdt/internal/eval/target/CodeSnippet".toCharArray();
public static final char[] ROOT_CLASS_NAME = "CodeSnippet".toCharArray();
- public static final String ROOT_FULL_CLASS_NAME =
- new String(PACKAGE_NAME) + "." + new String(ROOT_CLASS_NAME);
+ public static final String ROOT_FULL_CLASS_NAME = new String(PACKAGE_NAME) + "." + new String(ROOT_CLASS_NAME);
public static final char[] SETRESULT_SELECTOR = "setResult".toCharArray();
- public static final char[] SETRESULT_ARGUMENTS =
- "Ljava.lang.Object;Ljava.lang.Class;".toCharArray();
- public static final char[][] ROOT_COMPOUND_NAME =
- CharOperation.arrayConcat(
- CharOperation.splitOn('.', PACKAGE_NAME),
- ROOT_CLASS_NAME);
+ public static final char[] SETRESULT_ARGUMENTS = "Ljava.lang.Object;Ljava.lang.Class;".toCharArray();
+ public static final char[][] ROOT_COMPOUND_NAME = CharOperation.arrayConcat(CharOperation.splitOn('.', PACKAGE_NAME), ROOT_CLASS_NAME);
public static final String RUN_METHOD = "run";
public static final String RESULT_VALUE_FIELD = "resultValue";
public static final String RESULT_TYPE_FIELD = "resultType";
public final static char[] LOCAL_VAR_PREFIX = "val$".toCharArray();
public final static char[] DELEGATE_THIS = "val$this".toCharArray();
-
+
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/EvaluationContext.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
index 2c133205cd..5fd2936437 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/EvaluationContext.java
@@ -44,1353 +44,490 @@ public class EvaluationContext implements EvaluationConstants {
int[] localVariableModifiers;
char[][] localVariableTypeNames;
char[][] localVariableNames;
-
+
/* can 'this' be used in this context */
boolean isStatic = true;
boolean isConstructorCall = false;
- /**
- * Creates a new evaluation context.
- */
- public EvaluationContext() {
- }
-
- /**
- * Returns the global variables of this evaluation context in the order they were created in.
- */
- public GlobalVariable[] allVariables() {
- GlobalVariable[] result = new GlobalVariable[this.variableCount];
- System.arraycopy(this.variables, 0, result, 0, this.variableCount);
- return result;
- }
-
- /**
- * Computes a completion at the specified position of the given code snippet.
- * (Note that this evaluation context's VM doesn't need to be running.)
- *
- * @param environment com.ibm.codeassist.java.api.ISearchableNameEnvironment
- * used to resolve type/package references and search for types/packages
- * based on partial names.
- *
- * @param requestor com.ibm.codeassist.java.api.ICompletionRequestor
- * since the engine might produce answers of various forms, the engine
- * is associated with a requestor able to accept all possible completions.
- *
- * @param options com.ibm.compiler.java.api.ConfigurableOptions
- * set of options used to configure the code assist engine.
- */
- public void complete(
- char[] codeSnippet,
- int completionPosition,
- ISearchableNameEnvironment environment,
- ICompletionRequestor requestor,
- ConfigurableOption[] options) {
- final char[] className = "CodeSnippetCompletion".toCharArray();
- final CodeSnippetToCuMapper mapper =
- new CodeSnippetToCuMapper(
- codeSnippet,
- this.packageName,
- this.imports,
- className,
- this.installedVars == null ? null : this.installedVars.className,
- this.localVariableNames,
- this.localVariableTypeNames,
- this.localVariableModifiers,
- this.declaringTypeName);
- ICompilationUnit sourceUnit = new ICompilationUnit() {
- public char[] getFileName() {
- return CharOperation.concat(className, "java".toCharArray(), '.');
- }
- public char[] getContents() {
- return mapper.getCUSource();
- }
- public char[] getMainTypeName() {
- return className;
- }
- };
- CompletionEngine engine =
- new CompletionEngine(
- environment,
- mapper.getCompletionRequestor(requestor),
- options);
- engine.complete(sourceUnit, mapper.startPosOffset + completionPosition);
- }
-
- /**
- * Deletes the given variable from this evaluation context. This will take effect in the target VM only
- * the next time global variables are installed.
- */
- public void deleteVariable(GlobalVariable variable) {
- GlobalVariable[] vars = this.variables;
- int index = -1;
- for (int i = 0; i < this.variableCount; i++) {
- if (vars[i].equals(variable)) {
- index = i;
- break;
- }
+/**
+ * Creates a new evaluation context.
+ */
+public EvaluationContext() {
+}
+/**
+ * Returns the global variables of this evaluation context in the order they were created in.
+ */
+public GlobalVariable[] allVariables() {
+ GlobalVariable[] result = new GlobalVariable[this.variableCount];
+ System.arraycopy(this.variables, 0, result, 0, this.variableCount);
+ return result;
+}
+/**
+ * Computes a completion at the specified position of the given code snippet.
+ * (Note that this evaluation context's VM doesn't need to be running.)
+ *
+ * @param environment com.ibm.codeassist.java.api.ISearchableNameEnvironment
+ * used to resolve type/package references and search for types/packages
+ * based on partial names.
+ *
+ * @param requestor com.ibm.codeassist.java.api.ICompletionRequestor
+ * since the engine might produce answers of various forms, the engine
+ * is associated with a requestor able to accept all possible completions.
+ *
+ * @param options com.ibm.compiler.java.api.ConfigurableOptions
+ * set of options used to configure the code assist engine.
+ */
+public void complete(char[] codeSnippet, int completionPosition, ISearchableNameEnvironment environment, ICompletionRequestor requestor, ConfigurableOption[] options) {
+ final char[] className = "CodeSnippetCompletion".toCharArray();
+ final CodeSnippetToCuMapper mapper = new CodeSnippetToCuMapper(
+ codeSnippet,
+ this.packageName,
+ this.imports,
+ className,
+ this.installedVars == null ? null : this.installedVars.className,
+ this.localVariableNames,
+ this.localVariableTypeNames,
+ this.localVariableModifiers,
+ this.declaringTypeName
+ );
+ ICompilationUnit sourceUnit = new ICompilationUnit() {
+ public char[] getFileName() {
+ return CharOperation.concat(className, "java".toCharArray(), '.');
+ }
+ public char[] getContents() {
+ return mapper.getCUSource();
}
- if (index == -1) {
- return;
+ public char[] getMainTypeName() {
+ return className;
}
- int elementCount = this.variableCount--;
- int j = elementCount - index - 1;
- if (j > 0) {
- System.arraycopy(vars, index + 1, vars, index, j);
+ };
+ CompletionEngine engine = new CompletionEngine(environment, mapper.getCompletionRequestor(requestor), options);
+ engine.complete(sourceUnit, mapper.startPosOffset + completionPosition);
+}
+/**
+ * Deletes the given variable from this evaluation context. This will take effect in the target VM only
+ * the next time global variables are installed.
+ */
+public void deleteVariable(GlobalVariable variable) {
+ GlobalVariable[] vars = this.variables;
+ int index = -1;
+ for (int i = 0; i < this.variableCount; i++) {
+ if (vars[i].equals(variable)) {
+ index = i;
+ break;
}
- vars[elementCount - 1] = null;
- this.varsChanged = true;
}
-
- private void deployCodeSnippetClassIfNeeded(IRequestor requestor) {
- if (this.codeSnippetBinary == null) {
- // Deploy CodeSnippet class (only once)
- requestor
- .acceptClassFiles(
- new ClassFile[] {
- new ClassFile() { public byte[] getBytes() { return getCodeSnippetBytes();
+ if (index == -1) {
+ return;
+ }
+ int elementCount = this.variableCount--;
+ int j = elementCount - index - 1;
+ if (j > 0) {
+ System.arraycopy(vars, index + 1, vars, index, j);
+ }
+ vars[elementCount - 1] = null;
+ this.varsChanged = true;
+}
+private void deployCodeSnippetClassIfNeeded(IRequestor requestor) {
+ if (this.codeSnippetBinary == null) {
+ // Deploy CodeSnippet class (only once)
+ requestor.acceptClassFiles(
+ new ClassFile[] {
+ new ClassFile() {
+ public byte[] getBytes() {
+ return getCodeSnippetBytes();
}
public char[][] getCompoundName() {
return EvaluationConstants.ROOT_COMPOUND_NAME;
}
}
- }, null);
- }
+ },
+ null);
}
-
- /**
- * @see org.eclipse.jdt.internal.eval.IEvaluationContext
- * @exception org.eclipse.jdt.internal.eval.InstallException if the code snippet class files could not be deployed.
- */
- public void evaluate(
- char[] codeSnippet,
- char[][] localVariableTypeNames,
- char[][] localVariableNames,
- int[] localVariableModifiers,
- char[] declaringTypeName,
- boolean isStatic,
- boolean isConstructorCall,
- INameEnvironment environment,
- ConfigurableOption[] options,
- final IRequestor requestor,
- IProblemFactory problemFactory)
- throws InstallException {
-
- // Initialialize context
- this.localVariableTypeNames = localVariableTypeNames;
- this.localVariableNames = localVariableNames;
- this.localVariableModifiers = localVariableModifiers;
- this.declaringTypeName = declaringTypeName;
- this.isStatic = isStatic;
- this.isConstructorCall = isConstructorCall;
-
- this.deployCodeSnippetClassIfNeeded(requestor);
-
- try {
- // Install new variables if needed
- class ForwardingRequestor implements IRequestor {
- boolean hasErrors = false;
- public boolean acceptClassFiles(
- ClassFile[] classFiles,
- char[] codeSnippetClassName) {
- return requestor.acceptClassFiles(classFiles, codeSnippetClassName);
- }
- public void acceptProblem(
- IProblem problem,
- char[] fragmentSource,
- int fragmentKind) {
- requestor.acceptProblem(problem, fragmentSource, fragmentKind);
- if (problem.isError()) {
- hasErrors = true;
- }
- }
- };
- ForwardingRequestor forwardingRequestor = new ForwardingRequestor();
- if (this.varsChanged) {
- evaluateVariables(environment, options, forwardingRequestor, problemFactory);
+}
+/**
+ * @see org.eclipse.jdt.internal.eval.IEvaluationContext
+ * @exception org.eclipse.jdt.internal.eval.InstallException if the code snippet class files could not be deployed.
+ */
+public void evaluate(
+ char[] codeSnippet,
+ char[][] localVariableTypeNames,
+ char[][] localVariableNames,
+ int[] localVariableModifiers,
+ char[] declaringTypeName,
+ boolean isStatic,
+ boolean isConstructorCall,
+ INameEnvironment environment,
+ ConfigurableOption[] options,
+ final IRequestor requestor,
+ IProblemFactory problemFactory) throws InstallException {
+
+ // Initialialize context
+ this.localVariableTypeNames = localVariableTypeNames;
+ this.localVariableNames = localVariableNames;
+ this.localVariableModifiers = localVariableModifiers;
+ this.declaringTypeName = declaringTypeName;
+ this.isStatic = isStatic;
+ this.isConstructorCall = isConstructorCall;
+
+ this.deployCodeSnippetClassIfNeeded(requestor);
+
+ try {
+ // Install new variables if needed
+ class ForwardingRequestor implements IRequestor {
+ boolean hasErrors = false;
+ public boolean acceptClassFiles(ClassFile[] classFiles, char[] codeSnippetClassName) {
+ return requestor.acceptClassFiles(classFiles, codeSnippetClassName);
}
-
- // Compile code snippet if there was no errors while evaluating the variables
- if (!forwardingRequestor.hasErrors) {
- Evaluator evaluator =
- new CodeSnippetEvaluator(
- codeSnippet,
- this,
- environment,
- options,
- requestor,
- problemFactory);
- ClassFile[] classes = null;
- if (TIMING) {
- long start = System.currentTimeMillis();
- classes = evaluator.getClasses();
- System.out.println(
- "Time to compile ["
- + new String(codeSnippet)
- + "] was "
- + (System.currentTimeMillis() - start)
- + "ms");
- } else {
- classes = evaluator.getClasses();
- }
- // Send code snippet on target
- if (classes != null && classes.length > 0) {
- char[] simpleClassName = evaluator.getClassName();
- char[] packageName = this.getPackageName();
- char[] qualifiedClassName =
- packageName.length == 0
- ? simpleClassName
- : CharOperation.concat(packageName, simpleClassName, '.');
- CODE_SNIPPET_COUNTER++;
- requestor.acceptClassFiles(classes, qualifiedClassName);
+ public void acceptProblem(IProblem problem, char[] fragmentSource, int fragmentKind) {
+ requestor.acceptProblem(problem, fragmentSource, fragmentKind);
+ if (problem.isError()) {
+ hasErrors = true;
}
}
- } finally {
- // Reinitialize context to default values
- this.localVariableTypeNames = null;
- this.localVariableNames = null;
- this.localVariableModifiers = null;
- this.declaringTypeName = null;
- this.isStatic = true;
- this.isConstructorCall = false;
+ };
+ ForwardingRequestor forwardingRequestor = new ForwardingRequestor();
+ if (this.varsChanged) {
+ evaluateVariables(environment, options, forwardingRequestor, problemFactory);
}
- }
-
- /**
- * @see org.eclipse.jdt.internal.eval.IEvaluationContext
- * @exception org.eclipse.jdt.internal.eval.InstallException if the code snippet class files could not be deployed.
- */
- public void evaluate(
- char[] codeSnippet,
- INameEnvironment environment,
- ConfigurableOption[] options,
- final IRequestor requestor,
- IProblemFactory problemFactory)
- throws InstallException {
- this.evaluate(
- codeSnippet,
- null,
- null,
- null,
- null,
- true,
- false,
- environment,
- options,
- requestor,
- problemFactory);
- }
-
- /**
- * @see org.eclipse.jdt.core.eval.IEvaluationContext
- */
- public void evaluateImports(
- INameEnvironment environment,
- IRequestor requestor,
- IProblemFactory problemFactory) {
- for (int i = 0; i < this.imports.length; i++) {
- IProblem[] problems = new IProblem[] { null };
- char[] importDeclaration = this.imports[i];
- char[][] splitDeclaration = CharOperation.splitOn('.', importDeclaration);
- int splitLength = splitDeclaration.length;
- if (splitLength > 0) {
- char[] packageName = splitDeclaration[splitLength - 1];
- if (packageName.length == 1 && packageName[0] == '*') {
- char[][] parentName;
- switch (splitLength) {
- case 1 :
- parentName = null;
- break;
- case 2 :
- parentName = null;
- packageName = splitDeclaration[splitLength - 2];
- break;
- default :
- parentName = CharOperation.subarray(splitDeclaration, 0, splitLength - 2);
- packageName = splitDeclaration[splitLength - 2];
- }
- if (!environment.isPackage(parentName, packageName)) {
- problems[0] =
- problemFactory.createProblem(
- importDeclaration,
- ProblemIrritants.ImportProblemBase + ProblemReasons.NotFound,
- new String[] { new String(importDeclaration)},
- ProblemSeverities.Warning,
- 0,
- importDeclaration.length - 1,
- i);
- }
- } else {
- if (environment.findType(splitDeclaration) == null) {
- problems[0] =
- problemFactory.createProblem(
- importDeclaration,
- ProblemIrritants.ImportProblemBase + ProblemReasons.NotFound,
- new String[] { new String(importDeclaration)},
- ProblemSeverities.Warning,
- 0,
- importDeclaration.length - 1,
- i);
- }
- }
+
+ // Compile code snippet if there was no errors while evaluating the variables
+ if (!forwardingRequestor.hasErrors) {
+ Evaluator evaluator =
+ new CodeSnippetEvaluator(
+ codeSnippet,
+ this,
+ environment,
+ options,
+ requestor,
+ problemFactory);
+ ClassFile[] classes = null;
+ if (TIMING) {
+ long start = System.currentTimeMillis();
+ classes = evaluator.getClasses();
+ System.out.println("Time to compile [" + new String(codeSnippet) + "] was " + (System.currentTimeMillis() - start) + "ms");
} else {
- problems[0] =
- problemFactory.createProblem(
- importDeclaration,
- ProblemIrritants.ImportProblemBase + ProblemReasons.NotFound,
- new String[] { new String(importDeclaration)},
- ProblemSeverities.Warning,
- 0,
- importDeclaration.length - 1,
- i);
+ classes = evaluator.getClasses();
}
- if (problems[0] != null) {
- requestor.acceptProblem(
- problems[0],
- importDeclaration,
- EvaluationResult.T_IMPORT);
+ // Send code snippet on target
+ if (classes != null && classes.length > 0) {
+ char[] simpleClassName = evaluator.getClassName();
+ char[] packageName = this.getPackageName();
+ char[] qualifiedClassName =
+ packageName.length == 0 ?
+ simpleClassName :
+ CharOperation.concat(packageName, simpleClassName, '.');
+ CODE_SNIPPET_COUNTER++;
+ requestor.acceptClassFiles(classes, qualifiedClassName);
}
}
+ } finally {
+ // Reinitialize context to default values
+ this.localVariableTypeNames = null;
+ this.localVariableNames = null;
+ this.localVariableModifiers = null;
+ this.declaringTypeName = null;
+ this.isStatic = true;
+ this.isConstructorCall = false;
}
-
- /**
- * @see org.eclipse.jdt.internal.eval.IEvaluationContext
- * @exception org.eclipse.jdt.internal.eval.InstallException if the code snippet class files could not be deployed.
- * @exception java.lang.IllegalArgumentException if the global has not been installed yet.
- */
- public void evaluateVariable(
- GlobalVariable variable,
- INameEnvironment environment,
- ConfigurableOption[] options,
- IRequestor requestor,
- IProblemFactory problemFactory)
- throws InstallException {
- this.evaluate(
- variable.getName(),
- environment,
- options,
- requestor,
- problemFactory);
- }
-
- /**
- * @see org.eclipse.jdt.internal.eval.IEvaluationContext
- * @exception org.eclipse.jdt.internal.eval.InstallException if the code snippet class files could not be deployed.
- */
- public void evaluateVariables(
- INameEnvironment environment,
- ConfigurableOption[] options,
- IRequestor requestor,
- IProblemFactory problemFactory)
- throws InstallException {
- this.deployCodeSnippetClassIfNeeded(requestor);
- VariablesEvaluator evaluator =
- new VariablesEvaluator(this, environment, options, requestor, problemFactory);
- ClassFile[] classes = evaluator.getClasses();
- if (classes != null) {
- if (classes.length > 0) {
- // Send classes
- if (!requestor.acceptClassFiles(classes, null)) {
- throw new InstallException("Could not deploy classes for global variables");
+}
+/**
+ * @see org.eclipse.jdt.internal.eval.IEvaluationContext
+ * @exception org.eclipse.jdt.internal.eval.InstallException if the code snippet class files could not be deployed.
+ */
+public void evaluate(char[] codeSnippet, INameEnvironment environment, ConfigurableOption[] options, final IRequestor requestor, IProblemFactory problemFactory) throws InstallException {
+ this.evaluate(
+ codeSnippet,
+ null,
+ null,
+ null,
+ null,
+ true,
+ false,
+ environment,
+ options,
+ requestor,
+ problemFactory);
+}
+/**
+ * @see org.eclipse.jdt.core.eval.IEvaluationContext
+ */
+public void evaluateImports(INameEnvironment environment, IRequestor requestor, IProblemFactory problemFactory) {
+ for (int i = 0; i < this.imports.length; i++) {
+ IProblem[] problems = new IProblem[] {null};
+ char[] importDeclaration = this.imports[i];
+ char[][] splitDeclaration = CharOperation.splitOn('.', importDeclaration);
+ int splitLength = splitDeclaration.length;
+ if (splitLength > 0) {
+ char[] packageName = splitDeclaration[splitLength - 1];
+ if (packageName.length == 1 && packageName[0] == '*') {
+ char[][] parentName;
+ switch (splitLength) {
+ case 1:
+ parentName = null;
+ break;
+ case 2:
+ parentName = null;
+ packageName = splitDeclaration[splitLength - 2];
+ break;
+ default:
+ parentName = CharOperation.subarray(splitDeclaration, 0, splitLength - 2);
+ packageName = splitDeclaration[splitLength - 2];
+ }
+ if (!environment.isPackage(parentName, packageName)) {
+ problems[0] = problemFactory.createProblem(importDeclaration, ProblemIrritants.ImportProblemBase + ProblemReasons.NotFound, new String[] {new String(importDeclaration)}, ProblemSeverities.Warning, 0, importDeclaration.length - 1, i);
+ }
+ } else {
+ if (environment.findType(splitDeclaration) == null) {
+ problems[0] = problemFactory.createProblem(importDeclaration, ProblemIrritants.ImportProblemBase + ProblemReasons.NotFound, new String[] {new String(importDeclaration)}, ProblemSeverities.Warning, 0, importDeclaration.length - 1, i);
}
-
- // Remember that the variables have been installed
- int variableCount = this.variableCount;
- GlobalVariable[] variablesCopy = new GlobalVariable[variableCount];
- System.arraycopy(this.variables, 0, variablesCopy, 0, variableCount);
- this.installedVars =
- new VariablesInfo(
- evaluator.getPackageName(),
- evaluator.getClassName(),
- classes,
- variablesCopy,
- variableCount);
- VAR_CLASS_COUNTER++;
}
- this.varsChanged = false;
- }
- }
-
- /**
- * Returns the bytes of the CodeSnippet class.
- * Generated using the following code snippet:
- [java.io.BufferedWriter writer = new java.io.BufferedWriter(new java.io.FileWriter("d:/temp/CodeSnippet.java"));
- writer.write(org.eclipse.jdt.internal.eval.EvaluationContext.getCodeSnippetSource());
- writer.close();
- org.eclipse.jdt.internal.compiler.batch.Main.compile(
- "d:/temp/CodeSnippet.java -d d:/temp -classpath d:/jdk1.2.2/jre/lib/rt.jar -verbose");
- java.io.FileInputStream reader = new java.io.FileInputStream("d:/temp/org/eclipse/jdt/internal/eval/target/CodeSnippet.class");
- byte[] bytes = org.eclipse.jdt.internal.core.Util.readContentsAsBytes(reader);
- reader.close();
- StringBuffer buffer = new StringBuffer();
- buffer.append("private byte[] getCodeSnippetBytes() {\n");
- buffer.append(" return new byte[] {\n");
- buffer.append(" ");
- for (int i = 0; i < bytes.length; i++) {
- buffer.append(bytes[i]);
- if (i == bytes.length - 1) {
- buffer.append("\n");
} else {
- buffer.append(", ");
+ problems[0] = problemFactory.createProblem(importDeclaration, ProblemIrritants.ImportProblemBase + ProblemReasons.NotFound, new String[] {new String(importDeclaration)}, ProblemSeverities.Warning, 0, importDeclaration.length - 1, i);
}
- }
-
- buffer.append(" };\n");
- buffer.append("}");
- buffer.toString()
- ]
- */
- private byte[] getCodeSnippetBytes() {
- return new byte[] {
- -54,
- -2,
- -70,
- -66,
- 0,
- 3,
- 0,
- 45,
- 0,
- 35,
- 1,
- 0,
- 48,
- 111,
- 114,
- 103,
- 47,
- 101,
- 99,
- 108,
- 105,
- 112,
- 115,
- 101,
- 47,
- 106,
- 100,
- 116,
- 47,
- 105,
- 110,
- 116,
- 101,
- 114,
- 110,
- 97,
- 108,
- 47,
- 101,
- 118,
- 97,
- 108,
- 47,
- 116,
- 97,
- 114,
- 103,
- 101,
- 116,
- 47,
- 67,
- 111,
- 100,
- 101,
- 83,
- 110,
- 105,
- 112,
- 112,
- 101,
- 116,
- 7,
- 0,
- 1,
- 1,
- 0,
- 16,
- 106,
- 97,
- 118,
- 97,
- 47,
- 108,
- 97,
- 110,
- 103,
- 47,
- 79,
- 98,
- 106,
- 101,
- 99,
- 116,
- 7,
- 0,
- 3,
- 1,
- 0,
- 10,
- 114,
- 101,
- 115,
- 117,
- 108,
- 116,
- 84,
- 121,
- 112,
- 101,
- 1,
- 0,
- 17,
- 76,
- 106,
- 97,
- 118,
- 97,
- 47,
- 108,
- 97,
- 110,
- 103,
- 47,
- 67,
- 108,
- 97,
- 115,
- 115,
- 59,
- 1,
- 0,
- 11,
- 114,
- 101,
- 115,
- 117,
- 108,
- 116,
- 86,
- 97,
- 108,
- 117,
- 101,
- 1,
- 0,
- 18,
- 76,
- 106,
- 97,
- 118,
- 97,
- 47,
- 108,
- 97,
- 110,
- 103,
- 47,
- 79,
- 98,
- 106,
- 101,
- 99,
- 116,
- 59,
- 1,
- 0,
- 7,
- 99,
- 108,
- 97,
- 115,
- 115,
- 36,
- 48,
- 1,
- 0,
- 9,
- 83,
- 121,
- 110,
- 116,
- 104,
- 101,
- 116,
- 105,
- 99,
- 1,
- 0,
- 6,
- 60,
- 105,
- 110,
- 105,
- 116,
- 62,
- 1,
- 0,
- 3,
- 40,
- 41,
- 86,
- 1,
- 0,
- 4,
- 67,
- 111,
- 100,
- 101,
- 12,
- 0,
- 11,
- 0,
- 12,
- 10,
- 0,
- 4,
- 0,
- 14,
- 1,
- 0,
- 14,
- 106,
- 97,
- 118,
- 97,
- 47,
- 108,
- 97,
- 110,
- 103,
- 47,
- 86,
- 111,
- 105,
- 100,
- 7,
- 0,
- 16,
- 1,
- 0,
- 4,
- 84,
- 89,
- 80,
- 69,
- 12,
- 0,
- 18,
- 0,
- 6,
- 9,
- 0,
- 17,
- 0,
- 19,
- 12,
- 0,
- 5,
- 0,
- 6,
- 9,
- 0,
- 2,
- 0,
- 21,
- 12,
- 0,
- 7,
- 0,
- 8,
- 9,
- 0,
- 2,
- 0,
- 23,
- 1,
- 0,
- 15,
- 76,
- 105,
- 110,
- 101,
- 78,
- 117,
- 109,
- 98,
- 101,
- 114,
- 84,
- 97,
- 98,
- 108,
- 101,
- 1,
- 0,
- 13,
- 103,
- 101,
- 116,
- 82,
- 101,
- 115,
- 117,
- 108,
- 116,
- 84,
- 121,
- 112,
- 101,
- 1,
- 0,
- 19,
- 40,
- 41,
- 76,
- 106,
- 97,
- 118,
- 97,
- 47,
- 108,
- 97,
- 110,
- 103,
- 47,
- 67,
- 108,
- 97,
- 115,
- 115,
- 59,
- 1,
- 0,
- 14,
- 103,
- 101,
- 116,
- 82,
- 101,
- 115,
- 117,
- 108,
- 116,
- 86,
- 97,
- 108,
- 117,
- 101,
- 1,
- 0,
- 20,
- 40,
- 41,
- 76,
- 106,
- 97,
- 118,
- 97,
- 47,
- 108,
- 97,
- 110,
- 103,
- 47,
- 79,
- 98,
- 106,
- 101,
- 99,
- 116,
- 59,
- 1,
- 0,
- 3,
- 114,
- 117,
- 110,
- 1,
- 0,
- 9,
- 115,
- 101,
- 116,
- 82,
- 101,
- 115,
- 117,
- 108,
- 116,
- 1,
- 0,
- 38,
- 40,
- 76,
- 106,
- 97,
- 118,
- 97,
- 47,
- 108,
- 97,
- 110,
- 103,
- 47,
- 79,
- 98,
- 106,
- 101,
- 99,
- 116,
- 59,
- 76,
- 106,
- 97,
- 118,
- 97,
- 47,
- 108,
- 97,
- 110,
- 103,
- 47,
- 67,
- 108,
- 97,
- 115,
- 115,
- 59,
- 41,
- 86,
- 1,
- 0,
- 10,
- 83,
- 111,
- 117,
- 114,
- 99,
- 101,
- 70,
- 105,
- 108,
- 101,
- 1,
- 0,
- 16,
- 67,
- 111,
- 100,
- 101,
- 83,
- 110,
- 105,
- 112,
- 112,
- 101,
- 116,
- 46,
- 106,
- 97,
- 118,
- 97,
- 0,
- 33,
- 0,
- 2,
- 0,
- 4,
- 0,
- 0,
- 0,
- 3,
- 0,
- 2,
- 0,
- 5,
- 0,
- 6,
- 0,
- 0,
- 0,
- 2,
- 0,
- 7,
- 0,
- 8,
- 0,
- 0,
- 0,
- 8,
- 0,
- 9,
- 0,
- 6,
- 0,
- 1,
- 0,
- 10,
- 0,
- 0,
- 0,
- 0,
- 0,
- 5,
- 0,
- 1,
- 0,
- 11,
- 0,
- 12,
- 0,
- 1,
- 0,
- 13,
- 0,
- 0,
- 0,
- 53,
- 0,
- 2,
- 0,
- 1,
- 0,
- 0,
- 0,
- 17,
- 42,
- -73,
- 0,
- 15,
- 42,
- -78,
- 0,
- 20,
- -75,
- 0,
- 22,
- 42,
- 1,
- -75,
- 0,
- 24,
- -79,
- 0,
- 0,
- 0,
- 1,
- 0,
- 25,
- 0,
- 0,
- 0,
- 18,
- 0,
- 4,
- 0,
- 0,
- 0,
- 17,
- 0,
- 4,
- 0,
- 18,
- 0,
- 11,
- 0,
- 19,
- 0,
- 16,
- 0,
- 17,
- 0,
- 1,
- 0,
- 26,
- 0,
- 27,
- 0,
- 1,
- 0,
- 13,
- 0,
- 0,
- 0,
- 29,
- 0,
- 1,
- 0,
- 1,
- 0,
- 0,
- 0,
- 5,
- 42,
- -76,
- 0,
- 22,
- -80,
- 0,
- 0,
- 0,
- 1,
- 0,
- 25,
- 0,
- 0,
- 0,
- 6,
- 0,
- 1,
- 0,
- 0,
- 0,
- 24,
- 0,
- 1,
- 0,
- 28,
- 0,
- 29,
- 0,
- 1,
- 0,
- 13,
- 0,
- 0,
- 0,
- 29,
- 0,
- 1,
- 0,
- 1,
- 0,
- 0,
- 0,
- 5,
- 42,
- -76,
- 0,
- 24,
- -80,
- 0,
- 0,
- 0,
- 1,
- 0,
- 25,
- 0,
- 0,
- 0,
- 6,
- 0,
- 1,
- 0,
- 0,
- 0,
- 30,
- 0,
- 1,
- 0,
- 30,
- 0,
- 12,
- 0,
- 1,
- 0,
- 13,
- 0,
- 0,
- 0,
- 25,
- 0,
- 0,
- 0,
- 1,
- 0,
- 0,
- 0,
- 1,
- -79,
- 0,
- 0,
- 0,
- 1,
- 0,
- 25,
- 0,
- 0,
- 0,
- 6,
- 0,
- 1,
- 0,
- 0,
- 0,
- 36,
- 0,
- 1,
- 0,
- 31,
- 0,
- 32,
- 0,
- 1,
- 0,
- 13,
- 0,
- 0,
- 0,
- 43,
- 0,
- 2,
- 0,
- 3,
- 0,
- 0,
- 0,
- 11,
- 42,
- 43,
- -75,
- 0,
- 24,
- 42,
- 44,
- -75,
- 0,
- 22,
- -79,
- 0,
- 0,
- 0,
- 1,
- 0,
- 25,
- 0,
- 0,
- 0,
- 14,
- 0,
- 3,
- 0,
- 0,
- 0,
- 42,
- 0,
- 5,
- 0,
- 43,
- 0,
- 10,
- 0,
- 41,
- 0,
- 1,
- 0,
- 33,
- 0,
- 0,
- 0,
- 2,
- 0,
- 34 };
- }
-
- /**
- * Returns the source of the CodeSnippet class.
- * This is used to generate the binary of the CodeSnippetClass
- * @see getCodeSnippetBytes
- */
- public static String getCodeSnippetSource() {
- return "package org.eclipse.jdt.internal.eval.target;\n"
- + "\n"
- + "/*\n"
- + " * (c) Copyright IBM Corp. 2000, 2001.\n"
- + " * All Rights Reserved.\n"
- + " */\n"
- + "/**\n"
- + " * The root of all code snippet classes. Code snippet classes\n"
- + " * are supposed to overide the run() method.\n"
- + " * <p>\n"
- + " * IMPORTANT NOTE:\n"
- + " * All methods in this class must be public since this class is going to be loaded by the\n"
- + " * bootstrap class loader, and the other code snippet support classes might be loaded by \n"
- + " * another class loader (so their runtime packages are going to be different).\n"
- + " */\n"
- + "public class CodeSnippet {\n"
- + " private Class resultType = void.class;\n"
- + " private Object resultValue = null;\n"
- + "/**\n"
- + " * Returns the result type of the code snippet evaluation.\n"
- + " */\n"
- + "public Class getResultType() {\n"
- + " return this.resultType;\n"
- + "}\n"
- + "/**\n"
- + " * Returns the result value of the code snippet evaluation.\n"
- + " */\n"
- + "public Object getResultValue() {\n"
- + " return this.resultValue;\n"
- + "}\n"
- + "/**\n"
- + " * The code snippet. Subclasses must override this method with a transformed code snippet\n"
- + " * that stores the result using setResult(Class, Object).\n"
- + " */\n"
- + "public void run() {\n"
- + "}\n"
- + "/**\n"
- + " * Stores the result type and value of the code snippet evaluation.\n"
- + " */\n"
- + "public void setResult(Object resultValue, Class resultType) {\n"
- + " this.resultValue = resultValue;\n"
- + " this.resultType = resultType;\n"
- + "}\n"
- + "}\n";
- }
-
- /**
- * Returns the imports of this evaluation context. An import is the name of a package
- * or the fully qualified name of a type as defined in the import statement of
- * a compilation unit.
- */
- public char[][] getImports() {
- return this.imports;
- }
-
- /**
- * Returns the dot-separated name of the package code snippets are run into.
- * Returns an empty array for the default package. This is the default if
- * the package name has never been set.
- */
- public char[] getPackageName() {
- return this.packageName;
- }
-
- /**
- * Return the binary for the root code snippet class (ie. org.eclipse.jdt.internal.eval.target.CodeSnippet).
- */
- IBinaryType getRootCodeSnippetBinary() {
- if (codeSnippetBinary == null) {
- this.codeSnippetBinary = new CodeSnippetSkeleton();
+ if (problems[0] != null) {
+ requestor.acceptProblem(problems[0], importDeclaration, EvaluationResult.T_IMPORT);
}
- return this.codeSnippetBinary;
- }
-
- /**
- * Returns the name of the file (including the package name) of the given class file.
- * The simple name doesn't contain the extension ".class".
- * The returned name doesn't start with a "/"
- */
- private String getSupportClassFileName(String simpleName) {
- char separator = File.separatorChar;
- char[][] compoundPackageName = CharOperation.splitOn('.', PACKAGE_NAME);
- return new String(CharOperation.concatWith(compoundPackageName, separator))
- + separator
- + simpleName
- + ".class";
}
+}
+/**
+ * @see org.eclipse.jdt.internal.eval.IEvaluationContext
+ * @exception org.eclipse.jdt.internal.eval.InstallException if the code snippet class files could not be deployed.
+ * @exception java.lang.IllegalArgumentException if the global has not been installed yet.
+ */
+public void evaluateVariable(GlobalVariable variable, INameEnvironment environment, ConfigurableOption[] options, IRequestor requestor, IProblemFactory problemFactory) throws InstallException {
+ this.evaluate(variable.getName(), environment, options, requestor, problemFactory);
+}
+/**
+ * @see org.eclipse.jdt.internal.eval.IEvaluationContext
+ * @exception org.eclipse.jdt.internal.eval.InstallException if the code snippet class files could not be deployed.
+ */
+public void evaluateVariables(INameEnvironment environment, ConfigurableOption[] options, IRequestor requestor, IProblemFactory problemFactory) throws InstallException {
+ this.deployCodeSnippetClassIfNeeded(requestor);
+ VariablesEvaluator evaluator = new VariablesEvaluator(this, environment, options, requestor, problemFactory);
+ ClassFile[] classes = evaluator.getClasses();
+ if (classes != null) {
+ if (classes.length > 0) {
+ // Send classes
+ if (!requestor.acceptClassFiles(classes, null)) {
+ throw new InstallException("Could not deploy classes for global variables");
+ }
- /**
- * Creates a new global variable with the given name, type and initializer.
- * If the variable is not initialized, the initializer can be null.
- * Note that this doesn't install it to this evaluation context's VM.
- *
- * @see GlobalVariable
- */
- public GlobalVariable newVariable(
- char[] typeName,
- char[] name,
- char[] initializer) {
- GlobalVariable var = new GlobalVariable(typeName, name, initializer);
- try {
- this.variables[this.variableCount++] = var;
- } catch (ArrayIndexOutOfBoundsException e) {
- int index = this.variableCount - 1;
- GlobalVariable[] oldVars = this.variables;
- GlobalVariable[] newVars = new GlobalVariable[index * 2];
- System.arraycopy(oldVars, 0, newVars, 0, index);
- newVars[index] = var;
- this.variables = newVars;
+ // Remember that the variables have been installed
+ int variableCount = this.variableCount;
+ GlobalVariable[] variablesCopy = new GlobalVariable[variableCount];
+ System.arraycopy(this.variables, 0, variablesCopy, 0, variableCount);
+ this.installedVars = new VariablesInfo(evaluator.getPackageName(), evaluator.getClassName(), classes, variablesCopy, variableCount);
+ VAR_CLASS_COUNTER++;
}
- this.varsChanged = true;
- return var;
+ this.varsChanged = false;
}
-
- /**
- * Computes the selection at the specified positions of the given code snippet.
- * (Note that this evaluation context's VM doesn't need to be running.)
- *
- * @param environment com.ibm.codeassist.java.api.ISearchableNameEnvironment
- * used to resolve type/package references and search for types/packages
- * based on partial names.
- *
- * @param requestor com.ibm.codeassist.java.api.ISelectionRequestor
- * since the engine might produce answers of various forms, the engine
- * is associated with a requestor able to accept all possible selections.
- *
- * @param options com.ibm.compiler.java.api.ConfigurableOptions
- * set of options used to configure the code assist engine.
- */
- public void select(
- char[] codeSnippet,
- int selectionSourceStart,
- int selectionSourceEnd,
- ISearchableNameEnvironment environment,
- ISelectionRequestor requestor,
- ConfigurableOption[] options) {
-
- final char[] className = "CodeSnippetSelection".toCharArray();
- final CodeSnippetToCuMapper mapper =
- new CodeSnippetToCuMapper(
- codeSnippet,
- this.packageName,
- this.imports,
- className,
- this.installedVars == null ? null : this.installedVars.className,
- this.localVariableNames,
- this.localVariableTypeNames,
- this.localVariableModifiers,
- this.declaringTypeName);
- ICompilationUnit sourceUnit = new ICompilationUnit() {
- public char[] getFileName() {
- return CharOperation.concat(className, "java".toCharArray(), '.');
- }
- public char[] getContents() {
- return mapper.getCUSource();
- }
- public char[] getMainTypeName() {
- return className;
- }
- };
- SelectionEngine engine =
- new SelectionEngine(
- environment,
- mapper.getSelectionRequestor(requestor),
- options);
- engine.select(
- sourceUnit,
- mapper.startPosOffset + selectionSourceStart,
- mapper.startPosOffset + selectionSourceEnd);
+}
+/**
+ * Returns the bytes of the CodeSnippet class.
+ * Generated using the following code snippet:
+[java.io.BufferedWriter writer = new java.io.BufferedWriter(new java.io.FileWriter("d:/temp/CodeSnippet.java"));
+writer.write(org.eclipse.jdt.internal.eval.EvaluationContext.getCodeSnippetSource());
+writer.close();
+org.eclipse.jdt.internal.compiler.batch.Main.compile(
+ "d:/temp/CodeSnippet.java -d d:/temp -classpath d:/jdk1.2.2/jre/lib/rt.jar -verbose");
+java.io.FileInputStream reader = new java.io.FileInputStream("d:/temp/org/eclipse/jdt/internal/eval/target/CodeSnippet.class");
+byte[] bytes = org.eclipse.jdt.internal.core.Util.readContentsAsBytes(reader);
+reader.close();
+StringBuffer buffer = new StringBuffer();
+buffer.append("private byte[] getCodeSnippetBytes() {\n");
+buffer.append(" return new byte[] {\n");
+buffer.append(" ");
+for (int i = 0; i < bytes.length; i++) {
+ buffer.append(bytes[i]);
+ if (i == bytes.length - 1) {
+ buffer.append("\n");
+ } else {
+ buffer.append(", ");
}
-
- /**
- * Sets the imports of this evaluation context. An import is the name of a package
- * or the fully qualified name of a type as defined in the import statement of
- * a compilation unit (see the Java Language Specifications for more details).
- */
- public void setImports(char[][] imports) {
- this.imports = imports;
- this.varsChanged = true;
- // this may change the visibility of the variable's types
+}
+buffer.append(" };\n");
+buffer.append("}");
+buffer.toString()
+]
+ */
+private byte[] getCodeSnippetBytes() {
+ return new byte[] {
+ -54, -2, -70, -66, 0, 3, 0, 45, 0, 35, 1, 0, 48, 111, 114, 103, 47, 101, 99, 108, 105, 112, 115, 101, 47, 106, 100, 116, 47, 105, 110, 116, 101, 114, 110, 97, 108, 47, 101, 118, 97, 108, 47, 116, 97, 114, 103, 101, 116, 47, 67, 111, 100, 101, 83, 110, 105, 112, 112, 101, 116, 7, 0, 1, 1, 0, 16, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 79, 98, 106, 101, 99, 116, 7, 0, 3, 1, 0, 10, 114, 101, 115, 117, 108, 116, 84, 121, 112, 101, 1, 0, 17, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 67, 108, 97, 115, 115, 59, 1, 0, 11, 114, 101, 115, 117, 108, 116, 86, 97, 108, 117, 101, 1, 0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 79, 98, 106, 101, 99, 116, 59, 1, 0, 7, 99, 108, 97, 115, 115, 36, 48, 1, 0, 9, 83, 121, 110, 116, 104, 101, 116, 105, 99, 1, 0, 6, 60, 105, 110, 105, 116, 62, 1, 0, 3, 40, 41, 86, 1, 0, 4, 67, 111, 100, 101, 12, 0, 11, 0, 12, 10, 0, 4, 0, 14, 1, 0, 14, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 86, 111, 105, 100, 7, 0, 16, 1, 0, 4, 84, 89, 80, 69, 12, 0, 18, 0, 6, 9, 0, 17, 0, 19, 12, 0, 5, 0, 6, 9, 0, 2, 0, 21, 12, 0, 7, 0, 8, 9, 0, 2, 0, 23, 1, 0, 15, 76, 105, 110, 101, 78, 117, 109, 98, 101, 114, 84, 97, 98, 108, 101, 1, 0, 13, 103, 101, 116, 82, 101, 115, 117, 108, 116, 84, 121, 112, 101, 1, 0, 19, 40, 41, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 67, 108, 97, 115, 115, 59, 1, 0, 14, 103, 101, 116, 82, 101, 115, 117, 108, 116, 86, 97, 108, 117, 101, 1, 0, 20, 40, 41, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 79, 98, 106, 101, 99, 116, 59, 1, 0, 3, 114, 117, 110, 1, 0, 9, 115, 101, 116, 82, 101, 115, 117, 108, 116, 1, 0, 38, 40, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 79, 98, 106, 101, 99, 116, 59, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 67, 108, 97, 115, 115, 59, 41, 86, 1, 0, 10, 83, 111, 117, 114, 99, 101, 70, 105, 108, 101, 1, 0, 16, 67, 111, 100, 101, 83, 110, 105, 112, 112, 101, 116, 46, 106, 97, 118, 97, 0, 33, 0, 2, 0, 4, 0, 0, 0, 3, 0, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 7, 0, 8, 0, 0, 0, 8, 0, 9, 0, 6, 0, 1, 0, 10, 0, 0, 0, 0, 0, 5, 0, 1, 0, 11, 0, 12, 0, 1, 0, 13, 0, 0, 0, 53, 0, 2, 0, 1, 0, 0, 0, 17, 42, -73, 0, 15, 42, -78, 0, 20, -75, 0, 22, 42, 1, -75, 0, 24, -79, 0, 0, 0, 1, 0, 25, 0, 0, 0, 18, 0, 4, 0, 0, 0, 17, 0, 4, 0, 18, 0, 11, 0, 19, 0, 16, 0, 17, 0, 1, 0, 26, 0, 27, 0, 1, 0, 13, 0, 0, 0, 29, 0, 1, 0, 1, 0, 0, 0, 5, 42, -76, 0, 22, -80, 0, 0, 0, 1, 0, 25, 0, 0, 0, 6, 0, 1, 0, 0, 0, 24, 0, 1, 0, 28, 0, 29, 0, 1, 0, 13, 0, 0, 0, 29, 0, 1, 0, 1, 0, 0, 0, 5, 42, -76, 0, 24, -80, 0, 0, 0, 1, 0, 25, 0, 0, 0, 6, 0, 1, 0, 0, 0, 30, 0, 1, 0, 30, 0, 12, 0, 1, 0, 13, 0, 0, 0, 25, 0, 0, 0, 1, 0, 0, 0, 1, -79, 0, 0, 0, 1, 0, 25, 0, 0, 0, 6, 0, 1, 0, 0, 0, 36, 0, 1, 0, 31, 0, 32, 0, 1, 0, 13, 0, 0, 0, 43, 0, 2, 0, 3, 0, 0, 0, 11, 42, 43, -75, 0, 24, 42, 44, -75, 0, 22, -79, 0, 0, 0, 1, 0, 25, 0, 0, 0, 14, 0, 3, 0, 0, 0, 42, 0, 5, 0, 43, 0, 10, 0, 41, 0, 1, 0, 33, 0, 0, 0, 2, 0, 34
+ };
+}
+/**
+ * Returns the source of the CodeSnippet class.
+ * This is used to generate the binary of the CodeSnippetClass
+ * @see getCodeSnippetBytes
+ */
+public static String getCodeSnippetSource() {
+ return
+ "package org.eclipse.jdt.internal.eval.target;\n" +
+ "\n" +
+ "/*\n" +
+ " * (c) Copyright IBM Corp. 2000, 2001.\n" +
+ " * All Rights Reserved.\n" +
+ " */\n" +
+ "/**\n" +
+ " * The root of all code snippet classes. Code snippet classes\n" +
+ " * are supposed to overide the run() method.\n" +
+ " * <p>\n" +
+ " * IMPORTANT NOTE:\n" +
+ " * All methods in this class must be public since this class is going to be loaded by the\n" +
+ " * bootstrap class loader, and the other code snippet support classes might be loaded by \n" +
+ " * another class loader (so their runtime packages are going to be different).\n" +
+ " */\n" +
+ "public class CodeSnippet {\n" +
+ " private Class resultType = void.class;\n" +
+ " private Object resultValue = null;\n" +
+ "/**\n" +
+ " * Returns the result type of the code snippet evaluation.\n" +
+ " */\n" +
+ "public Class getResultType() {\n" +
+ " return this.resultType;\n" +
+ "}\n" +
+ "/**\n" +
+ " * Returns the result value of the code snippet evaluation.\n" +
+ " */\n" +
+ "public Object getResultValue() {\n" +
+ " return this.resultValue;\n" +
+ "}\n" +
+ "/**\n" +
+ " * The code snippet. Subclasses must override this method with a transformed code snippet\n" +
+ " * that stores the result using setResult(Class, Object).\n" +
+ " */\n" +
+ "public void run() {\n" +
+ "}\n" +
+ "/**\n" +
+ " * Stores the result type and value of the code snippet evaluation.\n" +
+ " */\n" +
+ "public void setResult(Object resultValue, Class resultType) {\n" +
+ " this.resultValue = resultValue;\n" +
+ " this.resultType = resultType;\n" +
+ "}\n" +
+ "}\n";
+}
+/**
+ * Returns the imports of this evaluation context. An import is the name of a package
+ * or the fully qualified name of a type as defined in the import statement of
+ * a compilation unit.
+ */
+public char[][] getImports() {
+ return this.imports;
+}
+/**
+ * Returns the dot-separated name of the package code snippets are run into.
+ * Returns an empty array for the default package. This is the default if
+ * the package name has never been set.
+ */
+public char[] getPackageName() {
+ return this.packageName;
+}
+/**
+ * Return the binary for the root code snippet class (ie. org.eclipse.jdt.internal.eval.target.CodeSnippet).
+ */
+IBinaryType getRootCodeSnippetBinary() {
+ if (codeSnippetBinary == null) {
+ this.codeSnippetBinary = new CodeSnippetSkeleton();
}
-
- /**
- * Sets the dot-separated name of the package code snippets are ran into.
- * The default package name is an empty array.
- */
- public void setPackageName(char[] packageName) {
- this.packageName = packageName;
- this.varsChanged = true;
- // this may change the visibility of the variable's types
+ return this.codeSnippetBinary;
+}
+/**
+ * Returns the name of the file (including the package name) of the given class file.
+ * The simple name doesn't contain the extension ".class".
+ * The returned name doesn't start with a "/"
+ */
+private String getSupportClassFileName(String simpleName) {
+ char separator = File.separatorChar;
+ char[][] compoundPackageName = CharOperation.splitOn('.', PACKAGE_NAME);
+ return new String(CharOperation.concatWith(compoundPackageName, separator)) + separator + simpleName + ".class";
+}
+/**
+ * Creates a new global variable with the given name, type and initializer.
+ * If the variable is not initialized, the initializer can be null.
+ * Note that this doesn't install it to this evaluation context's VM.
+ *
+ * @see GlobalVariable
+ */
+public GlobalVariable newVariable(char[] typeName, char[] name, char[] initializer) {
+ GlobalVariable var = new GlobalVariable(typeName, name, initializer);
+ try {
+ this.variables[this.variableCount++] = var;
+ } catch (ArrayIndexOutOfBoundsException e) {
+ int index = this.variableCount - 1;
+ GlobalVariable[] oldVars = this.variables;
+ GlobalVariable[] newVars = new GlobalVariable[index * 2];
+ System.arraycopy(oldVars, 0, newVars, 0, index);
+ newVars[index] = var;
+ this.variables = newVars;
}
-
+ this.varsChanged = true;
+ return var;
+}
+/**
+ * Computes the selection at the specified positions of the given code snippet.
+ * (Note that this evaluation context's VM doesn't need to be running.)
+ *
+ * @param environment com.ibm.codeassist.java.api.ISearchableNameEnvironment
+ * used to resolve type/package references and search for types/packages
+ * based on partial names.
+ *
+ * @param requestor com.ibm.codeassist.java.api.ISelectionRequestor
+ * since the engine might produce answers of various forms, the engine
+ * is associated with a requestor able to accept all possible selections.
+ *
+ * @param options com.ibm.compiler.java.api.ConfigurableOptions
+ * set of options used to configure the code assist engine.
+ */
+public void select(
+ char[] codeSnippet,
+ int selectionSourceStart,
+ int selectionSourceEnd,
+ ISearchableNameEnvironment environment,
+ ISelectionRequestor requestor,
+ ConfigurableOption[] options) {
+
+ final char[] className = "CodeSnippetSelection".toCharArray();
+ final CodeSnippetToCuMapper mapper = new CodeSnippetToCuMapper(
+ codeSnippet,
+ this.packageName,
+ this.imports,
+ className,
+ this.installedVars == null ? null : this.installedVars.className,
+ this.localVariableNames,
+ this.localVariableTypeNames,
+ this.localVariableModifiers,
+ this.declaringTypeName
+ );
+ ICompilationUnit sourceUnit = new ICompilationUnit() {
+ public char[] getFileName() {
+ return CharOperation.concat(className, "java".toCharArray(), '.');
+ }
+ public char[] getContents() {
+ return mapper.getCUSource();
+ }
+ public char[] getMainTypeName() {
+ return className;
+ }
+ };
+ SelectionEngine engine = new SelectionEngine(environment, mapper.getSelectionRequestor(requestor), options);
+ engine.select(sourceUnit, mapper.startPosOffset + selectionSourceStart, mapper.startPosOffset + selectionSourceEnd);
+}
+/**
+ * Sets the imports of this evaluation context. An import is the name of a package
+ * or the fully qualified name of a type as defined in the import statement of
+ * a compilation unit (see the Java Language Specifications for more details).
+ */
+public void setImports(char[][] imports) {
+ this.imports = imports;
+ this.varsChanged = true; // this may change the visibility of the variable's types
+}
+/**
+ * Sets the dot-separated name of the package code snippets are ran into.
+ * The default package name is an empty array.
+ */
+public void setPackageName(char[] packageName) {
+ this.packageName = packageName;
+ this.varsChanged = true; // this may change the visibility of the variable's types
+}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/EvaluationResult.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/EvaluationResult.java
index c0bb8f0993..9d0e9614d2 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/EvaluationResult.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/EvaluationResult.java
@@ -17,7 +17,7 @@ import org.eclipse.jdt.internal.compiler.IProblem;
*/
public class EvaluationResult {
static final IProblem[] NO_PROBLEMS = new IProblem[0];
-
+
char[] evaluationID;
int evaluationType;
IProblem[] problems;
@@ -53,194 +53,173 @@ public class EvaluationResult {
* The evaluation result reports an internal problem.
*/
public static final int T_INTERNAL = 5;
-
- public EvaluationResult(
- char[] evaluationID,
- int evaluationType,
- char[] displayString,
- char[] typeName) {
- this.evaluationID = evaluationID;
- this.evaluationType = evaluationType;
- this.displayString = displayString;
- this.typeName = typeName;
- this.problems = NO_PROBLEMS;
- }
-
- public EvaluationResult(
- char[] evaluationID,
- int evaluationType,
- IProblem[] problems) {
- this.evaluationID = evaluationID;
- this.evaluationType = evaluationType;
- this.problems = problems;
- }
-
- /**
- * Adds the given problem to the list of problems of this evaluation result.
- */
- void addProblem(IProblem problem) {
- IProblem[] existingProblems = this.problems;
- int existingLength = existingProblems.length;
- this.problems = new IProblem[existingLength + 1];
- System.arraycopy(existingProblems, 0, this.problems, 0, existingLength);
- this.problems[existingLength] = problem;
- }
-
- /**
- * Returns the ID of the evaluation.
- * If the result is about a global variable, returns the name of the variable.
- * If the result is about a code snippet, returns the code snippet.
- * If the result is about an import, returns the import.
- * If the result is about a package declaration, returns the package declaration.
- */
- public char[] getEvaluationID() {
- return this.evaluationID;
- }
-
- /**
- * Returns the type of evaluation this result is about.
- * This indicates if the result is about a global variable,
- * a code snippet, an import or a package declaration.
- * Use getEvaluationID() to get the object itself.
- */
- public int getEvaluationType() {
- return this.evaluationType;
- }
-
- /**
- * Returns an array of problems (errors and warnings) encountered
- * during the compilation of a code snippet or a global variable definition,
- * or during the analysis of a package name or an import.
- * Returns an empty array if there are no problems.
- */
- public IProblem[] getProblems() {
- return this.problems;
- }
-
- /**
- * Returns a proxy object on this result's value.
- * Returns null if the result's value is null.
- * The returned value is undefined if there is no result.
- * The proxy object is expected to answer questions like:
- * - What is the proxy type for this object?
- * - What is the toString() representation for this object?
- * - What are the field names of this object?
- * - What is the value for a given field name?
- * Special proxy objects are expected if the value is a primitive type.
- */
- public Object getValue() {
- return null; // Not yet implemented
- }
-
- /**
- * Returns the displayable representation of this result's value.
- * This is obtained by sending toString() to the result object on the target side
- * if it is not a primitive value. If it is a primitive value, the corresponding
- * static toString(...) is used, eg. Integer.toString(int n) if it is an int.
- * Returns null if there is no value.
- */
- public char[] getValueDisplayString() {
- return this.displayString;
- }
-
- /**
- * Returns the dot-separated fully qualified name of this result's value type.
- * If the value is a primitive value, returns the toString() representation of its type
- * (eg. "int", "boolean", etc.)
- * Returns null if there is no value.
- */
- public char[] getValueTypeName() {
- return this.typeName;
- }
-
- /**
- * Returns whether there are errors in the code snippet or the global variable definition.
- */
- public boolean hasErrors() {
- if (this.problems == null) {
- return false;
- } else {
- for (int i = 0; i < this.problems.length; i++) {
- if (this.problems[i].isError()) {
- return true;
- }
+
+public EvaluationResult(char[] evaluationID, int evaluationType, char[] displayString, char[] typeName) {
+ this.evaluationID = evaluationID;
+ this.evaluationType = evaluationType;
+ this.displayString = displayString;
+ this.typeName = typeName;
+ this.problems = NO_PROBLEMS;
+}
+public EvaluationResult(char[] evaluationID, int evaluationType, IProblem[] problems) {
+ this.evaluationID = evaluationID;
+ this.evaluationType = evaluationType;
+ this.problems = problems;
+}
+/**
+ * Adds the given problem to the list of problems of this evaluation result.
+ */
+void addProblem(IProblem problem) {
+ IProblem[] existingProblems = this.problems;
+ int existingLength = existingProblems.length;
+ this.problems = new IProblem[existingLength + 1];
+ System.arraycopy(existingProblems, 0, this.problems, 0, existingLength);
+ this.problems[existingLength] = problem;
+}
+/**
+ * Returns the ID of the evaluation.
+ * If the result is about a global variable, returns the name of the variable.
+ * If the result is about a code snippet, returns the code snippet.
+ * If the result is about an import, returns the import.
+ * If the result is about a package declaration, returns the package declaration.
+ */
+public char[] getEvaluationID() {
+ return this.evaluationID;
+}
+/**
+ * Returns the type of evaluation this result is about.
+ * This indicates if the result is about a global variable,
+ * a code snippet, an import or a package declaration.
+ * Use getEvaluationID() to get the object itself.
+ */
+public int getEvaluationType() {
+ return this.evaluationType;
+}
+/**
+ * Returns an array of problems (errors and warnings) encountered
+ * during the compilation of a code snippet or a global variable definition,
+ * or during the analysis of a package name or an import.
+ * Returns an empty array if there are no problems.
+ */
+public IProblem[] getProblems() {
+ return this.problems;
+}
+/**
+ * Returns a proxy object on this result's value.
+ * Returns null if the result's value is null.
+ * The returned value is undefined if there is no result.
+ * The proxy object is expected to answer questions like:
+ * - What is the proxy type for this object?
+ * - What is the toString() representation for this object?
+ * - What are the field names of this object?
+ * - What is the value for a given field name?
+ * Special proxy objects are expected if the value is a primitive type.
+ */
+public Object getValue() {
+ return null; // Not yet implemented
+}
+/**
+ * Returns the displayable representation of this result's value.
+ * This is obtained by sending toString() to the result object on the target side
+ * if it is not a primitive value. If it is a primitive value, the corresponding
+ * static toString(...) is used, eg. Integer.toString(int n) if it is an int.
+ * Returns null if there is no value.
+ */
+public char[] getValueDisplayString() {
+ return this.displayString;
+}
+/**
+ * Returns the dot-separated fully qualified name of this result's value type.
+ * If the value is a primitive value, returns the toString() representation of its type
+ * (eg. "int", "boolean", etc.)
+ * Returns null if there is no value.
+ */
+public char[] getValueTypeName() {
+ return this.typeName;
+}
+/**
+ * Returns whether there are errors in the code snippet or the global variable definition.
+ */
+public boolean hasErrors() {
+ if (this.problems == null) {
+ return false;
+ } else {
+ for (int i = 0; i < this.problems.length; i++) {
+ if (this.problems[i].isError()) {
+ return true;
}
- return false;
}
+ return false;
}
-
- /**
- * Returns whether there are problems in the code snippet or the global variable definition.
- */
- public boolean hasProblems() {
- return (this.problems != null) && (this.problems.length != 0);
- }
-
- /**
- * Returns whether this result has a value.
- */
- public boolean hasValue() {
- return this.displayString != null;
- }
-
- /**
- * Returns whether there are warnings in the code snippet or the global variable definition.
- */
- public boolean hasWarnings() {
- if (this.problems == null) {
- return false;
- } else {
- for (int i = 0; i < this.problems.length; i++) {
- if (this.problems[i].isWarning()) {
- return true;
- }
+}
+/**
+ * Returns whether there are problems in the code snippet or the global variable definition.
+ */
+public boolean hasProblems() {
+ return (this.problems != null) && (this.problems.length != 0);
+}
+/**
+ * Returns whether this result has a value.
+ */
+public boolean hasValue() {
+ return this.displayString != null;
+}
+/**
+ * Returns whether there are warnings in the code snippet or the global variable definition.
+ */
+public boolean hasWarnings() {
+ if (this.problems == null) {
+ return false;
+ } else {
+ for (int i = 0; i < this.problems.length; i++) {
+ if (this.problems[i].isWarning()) {
+ return true;
}
- return false;
}
+ return false;
}
-
- /**
- * Returns a readable representation of this result.
- * This is for debugging purpose only.
- */
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- switch (this.evaluationType) {
- case T_CODE_SNIPPET :
- buffer.append("Code snippet");
- break;
- case T_IMPORT :
- buffer.append("Import");
- break;
- case T_INTERNAL :
- buffer.append("Internal problem");
- break;
- case T_PACKAGE :
- buffer.append("Package");
- break;
- case T_VARIABLE :
- buffer.append("Global variable");
- break;
+}
+/**
+ * Returns a readable representation of this result.
+ * This is for debugging purpose only.
+ */
+public String toString() {
+ StringBuffer buffer = new StringBuffer();
+ switch (this.evaluationType) {
+ case T_CODE_SNIPPET:
+ buffer.append("Code snippet");
+ break;
+ case T_IMPORT:
+ buffer.append("Import");
+ break;
+ case T_INTERNAL:
+ buffer.append("Internal problem");
+ break;
+ case T_PACKAGE:
+ buffer.append("Package");
+ break;
+ case T_VARIABLE:
+ buffer.append("Global variable");
+ break;
+ }
+ buffer.append(": ");
+ buffer.append(this.evaluationID);
+ buffer.append("\n");
+ if (hasProblems()) {
+ buffer.append("Problems:\n");
+ for (int i = 0; i < this.problems.length; i++) {
+ buffer.append(this.problems[i].toString());
}
- buffer.append(": ");
- buffer.append(this.evaluationID);
- buffer.append("\n");
- if (hasProblems()) {
- buffer.append("Problems:\n");
- for (int i = 0; i < this.problems.length; i++) {
- buffer.append(this.problems[i].toString());
- }
+ } else {
+ if (hasValue()) {
+ buffer.append("(");
+ buffer.append(this.typeName);
+ buffer.append(") ");
+ buffer.append(this.displayString);
} else {
- if (hasValue()) {
- buffer.append("(");
- buffer.append(this.typeName);
- buffer.append(") ");
- buffer.append(this.displayString);
- } else {
- buffer.append("(No explicit return value)");
- }
+ buffer.append("(No explicit return value)");
}
- return buffer.toString();
}
-
+ return buffer.toString();
+}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/Evaluator.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/Evaluator.java
index ee0a13dc8b..a04c64cdbc 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/Evaluator.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/Evaluator.java
@@ -21,155 +21,133 @@ public abstract class Evaluator {
ConfigurableOption[] options;
IRequestor requestor;
IProblemFactory problemFactory;
- /**
- * Creates a new evaluator.
- */
- Evaluator(
- EvaluationContext context,
- INameEnvironment environment,
- ConfigurableOption[] options,
- IRequestor requestor,
- IProblemFactory problemFactory) {
- this.context = context;
- this.environment = environment;
- this.options = options;
- this.requestor = requestor;
- this.problemFactory = problemFactory;
+/**
+ * Creates a new evaluator.
+ */
+Evaluator(EvaluationContext context, INameEnvironment environment, ConfigurableOption[] options, IRequestor requestor, IProblemFactory problemFactory) {
+ this.context = context;
+ this.environment = environment;
+ this.options = options;
+ this.requestor = requestor;
+ this.problemFactory = problemFactory;
+}
+/**
+ * Adds the given problem to the corresponding evaluation result in the given table. If the evaluation
+ * result doesn't exist yet, adds it in the table. Its evaluation id and evaluation type
+ * are computed so that they correspond to the given problem. If it is found to be an internal problem,
+ * then the evaluation id of the result is the given compilation unit source.
+ */
+abstract protected void addEvaluationResultForCompilationProblem(Hashtable resultsByIDs,IProblem problem, char[] cuSource);
+/**
+ * Returns the evaluation results that converts the given compilation result that has problems.
+ * If the compilation result has more than one problem, then the problems are broken down so that
+ * each evaluation result has the same evaluation id.
+ */
+protected EvaluationResult[] evaluationResultsForCompilationProblems(CompilationResult result, char[] cuSource) {
+ // Break down the problems and group them by ids in evaluation results
+ IProblem[] problems = result.getProblems();
+ Hashtable resultsByIDs = new Hashtable(5);
+ for (int i = 0; i < problems.length; i++) {
+ addEvaluationResultForCompilationProblem(resultsByIDs, problems[i], cuSource);
}
- /**
- * Adds the given problem to the corresponding evaluation result in the given table. If the evaluation
- * result doesn't exist yet, adds it in the table. Its evaluation id and evaluation type
- * are computed so that they correspond to the given problem. If it is found to be an internal problem,
- * then the evaluation id of the result is the given compilation unit source.
- */
- abstract protected void addEvaluationResultForCompilationProblem(
- Hashtable resultsByIDs,
- IProblem problem,
- char[] cuSource);
- /**
- * Returns the evaluation results that converts the given compilation result that has problems.
- * If the compilation result has more than one problem, then the problems are broken down so that
- * each evaluation result has the same evaluation id.
- */
- protected EvaluationResult[] evaluationResultsForCompilationProblems(
- CompilationResult result,
- char[] cuSource) {
- // Break down the problems and group them by ids in evaluation results
- IProblem[] problems = result.getProblems();
- Hashtable resultsByIDs = new Hashtable(5);
- for (int i = 0; i < problems.length; i++) {
- addEvaluationResultForCompilationProblem(resultsByIDs, problems[i], cuSource);
- }
-
- // Copy results
- int size = resultsByIDs.size();
- EvaluationResult[] evalResults = new EvaluationResult[size];
- Enumeration results = resultsByIDs.elements();
- for (int i = 0; i < size; i++) {
- evalResults[i] = (EvaluationResult) results.nextElement();
- }
-
- return evalResults;
+ // Copy results
+ int size = resultsByIDs.size();
+ EvaluationResult[] evalResults = new EvaluationResult[size];
+ Enumeration results = resultsByIDs.elements();
+ for (int i = 0; i < size; i++) {
+ evalResults[i] = (EvaluationResult)results.nextElement();
}
- /**
- * Compiles and returns the class definitions for the current compilation unit.
- * Returns null if there are any errors.
- */
- ClassFile[] getClasses() {
- final char[] source = getSource();
- final Vector classDefinitions = new Vector();
+ return evalResults;
+}
+/**
+ * Compiles and returns the class definitions for the current compilation unit.
+ * Returns null if there are any errors.
+ */
+ClassFile[] getClasses() {
+ final char[] source = getSource();
+ final Vector classDefinitions = new Vector();
- // The requestor collects the class definitions and problems
- class CompilerRequestor implements ICompilerRequestor {
- boolean hasErrors = false;
- public void acceptResult(CompilationResult result) {
- if (result.hasProblems()) {
- EvaluationResult[] evalResults =
- evaluationResultsForCompilationProblems(result, source);
- for (int i = 0; i < evalResults.length; i++) {
- EvaluationResult evalResult = evalResults[i];
- IProblem[] problems = evalResult.getProblems();
- for (int j = 0; j < problems.length; j++) {
- Evaluator.this.requestor.acceptProblem(
- problems[j],
- evalResult.getEvaluationID(),
- evalResult.getEvaluationType());
- }
- }
- }
- if (result.hasErrors()) {
- hasErrors = true;
- } else {
- ClassFile[] classFiles = result.getClassFiles();
- for (int i = 0; i < classFiles.length; i++) {
- ClassFile classFile = classFiles[i];
- /*
-
- char[] filename = classFile.fileName();
- int length = filename.length;
- char[] relativeName = new char[length + 6];
- System.arraycopy(filename, 0, relativeName, 0, length);
- System.arraycopy(".class".toCharArray(), 0, relativeName, length, 6);
- CharOperation.replace(relativeName, '/', java.io.File.separatorChar);
- ClassFile.writeToDisk("d:/test/snippet", new String(relativeName), classFile.getBytes());
- String str = "d:/test/snippet" + "/" + new String(relativeName);
- System.out.println(com.ibm.compiler.java.classfmt.disassembler.ClassFileDisassembler.disassemble(str));
- */
- classDefinitions.addElement(classFile);
+ // The requestor collects the class definitions and problems
+ class CompilerRequestor implements ICompilerRequestor {
+ boolean hasErrors = false;
+ public void acceptResult(CompilationResult result) {
+ if (result.hasProblems()) {
+ EvaluationResult[] evalResults = evaluationResultsForCompilationProblems(result, source);
+ for (int i = 0; i < evalResults.length; i++) {
+ EvaluationResult evalResult = evalResults[i];
+ IProblem[] problems = evalResult.getProblems();
+ for (int j = 0; j < problems.length; j++) {
+ Evaluator.this.requestor.acceptProblem(problems[j], evalResult.getEvaluationID(), evalResult.getEvaluationType());
}
}
}
- }
-
- // Compile compilation unit
- CompilerRequestor compilerRequestor = new CompilerRequestor();
- Compiler compiler = getCompiler(compilerRequestor);
- compiler
- .compile(
- new ICompilationUnit[] { new ICompilationUnit() { public char[] getFileName() {
- // Name of class is name of CU
- return CharOperation.concat(
- Evaluator.this.getClassName(),
- ".java".toCharArray());
- }
- public char[] getContents() {
- return source;
- }
- public char[] getMainTypeName() {
- return Evaluator.this.getClassName();
+ if (result.hasErrors()) {
+ hasErrors = true;
+ } else {
+ ClassFile[] classFiles = result.getClassFiles();
+ for (int i = 0; i < classFiles.length; i++) {
+ ClassFile classFile = classFiles[i];
+/*
+
+ char[] filename = classFile.fileName();
+ int length = filename.length;
+ char[] relativeName = new char[length + 6];
+ System.arraycopy(filename, 0, relativeName, 0, length);
+ System.arraycopy(".class".toCharArray(), 0, relativeName, length, 6);
+ CharOperation.replace(relativeName, '/', java.io.File.separatorChar);
+ ClassFile.writeToDisk("d:/test/snippet", new String(relativeName), classFile.getBytes());
+ String str = "d:/test/snippet" + "/" + new String(relativeName);
+ System.out.println(com.ibm.compiler.java.classfmt.disassembler.ClassFileDisassembler.disassemble(str));
+ */
+ classDefinitions.addElement(classFile);
}
}
- });
- if (compilerRequestor.hasErrors) {
- return null;
- } else {
- ClassFile[] result = new ClassFile[classDefinitions.size()];
- classDefinitions.copyInto(result);
- return result;
}
}
- /**
- * Returns the name of the current class. This is the simple name of the class.
- * This doesn't include the extension ".java" nor the name of the package.
- */
- abstract protected char[] getClassName();
- /**
- * Creates and returns a compiler for this evaluator.
- */
- Compiler getCompiler(ICompilerRequestor requestor) {
- return new Compiler(
- this.environment,
- DefaultErrorHandlingPolicies.exitAfterAllProblems(),
- this.options,
- requestor,
- this.problemFactory);
+ // Compile compilation unit
+ CompilerRequestor compilerRequestor = new CompilerRequestor();
+ Compiler compiler = getCompiler(compilerRequestor);
+ compiler.compile(new ICompilationUnit[] {new ICompilationUnit() {
+ public char[] getFileName() {
+ // Name of class is name of CU
+ return CharOperation.concat(Evaluator.this.getClassName(), ".java".toCharArray());
+ }
+ public char[] getContents() {
+ return source;
+ }
+ public char[] getMainTypeName() {
+ return Evaluator.this.getClassName();
+ }
+ }});
+ if (compilerRequestor.hasErrors) {
+ return null;
+ } else {
+ ClassFile[] result = new ClassFile[classDefinitions.size()];
+ classDefinitions.copyInto(result);
+ return result;
}
-
- /**
- * Builds and returns the source for the current compilation unit.
- */
- abstract protected char[] getSource();
+}
+/**
+ * Returns the name of the current class. This is the simple name of the class.
+ * This doesn't include the extension ".java" nor the name of the package.
+ */
+abstract protected char[] getClassName();
+/**
+ * Creates and returns a compiler for this evaluator.
+ */
+Compiler getCompiler(ICompilerRequestor requestor) {
+ return new Compiler(
+ this.environment,
+ DefaultErrorHandlingPolicies.exitAfterAllProblems(),
+ this.options,
+ requestor,
+ this.problemFactory);
+}
+/**
+ * Builds and returns the source for the current compilation unit.
+ */
+abstract protected char[] getSource();
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/GlobalVariable.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/GlobalVariable.java
index 8fd60802cc..88112765c4 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/GlobalVariable.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/GlobalVariable.java
@@ -4,58 +4,52 @@ public class GlobalVariable {
char[] typeName;
char[] name;
char[] initializer;
- int declarationStart = -1, initializerStart = -1, initExpressionStart;
- // positions in the global variable class definition
+ int declarationStart = -1, initializerStart = -1, initExpressionStart; // positions in the global variable class definition
int initializerLineStart = -1; // line in the global variable class definition
- /**
- * Creates a new global variable with the given type name, name and initializer.
- * initializer can be null if there is none.
- */
- public GlobalVariable(char[] typeName, char[] name, char[] initializer) {
- this.typeName = typeName;
- this.name = name;
- this.initializer = initializer;
- }
-
- /**
- * Returns the initializer of this global variable. The initializer is a
- * variable initializer (ie. an expression or an array initializer) as defined
- * in the Java Language Specifications.
- */
- public char[] getInitializer() {
- return this.initializer;
- }
-
- /**
- * Returns the name of this global variable.
- */
- public char[] getName() {
- return this.name;
- }
-
- /**
- * Returns the dot separated fully qualified name of the type of this global variable,
- * or its simple representation if it is a primitive type (eg. int, boolean, etc.)
- */
- public char[] getTypeName() {
- return this.typeName;
- }
-
- /**
- * Returns a readable representation of the receiver.
- * This is for debugging purpose only.
- */
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append(this.typeName);
- buffer.append(" ");
- buffer.append(this.name);
- if (this.initializer != null) {
- buffer.append("= ");
- buffer.append(this.initializer);
- }
- buffer.append(";");
- return buffer.toString();
+/**
+ * Creates a new global variable with the given type name, name and initializer.
+ * initializer can be null if there is none.
+ */
+public GlobalVariable(char[] typeName, char[] name, char[] initializer) {
+ this.typeName = typeName;
+ this.name = name;
+ this.initializer = initializer;
+}
+/**
+ * Returns the initializer of this global variable. The initializer is a
+ * variable initializer (ie. an expression or an array initializer) as defined
+ * in the Java Language Specifications.
+ */
+public char[] getInitializer() {
+ return this.initializer;
+}
+/**
+ * Returns the name of this global variable.
+ */
+public char[] getName() {
+ return this.name;
+}
+/**
+ * Returns the dot separated fully qualified name of the type of this global variable,
+ * or its simple representation if it is a primitive type (eg. int, boolean, etc.)
+ */
+public char[] getTypeName() {
+ return this.typeName;
+}
+/**
+ * Returns a readable representation of the receiver.
+ * This is for debugging purpose only.
+ */
+public String toString() {
+ StringBuffer buffer = new StringBuffer();
+ buffer.append(this.typeName);
+ buffer.append(" ");
+ buffer.append(this.name);
+ if (this.initializer != null) {
+ buffer.append("= ");
+ buffer.append(this.initializer);
}
-
+ buffer.append(";");
+ return buffer.toString();
+}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/IRequestor.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/IRequestor.java
index 56c820fe42..8d5049392e 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/IRequestor.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/IRequestor.java
@@ -11,12 +11,12 @@ import org.eclipse.jdt.internal.compiler.IProblem;
* A callback interface for receiving code snippet evaluation results.
*/
public interface IRequestor {
- /**
- * @see ICodeSnippetRequestor
- */
- boolean acceptClassFiles(ClassFile[] classFiles, char[] codeSnippetClassName);
- /**
- * @see ICodeSnippetRequestor
- */
- void acceptProblem(IProblem problem, char[] fragmentSource, int fragmentKind);
+/**
+ * @see ICodeSnippetRequestor
+ */
+boolean acceptClassFiles(ClassFile[] classFiles, char[] codeSnippetClassName);
+/**
+ * @see ICodeSnippetRequestor
+ */
+void acceptProblem(IProblem problem, char[] fragmentSource, int fragmentKind);
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/InstallException.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/InstallException.java
index b12801b14c..1ee669fa5f 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/InstallException.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/InstallException.java
@@ -1,21 +1,19 @@
package org.eclipse.jdt.internal.eval;
public class InstallException extends Exception {
- /**
- * Constructs a <code>InstallException</code> with no detail message.
- */
- public InstallException() {
- super();
- }
-
- /**
- * Constructs a <code>InstallException</code> with the specified
- * detail message.
- *
- * @param s the detail message.
- */
- public InstallException(String s) {
- super(s);
- }
-
+/**
+ * Constructs a <code>InstallException</code> with no detail message.
+ */
+public InstallException() {
+ super();
+}
+/**
+ * Constructs a <code>InstallException</code> with the specified
+ * detail message.
+ *
+ * @param s the detail message.
+ */
+public InstallException(String s) {
+ super(s);
+}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/VariablesEvaluator.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/VariablesEvaluator.java
index c4d99fa3b0..1967713666 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/VariablesEvaluator.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/VariablesEvaluator.java
@@ -16,312 +16,283 @@ import java.util.*;
* A variables evaluator compiles the global variables of an evaluation context and returns
* the corresponding class files. Or it reports problems against these variables.
*/
-public class VariablesEvaluator
- extends Evaluator
- implements EvaluationConstants {
+public class VariablesEvaluator extends Evaluator implements EvaluationConstants {
int startPosOffset = 0;
- /**
- * Creates a new global variables evaluator.
- */
- VariablesEvaluator(
- EvaluationContext context,
- INameEnvironment environment,
- ConfigurableOption[] options,
- IRequestor requestor,
- IProblemFactory problemFactory) {
- super(context, environment, options, requestor, problemFactory);
- }
-
- /**
- * @see org.eclipse.jdt.internal.eval.Evaluator
- */
- protected void addEvaluationResultForCompilationProblem(
- Hashtable resultsByIDs,
- IProblem problem,
- char[] cuSource) {
- // set evaluation id and type to an internal problem by default
- char[] evaluationID = cuSource;
- int evaluationType = EvaluationResult.T_INTERNAL;
-
- int pbLine = problem.getSourceLineNumber();
- int currentLine = 1;
-
- // check package declaration
- char[] packageName = getPackageName();
- if (packageName.length > 0) {
- if (pbLine == 1) {
- // set evaluation id and type
- evaluationID = packageName;
- evaluationType = EvaluationResult.T_PACKAGE;
+/**
+ * Creates a new global variables evaluator.
+ */
+VariablesEvaluator(EvaluationContext context, INameEnvironment environment, ConfigurableOption[] options, IRequestor requestor, IProblemFactory problemFactory) {
+ super(context, environment, options, requestor, problemFactory);
+}
+/**
+ * @see org.eclipse.jdt.internal.eval.Evaluator
+ */
+protected void addEvaluationResultForCompilationProblem(Hashtable resultsByIDs, IProblem problem, char[] cuSource) {
+ // set evaluation id and type to an internal problem by default
+ char[] evaluationID = cuSource;
+ int evaluationType = EvaluationResult.T_INTERNAL;
- // shift line number, source start and source end
- problem.setSourceLineNumber(1);
- problem.setSourceStart(0);
- problem.setSourceEnd(evaluationID.length - 1);
- }
- currentLine++;
- }
+ int pbLine = problem.getSourceLineNumber();
+ int currentLine = 1;
- // check imports
- char[][] imports = this.context.imports;
- if ((currentLine <= pbLine) && (pbLine < (currentLine + imports.length))) {
+ // check package declaration
+ char[] packageName = getPackageName();
+ if (packageName.length > 0) {
+ if (pbLine == 1) {
// set evaluation id and type
- evaluationID = imports[pbLine - currentLine];
- evaluationType = EvaluationResult.T_IMPORT;
+ evaluationID = packageName;
+ evaluationType = EvaluationResult.T_PACKAGE;
// shift line number, source start and source end
problem.setSourceLineNumber(1);
problem.setSourceStart(0);
problem.setSourceEnd(evaluationID.length - 1);
}
- currentLine += imports.length + 1; // + 1 to skip the class declaration line
-
- // check variable declarations
- int varCount = this.context.variableCount;
- if ((currentLine <= pbLine) && (pbLine < currentLine + varCount)) {
- GlobalVariable var = this.context.variables[pbLine - currentLine];
-
- // set evaluation id and type
- evaluationID = var.getName();
- evaluationType = EvaluationResult.T_VARIABLE;
-
- // shift line number, source start and source end
- int pbStart = problem.getSourceStart() - var.declarationStart;
- int pbEnd = problem.getSourceEnd() - var.declarationStart;
- int typeLength = var.getTypeName().length;
- if ((0 <= pbStart) && (pbEnd < typeLength)) {
- // problem on the type of the variable
- problem.setSourceLineNumber(-1);
- } else {
- // problem on the name of the variable
- pbStart -= typeLength + 1; // type length + space
- pbEnd -= typeLength + 1; // type length + space
- problem.setSourceLineNumber(0);
- }
- problem.setSourceStart(pbStart);
- problem.setSourceEnd(pbEnd);
- }
- currentLine = -1; // not needed any longer
+ currentLine++;
+ }
- // check variable initializers
- for (int i = 0; i < varCount; i++) {
- GlobalVariable var = this.context.variables[i];
- char[] initializer = var.getInitializer();
- int initializerLength = initializer == null ? 0 : initializer.length;
- if ((var.initializerStart <= problem.getSourceStart())
- && (problem.getSourceEnd() < var.initializerStart + var.name.length)) {
- /* Problem with the variable name.
- Ignore because it must have already been reported
- when checking the declaration.
- */
- return;
- } else
- if ((var.initExpressionStart <= problem.getSourceStart())
- && (problem.getSourceEnd() < var.initExpressionStart + initializerLength)) {
- // set evaluation id and type
- evaluationID = var.name;
- evaluationType = EvaluationResult.T_VARIABLE;
+ // check imports
+ char[][] imports = this.context.imports;
+ if ((currentLine <= pbLine) && (pbLine < (currentLine + imports.length))) {
+ // set evaluation id and type
+ evaluationID = imports[pbLine - currentLine];
+ evaluationType = EvaluationResult.T_IMPORT;
- // shift line number, source start and source end
- problem.setSourceLineNumber(pbLine - var.initializerLineStart + 1);
- problem.setSourceStart(problem.getSourceStart() - var.initExpressionStart);
- problem.setSourceEnd(problem.getSourceEnd() - var.initExpressionStart);
+ // shift line number, source start and source end
+ problem.setSourceLineNumber(1);
+ problem.setSourceStart(0);
+ problem.setSourceEnd(evaluationID.length - 1);
+ }
+ currentLine += imports.length + 1; // + 1 to skip the class declaration line
- break;
- }
- }
+ // check variable declarations
+ int varCount = this.context.variableCount;
+ if ((currentLine <= pbLine) && (pbLine < currentLine + varCount)) {
+ GlobalVariable var = this.context.variables[pbLine - currentLine];
+
+ // set evaluation id and type
+ evaluationID = var.getName();
+ evaluationType = EvaluationResult.T_VARIABLE;
- EvaluationResult result = (EvaluationResult) resultsByIDs.get(evaluationID);
- if (result == null) {
- resultsByIDs.put(
- evaluationID,
- new EvaluationResult(evaluationID, evaluationType, new IProblem[] { problem }));
+ // shift line number, source start and source end
+ int pbStart = problem.getSourceStart() - var.declarationStart;
+ int pbEnd = problem.getSourceEnd() - var.declarationStart;
+ int typeLength = var.getTypeName().length;
+ if ((0 <= pbStart) && (pbEnd < typeLength)) {
+ // problem on the type of the variable
+ problem.setSourceLineNumber(-1);
} else {
- result.addProblem(problem);
+ // problem on the name of the variable
+ pbStart -= typeLength + 1; // type length + space
+ pbEnd -= typeLength + 1; // type length + space
+ problem.setSourceLineNumber(0);
}
+ problem.setSourceStart(pbStart);
+ problem.setSourceEnd(pbEnd);
}
+ currentLine = -1; // not needed any longer
- /**
- * @see org.eclipse.jdt.internal.eval.Evaluator
- */
- protected char[] getClassName() {
- return CharOperation.concat(
- this.context.GLOBAL_VARS_CLASS_NAME_PREFIX,
- Integer.toString(this.context.VAR_CLASS_COUNTER + 1).toCharArray());
- }
-
- /**
- * Creates and returns a compiler for this evaluator.
- */
- Compiler getCompiler(ICompilerRequestor requestor) {
- Compiler compiler = super.getCompiler(requestor);
+ // check variable initializers
+ for (int i = 0; i < varCount; i++) {
+ GlobalVariable var = this.context.variables[i];
+ char[] initializer = var.getInitializer();
+ int initializerLength = initializer == null ? 0 : initializer.length;
+ if ((var.initializerStart <= problem.getSourceStart()) && (problem.getSourceEnd() < var.initializerStart + var.name.length)) {
+ /* Problem with the variable name.
+ Ignore because it must have already been reported
+ when checking the declaration.
+ */
+ return;
+ } else if ((var.initExpressionStart <= problem.getSourceStart()) && (problem.getSourceEnd() < var.initExpressionStart + initializerLength)) {
+ // set evaluation id and type
+ evaluationID = var.name;
+ evaluationType = EvaluationResult.T_VARIABLE;
- // Initialize the compiler's lookup environment with the already compiled super class
- IBinaryType binaryType = this.context.getRootCodeSnippetBinary();
- if (binaryType != null) {
- compiler.lookupEnvironment.cacheBinaryType(binaryType);
- }
+ // shift line number, source start and source end
+ problem.setSourceLineNumber(pbLine - var.initializerLineStart + 1);
+ problem.setSourceStart(problem.getSourceStart() - var.initExpressionStart);
+ problem.setSourceEnd(problem.getSourceEnd() - var.initExpressionStart);
- // and the installed global variable classes
- VariablesInfo installedVars = this.context.installedVars;
- if (installedVars != null) {
- ClassFile[] classFiles = installedVars.classFiles;
- for (int i = 0; i < classFiles.length; i++) {
- ClassFile classFile = classFiles[i];
- IBinaryType binary = null;
- try {
- binary = new ClassFileReader(classFile.getBytes(), null);
- } catch (ClassFormatException e) {
- e.printStackTrace(); // Should never happen since we compiled this type
- }
- compiler.lookupEnvironment.cacheBinaryType(binary);
- }
+ break;
}
-
- return compiler;
}
- /**
- * Returns the name of package of the current compilation unit.
- */
- protected char[] getPackageName() {
- return this.context.packageName;
+ EvaluationResult result = (EvaluationResult)resultsByIDs.get(evaluationID);
+ if (result == null) {
+ resultsByIDs.put(evaluationID, new EvaluationResult(evaluationID, evaluationType, new IProblem[] {problem}));
+ } else {
+ result.addProblem(problem);
+ }
+}
+/**
+ * @see org.eclipse.jdt.internal.eval.Evaluator
+ */
+protected char[] getClassName() {
+ return CharOperation.concat(this.context.GLOBAL_VARS_CLASS_NAME_PREFIX, Integer.toString(this.context.VAR_CLASS_COUNTER + 1).toCharArray());
+}
+/**
+ * Creates and returns a compiler for this evaluator.
+ */
+Compiler getCompiler(ICompilerRequestor requestor) {
+ Compiler compiler = super.getCompiler(requestor);
+
+ // Initialize the compiler's lookup environment with the already compiled super class
+ IBinaryType binaryType = this.context.getRootCodeSnippetBinary();
+ if (binaryType != null) {
+ compiler.lookupEnvironment.cacheBinaryType(binaryType);
}
- /**
- * @see org.eclipse.jdt.internal.eval.Evaluator
- */
- protected char[] getSource() {
- StringBuffer buffer = new StringBuffer();
- int lineNumberOffset = 1;
-
- // package declaration
- char[] packageName = getPackageName();
- if (packageName.length != 0) {
- buffer.append("package ");
- buffer.append(packageName);
- buffer.append(';').append(JavaModelManager.LINE_SEPARATOR);
- lineNumberOffset++;
- }
-
- // import declarations
- char[][] imports = this.context.imports;
- for (int i = 0; i < imports.length; i++) {
- buffer.append("import ");
- buffer.append(imports[i]);
- buffer.append(';').append(JavaModelManager.LINE_SEPARATOR);
- lineNumberOffset++;
+ // and the installed global variable classes
+ VariablesInfo installedVars = this.context.installedVars;
+ if (installedVars != null) {
+ ClassFile[] classFiles = installedVars.classFiles;
+ for (int i = 0; i < classFiles.length; i++) {
+ ClassFile classFile = classFiles[i];
+ IBinaryType binary = null;
+ try {
+ binary = new ClassFileReader(classFile.getBytes(), null);
+ } catch (ClassFormatException e) {
+ e.printStackTrace(); // Should never happen since we compiled this type
+ }
+ compiler.lookupEnvironment.cacheBinaryType(binary);
}
+ }
+
+ return compiler;
+}
+/**
+ * Returns the name of package of the current compilation unit.
+ */
+protected char[] getPackageName() {
+ return this.context.packageName;
+}
+/**
+ * @see org.eclipse.jdt.internal.eval.Evaluator
+ */
+protected char[] getSource() {
+ StringBuffer buffer = new StringBuffer();
+ int lineNumberOffset = 1;
+
+ // package declaration
+ char[] packageName = getPackageName();
+ if (packageName.length != 0) {
+ buffer.append("package ");
+ buffer.append(packageName);
+ buffer.append(';').append(JavaModelManager.LINE_SEPARATOR);
+ lineNumberOffset++;
+ }
- // class declaration
- buffer.append("public class ");
- buffer.append(getClassName());
- buffer.append(" extends ");
- buffer.append(PACKAGE_NAME);
- buffer.append(".");
- buffer.append(ROOT_CLASS_NAME);
- buffer.append(" {").append(JavaModelManager.LINE_SEPARATOR);
+ // import declarations
+ char[][] imports = this.context.imports;
+ for (int i = 0; i < imports.length; i++) {
+ buffer.append("import ");
+ buffer.append(imports[i]);
+ buffer.append(';').append(JavaModelManager.LINE_SEPARATOR);
lineNumberOffset++;
- startPosOffset = buffer.length();
+ }
- // field declarations
- GlobalVariable[] vars = this.context.variables;
- VariablesInfo installedVars = this.context.installedVars;
- for (int i = 0; i < this.context.variableCount; i++) {
- GlobalVariable var = vars[i];
- buffer.append("\tpublic static ");
- var.declarationStart = buffer.length();
- buffer.append(var.typeName);
- buffer.append(" ");
- char[] varName = var.name;
- buffer.append(varName);
- buffer.append(';').append(JavaModelManager.LINE_SEPARATOR);
- lineNumberOffset++;
- }
+ // class declaration
+ buffer.append("public class ");
+ buffer.append(getClassName());
+ buffer.append(" extends ");
+ buffer.append(PACKAGE_NAME);
+ buffer.append(".");
+ buffer.append(ROOT_CLASS_NAME);
+ buffer.append(" {").append(JavaModelManager.LINE_SEPARATOR);
+ lineNumberOffset++;
+ startPosOffset = buffer.length();
- // field initializations
- buffer.append("\tstatic {").append(JavaModelManager.LINE_SEPARATOR);
+ // field declarations
+ GlobalVariable[] vars = this.context.variables;
+ VariablesInfo installedVars = this.context.installedVars;
+ for (int i = 0; i < this.context.variableCount; i++){
+ GlobalVariable var = vars[i];
+ buffer.append("\tpublic static ");
+ var.declarationStart = buffer.length();
+ buffer.append(var.typeName);
+ buffer.append(" ");
+ char[] varName = var.name;
+ buffer.append(varName);
+ buffer.append(';').append(JavaModelManager.LINE_SEPARATOR);
lineNumberOffset++;
- for (int i = 0; i < this.context.variableCount; i++) {
- GlobalVariable var = vars[i];
- char[] varName = var.name;
- GlobalVariable installedVar =
- installedVars == null ? null : installedVars.varNamed(varName);
- if (installedVar == null
- || !CharOperation.equals(installedVar.typeName, var.typeName)) {
- // Initialize with initializer if there was no previous value
- char[] initializer = var.initializer;
- if (initializer != null) {
- buffer.append("\t\ttry {").append(JavaModelManager.LINE_SEPARATOR);
- lineNumberOffset++;
- var.initializerLineStart = lineNumberOffset;
- buffer.append("\t\t\t");
- var.initializerStart = buffer.length();
- buffer.append(varName);
- buffer.append("= ");
- var.initExpressionStart = buffer.length();
- buffer.append(initializer);
- lineNumberOffset += numberOfCRs(initializer);
- buffer.append(';').append(JavaModelManager.LINE_SEPARATOR);
- buffer.append("\t\t} catch (Throwable e) {").append(
- JavaModelManager.LINE_SEPARATOR);
- buffer.append("\t\t\te.printStackTrace();").append(
- JavaModelManager.LINE_SEPARATOR);
- buffer.append("\t\t}").append(JavaModelManager.LINE_SEPARATOR);
- lineNumberOffset += 4; // 4 CRs
- }
- } else {
- // Initialize with previous value if name and type are the same
- buffer.append("\t\t");
+ }
+
+ // field initializations
+ buffer.append("\tstatic {").append(JavaModelManager.LINE_SEPARATOR);
+ lineNumberOffset++;
+ for (int i = 0; i < this.context.variableCount; i++){
+ GlobalVariable var = vars[i];
+ char[] varName = var.name;
+ GlobalVariable installedVar = installedVars == null ? null : installedVars.varNamed(varName);
+ if (installedVar == null || !CharOperation.equals(installedVar.typeName, var.typeName)) {
+ // Initialize with initializer if there was no previous value
+ char[] initializer = var.initializer;
+ if (initializer != null) {
+ buffer.append("\t\ttry {").append(JavaModelManager.LINE_SEPARATOR);
+ lineNumberOffset++;
+ var.initializerLineStart = lineNumberOffset;
+ buffer.append("\t\t\t");
+ var.initializerStart = buffer.length();
buffer.append(varName);
buffer.append("= ");
- char[] installedPackageName = installedVars.packageName;
- if (installedPackageName != null && installedPackageName.length != 0) {
- buffer.append(installedPackageName);
- buffer.append(".");
- }
- buffer.append(installedVars.className);
- buffer.append(".");
- buffer.append(varName);
+ var.initExpressionStart = buffer.length();
+ buffer.append(initializer);
+ lineNumberOffset += numberOfCRs(initializer);
buffer.append(';').append(JavaModelManager.LINE_SEPARATOR);
- lineNumberOffset++;
+ buffer.append("\t\t} catch (Throwable e) {").append(JavaModelManager.LINE_SEPARATOR);
+ buffer.append("\t\t\te.printStackTrace();").append(JavaModelManager.LINE_SEPARATOR);
+ buffer.append("\t\t}").append(JavaModelManager.LINE_SEPARATOR);
+ lineNumberOffset += 4; // 4 CRs
}
+ } else {
+ // Initialize with previous value if name and type are the same
+ buffer.append("\t\t");
+ buffer.append(varName);
+ buffer.append("= ");
+ char[] installedPackageName = installedVars.packageName;
+ if (installedPackageName != null && installedPackageName.length != 0) {
+ buffer.append(installedPackageName);
+ buffer.append(".");
+ }
+ buffer.append(installedVars.className);
+ buffer.append(".");
+ buffer.append(varName);
+ buffer.append(';').append(JavaModelManager.LINE_SEPARATOR);
+ lineNumberOffset++;
}
- buffer.append("\t}").append(JavaModelManager.LINE_SEPARATOR);
-
- // end of class declaration
- buffer.append('}').append(JavaModelManager.LINE_SEPARATOR);
-
- // return result
- int length = buffer.length();
- char[] result = new char[length];
- buffer.getChars(0, length, result, 0);
- return result;
}
+ buffer.append("\t}").append(JavaModelManager.LINE_SEPARATOR);
+
+ // end of class declaration
+ buffer.append('}').append(JavaModelManager.LINE_SEPARATOR);
- /**
- * Returns the number of cariage returns included in the given source.
- */
- private int numberOfCRs(char[] source) {
- int numberOfCRs = 0;
- boolean lastWasCR = false;
- for (int i = 0; i < source.length; i++) {
- char currentChar = source[i];
- switch (currentChar) {
- case '\r' :
- lastWasCR = true;
- numberOfCRs++;
- break;
- case '\n' :
- if (!lastWasCR)
- numberOfCRs++; // merge CR-LF
- lastWasCR = false;
- break;
- default :
- lastWasCR = false;
- }
+ // return result
+ int length = buffer.length();
+ char[] result = new char[length];
+ buffer.getChars(0, length, result, 0);
+ return result;
+}
+/**
+ * Returns the number of cariage returns included in the given source.
+ */
+private int numberOfCRs(char[] source) {
+ int numberOfCRs = 0;
+ boolean lastWasCR = false;
+ for (int i = 0; i < source.length; i++) {
+ char currentChar = source[i];
+ switch(currentChar){
+ case '\r' :
+ lastWasCR = true;
+ numberOfCRs++;
+ break;
+ case '\n' :
+ if (!lastWasCR) numberOfCRs++; // merge CR-LF
+ lastWasCR = false;
+ break;
+ default :
+ lastWasCR = false;
}
- return numberOfCRs;
}
-
+ return numberOfCRs;
+}
}
diff --git a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/VariablesInfo.java b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/VariablesInfo.java
index f31afbbb74..ad480ba4a0 100644
--- a/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/VariablesInfo.java
+++ b/org.eclipse.jdt.core/eval/org/eclipse/jdt/internal/eval/VariablesInfo.java
@@ -15,54 +15,45 @@ import java.util.*;
* compiling the code snippet).
*/
public class VariablesInfo {
- GlobalVariable[] variables;
- ;
+ GlobalVariable[] variables;;
int variableCount;
char[] packageName;
char[] className;
ClassFile[] classFiles;
- /**
- * Creates a new variables info.
- * The name of the global variable class is the simple name of this class.
- * The package name can be null if the variables have been defined in the default package.
- */
- public VariablesInfo(
- char[] packageName,
- char[] className,
- ClassFile[] classFiles,
- GlobalVariable[] variables,
- int variableCount) {
- this.packageName = packageName;
- this.className = className;
- this.classFiles = classFiles;
- this.variables = variables;
- this.variableCount = variableCount;
- }
-
- /**
- * Returns the index of the given variable.
- * Returns -1 if not found.
- */
- int indexOf(GlobalVariable var) {
- for (int i = 0; i < this.variableCount; i++) {
- if (var.equals(this.variables[i]))
- return i;
- };
- return -1;
- }
-
- /**
- * Returns the variable with the given name.
- * Returns null if not found.
- */
- GlobalVariable varNamed(char[] name) {
- GlobalVariable[] vars = this.variables;
- for (int i = 0; i < this.variableCount; i++) {
- GlobalVariable var = vars[i];
- if (CharOperation.equals(name, var.name))
- return var;
- };
- return null;
- }
-
+/**
+ * Creates a new variables info.
+ * The name of the global variable class is the simple name of this class.
+ * The package name can be null if the variables have been defined in the default package.
+ */
+public VariablesInfo(char[] packageName, char[] className, ClassFile[] classFiles, GlobalVariable[] variables, int variableCount) {
+ this.packageName = packageName;
+ this.className = className;
+ this.classFiles = classFiles;
+ this.variables = variables;
+ this.variableCount = variableCount;
+}
+/**
+ * Returns the index of the given variable.
+ * Returns -1 if not found.
+ */
+int indexOf(GlobalVariable var) {
+ for (int i = 0; i < this.variableCount; i++) {
+ if (var.equals(this.variables[i]))
+ return i;
+ };
+ return -1;
+}
+/**
+ * Returns the variable with the given name.
+ * Returns null if not found.
+ */
+GlobalVariable varNamed(char[] name) {
+ GlobalVariable[] vars = this.variables;
+ for (int i = 0; i < this.variableCount; i++) {
+ GlobalVariable var = vars[i];
+ if (CharOperation.equals(name, var.name))
+ return var;
+ };
+ return null;
+}
}
diff --git a/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/CodeFormatter.java b/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/CodeFormatter.java
index bc2b004b80..8c5dac5a26 100644
--- a/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/CodeFormatter.java
+++ b/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/CodeFormatter.java
@@ -80,7 +80,7 @@ public class CodeFormatter implements TerminalSymbols {
* Collections of positions to map
*/
private int[] positionsToMap;
-
+
/**
* Collections of mapped positions
*/
@@ -89,7 +89,7 @@ public class CodeFormatter implements TerminalSymbols {
private int indexToMap;
private int indexInMap;
-
+
private int globalDelta;
private int lineDelta;
@@ -97,339 +97,332 @@ public class CodeFormatter implements TerminalSymbols {
private int splitDelta;
private int beginningOfLineIndex;
- /**
- * Creates a new instance of Code Formatter using the FormattingOptions object
- * given as argument
- * @deprecated Use CodeFormatter(ConfigurableOption[]) instead
- */
- public CodeFormatter() {
- this(null);
- }
-
- /**
- * Creates a new instance of Code Formatter using the given settings.
- */
- public CodeFormatter(ConfigurableOption[] settings) {
-
- // initialize internal state
- constructionsCount = 0;
- constructions = new int[10];
- currentLineIndentationLevel = indentationLevel = initialIndentationLevel;
- currentCommentOffset = -1;
-
- // initialize primary and secondary scanners
- scanner = new Scanner(true, true); // regular scanner for forming lines
- scanner.recordLineSeparator = true;
- // to remind of the position of the beginning of the line.
- splitScanner = new Scanner(true, true);
- // secondary scanner to split long lines formed by primary scanning
-
- // initialize current line buffer
- currentLineBuffer = new StringBuffer();
- this.options = new FormatterOptions(settings);
- }
-
- /**
- * Sets the behaviour of the formatter about the braces using the given flag.<br>
- * <ul>
- * <li>if true, the formatter add new line & indent before the opening brace.
- * <li>if false, the formatter leaves the brace on the same line.
- * </ul>
- * @deprecated backward compatibility with VAJ
- */
+/**
+ * Creates a new instance of Code Formatter using the FormattingOptions object
+ * given as argument
+ * @deprecated Use CodeFormatter(ConfigurableOption[]) instead
+ */
+public CodeFormatter() {
+ this(null);
+}
+/**
+ * Creates a new instance of Code Formatter using the given settings.
+ */
+public CodeFormatter(ConfigurableOption[] settings) {
+
+ // initialize internal state
+ constructionsCount = 0;
+ constructions = new int[10];
+ currentLineIndentationLevel = indentationLevel = initialIndentationLevel;
+ currentCommentOffset = -1;
+
+ // initialize primary and secondary scanners
+ scanner = new Scanner(true,true); // regular scanner for forming lines
+ scanner.recordLineSeparator = true; // to remind of the position of the beginning of the line.
+ splitScanner = new Scanner(true,true); // secondary scanner to split long lines formed by primary scanning
+
+ // initialize current line buffer
+ currentLineBuffer = new StringBuffer();
+ this.options = new FormatterOptions(settings);
+}
+/**
+ * Sets the behaviour of the formatter about the braces using the given flag.<br>
+ * <ul>
+ * <li>if true, the formatter add new line & indent before the opening brace.
+ * <li>if false, the formatter leaves the brace on the same line.
+ * </ul>
+ * @deprecated backward compatibility with VAJ
+ */
- /** */
- public void addNewLineOnOpeningBrace(boolean flag) {
- options.setNewLineBeforeOpeningBraceMode(flag);
+ /** */
+public void addNewLineOnOpeningBrace(boolean flag) {
+ options.setNewLineBeforeOpeningBraceMode(flag);
+}
+/**
+ * Returns true if a lineSeparator has to be inserted before <code>operator</code>
+ * false otherwise.
+ */
+private static boolean breakLineBeforeOperator(int operator) {
+ switch (operator) {
+ case TokenNameCOMMA :
+ case TokenNameSEMICOLON :
+ case TokenNameEQUAL :
+ return false;
+ default :
+ return true;
}
-
- /**
- * Returns true if a lineSeparator has to be inserted before <code>operator</code>
- * false otherwise.
- */
- private static boolean breakLineBeforeOperator(int operator) {
- switch (operator) {
- case TokenNameCOMMA :
- case TokenNameSEMICOLON :
- case TokenNameEQUAL :
- return false;
- default :
- return true;
- }
+}
+/**
+ * Returns the end of the source code.
+ */
+private final String copyRemainingSource() {
+ char str[] = scanner.source;
+ int startPosition = scanner.startPosition;
+ int length = str.length - startPosition;
+ StringBuffer bufr = new StringBuffer(length);
+ if (startPosition < str.length) {
+ bufr.append(str, startPosition, length);
}
-
- /**
- * Returns the end of the source code.
- */
- private final String copyRemainingSource() {
- char str[] = scanner.source;
- int startPosition = scanner.startPosition;
- int length = str.length - startPosition;
- StringBuffer bufr = new StringBuffer(length);
- if (startPosition < str.length) {
- bufr.append(str, startPosition, length);
+ return (bufr.toString());
+}
+/**
+ * Inserts <code>tabCount</code> tab character or their equivalent number of spaces.
+ */
+private void dumpTab(int tabCount) {
+ if (options.indentWithTab) {
+ for (int j = 0; j < tabCount; j++) {
+ formattedSource.append('\t');
+ increaseSplitDelta(1);
}
- return (bufr.toString());
- }
-
- /**
- * Inserts <code>tabCount</code> tab character or their equivalent number of spaces.
- */
- private void dumpTab(int tabCount) {
- if (options.indentWithTab) {
- for (int j = 0; j < tabCount; j++) {
- formattedSource.append('\t');
- increaseSplitDelta(1);
- }
- } else {
- for (int i = 0, max = options.tabSize * tabCount; i < max; i++) {
- formattedSource.append(' ');
- increaseSplitDelta(1);
- }
+ } else {
+ for (int i = 0, max = options.tabSize * tabCount; i < max; i++) {
+ formattedSource.append(' ');
+ increaseSplitDelta(1);
}
}
-
- /**
- * Dumps <code>currentLineBuffer</code> into the formatted string.
- */
- private void flushBuffer() {
- String currentString = currentLineBuffer.toString();
- splitDelta = 0;
- beginningOfLineIndex = formattedSource.length();
- if (options.maxLineLength != 0) {
- if (containsOpenCloseBraces) {
- containsOpenCloseBraces = false;
- outputLine(
- currentString,
- false,
- indentationLevelForOpenCloseBraces,
- 0,
- -1,
- null,
- 0);
+}
+/**
+ * Dumps <code>currentLineBuffer</code> into the formatted string.
+ */
+private void flushBuffer() {
+ String currentString = currentLineBuffer.toString();
+ splitDelta = 0;
+ beginningOfLineIndex = formattedSource.length();
+ if (options.maxLineLength!=0){
+ if (containsOpenCloseBraces) {
+ containsOpenCloseBraces = false;
+ outputLine(currentString,
+ false,
+ indentationLevelForOpenCloseBraces,
+ 0,
+ -1,
+ null,
+ 0);
indentationLevelForOpenCloseBraces = currentLineIndentationLevel;
- } else {
- outputLine(currentString, false, currentLineIndentationLevel, 0, -1, null, 0);
- }
} else {
- formattedSource.append(currentString);
- }
+ outputLine(currentString,
+ false,
+ currentLineIndentationLevel,
+ 0,
+ -1,
+ null,
+ 0);
+ }
+ } else {
+ formattedSource.append(currentString);
}
-
- /**
- * Formats the input string.
- */
- private void format() {
- int token = 0;
- int previousToken = 0;
- int previousCompilableToken = 0;
-
- int indentationOffset = 0;
-
- int newLinesInWhitespace = 0;
- // number of new lines in the previous whitespace token
- // (used to leave blank lines before comments)
- int pendingNewLines = 0;
- boolean expectingOpenBrace = false;
- boolean clearNonBlockIndents = false;
- // true if all indentations till the 1st { (usefull after } or ;)
- boolean pendingSpace = true;
- boolean pendingNewlineAfterParen = false;
- // true when a cr is to be put after a ) (in conditional statements)
- boolean inAssignment = false;
- boolean inArrayAssignment = false;
- boolean inThrowsClause = false;
- boolean inClassOrInterfaceHeader = false;
-
- // openBracketCount is used to count the number of open brackets not closed yet.
- int openBracketCount = 0;
-
- int unarySignModifier = 0;
-
- // openParenthesis[0] is used to count the parenthesis not belonging to a condition
- // (eg foo();). parenthesis in for (...) are count elsewhere in the array.
- int openParenthesisCount = 1;
- int[] openParenthesis = new int[10];
-
- // tokenBeforeColon is used to know what token goes along with the current :
- // it can be case or ?
- int tokenBeforeColonCount = 0;
- int[] tokenBeforeColon = new int[10];
-
- constructionsCount = 0; // initializes the constructions count.
-
- // contains DO if in a DO..WHILE statement, UNITIALIZED otherwise.
- int nlicsToken = 0;
-
- // fix for 1FF17XY: LFCOM:ALL - Format problem on not matching } and else
- boolean specialElse = false;
-
- // OPTION (IndentationLevel): initial indentation level may be non-zero.
- currentLineIndentationLevel += constructionsCount;
-
- // An InvalidInputException exception might cause the termination of this loop.
- try {
- while (true) {
- // Get the next token. Catch invalid input and output it
- // with minimal formatting, also catch end of input and
- // exit the loop.
- try {
- token = scanner.getNextToken();
- } catch (InvalidInputException e) {
- if (!handleInvalidToken(e)) {
- throw e;
- }
- token = 0;
+}
+/**
+ * Formats the input string.
+ */
+private void format() {
+ int token = 0;
+ int previousToken = 0;
+ int previousCompilableToken = 0;
+
+ int indentationOffset = 0;
+
+ int newLinesInWhitespace = 0;
+ // number of new lines in the previous whitespace token
+ // (used to leave blank lines before comments)
+ int pendingNewLines = 0;
+ boolean expectingOpenBrace = false;
+ boolean clearNonBlockIndents = false;
+ // true if all indentations till the 1st { (usefull after } or ;)
+ boolean pendingSpace = true;
+ boolean pendingNewlineAfterParen = false;
+ // true when a cr is to be put after a ) (in conditional statements)
+ boolean inAssignment = false;
+ boolean inArrayAssignment = false;
+ boolean inThrowsClause = false;
+ boolean inClassOrInterfaceHeader = false;
+
+ // openBracketCount is used to count the number of open brackets not closed yet.
+ int openBracketCount = 0;
+
+ int unarySignModifier = 0;
+
+ // openParenthesis[0] is used to count the parenthesis not belonging to a condition
+ // (eg foo();). parenthesis in for (...) are count elsewhere in the array.
+ int openParenthesisCount = 1;
+ int[] openParenthesis = new int[10];
+
+ // tokenBeforeColon is used to know what token goes along with the current :
+ // it can be case or ?
+ int tokenBeforeColonCount = 0;
+ int[] tokenBeforeColon = new int[10];
+
+ constructionsCount = 0; // initializes the constructions count.
+
+ // contains DO if in a DO..WHILE statement, UNITIALIZED otherwise.
+ int nlicsToken = 0;
+
+ // fix for 1FF17XY: LFCOM:ALL - Format problem on not matching } and else
+ boolean specialElse = false;
+
+ // OPTION (IndentationLevel): initial indentation level may be non-zero.
+ currentLineIndentationLevel += constructionsCount;
+
+
+ // An InvalidInputException exception might cause the termination of this loop.
+ try {
+ while (true) {
+ // Get the next token. Catch invalid input and output it
+ // with minimal formatting, also catch end of input and
+ // exit the loop.
+ try {
+ token = scanner.getNextToken();
+ } catch (InvalidInputException e) {
+ if (!handleInvalidToken(e)) {
+ throw e;
}
- if (token == Scanner.TokenNameEOF)
- break;
+ token = 0;
+ }
+ if (token == Scanner.TokenNameEOF)
+ break;
- /* ## MODIFYING the indentation level before generating new lines
- and indentation in the output string
- */
+ /* ## MODIFYING the indentation level before generating new lines
+ and indentation in the output string
+ */
- // Removes all the indentations made by statements not followed by a block
- // except if the current token is ELSE, CATCH or if we are in a switch/case
+ // Removes all the indentations made by statements not followed by a block
+ // except if the current token is ELSE, CATCH or if we are in a switch/case
- if (clearNonBlockIndents && (token != Scanner.TokenNameWHITESPACE)) {
+ if (clearNonBlockIndents && (token != Scanner.TokenNameWHITESPACE)) {
- switch (token) {
- case TokenNameelse :
- if (constructionsCount > 0
- && constructions[constructionsCount - 1] == TokenNameelse) {
- pendingNewLines = 1;
- specialElse = true;
- }
- indentationLevel += popInclusiveUntil(TokenNameif);
- break;
- case TokenNamecatch :
- indentationLevel += popInclusiveUntil(TokenNamecatch);
- break;
- case TokenNamefinally :
- indentationLevel += popInclusiveUntil(TokenNamecatch);
+ switch (token) {
+ case TokenNameelse :
+ if (constructionsCount > 0 && constructions[constructionsCount-1] == TokenNameelse){
+ pendingNewLines = 1;
+ specialElse = true;
+ }
+ indentationLevel += popInclusiveUntil(TokenNameif);
+ break;
+ case TokenNamecatch :
+ indentationLevel += popInclusiveUntil(TokenNamecatch);
+ break;
+ case TokenNamefinally :
+ indentationLevel += popInclusiveUntil(TokenNamecatch);
+ break;
+ case TokenNamewhile :
+ if (nlicsToken == TokenNamedo) {
+ indentationLevel += pop(TokenNamedo);
break;
- case TokenNamewhile :
- if (nlicsToken == TokenNamedo) {
- indentationLevel += pop(TokenNamedo);
- break;
- }
- default :
- indentationLevel += popExclusiveUntilBlockOrCase();
- // clear until a CASE, DEFAULT or BLOCK is encountered.
- // Thus, the indentationLevel is correctly cleared either
- // in a switch/case statement or in any other situation.
- }
- clearNonBlockIndents = false;
- }
-
- // returns to the indentation level created by the SWITCH keyword
- // if the current token is a CASE or a DEFAULT
-
- if (token == TokenNamecase || token == TokenNamedefault) {
- indentationLevel += pop(TokenNamecase);
- }
-
- if (token == Scanner.TokenNamethrows) {
- inThrowsClause = true;
- }
-
- if (token == Scanner.TokenNameclass || token == Scanner.TokenNameinterface) {
- inClassOrInterfaceHeader = true;
- }
- /* ## APPEND newlines and indentations to the output string
- */
-
- // Do not add a new line between ELSE and IF, if the option elseIfOnSameLine is true.
- // Fix for 1ETLWPZ: IVJCOM:ALL - incorrect "else if" formatting
- if (pendingNewlineAfterParen
- && previousCompilableToken == TokenNameelse
- && token == TokenNameif
- && options.compactElseIfMode) {
- pendingNewlineAfterParen = false;
- pendingNewLines = 0;
- indentationLevel += pop(TokenNameelse);
- // because else if is now one single statement,
- // the indentation level after it is increased by one and not by 2
- // (else = 1 indent, if = 1 indent, but else if = 1 indent, not 2).
+ }
+ default :
+ indentationLevel += popExclusiveUntilBlockOrCase();
+ // clear until a CASE, DEFAULT or BLOCK is encountered.
+ // Thus, the indentationLevel is correctly cleared either
+ // in a switch/case statement or in any other situation.
}
+ clearNonBlockIndents = false;
+ }
- // Add a newline & indent to the formatted source string if
- // a for/if-else/while statement was scanned and there is no block
- // following it.
+ // returns to the indentation level created by the SWITCH keyword
+ // if the current token is a CASE or a DEFAULT
- pendingNewlineAfterParen =
- pendingNewlineAfterParen
- || (previousCompilableToken == TokenNameRPAREN && token == TokenNameLBRACE);
- if (pendingNewlineAfterParen && token != Scanner.TokenNameWHITESPACE) {
- pendingNewlineAfterParen = false;
+ if (token == TokenNamecase || token == TokenNamedefault) {
+ indentationLevel += pop(TokenNamecase);
+ }
- // Do to add a newline & indent sequence if the current token is an
- // open brace or a period or if the current token is a semi-colon and the
- // previous token is a close paren.
- // add a new line if a parenthesis belonging to a for() statement
- // has been closed and the current token is not an opening brace
+ if (token == Scanner.TokenNamethrows) {
+ inThrowsClause = true;
+ }
- if (token != TokenNameLBRACE
- && !isComment(token) // to avoid adding new line between else and a comment
+ if (token == Scanner.TokenNameclass || token == Scanner.TokenNameinterface) {
+ inClassOrInterfaceHeader = true;
+ }
+ /* ## APPEND newlines and indentations to the output string
+ */
+
+ // Do not add a new line between ELSE and IF, if the option elseIfOnSameLine is true.
+ // Fix for 1ETLWPZ: IVJCOM:ALL - incorrect "else if" formatting
+ if (pendingNewlineAfterParen && previousCompilableToken == TokenNameelse && token == TokenNameif && options.compactElseIfMode){
+ pendingNewlineAfterParen = false;
+ pendingNewLines = 0;
+ indentationLevel += pop(TokenNameelse);
+ // because else if is now one single statement,
+ // the indentation level after it is increased by one and not by 2
+ // (else = 1 indent, if = 1 indent, but else if = 1 indent, not 2).
+ }
+
+ // Add a newline & indent to the formatted source string if
+ // a for/if-else/while statement was scanned and there is no block
+ // following it.
+
+ pendingNewlineAfterParen = pendingNewlineAfterParen || (previousCompilableToken == TokenNameRPAREN && token == TokenNameLBRACE);
+ if (pendingNewlineAfterParen && token != Scanner.TokenNameWHITESPACE) {
+ pendingNewlineAfterParen = false;
+
+ // Do to add a newline & indent sequence if the current token is an
+ // open brace or a period or if the current token is a semi-colon and the
+ // previous token is a close paren.
+ // add a new line if a parenthesis belonging to a for() statement
+ // has been closed and the current token is not an opening brace
+
+ if (token != TokenNameLBRACE && !isComment(token)
+ // to avoid adding new line between else and a comment
&& token != TokenNameDOT
- && !(previousCompilableToken == TokenNameRPAREN && token == TokenNameSEMICOLON)) {
- newLine(1);
- currentLineIndentationLevel += indentationLevel;
- pendingNewLines = 0;
- pendingSpace = false;
- } else {
- if (token == TokenNameLBRACE && options.newLineBeforeOpeningBraceMode) {
- newLine(1);
- currentLineIndentationLevel = indentationLevel;
- pendingNewLines = 0;
- pendingSpace = false;
- }
- }
- }
-
- // see PR 1G5G8EC
- if (token == TokenNameLBRACE && inThrowsClause) {
- inThrowsClause = false;
- if (options.newLineBeforeOpeningBraceMode) {
+ && ! (previousCompilableToken == TokenNameRPAREN
+ && token == TokenNameSEMICOLON)) {
+ newLine(1);
+ currentLineIndentationLevel += indentationLevel;
+ pendingNewLines = 0;
+ pendingSpace = false;
+ } else {
+ if (token == TokenNameLBRACE && options.newLineBeforeOpeningBraceMode) {
newLine(1);
currentLineIndentationLevel = indentationLevel;
pendingNewLines = 0;
pendingSpace = false;
}
}
+ }
- // see PR 1G5G82G
- if (token == TokenNameLBRACE && inClassOrInterfaceHeader) {
- inClassOrInterfaceHeader = false;
- if (options.newLineBeforeOpeningBraceMode) {
- newLine(1);
- currentLineIndentationLevel = indentationLevel;
- pendingNewLines = 0;
- pendingSpace = false;
- }
+ // see PR 1G5G8EC
+ if (token == TokenNameLBRACE && inThrowsClause) {
+ inThrowsClause = false;
+ if (options.newLineBeforeOpeningBraceMode) {
+ newLine(1);
+ currentLineIndentationLevel = indentationLevel;
+ pendingNewLines = 0;
+ pendingSpace = false;
+ }
+ }
+
+ // see PR 1G5G82G
+ if (token == TokenNameLBRACE && inClassOrInterfaceHeader) {
+ inClassOrInterfaceHeader = false;
+ if (options.newLineBeforeOpeningBraceMode) {
+ newLine(1);
+ currentLineIndentationLevel = indentationLevel;
+ pendingNewLines = 0;
+ pendingSpace = false;
}
- // Add pending new lines to the formatted source string.
- // Note: pending new lines are not added if the current token
- // is a single line comment or whitespace.
- // if the comment is between parenthesis, there is no blank line preservation
- // (if it's a one-line comment, a blank line is added after it).
-
- if (((pendingNewLines > 0 && (!isComment(token)))
- || (newLinesInWhitespace > 0 && (openParenthesisCount <= 1 && isComment(token)))
+ }
+ // Add pending new lines to the formatted source string.
+ // Note: pending new lines are not added if the current token
+ // is a single line comment or whitespace.
+ // if the comment is between parenthesis, there is no blank line preservation
+ // (if it's a one-line comment, a blank line is added after it).
+
+ if (((pendingNewLines > 0 && (!isComment(token)))
+ || (newLinesInWhitespace > 0
+ && (openParenthesisCount <= 1 && isComment(token)))
|| (previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE))
- && token != Scanner.TokenNameWHITESPACE) {
+ && token != Scanner.TokenNameWHITESPACE) {
- // Do not add newline & indent between an adjoining close brace and
- // close paren. Anonymous inner classes may use this form.
+ // Do not add newline & indent between an adjoining close brace and
+ // close paren. Anonymous inner classes may use this form.
- boolean closeBraceAndCloseParen =
- previousToken == TokenNameRBRACE && token == TokenNameRPAREN;
+ boolean closeBraceAndCloseParen =
+ previousToken == TokenNameRBRACE && token == TokenNameRPAREN;
- // OPTION (NewLineInCompoundStatement): do not add newline & indent
- // between close brace and else, (do) while, catch, and finally if
- // newlineInCompoundStatement is true.
+ // OPTION (NewLineInCompoundStatement): do not add newline & indent
+ // between close brace and else, (do) while, catch, and finally if
+ // newlineInCompoundStatement is true.
- boolean nlicsOption =
+ boolean nlicsOption =
previousToken == TokenNameRBRACE
&& !options.newlineInControlStatementMode
&& (token == TokenNameelse
@@ -437,1979 +430,1852 @@ public class CodeFormatter implements TerminalSymbols {
|| token == TokenNamecatch
|| token == TokenNamefinally);
- // Do not add a newline & indent between a close brace and semi-colon.
-
- boolean semiColonAndCloseBrace =
- previousToken == TokenNameRBRACE && token == TokenNameSEMICOLON;
-
- // Do not add a new line & indent between a multiline comment and a opening brace
-
- boolean commentAndOpenBrace =
- previousToken == Scanner.TokenNameCOMMENT_BLOCK && token == TokenNameLBRACE;
-
- // Do not add a newline & indent between a close brace and a colon (in array assignments, for example).
-
- boolean commaAndCloseBrace =
- previousToken == TokenNameRBRACE && token == TokenNameCOMMA;
-
- // Add a newline and indent, if appropriate.
-
- if (specialElse
- || (!commentAndOpenBrace
- && !closeBraceAndCloseParen
- && !nlicsOption
- && !semiColonAndCloseBrace
- && !commaAndCloseBrace)) {
- // if clearAllBlankLinesMode=false, leaves the blank lines
- // inserted by the user
- // if clearAllBlankLinesMode=true, removes all of then
- // and insert only blank lines required by the formatting.
- if (!options.clearAllBlankLinesMode) {
- pendingNewLines = (pendingNewLines < newLinesInWhitespace)
- // (isComment(token))
- ? newLinesInWhitespace : pendingNewLines;
- pendingNewLines = (pendingNewLines > 2) ? 2 : pendingNewLines;
- }
+ // Do not add a newline & indent between a close brace and semi-colon.
+
+ boolean semiColonAndCloseBrace =
+ previousToken == TokenNameRBRACE && token == TokenNameSEMICOLON;
+
+ // Do not add a new line & indent between a multiline comment and a opening brace
+
+ boolean commentAndOpenBrace = previousToken == Scanner.TokenNameCOMMENT_BLOCK && token == TokenNameLBRACE;
+
+ // Do not add a newline & indent between a close brace and a colon (in array assignments, for example).
+
+ boolean commaAndCloseBrace =
+ previousToken == TokenNameRBRACE && token == TokenNameCOMMA;
+
+ // Add a newline and indent, if appropriate.
+
+ if (specialElse || (!commentAndOpenBrace && !closeBraceAndCloseParen && !nlicsOption && !semiColonAndCloseBrace && !commaAndCloseBrace)) {
+ // if clearAllBlankLinesMode=false, leaves the blank lines
+ // inserted by the user
+ // if clearAllBlankLinesMode=true, removes all of then
+ // and insert only blank lines required by the formatting.
+ if (!options.clearAllBlankLinesMode) {
+ pendingNewLines =
+ (pendingNewLines < newLinesInWhitespace)
+// (isComment(token))
+ ? newLinesInWhitespace
+ : pendingNewLines;
+ pendingNewLines = (pendingNewLines > 2) ? 2 : pendingNewLines;
+ }
- if (previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE) {
- containsOpenCloseBraces = true;
- indentationLevelForOpenCloseBraces = currentLineIndentationLevel;
- if (isComment(previousToken)) {
- newLine(pendingNewLines);
- } else {
- /* if (!(constructionsCount > 1
- && constructions[constructionsCount-1] == NONINDENT_BLOCK
- && (constructions[constructionsCount-2] == TokenNamefor
- || constructions[constructionsCount-2] == TokenNamewhile))) {*/
- if (options.newLineInEmptyBlockMode) {
- if (inArrayAssignment) {
- newLine(1); // array assigment with an empty block
- } else {
- newLine(pendingNewLines);
- }
- }
- // }
- }
+ if (previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE) {
+ containsOpenCloseBraces = true;
+ indentationLevelForOpenCloseBraces = currentLineIndentationLevel;
+ if (isComment(previousToken)) {
+ newLine(pendingNewLines);
} else {
- // see PR 1FKKC3U: LFCOM:WINNT - Format problem with a comment before the ';'
- if (!((previousToken == Scanner.TokenNameCOMMENT_BLOCK
- || previousToken == Scanner.TokenNameCOMMENT_JAVADOC)
- && token == TokenNameSEMICOLON)) {
- newLine(pendingNewLines);
+/* if (!(constructionsCount > 1
+ && constructions[constructionsCount-1] == NONINDENT_BLOCK
+ && (constructions[constructionsCount-2] == TokenNamefor
+ || constructions[constructionsCount-2] == TokenNamewhile))) {*/
+ if (options.newLineInEmptyBlockMode) {
+ if (inArrayAssignment) {
+ newLine(1); // array assigment with an empty block
+ } else {
+ newLine(pendingNewLines);
+ }
}
+// }
+ }
+ } else {
+ // see PR 1FKKC3U: LFCOM:WINNT - Format problem with a comment before the ';'
+ if (!((previousToken == Scanner.TokenNameCOMMENT_BLOCK || previousToken == Scanner.TokenNameCOMMENT_JAVADOC) && token == TokenNameSEMICOLON)) {
+ newLine(pendingNewLines);
}
- if (((previousCompilableToken == TokenNameSEMICOLON)
+ }
+ if (((previousCompilableToken == TokenNameSEMICOLON)
|| (previousCompilableToken == TokenNameLBRACE)
|| (previousCompilableToken == TokenNameRBRACE)
|| (isComment(previousToken)))
- && (token == TokenNameRBRACE)) {
- indentationOffset = -1;
- indentationLevel += popExclusiveUntilBlock();
- }
-
- if (previousToken == Scanner.TokenNameCOMMENT_LINE && inAssignment) {
- // PR 1FI5IPO
- currentLineIndentationLevel++;
- } else {
- currentLineIndentationLevel = indentationLevel + indentationOffset;
- }
-
- pendingSpace = false;
- indentationOffset = 0;
+ && (token == TokenNameRBRACE)) {
+ indentationOffset = -1;
+ indentationLevel += popExclusiveUntilBlock();
}
- pendingNewLines = 0;
- newLinesInWhitespace = 0;
- specialElse = false;
- if (nlicsToken == TokenNamedo && token == TokenNamewhile) {
- nlicsToken = 0;
+ if (previousToken == Scanner.TokenNameCOMMENT_LINE && inAssignment) {
+ // PR 1FI5IPO
+ currentLineIndentationLevel++;
+ } else {
+ currentLineIndentationLevel = indentationLevel + indentationOffset;
}
+
+ pendingSpace = false;
+ indentationOffset = 0;
}
+ pendingNewLines = 0;
+ newLinesInWhitespace = 0;
+ specialElse = false;
- switch (token) {
- case TokenNameelse :
- case TokenNamefinally :
- expectingOpenBrace = true;
- pendingNewlineAfterParen = true;
- indentationLevel += pushControlStatement(token);
- break;
- case TokenNamecase :
- case TokenNamedefault :
- if (tokenBeforeColonCount == tokenBeforeColon.length) {
- System.arraycopy(
- tokenBeforeColon,
- 0,
- (tokenBeforeColon = new int[tokenBeforeColonCount * 2]),
- 0,
- tokenBeforeColonCount);
- }
- tokenBeforeColon[tokenBeforeColonCount++] = TokenNamecase;
- indentationLevel += pushControlStatement(TokenNamecase);
- break;
- case TokenNameQUESTION :
- if (tokenBeforeColonCount == tokenBeforeColon.length) {
- System.arraycopy(
- tokenBeforeColon,
- 0,
- (tokenBeforeColon = new int[tokenBeforeColonCount * 2]),
- 0,
- tokenBeforeColonCount);
- }
- tokenBeforeColon[tokenBeforeColonCount++] = token;
- break;
- case TokenNameswitch :
- case TokenNamefor :
- case TokenNameif :
- case TokenNamewhile :
- if (openParenthesisCount == openParenthesis.length) {
- System.arraycopy(
- openParenthesis,
- 0,
- (openParenthesis = new int[openParenthesisCount * 2]),
- 0,
- openParenthesisCount);
- }
- openParenthesis[openParenthesisCount++] = 0;
- expectingOpenBrace = true;
+ if (nlicsToken == TokenNamedo && token == TokenNamewhile) {
+ nlicsToken = 0;
+ }
+ }
- indentationLevel += pushControlStatement(token);
- break;
- case TokenNametry :
- pendingNewlineAfterParen = true;
- case TokenNamecatch :
- // several CATCH statements can be contiguous.
- // a CATCH is encountered pop until first CATCH (if a CATCH follows a TRY it works the same way,
- // as CATCH and TRY are the same token in the stack).
- expectingOpenBrace = true;
- indentationLevel += pushControlStatement(TokenNamecatch);
- break;
+ switch (token) {
+ case TokenNameelse :
+ case TokenNamefinally :
+ expectingOpenBrace = true;
+ pendingNewlineAfterParen = true;
+ indentationLevel += pushControlStatement(token);
+ break;
+ case TokenNamecase :
+ case TokenNamedefault :
+ if (tokenBeforeColonCount == tokenBeforeColon.length) {
+ System.arraycopy(
+ tokenBeforeColon,
+ 0,
+ (tokenBeforeColon = new int[tokenBeforeColonCount * 2]),
+ 0,
+ tokenBeforeColonCount);
+ }
+ tokenBeforeColon[tokenBeforeColonCount++] = TokenNamecase;
+ indentationLevel += pushControlStatement(TokenNamecase);
+ break;
+ case TokenNameQUESTION :
+ if (tokenBeforeColonCount == tokenBeforeColon.length) {
+ System.arraycopy(
+ tokenBeforeColon,
+ 0,
+ (tokenBeforeColon = new int[tokenBeforeColonCount * 2]),
+ 0,
+ tokenBeforeColonCount);
+ }
+ tokenBeforeColon[tokenBeforeColonCount++] = token;
+ break;
+ case TokenNameswitch :
+ case TokenNamefor :
+ case TokenNameif :
+ case TokenNamewhile :
+ if (openParenthesisCount == openParenthesis.length) {
+ System.arraycopy(
+ openParenthesis,
+ 0,
+ (openParenthesis = new int[openParenthesisCount * 2]),
+ 0,
+ openParenthesisCount);
+ }
+ openParenthesis[openParenthesisCount++] = 0;
+ expectingOpenBrace = true;
+
+ indentationLevel += pushControlStatement(token);
+ break;
+ case TokenNametry :
+ pendingNewlineAfterParen = true;
+ case TokenNamecatch :
+ // several CATCH statements can be contiguous.
+ // a CATCH is encountered pop until first CATCH (if a CATCH follows a TRY it works the same way,
+ // as CATCH and TRY are the same token in the stack).
+ expectingOpenBrace = true;
+ indentationLevel += pushControlStatement(TokenNamecatch);
+ break;
- case TokenNamedo :
- expectingOpenBrace = true;
- indentationLevel += pushControlStatement(token);
- nlicsToken = token;
- break;
- case TokenNamenew :
+ case TokenNamedo :
+ expectingOpenBrace = true;
+ indentationLevel += pushControlStatement(token);
+ nlicsToken = token;
+ break;
+ case TokenNamenew :
- // The flag inAssigment is used to properly format
- // array assignments, and if a non-array assignment
- // statement is in progress, it is no longer
- // beneficial to know this, so set the flag to false.
+ // The flag inAssigment is used to properly format
+ // array assignments, and if a non-array assignment
+ // statement is in progress, it is no longer
+ // beneficial to know this, so set the flag to false.
- /* if (!inArrayAssignment) {
- inAssignment = false;
- }*/
- break;
- case TokenNameLPAREN :
-
- // Put a space between the previous and current token if the
- // previous token was not a keyword, open paren, logical
- // compliment (eg: !), semi-colon, open brace, close brace,
- // super, or this.
-
- if (previousCompilableToken != TokenNameLBRACKET
- && previousToken != TokenNameIdentifier
- && previousToken != 0
- && previousToken != TokenNameNOT
- && previousToken != TokenNameLPAREN
- && previousToken != TokenNameTWIDDLE
- && previousToken != TokenNameSEMICOLON
- && previousToken != TokenNameLBRACE
- && previousToken != TokenNameRBRACE
- && previousToken != TokenNamesuper
- && previousToken != TokenNamethis) {
- space();
- }
+/* if (!inArrayAssignment) {
+ inAssignment = false;
+ }*/
+ break;
+ case TokenNameLPAREN :
+
+ // Put a space between the previous and current token if the
+ // previous token was not a keyword, open paren, logical
+ // compliment (eg: !), semi-colon, open brace, close brace,
+ // super, or this.
+
+ if (previousCompilableToken != TokenNameLBRACKET
+ && previousToken != TokenNameIdentifier
+ && previousToken != 0
+ && previousToken != TokenNameNOT
+ && previousToken != TokenNameLPAREN
+ && previousToken != TokenNameTWIDDLE
+ && previousToken != TokenNameSEMICOLON
+ && previousToken != TokenNameLBRACE
+ && previousToken != TokenNameRBRACE
+ && previousToken != TokenNamesuper
+ && previousToken != TokenNamethis) {
+ space();
+ }
- // If in a for/if/while statement, increase the parenthesis count
- // for the current openParenthesisCount
- // else increase the count for stand alone parenthesis.
- if (openParenthesisCount > 0)
- openParenthesis[openParenthesisCount - 1]++;
- else
- openParenthesis[0]++;
+ // If in a for/if/while statement, increase the parenthesis count
+ // for the current openParenthesisCount
+ // else increase the count for stand alone parenthesis.
+ if (openParenthesisCount > 0)
+ openParenthesis[openParenthesisCount - 1]++;
+ else
+ openParenthesis[0]++;
- pendingSpace = false;
- break;
- case TokenNameRPAREN :
+ pendingSpace = false;
+ break;
+ case TokenNameRPAREN :
- // Decrease the parenthesis count
- // if there is no more unclosed parenthesis,
- // a new line and indent may be append (depending on the next token).
+ // Decrease the parenthesis count
+ // if there is no more unclosed parenthesis,
+ // a new line and indent may be append (depending on the next token).
- if ((openParenthesisCount > 1)
- && (openParenthesis[openParenthesisCount - 1] > 0)) {
- openParenthesis[openParenthesisCount - 1]--;
- if (openParenthesis[openParenthesisCount - 1] <= 0) {
- pendingNewlineAfterParen = true;
- inAssignment = false;
- openParenthesisCount--;
+ if ((openParenthesisCount > 1)
+ && (openParenthesis[openParenthesisCount - 1] > 0)) {
+ openParenthesis[openParenthesisCount - 1]--;
+ if (openParenthesis[openParenthesisCount - 1] <= 0) {
+ pendingNewlineAfterParen = true;
+ inAssignment = false;
+ openParenthesisCount--;
- }
- } else {
- openParenthesis[0]--;
}
+ } else {
+ openParenthesis[0]--;
+ }
+ pendingSpace = false;
+ break;
+ case TokenNameLBRACE :
+ if ((previousCompilableToken == TokenNameRBRACKET) || (previousCompilableToken == TokenNameEQUAL)) {
+// if (previousCompilableToken == TokenNameRBRACKET) {
+ inArrayAssignment = true;
+ inAssignment = false;
+ }
+ if (inArrayAssignment) {
+ indentationLevel += pushBlock();
+ } else {
+ // Add new line and increase indentation level after open brace.
+ pendingNewLines = 1;
+ indentationLevel += pushBlock();
+ }
+ break;
+ case TokenNameRBRACE :
+ if (previousCompilableToken == TokenNameRPAREN) {
pendingSpace = false;
- break;
- case TokenNameLBRACE :
- if ((previousCompilableToken == TokenNameRBRACKET)
- || (previousCompilableToken == TokenNameEQUAL)) {
- // if (previousCompilableToken == TokenNameRBRACKET) {
- inArrayAssignment = true;
- inAssignment = false;
- }
- if (inArrayAssignment) {
- indentationLevel += pushBlock();
- } else {
- // Add new line and increase indentation level after open brace.
- pendingNewLines = 1;
- indentationLevel += pushBlock();
- }
- break;
- case TokenNameRBRACE :
- if (previousCompilableToken == TokenNameRPAREN) {
- pendingSpace = false;
- }
- if (inArrayAssignment) {
- inArrayAssignment = false;
- pendingNewLines = 1;
- indentationLevel += popInclusiveUntilBlock();
- } else {
- pendingNewLines = 1;
- indentationLevel += popInclusiveUntilBlock();
+ }
+ if (inArrayAssignment) {
+ inArrayAssignment = false;
+ pendingNewLines = 1;
+ indentationLevel += popInclusiveUntilBlock();
+ } else {
+ pendingNewLines = 1;
+ indentationLevel += popInclusiveUntilBlock();
- if (previousCompilableToken == TokenNameRPAREN) {
- // fix for 1FGDDV6: LFCOM:WIN98 - Weird splitting on message expression
- currentLineBuffer.append(options.lineSeparatorSequence);
- increaseLineDelta(options.lineSeparatorSequence.length);
- }
+ if (previousCompilableToken == TokenNameRPAREN){
+ // fix for 1FGDDV6: LFCOM:WIN98 - Weird splitting on message expression
+ currentLineBuffer.append(options.lineSeparatorSequence);
+ increaseLineDelta(options.lineSeparatorSequence.length);
+ }
- if (constructionsCount > 0) {
- switch (constructions[constructionsCount - 1]) {
- case TokenNamefor :
- //indentationLevel += popExclusiveUntilBlock();
- //break;
- case TokenNameswitch :
- case TokenNameif :
- case TokenNameelse :
- case TokenNametry :
- case TokenNamecatch :
- case TokenNamefinally :
- case TokenNamewhile :
- case TokenNamedo :
- clearNonBlockIndents = true;
- default :
- break;
- }
+ if (constructionsCount > 0) {
+ switch (constructions[constructionsCount - 1]) {
+ case TokenNamefor :
+ //indentationLevel += popExclusiveUntilBlock();
+ //break;
+ case TokenNameswitch :
+ case TokenNameif :
+ case TokenNameelse :
+ case TokenNametry :
+ case TokenNamecatch :
+ case TokenNamefinally :
+ case TokenNamewhile :
+ case TokenNamedo :
+ clearNonBlockIndents = true;
+ default :
+ break;
}
-
}
- break;
- case TokenNameLBRACKET :
- openBracketCount++;
- pendingSpace = false;
- break;
- case TokenNameRBRACKET :
- openBracketCount -= (openBracketCount > 0) ? 1 : 0;
- // if there is no left bracket to close, the right bracket is ignored.
- pendingSpace = false;
- break;
- case TokenNameCOMMA :
- case TokenNameDOT :
- pendingSpace = false;
- break;
- case TokenNameSEMICOLON :
- // Do not generate line terminators in the definition of
- // the for statement.
- // if not in this case, jump a line and reduce indentation after the brace
- // if the block it closes belongs to a conditional statement (if, while, do...).
+ }
+ break;
+ case TokenNameLBRACKET :
+ openBracketCount++;
+ pendingSpace = false;
+ break;
+ case TokenNameRBRACKET :
+ openBracketCount-=(openBracketCount>0)?1:0;
+ // if there is no left bracket to close, the right bracket is ignored.
+ pendingSpace = false;
+ break;
+ case TokenNameCOMMA :
+ case TokenNameDOT :
+ pendingSpace = false;
+ break;
+ case TokenNameSEMICOLON :
+
+ // Do not generate line terminators in the definition of
+ // the for statement.
+ // if not in this case, jump a line and reduce indentation after the brace
+ // if the block it closes belongs to a conditional statement (if, while, do...).
- if (openParenthesisCount <= 1) {
- pendingNewLines = 1;
- if (expectingOpenBrace) {
- clearNonBlockIndents = true;
- expectingOpenBrace = false;
- }
+ if (openParenthesisCount <= 1) {
+ pendingNewLines = 1;
+ if (expectingOpenBrace) {
+ clearNonBlockIndents = true;
+ expectingOpenBrace = false;
}
- inAssignment = false;
- pendingSpace = false;
- break;
- case TokenNamePLUS_PLUS :
- case TokenNameMINUS_MINUS :
+ }
+ inAssignment = false;
+ pendingSpace = false;
+ break;
+ case TokenNamePLUS_PLUS :
+ case TokenNameMINUS_MINUS :
- // Do not put a space between a post-increment/decrement
- // and the identifier being modified.
+ // Do not put a space between a post-increment/decrement
+ // and the identifier being modified.
- if (previousToken == TokenNameIdentifier
- || previousToken == TokenNameRBRACKET) {
- pendingSpace = false;
- }
- break;
- case TokenNamePLUS : // previously ADDITION
- case TokenNameMINUS :
+ if (previousToken == TokenNameIdentifier
+ || previousToken == TokenNameRBRACKET) {
+ pendingSpace = false;
+ }
+ break;
+ case TokenNamePLUS : // previously ADDITION
+ case TokenNameMINUS :
- // Handle the unary operators plus and minus via a 3-state flag.
+ // Handle the unary operators plus and minus via a 3-state flag.
- if (!isLiteralToken(previousToken)
- && previousToken != TokenNameIdentifier
- && previousToken != TokenNameRPAREN
- && previousToken != TokenNameRBRACKET) {
- unarySignModifier = 2;
- }
- break;
- case TokenNameCOLON :
+ if (!isLiteralToken(previousToken)
+ && previousToken != TokenNameIdentifier
+ && previousToken != TokenNameRPAREN
+ && previousToken != TokenNameRBRACKET) {
+ unarySignModifier = 2;
+ }
+ break;
+ case TokenNameCOLON :
- // In a switch/case statement, add a newline & indent
- // when a colon is encountered.
- if (tokenBeforeColonCount > 0) {
- if (tokenBeforeColon[tokenBeforeColonCount - 1] == TokenNamecase) {
- pendingNewLines = 1;
- }
- tokenBeforeColonCount--;
- }
- break;
- case TokenNameEQUAL :
- inAssignment = true;
- break;
- case Scanner.TokenNameCOMMENT_LINE :
- pendingNewLines = 1;
- if (inAssignment) {
- currentLineIndentationLevel++;
- }
- break; // a line is always inserted after a one-line comment
- case Scanner.TokenNameCOMMENT_JAVADOC :
- case Scanner.TokenNameCOMMENT_BLOCK :
- currentCommentOffset = getCurrentCommentOffset();
- if (openParenthesis[0] == 0 && openBracketCount < 1) {
+ // In a switch/case statement, add a newline & indent
+ // when a colon is encountered.
+ if (tokenBeforeColonCount > 0) {
+ if (tokenBeforeColon[tokenBeforeColonCount - 1] == TokenNamecase) {
pendingNewLines = 1;
- // a new line is inserted only if the comment is not between parenthesis.
}
- break;
- case Scanner.TokenNameWHITESPACE :
-
- // Count the number of line terminators in the whitespace so
- // line spacing can be preserved near comments.
-
- char[] source = scanner.source;
- newLinesInWhitespace = 0;
- for (int i = scanner.startPosition, max = scanner.currentPosition;
- i < max;
- i++) {
- if (source[i] == '\n') {
- newLinesInWhitespace++;
- }
+ tokenBeforeColonCount--;
+ }
+ break;
+ case TokenNameEQUAL :
+ inAssignment = true;
+ break;
+ case Scanner.TokenNameCOMMENT_LINE :
+ pendingNewLines = 1;
+ if (inAssignment) {
+ currentLineIndentationLevel++;
+ }
+ break; // a line is always inserted after a one-line comment
+ case Scanner.TokenNameCOMMENT_JAVADOC :
+ case Scanner.TokenNameCOMMENT_BLOCK :
+ currentCommentOffset = getCurrentCommentOffset();
+ if (openParenthesis[0]==0 && openBracketCount < 1){
+ pendingNewLines = 1;
+ // a new line is inserted only if the comment is not between parenthesis.
+ }
+ break;
+ case Scanner.TokenNameWHITESPACE :
+
+ // Count the number of line terminators in the whitespace so
+ // line spacing can be preserved near comments.
+
+ char[] source = scanner.source;
+ newLinesInWhitespace = 0;
+ for (
+ int i = scanner.startPosition, max = scanner.currentPosition;
+ i < max;
+ i++) {
+ if (source[i] == '\n') {
+ newLinesInWhitespace++;
}
- increaseLineDelta(scanner.startPosition - scanner.currentPosition);
- break;
- default :
- if ((token == TokenNameIdentifier)
- || isLiteralToken(token)
- || token == TokenNamesuper
- || token == TokenNamethis) {
-
- // Do not put a space between a unary operator
- // (eg: ++, --, +, -) and the identifier being modified.
-
- unarySignModifier -= (unarySignModifier > 0) ? 1 : 0;
- if (previousToken == TokenNamePLUS_PLUS
- || previousToken == TokenNameMINUS_MINUS
- || (unarySignModifier > 0)) {
- pendingSpace = false;
- }
+ }
+ increaseLineDelta(scanner.startPosition - scanner.currentPosition);
+ break;
+ default :
+ if ((token == TokenNameIdentifier)
+ || isLiteralToken(token)
+ || token == TokenNamesuper
+ || token == TokenNamethis) {
+
+ // Do not put a space between a unary operator
+ // (eg: ++, --, +, -) and the identifier being modified.
+
+ unarySignModifier -= (unarySignModifier > 0) ? 1 : 0;
+ if (previousToken == TokenNamePLUS_PLUS
+ || previousToken == TokenNameMINUS_MINUS
+ || (unarySignModifier > 0)) {
+ pendingSpace = false;
}
- break;
- }
-
- // Do not output whitespace tokens.
-
- if (token != Scanner.TokenNameWHITESPACE) {
-
- /* Add pending space to the formatted source string.
- Do not output a space under the following circumstances:
- 1) this is the first pass
- 2) previous token is an open paren
- 3) previous token is a period
- 4) previous token is the logical compliment (eg: !)
- 5) previous token is the bitwise compliment (eg: ~)
- 6) previous token is the open bracket (eg: [)
- 7) in an assignment statement, if the previous token is an
- open brace or the current token is a close brace
- 8) previous token is a single line comment
- */
-
- boolean openAndCloseBrace =
- previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE;
-
- // to be replaced by a nicer condition.
-
- if (pendingSpace
- && insertSpaceAfter(previousToken)
- && !(inAssignment
- && (previousToken == TokenNameLBRACE || token == TokenNameRBRACE))
- && previousToken != Scanner.TokenNameCOMMENT_LINE) {
- if ((!(options.compactAssignmentMode && token == TokenNameEQUAL))
- && !openAndCloseBrace)
- space();
}
+ break;
+ }
- // Add the next token to the formatted source string.
+ // Do not output whitespace tokens.
+
+ if (token != Scanner.TokenNameWHITESPACE) {
+
+ /* Add pending space to the formatted source string.
+ Do not output a space under the following circumstances:
+ 1) this is the first pass
+ 2) previous token is an open paren
+ 3) previous token is a period
+ 4) previous token is the logical compliment (eg: !)
+ 5) previous token is the bitwise compliment (eg: ~)
+ 6) previous token is the open bracket (eg: [)
+ 7) in an assignment statement, if the previous token is an
+ open brace or the current token is a close brace
+ 8) previous token is a single line comment
+ */
- outputCurrentToken(token);
- if (token == Scanner.TokenNameCOMMENT_LINE && openParenthesisCount > 1) {
- pendingNewLines = 0;
- currentLineBuffer.append(options.lineSeparatorSequence);
- increaseLineDelta(options.lineSeparatorSequence.length);
- }
- pendingSpace = true;
+ boolean openAndCloseBrace = previousCompilableToken == TokenNameLBRACE && token == TokenNameRBRACE;
+
+ // to be replaced by a nicer condition.
+
+ if (pendingSpace
+ && insertSpaceAfter(previousToken)
+ && ! (inAssignment
+ && (previousToken == TokenNameLBRACE || token == TokenNameRBRACE))
+ && previousToken != Scanner.TokenNameCOMMENT_LINE) {
+ if ((! (options.compactAssignmentMode && token == TokenNameEQUAL)) && !openAndCloseBrace)
+ space();
}
- // Whitespace tokens do not need to be remembered.
+ // Add the next token to the formatted source string.
- if (token != Scanner.TokenNameWHITESPACE) {
- previousToken = token;
- if (token != Scanner.TokenNameCOMMENT_BLOCK
- && token != Scanner.TokenNameCOMMENT_LINE
- && token != Scanner.TokenNameCOMMENT_JAVADOC) {
- previousCompilableToken = token;
- }
+ outputCurrentToken(token);
+ if (token == Scanner.TokenNameCOMMENT_LINE && openParenthesisCount > 1){
+ pendingNewLines = 0;
+ currentLineBuffer.append(options.lineSeparatorSequence);
+ increaseLineDelta(options.lineSeparatorSequence.length);
}
-
+ pendingSpace = true;
}
- output(copyRemainingSource());
- flushBuffer(); // dump the last token of the source in the formatted output.
- } catch (InvalidInputException e) {
- output(copyRemainingSource());
- flushBuffer(); // dump the last token of the source in the formatted output.
- }
- }
- /**
- * Formats a given source string, starting indenting it at depth 0
- * using default options.
- */
- public static String format(String sourceString) {
- return format(sourceString, 0, null);
- }
+ // Whitespace tokens do not need to be remembered.
- /**
- * Formats a given source string, starting indenting it at a particular
- * depth and using the given options
- */
- public static String format(
- String sourceString,
- int initialIndentationLevel,
- ConfigurableOption[] options) {
- CodeFormatter formatter = new CodeFormatter(options);
- formatter.setInitialIndentationLevel(initialIndentationLevel);
- return formatter.formatSourceString(sourceString);
- }
-
- /**
- * Formats the char array <code>sourceString</code>,
- * and returns a string containing the formatted version.
- * @return the formatted ouput.
- */
- public String formatSourceString(String sourceString) {
- char[] sourceChars = sourceString.toCharArray();
- formattedSource = new StringBuffer(sourceChars.length);
- scanner.setSourceBuffer(sourceChars);
- format();
- return formattedSource.toString();
- }
-
- /**
- * Returns the number of characters and tab char between the beginning of the line
- * and the beginning of the comment.
- */
- private int getCurrentCommentOffset() {
- int linePtr = scanner.linePtr;
- // if there is no beginning of line, return 0.
- if (linePtr < 0)
- return 0;
- int offset = 0;
- int beginningOfLine = scanner.lineEnds[linePtr];
- int currentStartPosition = scanner.startPosition;
- char[] source = scanner.source;
-
- // find the position of the beginning of the line containing the comment
- while (beginningOfLine > currentStartPosition) {
- if (linePtr > 0) {
- beginningOfLine = scanner.lineEnds[--linePtr];
- } else {
- beginningOfLine = 0;
- break;
+ if (token != Scanner.TokenNameWHITESPACE) {
+ previousToken = token;
+ if (token != Scanner.TokenNameCOMMENT_BLOCK
+ && token != Scanner.TokenNameCOMMENT_LINE
+ && token != Scanner.TokenNameCOMMENT_JAVADOC) {
+ previousCompilableToken = token;
+ }
}
- }
- for (int i = beginningOfLine; i < currentStartPosition; i++) {
- char currentCharacter = source[i];
- switch (currentCharacter) {
- case '\t' :
- offset += options.tabSize;
- case '\n' :
- case '\r' :
- break;
- default :
- offset++;
- }
}
-
- return offset;
- }
-
- /**
- * Returns an array of descriptions for the configurable options.
- * The descriptions may be changed and passed back to a different
- * compiler.
- */
- public static ConfigurableOption[] getDefaultOptions(Locale locale) {
- return new FormatterOptions().getConfigurableOptions(locale);
- }
-
- /**
- * Returns the array of mapped positions.
- * Returns null is no positions have been set.
- * @return int[]
- */
- public int[] getMappedPositions() {
- return mappedPositions;
+ output(copyRemainingSource());
+ flushBuffer(); // dump the last token of the source in the formatted output.
+ } catch (InvalidInputException e) {
+ output(copyRemainingSource());
+ flushBuffer(); // dump the last token of the source in the formatted output.
}
-
- /**
- * Returns the priority of the token given as argument<br>
- * The most prioritary the token is, the smallest the return value is.
- * @return the priority of <code>token</code>
- * @param token the token of which the priority is requested
- */
- private static int getTokenPriority(int token) {
- switch (token) {
- case TokenNameextends :
- case TokenNameimplements :
- case TokenNamethrows :
- return 10;
- case TokenNameSEMICOLON : // ;
- return 20;
- case TokenNameCOMMA : // ,
- return 25;
- case TokenNameEQUAL : // =
- return 30;
- case TokenNameAND_AND : // &&
- case TokenNameOR_OR : // ||
- return 40;
- case TokenNameQUESTION : // ?
- case TokenNameCOLON : // :
- return 50; // it's better cutting on ?: than on ;
- case TokenNameEQUAL_EQUAL : // ==
- case TokenNameNOT_EQUAL : // !=
- return 60;
- case TokenNameLESS : // <
- case TokenNameLESS_EQUAL : // <=
- case TokenNameGREATER : // >
- case TokenNameGREATER_EQUAL : // >=
- case TokenNameinstanceof : // instanceof
- return 70;
- case TokenNamePLUS : // +
- case TokenNameMINUS : // -
- return 80;
- case TokenNameMULTIPLY : // *
- case TokenNameDIVIDE : // /
- case TokenNameREMAINDER : // %
- return 90;
- case TokenNameLEFT_SHIFT : // <<
- case TokenNameRIGHT_SHIFT : // >>
- case TokenNameUNSIGNED_RIGHT_SHIFT : // >>>
- return 100;
- case TokenNameAND : // &
- case TokenNameOR : // |
- case TokenNameXOR : // ^
- return 110;
- case TokenNameMULTIPLY_EQUAL : // *=
- case TokenNameDIVIDE_EQUAL : // /=
- case TokenNameREMAINDER_EQUAL : // %=
- case TokenNamePLUS_EQUAL : // +=
- case TokenNameMINUS_EQUAL : // -=
- case TokenNameLEFT_SHIFT_EQUAL : // <<=
- case TokenNameRIGHT_SHIFT_EQUAL : // >>=
- case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>=
- case TokenNameAND_EQUAL : // &=
- case TokenNameXOR_EQUAL : // ^=
- case TokenNameOR_EQUAL : // |=
- return 120;
- case TokenNameDOT : // .
- return 130;
- default :
- return Integer.MAX_VALUE;
+}
+/**
+ * Formats a given source string, starting indenting it at depth 0
+ * using default options.
+ */
+public static String format(String sourceString) {
+ return format(sourceString, 0, null);
+}
+/**
+ * Formats a given source string, starting indenting it at a particular
+ * depth and using the given options
+ */
+public static String format(String sourceString, int initialIndentationLevel, ConfigurableOption[] options) {
+ CodeFormatter formatter = new CodeFormatter(options);
+ formatter.setInitialIndentationLevel(initialIndentationLevel);
+ return formatter.formatSourceString(sourceString);
+}
+/**
+ * Formats the char array <code>sourceString</code>,
+ * and returns a string containing the formatted version.
+ * @return the formatted ouput.
+ */
+public String formatSourceString(String sourceString) {
+ char[] sourceChars = sourceString.toCharArray();
+ formattedSource = new StringBuffer(sourceChars.length);
+ scanner.setSourceBuffer(sourceChars);
+ format();
+ return formattedSource.toString();
+}
+/**
+ * Returns the number of characters and tab char between the beginning of the line
+ * and the beginning of the comment.
+ */
+private int getCurrentCommentOffset() {
+ int linePtr = scanner.linePtr;
+ // if there is no beginning of line, return 0.
+ if (linePtr < 0)
+ return 0;
+ int offset = 0;
+ int beginningOfLine = scanner.lineEnds[linePtr];
+ int currentStartPosition = scanner.startPosition;
+ char[] source = scanner.source;
+
+ // find the position of the beginning of the line containing the comment
+ while (beginningOfLine > currentStartPosition) {
+ if (linePtr > 0) {
+ beginningOfLine = scanner.lineEnds[--linePtr];
+ } else {
+ beginningOfLine = 0;
+ break;
}
}
- /**
- * Handles the exception raised when an invalid token is encountered.
- * Returns true if the exception has been handled, false otherwise.
- */
- private boolean handleInvalidToken(Exception e) {
- if (e.getMessage().equals(Scanner.INVALID_CHARACTER_CONSTANT)
- || e.getMessage().equals(Scanner.INVALID_CHAR_IN_STRING)
- || e.getMessage().equals(Scanner.INVALID_ESCAPE)) {
- return true;
+ for (int i = beginningOfLine ; i < currentStartPosition ; i++){
+ char currentCharacter = source[i];
+ switch(currentCharacter){
+ case '\t':
+ offset += options.tabSize;
+ case '\n':
+ case '\r':
+ break;
+ default:
+ offset++;
}
- return false;
}
-
- private final void increaseGlobalDelta(int offset) {
- globalDelta += offset;
- }
-
- private final void increaseLineDelta(int offset) {
- lineDelta += offset;
- }
-
- private final void increaseSplitDelta(int offset) {
- splitDelta += offset;
+
+ return offset;
+}
+/**
+ * Returns an array of descriptions for the configurable options.
+ * The descriptions may be changed and passed back to a different
+ * compiler.
+ */
+public static ConfigurableOption[] getDefaultOptions(Locale locale) {
+ return new FormatterOptions().getConfigurableOptions(locale);
+}
+/**
+ * Returns the array of mapped positions.
+ * Returns null is no positions have been set.
+ * @return int[]
+ */
+public int[] getMappedPositions() {
+ return mappedPositions;
+}
+/**
+ * Returns the priority of the token given as argument<br>
+ * The most prioritary the token is, the smallest the return value is.
+ * @return the priority of <code>token</code>
+ * @param token the token of which the priority is requested
+ */
+private static int getTokenPriority(int token) {
+ switch (token) {
+ case TokenNameextends:
+ case TokenNameimplements:
+ case TokenNamethrows:
+ return 10;
+ case TokenNameSEMICOLON : // ;
+ return 20;
+ case TokenNameCOMMA : // ,
+ return 25;
+ case TokenNameEQUAL : // =
+ return 30;
+ case TokenNameAND_AND : // &&
+ case TokenNameOR_OR : // ||
+ return 40;
+ case TokenNameQUESTION : // ?
+ case TokenNameCOLON : // :
+ return 50; // it's better cutting on ?: than on ;
+ case TokenNameEQUAL_EQUAL : // ==
+ case TokenNameNOT_EQUAL : // !=
+ return 60;
+ case TokenNameLESS : // <
+ case TokenNameLESS_EQUAL : // <=
+ case TokenNameGREATER : // >
+ case TokenNameGREATER_EQUAL : // >=
+ case TokenNameinstanceof : // instanceof
+ return 70;
+ case TokenNamePLUS : // +
+ case TokenNameMINUS : // -
+ return 80;
+ case TokenNameMULTIPLY : // *
+ case TokenNameDIVIDE : // /
+ case TokenNameREMAINDER : // %
+ return 90;
+ case TokenNameLEFT_SHIFT : // <<
+ case TokenNameRIGHT_SHIFT : // >>
+ case TokenNameUNSIGNED_RIGHT_SHIFT : // >>>
+ return 100;
+ case TokenNameAND : // &
+ case TokenNameOR : // |
+ case TokenNameXOR : // ^
+ return 110;
+ case TokenNameMULTIPLY_EQUAL : // *=
+ case TokenNameDIVIDE_EQUAL : // /=
+ case TokenNameREMAINDER_EQUAL : // %=
+ case TokenNamePLUS_EQUAL : // +=
+ case TokenNameMINUS_EQUAL : // -=
+ case TokenNameLEFT_SHIFT_EQUAL : // <<=
+ case TokenNameRIGHT_SHIFT_EQUAL : // >>=
+ case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>=
+ case TokenNameAND_EQUAL : // &=
+ case TokenNameXOR_EQUAL : // ^=
+ case TokenNameOR_EQUAL : // |=
+ return 120;
+ case TokenNameDOT : // .
+ return 130;
+ default :
+ return Integer.MAX_VALUE;
}
-
- /**
- * Returns true if a space has to be inserted after <code>operator</code>
- * false otherwise.
- */
- private boolean insertSpaceAfter(int token) {
- switch (token) {
- case TokenNameLPAREN :
- case TokenNameNOT :
- case TokenNameTWIDDLE :
- case TokenNameDOT :
- case 0 : // no token
- case TokenNameLBRACKET :
- case Scanner.TokenNameCOMMENT_LINE :
- return false;
- default :
- return true;
- }
-
+}
+/**
+ * Handles the exception raised when an invalid token is encountered.
+ * Returns true if the exception has been handled, false otherwise.
+ */
+private boolean handleInvalidToken(Exception e) {
+ if (e.getMessage().equals(Scanner.INVALID_CHARACTER_CONSTANT)
+ || e.getMessage().equals(Scanner.INVALID_CHAR_IN_STRING)
+ || e.getMessage().equals(Scanner.INVALID_ESCAPE)) {
+ return true;
}
-
- /**
- * Returns true if a space has to be inserted before <code>operator</code>
- * false otherwise.<br>
- * Cannot be static as it uses the code formatter options
- * (to know if the compact assignment mode is on).
- */
- private boolean insertSpaceBefore(int token) {
- switch (token) {
- case TokenNameEQUAL :
- return (!options.compactAssignmentMode);
- default :
- return false;
- }
+ return false;
+}
+private final void increaseGlobalDelta(int offset) {
+ globalDelta += offset;
+}
+private final void increaseLineDelta(int offset) {
+ lineDelta += offset;
+}
+private final void increaseSplitDelta(int offset) {
+ splitDelta += offset;
+}
+/**
+ * Returns true if a space has to be inserted after <code>operator</code>
+ * false otherwise.
+ */
+private boolean insertSpaceAfter(int token) {
+ switch (token){
+ case TokenNameLPAREN:
+ case TokenNameNOT:
+ case TokenNameTWIDDLE:
+ case TokenNameDOT :
+ case 0: // no token
+ case TokenNameLBRACKET:
+ case Scanner.TokenNameCOMMENT_LINE:
+ return false;
+ default:
+ return true;
}
-
- private static boolean isComment(int token) {
- boolean result =
- token == Scanner.TokenNameCOMMENT_BLOCK
- || token == Scanner.TokenNameCOMMENT_LINE
- || token == Scanner.TokenNameCOMMENT_JAVADOC;
- return result;
+
+}
+/**
+ * Returns true if a space has to be inserted before <code>operator</code>
+ * false otherwise.<br>
+ * Cannot be static as it uses the code formatter options
+ * (to know if the compact assignment mode is on).
+ */
+private boolean insertSpaceBefore(int token) {
+ switch (token) {
+ case TokenNameEQUAL:
+ return (!options.compactAssignmentMode);
+ default :
+ return false;
}
-
- private static boolean isLiteralToken(int token) {
- boolean result =
- token == TokenNameIntegerLiteral
- || token == TokenNameLongLiteral
- || token == TokenNameFloatingPointLiteral
- || token == TokenNameDoubleLiteral
- || token == TokenNameCharacterLiteral
- || token == TokenNameStringLiteral;
- return result;
+}
+private static boolean isComment(int token) {
+ boolean result =
+ token == Scanner.TokenNameCOMMENT_BLOCK ||
+ token == Scanner.TokenNameCOMMENT_LINE ||
+ token == Scanner.TokenNameCOMMENT_JAVADOC;
+ return result;
+}
+private static boolean isLiteralToken(int token) {
+ boolean result =
+ token == TokenNameIntegerLiteral ||
+ token == TokenNameLongLiteral ||
+ token == TokenNameFloatingPointLiteral ||
+ token == TokenNameDoubleLiteral ||
+ token == TokenNameCharacterLiteral ||
+ token == TokenNameStringLiteral;
+ return result;
+}
+/**
+ * If the length of <code>oneLineBuffer</code> exceeds <code>maxLineLength</code>,
+ * it is split and the result is dumped in <code>formattedSource</code>
+ * @param newLineCount the number of new lines to append
+ */
+private void newLine(int newLineCount) {
+
+ // format current line
+ splitDelta = 0;
+ beginningOfLineIndex = formattedSource.length();
+ String currentLine = currentLineBuffer.toString();
+ if (containsOpenCloseBraces) {
+ containsOpenCloseBraces = false;
+ outputLine(currentLine,
+ false,
+ indentationLevelForOpenCloseBraces,
+ 0,
+ -1,
+ null,
+ 0);
+ indentationLevelForOpenCloseBraces = currentLineIndentationLevel;
+ } else {
+ outputLine(currentLine,
+ false,
+ currentLineIndentationLevel,
+ 0,
+ -1,
+ null,
+ 0);
}
-
- /**
- * If the length of <code>oneLineBuffer</code> exceeds <code>maxLineLength</code>,
- * it is split and the result is dumped in <code>formattedSource</code>
- * @param newLineCount the number of new lines to append
- */
- private void newLine(int newLineCount) {
-
- // format current line
- splitDelta = 0;
- beginningOfLineIndex = formattedSource.length();
- String currentLine = currentLineBuffer.toString();
- if (containsOpenCloseBraces) {
- containsOpenCloseBraces = false;
- outputLine(
- currentLine,
- false,
- indentationLevelForOpenCloseBraces,
- 0,
- -1,
- null,
- 0);
- indentationLevelForOpenCloseBraces = currentLineIndentationLevel;
- } else {
- outputLine(currentLine, false, currentLineIndentationLevel, 0, -1, null, 0);
- }
- // dump line break(s)
- for (int i = 0; i < newLineCount; i++) {
- formattedSource.append(options.lineSeparatorSequence);
- increaseSplitDelta(options.lineSeparatorSequence.length);
- }
- // reset formatter for next line
- int currentLength = currentLine.length();
- currentLineBuffer =
- new StringBuffer(
- currentLength > maxLineSize ? maxLineSize = currentLength : maxLineSize);
-
- increaseGlobalDelta(splitDelta);
- increaseGlobalDelta(lineDelta);
- lineDelta = 0;
- currentLineIndentationLevel = initialIndentationLevel;
+ // dump line break(s)
+ for (int i = 0; i < newLineCount; i++) {
+ formattedSource.append(options.lineSeparatorSequence);
+ increaseSplitDelta(options.lineSeparatorSequence.length);
}
+ // reset formatter for next line
+ int currentLength = currentLine.length();
+ currentLineBuffer = new StringBuffer(
+ currentLength > maxLineSize
+ ? maxLineSize = currentLength
+ : maxLineSize);
+
+ increaseGlobalDelta(splitDelta);
+ increaseGlobalDelta(lineDelta);
+ lineDelta = 0;
+ currentLineIndentationLevel = initialIndentationLevel;
+}
+private String operatorString(int operator) {
+ switch (operator) {
+ case TokenNameextends :
+ return "extends"/*nonNLS*/;
- private String operatorString(int operator) {
- switch (operator) {
- case TokenNameextends :
- return "extends";
-
- case TokenNameimplements :
- return "implements";
+ case TokenNameimplements :
+ return "implements"/*nonNLS*/;
- case TokenNamethrows :
- return "throws";
+ case TokenNamethrows :
+ return "throws"/*nonNLS*/;
- case TokenNameSEMICOLON : // ;
- return ";";
+ case TokenNameSEMICOLON : // ;
+ return ";"/*nonNLS*/;
- case TokenNameCOMMA : // ,
- return ",";
+ case TokenNameCOMMA : // ,
+ return ","/*nonNLS*/;
- case TokenNameEQUAL : // =
- return "=";
+ case TokenNameEQUAL : // =
+ return "="/*nonNLS*/;
- case TokenNameAND_AND : // && (15.22)
- return "&&";
+ case TokenNameAND_AND : // && (15.22)
+ return "&&"/*nonNLS*/;
- case TokenNameOR_OR : // || (15.23)
- return "||";
+ case TokenNameOR_OR : // || (15.23)
+ return "||"/*nonNLS*/;
- case TokenNameQUESTION : // ? (15.24)
- return "?";
+ case TokenNameQUESTION : // ? (15.24)
+ return "?"/*nonNLS*/;
- case TokenNameCOLON : // : (15.24)
- return ":";
+ case TokenNameCOLON : // : (15.24)
+ return ":"/*nonNLS*/;
- case TokenNameEQUAL_EQUAL : // == (15.20, 15.20.1, 15.20.2, 15.20.3)
- return "==";
+ case TokenNameEQUAL_EQUAL : // == (15.20, 15.20.1, 15.20.2, 15.20.3)
+ return "=="/*nonNLS*/;
- case TokenNameNOT_EQUAL : // != (15.20, 15.20.1, 15.20.2, 15.20.3)
- return "!=";
+ case TokenNameNOT_EQUAL : // != (15.20, 15.20.1, 15.20.2, 15.20.3)
+ return "!="/*nonNLS*/;
- case TokenNameLESS : // < (15.19.1)
- return "<";
+ case TokenNameLESS : // < (15.19.1)
+ return "<"/*nonNLS*/;
- case TokenNameLESS_EQUAL : // <= (15.19.1)
- return "<=";
+ case TokenNameLESS_EQUAL : // <= (15.19.1)
+ return "<="/*nonNLS*/;
- case TokenNameGREATER : // > (15.19.1)
- return ">";
+ case TokenNameGREATER : // > (15.19.1)
+ return ">"/*nonNLS*/;
- case TokenNameGREATER_EQUAL : // >= (15.19.1)
- return ">=";
+ case TokenNameGREATER_EQUAL : // >= (15.19.1)
+ return ">="/*nonNLS*/;
- case TokenNameinstanceof : // instanceof
- return "instanceof";
+ case TokenNameinstanceof : // instanceof
+ return "instanceof"/*nonNLS*/;
- case TokenNamePLUS : // + (15.17, 15.17.2)
- return "+";
+ case TokenNamePLUS : // + (15.17, 15.17.2)
+ return "+"/*nonNLS*/;
- case TokenNameMINUS : // - (15.17.2)
- return "-";
+ case TokenNameMINUS : // - (15.17.2)
+ return "-"/*nonNLS*/;
- case TokenNameMULTIPLY : // * (15.16.1)
- return "*";
+ case TokenNameMULTIPLY : // * (15.16.1)
+ return "*"/*nonNLS*/;
- case TokenNameDIVIDE : // / (15.16.2)
- return "/";
+ case TokenNameDIVIDE : // / (15.16.2)
+ return "/"/*nonNLS*/;
- case TokenNameREMAINDER : // % (15.16.3)
- return "%";
+ case TokenNameREMAINDER : // % (15.16.3)
+ return "%"/*nonNLS*/;
- case TokenNameLEFT_SHIFT : // << (15.18)
- return "<<";
+ case TokenNameLEFT_SHIFT : // << (15.18)
+ return "<<"/*nonNLS*/;
- case TokenNameRIGHT_SHIFT : // >> (15.18)
- return ">>";
+ case TokenNameRIGHT_SHIFT : // >> (15.18)
+ return ">>"/*nonNLS*/;
- case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18)
- return ">>>";
+ case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18)
+ return ">>>"/*nonNLS*/;
- case TokenNameAND : // & (15.21, 15.21.1, 15.21.2)
- return "&";
+ case TokenNameAND : // & (15.21, 15.21.1, 15.21.2)
+ return "&"/*nonNLS*/;
- case TokenNameOR : // | (15.21, 15.21.1, 15.21.2)
- return "|";
+ case TokenNameOR : // | (15.21, 15.21.1, 15.21.2)
+ return "|"/*nonNLS*/;
- case TokenNameXOR : // ^ (15.21, 15.21.1, 15.21.2)
- return "^";
+ case TokenNameXOR : // ^ (15.21, 15.21.1, 15.21.2)
+ return "^"/*nonNLS*/;
- case TokenNameMULTIPLY_EQUAL : // *= (15.25.2)
- return "*=";
+ case TokenNameMULTIPLY_EQUAL : // *= (15.25.2)
+ return "*="/*nonNLS*/;
- case TokenNameDIVIDE_EQUAL : // /= (15.25.2)
- return "/=";
+ case TokenNameDIVIDE_EQUAL : // /= (15.25.2)
+ return "/="/*nonNLS*/;
- case TokenNameREMAINDER_EQUAL : // %= (15.25.2)
- return "%=";
+ case TokenNameREMAINDER_EQUAL : // %= (15.25.2)
+ return "%="/*nonNLS*/;
- case TokenNamePLUS_EQUAL : // += (15.25.2)
- return "+=";
+ case TokenNamePLUS_EQUAL : // += (15.25.2)
+ return "+="/*nonNLS*/;
- case TokenNameMINUS_EQUAL : // -= (15.25.2)
- return "-=";
+ case TokenNameMINUS_EQUAL : // -= (15.25.2)
+ return "-="/*nonNLS*/;
- case TokenNameLEFT_SHIFT_EQUAL : // <<= (15.25.2)
- return "<<=";
+ case TokenNameLEFT_SHIFT_EQUAL : // <<= (15.25.2)
+ return "<<="/*nonNLS*/;
- case TokenNameRIGHT_SHIFT_EQUAL : // >>= (15.25.2)
- return ">>=";
+ case TokenNameRIGHT_SHIFT_EQUAL : // >>= (15.25.2)
+ return ">>="/*nonNLS*/;
- case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2)
- return ">>>=";
+ case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2)
+ return ">>>="/*nonNLS*/;
- case TokenNameAND_EQUAL : // &= (15.25.2)
- return "&=";
+ case TokenNameAND_EQUAL : // &= (15.25.2)
+ return "&="/*nonNLS*/;
- case TokenNameXOR_EQUAL : // ^= (15.25.2)
- return "^=";
+ case TokenNameXOR_EQUAL : // ^= (15.25.2)
+ return "^="/*nonNLS*/;
- case TokenNameOR_EQUAL : // |= (15.25.2)
- return "|=";
+ case TokenNameOR_EQUAL : // |= (15.25.2)
+ return "|="/*nonNLS*/;
- case TokenNameDOT : // .
- return ".";
+ case TokenNameDOT : // .
+ return "."/*nonNLS*/;
- default :
- return "";
- }
+ default :
+ return ""/*nonNLS*/;
}
-
- /**
- * Appends <code>stringToOutput</code> to the formatted output.<br>
- * If it contains \n, append a LINE_SEPARATOR and indent after it.
- */
- private void output(String stringToOutput) {
- char currentCharacter;
- for (int i = 0, max = stringToOutput.length(); i < max; i++) {
- currentCharacter = stringToOutput.charAt(i);
- if (currentCharacter != '\t') {
- currentLineBuffer.append(currentCharacter);
- }
+}
+/**
+ * Appends <code>stringToOutput</code> to the formatted output.<br>
+ * If it contains \n, append a LINE_SEPARATOR and indent after it.
+ */
+private void output(String stringToOutput) {
+ char currentCharacter;
+ for (int i = 0, max = stringToOutput.length(); i < max; i++) {
+ currentCharacter = stringToOutput.charAt(i);
+ if (currentCharacter != '\t') {
+ currentLineBuffer.append(currentCharacter);
}
- updateMappedPositions(scanner.startPosition);
}
-
- /**
- * Appends <code>token</code> to the formatted output.<br>
- * If it contains <code>\n</code>, append a LINE_SEPARATOR and indent after it.
- */
- private void outputCurrentToken(int token) {
- char[] source = scanner.source;
- int startPosition = scanner.startPosition;
-
- switch (token) {
- case Scanner.TokenNameCOMMENT_JAVADOC :
- case Scanner.TokenNameCOMMENT_BLOCK :
- case Scanner.TokenNameCOMMENT_LINE :
- boolean endOfLine = false;
- int currentCommentOffset = getCurrentCommentOffset();
- int beginningOfLineSpaces = 0;
- for (int i = startPosition, max = scanner.currentPosition; i < max; i++) {
- char currentCharacter = source[i];
- switch (currentCharacter) {
- case '\r' :
- case '\n' :
- endOfLine = true;
+ updateMappedPositions(scanner.startPosition);
+}
+/**
+ * Appends <code>token</code> to the formatted output.<br>
+ * If it contains <code>\n</code>, append a LINE_SEPARATOR and indent after it.
+ */
+private void outputCurrentToken(int token) {
+ char[] source = scanner.source;
+ int startPosition = scanner.startPosition;
+
+ switch(token) {
+ case Scanner.TokenNameCOMMENT_JAVADOC :
+ case Scanner.TokenNameCOMMENT_BLOCK :
+ case Scanner.TokenNameCOMMENT_LINE :
+ boolean endOfLine = false;
+ int currentCommentOffset = getCurrentCommentOffset();
+ int beginningOfLineSpaces = 0;
+ for (int i = startPosition, max = scanner.currentPosition; i < max; i++) {
+ char currentCharacter = source[i];
+ switch(currentCharacter) {
+ case '\r' :
+ case '\n' :
+ endOfLine = true;
+ currentLineBuffer.append(currentCharacter);
+ beginningOfLineSpaces = 0;
+ break;
+ case '\t' :
+ if (endOfLine) {
+ // we remove a maximum of currentCommentOffset characters (tabs are converted to space numbers).
+ beginningOfLineSpaces+=options.tabSize;
+ if (beginningOfLineSpaces > currentCommentOffset)
+ currentLineBuffer.append(currentCharacter);
+ } else {
currentLineBuffer.append(currentCharacter);
- beginningOfLineSpaces = 0;
- break;
- case '\t' :
- if (endOfLine) {
- // we remove a maximum of currentCommentOffset characters (tabs are converted to space numbers).
- beginningOfLineSpaces += options.tabSize;
- if (beginningOfLineSpaces > currentCommentOffset)
- currentLineBuffer.append(currentCharacter);
- } else {
- currentLineBuffer.append(currentCharacter);
- }
- break;
- case ' ' :
- if (endOfLine) {
- // we remove a maximum of currentCommentOffset characters (tabs are converted to space numbers).
- beginningOfLineSpaces++;
- if (beginningOfLineSpaces > currentCommentOffset)
- currentLineBuffer.append(currentCharacter);
- } else {
- currentLineBuffer.append(currentCharacter);
- }
- break;
- default :
- beginningOfLineSpaces = 0;
+ }
+ break;
+ case ' ' :
+ if (endOfLine) {
+ // we remove a maximum of currentCommentOffset characters (tabs are converted to space numbers).
+ beginningOfLineSpaces++;
+ if (beginningOfLineSpaces > currentCommentOffset)
+ currentLineBuffer.append(currentCharacter);
+ } else {
currentLineBuffer.append(currentCharacter);
- endOfLine = false;
- }
- }
- break;
- default :
- currentLineBuffer.append(
- source,
- startPosition,
- scanner.currentPosition - startPosition);
- }
- updateMappedPositions(startPosition);
- }
-
- /**
- * Outputs <code>currentString</code>:<br>
- * <ul><li>If its length is < maxLineLength, output
- * <li>Otherwise it is split.</ul>
- * @param currentString string to output
- * @param preIndented whether the string to output was pre-indented
- * @param depth number of indentation to put in front of <code>currentString</code>
- * @param operator value of the operator belonging to <code>currentString</code>.
- */
- private void outputLine(
- String currentString,
- boolean preIndented,
- int depth,
- int operator,
- int substringIndex,
- int[] startSubstringIndexes,
- int offsetInGlobalLine) {
-
- boolean emptyFirstSubString = false;
- String operatorString = operatorString(operator);
- boolean placeOperatorBehind = !breakLineBeforeOperator(operator);
- boolean placeOperatorAhead = !placeOperatorBehind;
-
- // dump prefix operator?
- if (placeOperatorAhead) {
- if (!preIndented) {
- dumpTab(depth);
- preIndented = true;
- }
- if (operator != 0) {
- if (insertSpaceBefore(operator)) {
- formattedSource.append(' ');
- increaseSplitDelta(1);
- }
- formattedSource.append(operatorString);
- increaseSplitDelta(operatorString.length());
-
- if (insertSpaceAfter(operator)
- && operator != TokenNameimplements
- && operator != TokenNameextends
- && operator != TokenNamethrows) {
- formattedSource.append(' ');
- increaseSplitDelta(1);
+ }
+ break;
+ default:
+ beginningOfLineSpaces = 0;
+ currentLineBuffer.append(currentCharacter);
+ endOfLine = false;
}
}
+ break;
+ default:
+ currentLineBuffer.append(source, startPosition, scanner.currentPosition - startPosition);
+ }
+ updateMappedPositions(startPosition);
+}
+/**
+ * Outputs <code>currentString</code>:<br>
+ * <ul><li>If its length is < maxLineLength, output
+ * <li>Otherwise it is split.</ul>
+ * @param currentString string to output
+ * @param preIndented whether the string to output was pre-indented
+ * @param depth number of indentation to put in front of <code>currentString</code>
+ * @param operator value of the operator belonging to <code>currentString</code>.
+ */
+private void outputLine(
+ String currentString,
+ boolean preIndented,
+ int depth,
+ int operator,
+ int substringIndex,
+ int[] startSubstringIndexes,
+ int offsetInGlobalLine) {
+
+ boolean emptyFirstSubString = false;
+ String operatorString = operatorString(operator);
+ boolean placeOperatorBehind = !breakLineBeforeOperator(operator);
+ boolean placeOperatorAhead = !placeOperatorBehind;
+
+ // dump prefix operator?
+ if (placeOperatorAhead) {
+ if (!preIndented) {
+ dumpTab(depth);
+ preIndented = true;
}
- SplitLine splitLine = null;
- if (options.maxLineLength == 0
- || currentString.length() < options.maxLineLength
- || (splitLine = split(currentString, offsetInGlobalLine)) == null) {
- // depending on the type of operator, outputs new line before of after dumping it
- // indent before postfix operator
- // indent also when the line cannot be split
-
- if (operator == TokenNameextends
- || operator == TokenNameimplements
- || operator == TokenNamethrows) {
+ if (operator != 0) {
+ if (insertSpaceBefore(operator)) {
formattedSource.append(' ');
increaseSplitDelta(1);
}
+ formattedSource.append(operatorString);
+ increaseSplitDelta(operatorString.length());
- if (placeOperatorBehind) {
- if (!preIndented) {
- dumpTab(depth);
- }
- }
-
- boolean containsMultiLineComment = currentString.lastIndexOf("/*") != -1;
- int numberOfSpaces = 0;
- int max = currentString.length();
- updateMappedPositionsWhileSplitting(
- beginningOfLineIndex,
- beginningOfLineIndex + max);
- for (int i = 0; i < max; i++) {
- char currentChar = currentString.charAt(i);
- switch (currentChar) {
- case '\r' :
- break;
- case '\n' :
- if (i != max - 1) {
- // fix for 1FFYL5C: LFCOM:ALL - Incorrect indentation when split with a comment inside a condition
- // a substring cannot end with a lineSeparatorSequence,
- // except if it has been added by format() after a one-line comment
- formattedSource.append(options.lineSeparatorSequence);
- increaseSplitDelta(options.lineSeparatorSequence.length);
-
- if (containsMultiLineComment) {
- // fix for 1FGGQCN: LFCOM:ALL - Space management in comments for the formatter
- dumpTab(currentLineIndentationLevel);
- } else {
- // 1FGDDV6: LFCOM:WIN98 - Weird splitting on message expression
- dumpTab(depth - 1);
- }
- }
- break;
- default :
- formattedSource.append(currentChar);
- }
- }
-
- // update positions inside the mappedPositions table
- if (substringIndex != -1) {
- int startPosition =
- beginningOfLineIndex + startSubstringIndexes[substringIndex];
- updateMappedPositionsWhileSplitting(startPosition, startPosition + max);
-
- // compute the splitDelta resulting with the operator and blank removal
- if (substringIndex + 1 != startSubstringIndexes.length) {
- increaseSplitDelta(
- startSubstringIndexes[substringIndex]
- + max
- - startSubstringIndexes[substringIndex
- + 1]);
- }
- }
- // dump postfix operator?
- if (placeOperatorBehind) {
- if (insertSpaceBefore(operator)) {
- formattedSource.append(' ');
- if (operator != 0) {
- increaseSplitDelta(1);
- }
- }
- formattedSource.append(operatorString);
- if (operator != 0) {
- increaseSplitDelta(operatorString.length());
- }
- }
- return;
- }
-
- // fix for 1FG0BA3: LFCOM:WIN98 - Weird splitting on interfaces
- // extends has to stand alone on a line when currentString has been split.
- if (options.maxLineLength != 0
- && splitLine != null
- && (operator == TokenNameextends
- || operator == TokenNameimplements
- || operator == TokenNamethrows)) {
- formattedSource.append(options.lineSeparatorSequence);
- increaseSplitDelta(options.lineSeparatorSequence.length);
-
- dumpTab(depth + 1);
- } else {
- if (operator == TokenNameextends
- || operator == TokenNameimplements
- || operator == TokenNamethrows) {
+ if (insertSpaceAfter(operator)
+ && operator != TokenNameimplements
+ && operator != TokenNameextends
+ && operator != TokenNamethrows) {
formattedSource.append(' ');
increaseSplitDelta(1);
}
}
-
- // perform actual splitting
- String result[] = splitLine.substrings;
- int[] splitOperators = splitLine.operators;
- int[] splitLineStartIndexes = splitLine.startSubstringsIndexes;
-
- if (result[0].length() == 0) {
- // when the substring 0 is null, the substring 1 is correctly indented.
- depth--;
- emptyFirstSubString = true;
+ }
+ SplitLine splitLine = null;
+ if (options.maxLineLength == 0
+ || currentString.length() < options.maxLineLength
+ || (splitLine = split(currentString, offsetInGlobalLine)) == null) {
+ // depending on the type of operator, outputs new line before of after dumping it
+ // indent before postfix operator
+ // indent also when the line cannot be split
+
+ if (operator == TokenNameextends
+ || operator == TokenNameimplements
+ || operator == TokenNamethrows) {
+ formattedSource.append(' ');
+ increaseSplitDelta(1);
}
- // the operator going in front of the result[0] string is the operator parameter
-
- for (int i = 0, max = result.length; i < max; i++) {
- // the new depth is the current one if this is the first substring,
- // the current one + 1 otherwise.
-
- // if the substring is a comment, use the current indentation Level instead of the depth
- // (-1 because the ouputline increases depth).
- // (fix for 1FFC72R: LFCOM:ALL - Incorrect line split in presence of line comments)
- String currentResult = result[i];
-
- if (currentResult.length() != 0 || splitOperators[i] != 0) {
- int newDepth =
- (currentResult.startsWith("/*") || currentResult.startsWith("//"))
- ? indentationLevel - 1
- : depth;
- outputLine(
- currentResult,
- i == 0 || (i == 1 && emptyFirstSubString) ? preIndented : false,
- i == 0 ? newDepth : newDepth + 1,
- splitOperators[i],
- i,
- splitLine.startSubstringsIndexes,
- currentString.indexOf(currentResult));
- if (i != max - 1) {
- formattedSource.append(options.lineSeparatorSequence);
- increaseSplitDelta(options.lineSeparatorSequence.length);
- }
+
+ if (placeOperatorBehind) {
+ if (!preIndented) {
+ dumpTab(depth);
}
}
- if (result.length == splitOperators.length - 1) {
- int lastOperator = splitOperators[result.length];
- String lastOperatorString = operatorString(lastOperator);
- formattedSource.append(options.lineSeparatorSequence);
- increaseSplitDelta(options.lineSeparatorSequence.length);
-
- if (breakLineBeforeOperator(lastOperator)) {
- dumpTab(depth + 1);
- if (lastOperator != 0) {
- if (insertSpaceBefore(lastOperator)) {
- formattedSource.append(' ');
- increaseSplitDelta(1);
- }
- formattedSource.append(lastOperatorString);
- increaseSplitDelta(lastOperatorString.length());
-
- if (insertSpaceAfter(lastOperator)
- && lastOperator != TokenNameimplements
- && lastOperator != TokenNameextends
- && lastOperator != TokenNamethrows) {
- formattedSource.append(' ');
- increaseSplitDelta(1);
+
+ boolean containsMultiLineComment = currentString.lastIndexOf("/*"/*nonNLS*/) != -1;
+ int numberOfSpaces = 0;
+ int max = currentString.length();
+ updateMappedPositionsWhileSplitting(
+ beginningOfLineIndex,
+ beginningOfLineIndex + max);
+ for (int i = 0; i < max; i++) {
+ char currentChar = currentString.charAt(i);
+ switch (currentChar) {
+ case '\r' :
+ break;
+ case '\n' :
+ if (i != max - 1) {
+ // fix for 1FFYL5C: LFCOM:ALL - Incorrect indentation when split with a comment inside a condition
+ // a substring cannot end with a lineSeparatorSequence,
+ // except if it has been added by format() after a one-line comment
+ formattedSource.append(options.lineSeparatorSequence);
+ increaseSplitDelta(options.lineSeparatorSequence.length);
+
+ if (containsMultiLineComment) {
+ // fix for 1FGGQCN: LFCOM:ALL - Space management in comments for the formatter
+ dumpTab(currentLineIndentationLevel);
+ } else {
+ // 1FGDDV6: LFCOM:WIN98 - Weird splitting on message expression
+ dumpTab(depth - 1);
+ }
}
- }
+ break;
+ default :
+ formattedSource.append(currentChar);
}
}
+
+ // update positions inside the mappedPositions table
+ if (substringIndex != -1) {
+ int startPosition =
+ beginningOfLineIndex + startSubstringIndexes[substringIndex];
+ updateMappedPositionsWhileSplitting(startPosition, startPosition + max);
+
+ // compute the splitDelta resulting with the operator and blank removal
+ if (substringIndex + 1 != startSubstringIndexes.length) {
+ increaseSplitDelta(
+ startSubstringIndexes[substringIndex]
+ + max
+ - startSubstringIndexes[substringIndex
+ + 1]);
+ }
+ }
+ // dump postfix operator?
if (placeOperatorBehind) {
if (insertSpaceBefore(operator)) {
formattedSource.append(' ');
- increaseSplitDelta(1);
+ if (operator != 0) {
+ increaseSplitDelta(1);
+ }
}
formattedSource.append(operatorString);
- //increaseSplitDelta(operatorString.length());
+ if (operator != 0) {
+ increaseSplitDelta(operatorString.length());
+ }
}
+ return;
}
- /**
- * Pops the top statement of the stack if it is <code>token</code>
- */
- private int pop(int token) {
- int delta = 0;
- if ((constructionsCount > 0)
- && (constructions[constructionsCount - 1] == token)) {
- delta--;
- constructionsCount--;
+ // fix for 1FG0BA3: LFCOM:WIN98 - Weird splitting on interfaces
+ // extends has to stand alone on a line when currentString has been split.
+ if (options.maxLineLength != 0
+ && splitLine != null
+ && (operator == TokenNameextends
+ || operator == TokenNameimplements
+ || operator == TokenNamethrows)) {
+ formattedSource.append(options.lineSeparatorSequence);
+ increaseSplitDelta(options.lineSeparatorSequence.length);
+
+ dumpTab(depth + 1);
+ } else {
+ if (operator == TokenNameextends
+ || operator == TokenNameimplements
+ || operator == TokenNamethrows) {
+ formattedSource.append(' ');
+ increaseSplitDelta(1);
}
- return delta;
}
- /**
- * Pops the top statement of the stack if it is a <code>BLOCK</code> or a <code>NONINDENT_BLOCK</code>.
- */
- private int popBlock() {
- int delta = 0;
- if ((constructionsCount > 0)
- && ((constructions[constructionsCount - 1] == BLOCK)
- || (constructions[constructionsCount - 1] == NONINDENT_BLOCK))) {
- if (constructions[constructionsCount - 1] == BLOCK)
- delta--;
- constructionsCount--;
- }
- return delta;
- }
+ // perform actual splitting
+ String result[] = splitLine.substrings;
+ int[] splitOperators = splitLine.operators;
+ int[] splitLineStartIndexes = splitLine.startSubstringsIndexes;
- /**
- * Pops elements until the stack is empty or the top element is <code>token</code>.<br>
- * Does not remove <code>token</code> from the stack.
- * @param token the token to be left as the top of the stack
- */
- private int popExclusiveUntil(int token) {
- int delta = 0;
- int startCount = constructionsCount;
- for (int i = startCount - 1; i >= 0 && constructions[i] != token; i--) {
- if (constructions[i] != NONINDENT_BLOCK)
- delta--;
- constructionsCount--;
- }
- return delta;
+ if (result[0].length() == 0) {
+ // when the substring 0 is null, the substring 1 is correctly indented.
+ depth--;
+ emptyFirstSubString = true;
}
-
- /**
- * Pops elements until the stack is empty or the top element is
- * a <code>BLOCK</code> or a <code>NONINDENT_BLOCK</code>.<br>
- * Does not remove it from the stack.
- */
- private int popExclusiveUntilBlock() {
- int startCount = constructionsCount;
- int delta = 0;
- for (int i = startCount - 1;
- i >= 0 && constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK;
- i--) {
- constructionsCount--;
- delta--;
+ // the operator going in front of the result[0] string is the operator parameter
+
+ for (int i = 0, max = result.length; i < max; i++) {
+ // the new depth is the current one if this is the first substring,
+ // the current one + 1 otherwise.
+
+ // if the substring is a comment, use the current indentation Level instead of the depth
+ // (-1 because the ouputline increases depth).
+ // (fix for 1FFC72R: LFCOM:ALL - Incorrect line split in presence of line comments)
+ String currentResult = result[i];
+
+ if (currentResult.length() != 0 || splitOperators[i] != 0) {
+ int newDepth =
+ (currentResult.startsWith("/*"/*nonNLS*/) || currentResult.startsWith("//"/*nonNLS*/))
+ ? indentationLevel - 1
+ : depth;
+ outputLine(
+ currentResult,
+ i == 0 || (i == 1 && emptyFirstSubString) ? preIndented : false,
+ i == 0 ? newDepth : newDepth + 1,
+ splitOperators[i],
+ i,
+ splitLine.startSubstringsIndexes,
+ currentString.indexOf(currentResult));
+ if (i != max - 1) {
+ formattedSource.append(options.lineSeparatorSequence);
+ increaseSplitDelta(options.lineSeparatorSequence.length);
+ }
}
- return delta;
}
+ if (result.length == splitOperators.length - 1) {
+ int lastOperator = splitOperators[result.length];
+ String lastOperatorString = operatorString(lastOperator);
+ formattedSource.append(options.lineSeparatorSequence);
+ increaseSplitDelta(options.lineSeparatorSequence.length);
- /**
- * Pops elements until the stack is empty or the top element is
- * a <code>BLOCK</code>, a <code>NONINDENT_BLOCK</code> or a <code>CASE</code>.<br>
- * Does not remove it from the stack.
- */
- private int popExclusiveUntilBlockOrCase() {
- int startCount = constructionsCount;
- int delta = 0;
- for (int i = startCount - 1;
- i >= 0
- && constructions[i] != BLOCK
- && constructions[i] != NONINDENT_BLOCK
- && constructions[i] != TokenNamecase;
- i--) {
- constructionsCount--;
- delta--;
- }
- return delta;
- }
+ if (breakLineBeforeOperator(lastOperator)) {
+ dumpTab(depth + 1);
+ if (lastOperator != 0) {
+ if (insertSpaceBefore(lastOperator)) {
+ formattedSource.append(' ');
+ increaseSplitDelta(1);
+ }
+ formattedSource.append(lastOperatorString);
+ increaseSplitDelta(lastOperatorString.length());
- /**
- * Pops elements until the stack is empty or the top element is <code>token</code>.<br>
- * Removes <code>token</code> from the stack too.
- * @param token the token to remove from the stack
- */
- private int popInclusiveUntil(int token) {
- int startCount = constructionsCount;
- int delta = 0;
- for (int i = startCount - 1; i >= 0 && constructions[i] != token; i--) {
- if (constructions[i] != NONINDENT_BLOCK)
- delta--;
- constructionsCount--;
- }
- if (constructionsCount > 0) {
- if (constructions[constructionsCount - 1] != NONINDENT_BLOCK)
- delta--;
- constructionsCount--;
+ if (insertSpaceAfter(lastOperator)
+ && lastOperator != TokenNameimplements
+ && lastOperator != TokenNameextends
+ && lastOperator != TokenNamethrows) {
+ formattedSource.append(' ');
+ increaseSplitDelta(1);
+ }
+ }
}
- return delta;
}
-
- /**
- * Pops elements until the stack is empty or the top element is
- * a <code>BLOCK</code> or a <code>NONINDENT_BLOCK</code>.<br>
- * Does not remove it from the stack.
- */
- private int popInclusiveUntilBlock() {
- int startCount = constructionsCount;
- int delta = 0;
- for (int i = startCount - 1;
- i >= 0 && (constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK);
- i--) {
- delta--;
- constructionsCount--;
- }
- if (constructionsCount > 0) {
- if (constructions[constructionsCount - 1] == BLOCK)
- delta--;
- constructionsCount--;
+ if (placeOperatorBehind) {
+ if (insertSpaceBefore(operator)) {
+ formattedSource.append(' ');
+ increaseSplitDelta(1);
}
- return delta;
+ formattedSource.append(operatorString);
+ //increaseSplitDelta(operatorString.length());
}
-
- /**
- * Pushes a block in the stack.<br>
- * Pushes a <code>BLOCK</code> if the stack is empty or if the top element is a <code>BLOCK</code>,
- * pushes <code>NONINDENT_BLOCK</code> otherwise.
- * Creates a new bigger array if the current one is full.
- */
- private int pushBlock() {
- int delta = 0;
- if (constructionsCount == constructions.length)
- System.arraycopy(
- constructions,
- 0,
- (constructions = new int[constructionsCount * 2]),
- 0,
- constructionsCount);
-
- if ((constructionsCount == 0)
- || (constructions[constructionsCount - 1] == BLOCK)
- || (constructions[constructionsCount - 1] == NONINDENT_BLOCK)
- || (constructions[constructionsCount - 1] == TokenNamecase)) {
- delta++;
- constructions[constructionsCount++] = BLOCK;
- } else {
- constructions[constructionsCount++] = NONINDENT_BLOCK;
- }
- return delta;
+}
+/**
+ * Pops the top statement of the stack if it is <code>token</code>
+ */
+private int pop(int token) {
+ int delta=0;
+ if ((constructionsCount>0) && (constructions[constructionsCount-1]==token)){
+ delta--;
+ constructionsCount--;
}
-
- /**
- * Pushes <code>token</code>.<br>
- * Creates a new bigger array if the current one is full.
- */
- private int pushControlStatement(int token) {
- if (constructionsCount == constructions.length)
- System.arraycopy(
- constructions,
- 0,
- (constructions = new int[constructionsCount * 2]),
- 0,
- constructionsCount);
- constructions[constructionsCount++] = token;
- return 1;
+ return delta;
+}
+/**
+ * Pops the top statement of the stack if it is a <code>BLOCK</code> or a <code>NONINDENT_BLOCK</code>.
+ */
+private int popBlock() {
+ int delta=0;
+ if ((constructionsCount>0) && ((constructions[constructionsCount-1]==BLOCK) || (constructions[constructionsCount-1]==NONINDENT_BLOCK))){
+ if (constructions[constructionsCount-1]==BLOCK)
+ delta--;
+ constructionsCount--;
}
-
- private static boolean separateFirstArgumentOn(int currentToken) {
- //return (currentToken == TokenNameCOMMA || currentToken == TokenNameSEMICOLON);
- return currentToken != TokenNameif
- && currentToken != TokenNameLPAREN
- && currentToken != TokenNameNOT
- && currentToken != TokenNamewhile
- && currentToken != TokenNamefor
- && currentToken != TokenNameswitch;
+ return delta;
+}
+/**
+ * Pops elements until the stack is empty or the top element is <code>token</code>.<br>
+ * Does not remove <code>token</code> from the stack.
+ * @param token the token to be left as the top of the stack
+ */
+private int popExclusiveUntil(int token) {
+ int delta=0;
+ int startCount=constructionsCount;
+ for (int i = startCount-1; i >= 0 && constructions[i] != token; i--){
+ if (constructions[i]!=NONINDENT_BLOCK)
+ delta--;
+ constructionsCount--;
}
-
- /**
- * Sets the behaviour of the formatter about the braces
- * using <coe>newBraceIndentationLevel</code><br>
- * <ul>
- * <li>if 0, the formatter add new line & indent
- * when current token is open brace,
- * remove extra indentation when current token is close brace.
- * <li>if -1, the formatter does not add a new line before the brace.</ul>
- *
- * @deprecated backward compatibility with VAJ APIs,
- * use addNewLineOnOpeningBrace(boolean) instead
- * @see addNewLineOnOpeningBrace(boolean)
- */
- public void setBraceIndentationLevel(int newBraceIndentationLevel) {
- options.setNewLineBeforeOpeningBraceMode(newBraceIndentationLevel == 0);
+ return delta;
+}
+/**
+ * Pops elements until the stack is empty or the top element is
+ * a <code>BLOCK</code> or a <code>NONINDENT_BLOCK</code>.<br>
+ * Does not remove it from the stack.
+ */
+private int popExclusiveUntilBlock(){
+ int startCount=constructionsCount;
+ int delta=0;
+ for (int i = startCount-1; i >= 0 && constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK; i--){
+ constructionsCount--;
+ delta--;
}
-
- /**
- * Sets the behaviour of the formatter regarding the whitespaces
- * in the string to format.
- * @param newClearBlankLines true if the blank lines can be wiped out
- * false otherwise.
- *
- * @deprecated backward compatibility with VAJ
- */
- public void setClearBlankLines(boolean newClearBlankLines) {
- options.setClearAllBlankLinesMode(newClearBlankLines);
+ return delta;
+}
+/**
+ * Pops elements until the stack is empty or the top element is
+ * a <code>BLOCK</code>, a <code>NONINDENT_BLOCK</code> or a <code>CASE</code>.<br>
+ * Does not remove it from the stack.
+ */
+private int popExclusiveUntilBlockOrCase(){
+ int startCount=constructionsCount;
+ int delta=0;
+ for (int i = startCount-1; i >= 0 && constructions[i] != BLOCK && constructions[i] != NONINDENT_BLOCK && constructions[i]!=TokenNamecase; i--){
+ constructionsCount--;
+ delta--;
}
-
- /**
- * Sets the number of consecutive spaces used to replace the tab char
- * if <code>newIndentationLength</code> is greater than one.<br>
- * @param newIndentationLength 1 if 1 indent = 1 tab char, n>1 if 1 indent = n consecutive spaces.
- *
- * @deprecated backward compatibility with VAJ
- */
- public void setIndentationLength(int newIndentationLength) {
- options.setTabSize(newIndentationLength);
+ return delta;
+}
+/**
+ * Pops elements until the stack is empty or the top element is <code>token</code>.<br>
+ * Removes <code>token</code> from the stack too.
+ * @param token the token to remove from the stack
+ */
+private int popInclusiveUntil(int token) {
+ int startCount=constructionsCount;
+ int delta=0;
+ for (int i = startCount-1; i >= 0 && constructions[i] != token; i--){
+ if (constructions[i]!=NONINDENT_BLOCK)
+ delta--;
+ constructionsCount--;
}
-
- /**
- * Sets the initial indentation level
- * @param indentationLevel new indentation level
- *
- * @deprecated
- */
- public void setInitialIndentationLevel(int newIndentationLevel) {
- this.initialIndentationLevel =
- currentLineIndentationLevel = indentationLevel = newIndentationLevel;
+ if (constructionsCount>0){
+ if (constructions[constructionsCount-1]!=NONINDENT_BLOCK)
+ delta--;
+ constructionsCount--;
}
-
- /**
- * Sets the behaviour of the scanner.<br>
- * if <code>flag</code> is true, newline & indent won't be added
- * between close brace and else, (do) while, catch, and finally.
- * @param flag must be true if newline & indent must NOT
- * be added between close brace and else, (do) while,
- * catch, and finally, false otherwise.
- *
- * @deprecated backward compatibility with VAJ
- */
- public void setNewlineInCompoundStatement(boolean flag) {
- options.setNewlineInControlStatementMode(flag);
+ return delta;
+}
+/**
+ * Pops elements until the stack is empty or the top element is
+ * a <code>BLOCK</code> or a <code>NONINDENT_BLOCK</code>.<br>
+ * Does not remove it from the stack.
+ */
+private int popInclusiveUntilBlock() {
+ int startCount=constructionsCount;
+ int delta=0;
+ for (int i = startCount-1; i >= 0 && (constructions[i] != BLOCK && constructions[i]!=NONINDENT_BLOCK); i--){
+ delta--;
+ constructionsCount--;
}
-
- /**
- * Set the positions to map. The mapped positions should be retrieved using the
- * getMappedPositions() method.
- * @see getMappedPositions()
- * @param positions int[]
- */
- public void setPositionsToMap(int[] positions) {
- positionsToMap = positions;
- lineDelta = 0;
- globalDelta = 0;
- mappedPositions = new int[positions.length];
+ if (constructionsCount>0){
+ if (constructions[constructionsCount-1]==BLOCK)
+ delta--;
+ constructionsCount--;
}
-
- /**
- * Appends a space character to the current line buffer.
- */
- private void space() {
- currentLineBuffer.append(' ');
- increaseLineDelta(1);
+ return delta;
+}
+/**
+ * Pushes a block in the stack.<br>
+ * Pushes a <code>BLOCK</code> if the stack is empty or if the top element is a <code>BLOCK</code>,
+ * pushes <code>NONINDENT_BLOCK</code> otherwise.
+ * Creates a new bigger array if the current one is full.
+ */
+private int pushBlock() {
+ int delta = 0;
+ if (constructionsCount == constructions.length)
+ System
+ .arraycopy(constructions,
+ 0,
+ (constructions = new int[constructionsCount * 2]),
+ 0,
+ constructionsCount);
+
+ if ((constructionsCount == 0)
+ || (constructions[constructionsCount - 1] == BLOCK)
+ || (constructions[constructionsCount - 1] == NONINDENT_BLOCK)
+ || (constructions[constructionsCount - 1] == TokenNamecase)) {
+ delta++;
+ constructions[constructionsCount++] = BLOCK;
}
-
- /**
- * Splits <code>stringToSplit</code> on the top level token<br>
- * If there are several identical token at the same level,
- * the string is cut into many pieces.
- * @return an object containing the operator and all the substrings
- * or null if the string cannot be split
- */
- public SplitLine split(String stringToSplit) {
- return split(stringToSplit, 0);
+ else {
+ constructions[constructionsCount++] = NONINDENT_BLOCK;
}
-
- /**
- * Splits <code>stringToSplit</code> on the top level token<br>
- * If there are several identical token at the same level,
- * the string is cut into many pieces.
- * @return an object containing the operator and all the substrings
- * or null if the string cannot be split
- */
- public SplitLine split(String stringToSplit, int offsetInGlobalLine) {
- // local variables
- int currentToken = 0;
- int splitTokenType = 0;
- int splitTokenDepth = Integer.MAX_VALUE;
- int splitTokenPriority = Integer.MAX_VALUE;
-
- int[] substringsStartPositions = new int[10];
- // contains the start position of substrings
- int[] substringsEndPositions = new int[10];
- // contains the start position of substrings
- int substringsCount = 1; // index in the substringsStartPosition array
- int[] splitOperators = new int[10];
- // contains the start position of substrings
- int splitOperatorsCount = 0; // index in the substringsStartPosition array
- int[] openParenthesisPosition = new int[10];
- int openParenthesisPositionCount = 0;
- int position = 0;
- int lastOpenParenthesisPosition = -1;
- // used to remember the position of the 1st open parenthesis
- // needed for a pattern like: A.B(C); we want formatted like A.B( split C);
- // setup the scanner with a new source
- int lastCommentStartPosition = -1;
- // to remember the start position of the last comment
- int firstTokenOnLine = -1;
- // to remember the first token of the line
- int previousToken = -1;
- // to remember the previous token.
- splitScanner.setSourceBuffer(stringToSplit.toCharArray());
-
- try {
- // start the loop
- while (true) {
- // takes the next token
- try {
- if (currentToken != Scanner.TokenNameWHITESPACE)
- previousToken = currentToken;
- currentToken = splitScanner.getNextToken();
- } catch (InvalidInputException e) {
- if (!handleInvalidToken(e))
- throw e;
- currentToken = 0; // this value is not modify when an exception is raised.
- }
- if (currentToken == TokenNameEOF)
- break;
-
- if (firstTokenOnLine == -1) {
- firstTokenOnLine = currentToken;
- }
-
- switch (currentToken) {
- case TokenNameRBRACE :
- case TokenNameRPAREN :
- if (openParenthesisPositionCount > 0) {
- if (openParenthesisPositionCount == 1
- && lastOpenParenthesisPosition < openParenthesisPosition[0]) {
- lastOpenParenthesisPosition = openParenthesisPosition[0];
- } else
- if ((splitTokenDepth == Integer.MAX_VALUE)
- || (splitTokenDepth > openParenthesisPositionCount
- && openParenthesisPositionCount == 1)) {
- splitTokenType = 0;
- splitTokenDepth = openParenthesisPositionCount;
- splitTokenPriority = Integer.MAX_VALUE;
- substringsStartPositions[0] = 0;
- // better token means the whole line until now is the first substring
- substringsCount = 1; // resets the count of substrings
-
- substringsEndPositions[0] = openParenthesisPosition[0];
- // substring ends on operator start
- position = openParenthesisPosition[0];
- // the string mustn't be cut before the closing parenthesis but after the opening one.
- splitOperatorsCount = 1; // resets the count of split operators
- splitOperators[0] = 0;
- }
- openParenthesisPositionCount--;
- }
- break;
- case TokenNameLBRACE :
- case TokenNameLPAREN :
- if (openParenthesisPositionCount == openParenthesisPosition.length) {
- System.arraycopy(
- openParenthesisPosition,
- 0,
- (openParenthesisPosition = new int[openParenthesisPositionCount * 2]),
- 0,
- openParenthesisPositionCount);
- }
- openParenthesisPosition[openParenthesisPositionCount++] =
- splitScanner.currentPosition;
- if (currentToken == TokenNameLPAREN && previousToken == TokenNameRPAREN) {
- openParenthesisPosition[openParenthesisPositionCount - 1] =
- splitScanner.startPosition;
- }
- break;
- case TokenNameSEMICOLON : // ;
- case TokenNameCOMMA : // ,
- case TokenNameEQUAL : // =
- if (openParenthesisPositionCount < splitTokenDepth
- || (openParenthesisPositionCount == splitTokenDepth
- && splitTokenPriority > getTokenPriority(currentToken))) {
- // the current token is better than the one we currently have
- // (in level or in priority if same level)
- // reset the substringsCount
- splitTokenDepth = openParenthesisPositionCount;
- splitTokenType = currentToken;
- splitTokenPriority = getTokenPriority(currentToken);
- substringsStartPositions[0] = 0;
- // better token means the whole line until now is the first substring
-
- if (separateFirstArgumentOn(firstTokenOnLine)
- && openParenthesisPositionCount > 0) {
- substringsCount = 2; // resets the count of substrings
-
- substringsEndPositions[0] = openParenthesisPosition[splitTokenDepth - 1];
- substringsStartPositions[1] = openParenthesisPosition[splitTokenDepth - 1];
- substringsEndPositions[1] = splitScanner.startPosition;
- splitOperatorsCount = 2; // resets the count of split operators
- splitOperators[0] = 0;
- splitOperators[1] = currentToken;
- position = splitScanner.currentPosition;
- // next substring will start from operator end
- } else {
+ return delta;
+}
+/**
+ * Pushes <code>token</code>.<br>
+ * Creates a new bigger array if the current one is full.
+ */
+private int pushControlStatement(int token) {
+ if (constructionsCount == constructions.length)
+ System.arraycopy(constructions, 0, (constructions = new int[constructionsCount * 2]), 0, constructionsCount);
+ constructions[constructionsCount++] = token;
+ return 1;
+}
+private static boolean separateFirstArgumentOn(int currentToken) {
+ //return (currentToken == TokenNameCOMMA || currentToken == TokenNameSEMICOLON);
+ return currentToken != TokenNameif
+ && currentToken != TokenNameLPAREN
+ && currentToken != TokenNameNOT
+ && currentToken != TokenNamewhile
+ && currentToken != TokenNamefor
+ && currentToken != TokenNameswitch;
+}
+/**
+ * Sets the behaviour of the formatter about the braces
+ * using <coe>newBraceIndentationLevel</code><br>
+ * <ul>
+ * <li>if 0, the formatter add new line & indent
+ * when current token is open brace,
+ * remove extra indentation when current token is close brace.
+ * <li>if -1, the formatter does not add a new line before the brace.</ul>
+ *
+ * @deprecated backward compatibility with VAJ APIs,
+ * use addNewLineOnOpeningBrace(boolean) instead
+ * @see addNewLineOnOpeningBrace(boolean)
+ */
+public void setBraceIndentationLevel(int newBraceIndentationLevel) {
+ options.setNewLineBeforeOpeningBraceMode(newBraceIndentationLevel==0);
+}
+/**
+ * Sets the behaviour of the formatter regarding the whitespaces
+ * in the string to format.
+ * @param newClearBlankLines true if the blank lines can be wiped out
+ * false otherwise.
+ *
+ * @deprecated backward compatibility with VAJ
+ */
+public void setClearBlankLines(boolean newClearBlankLines) {
+ options.setClearAllBlankLinesMode(newClearBlankLines);
+}
+/**
+ * Sets the number of consecutive spaces used to replace the tab char
+ * if <code>newIndentationLength</code> is greater than one.<br>
+ * @param newIndentationLength 1 if 1 indent = 1 tab char, n>1 if 1 indent = n consecutive spaces.
+ *
+ * @deprecated backward compatibility with VAJ
+ */
+public void setIndentationLength(int newIndentationLength) {
+ options.setTabSize(newIndentationLength);
+}
+/**
+ * Sets the initial indentation level
+ * @param indentationLevel new indentation level
+ *
+ * @deprecated
+ */
+public void setInitialIndentationLevel(int newIndentationLevel) {
+ this.initialIndentationLevel = currentLineIndentationLevel = indentationLevel = newIndentationLevel;
+}
+/**
+ * Sets the behaviour of the scanner.<br>
+ * if <code>flag</code> is true, newline & indent won't be added
+ * between close brace and else, (do) while, catch, and finally.
+ * @param flag must be true if newline & indent must NOT
+ * be added between close brace and else, (do) while,
+ * catch, and finally, false otherwise.
+ *
+ * @deprecated backward compatibility with VAJ
+ */
+public void setNewlineInCompoundStatement(boolean flag) {
+ options.setNewlineInControlStatementMode(flag);
+}
+/**
+ * Set the positions to map. The mapped positions should be retrieved using the
+ * getMappedPositions() method.
+ * @see getMappedPositions()
+ * @param positions int[]
+ */
+public void setPositionsToMap(int[] positions) {
+ positionsToMap = positions;
+ lineDelta = 0;
+ globalDelta = 0;
+ mappedPositions = new int[positions.length];
+}
+/**
+ * Appends a space character to the current line buffer.
+ */
+private void space() {
+ currentLineBuffer.append(' ');
+ increaseLineDelta(1);
+}
+/**
+ * Splits <code>stringToSplit</code> on the top level token<br>
+ * If there are several identical token at the same level,
+ * the string is cut into many pieces.
+ * @return an object containing the operator and all the substrings
+ * or null if the string cannot be split
+ */
+public SplitLine split(String stringToSplit) {
+ return split(stringToSplit, 0);
+}
+/**
+ * Splits <code>stringToSplit</code> on the top level token<br>
+ * If there are several identical token at the same level,
+ * the string is cut into many pieces.
+ * @return an object containing the operator and all the substrings
+ * or null if the string cannot be split
+ */
+public SplitLine split(String stringToSplit, int offsetInGlobalLine) {
+ // local variables
+ int currentToken = 0;
+ int splitTokenType = 0;
+ int splitTokenDepth = Integer.MAX_VALUE;
+ int splitTokenPriority = Integer.MAX_VALUE;
+
+ int[] substringsStartPositions = new int[10];
+ // contains the start position of substrings
+ int[] substringsEndPositions = new int[10];
+ // contains the start position of substrings
+ int substringsCount = 1; // index in the substringsStartPosition array
+ int[] splitOperators = new int[10];
+ // contains the start position of substrings
+ int splitOperatorsCount = 0; // index in the substringsStartPosition array
+ int[] openParenthesisPosition = new int[10];
+ int openParenthesisPositionCount = 0;
+ int position = 0;
+ int lastOpenParenthesisPosition = -1;
+ // used to remember the position of the 1st open parenthesis
+ // needed for a pattern like: A.B(C); we want formatted like A.B( split C);
+ // setup the scanner with a new source
+ int lastCommentStartPosition = -1;
+ // to remember the start position of the last comment
+ int firstTokenOnLine = -1;
+ // to remember the first token of the line
+ int previousToken = -1;
+ // to remember the previous token.
+ splitScanner.setSourceBuffer(stringToSplit.toCharArray());
+
+ try {
+ // start the loop
+ while (true) {
+ // takes the next token
+ try {
+ if (currentToken != Scanner.TokenNameWHITESPACE)
+ previousToken = currentToken;
+ currentToken = splitScanner.getNextToken();
+ } catch (InvalidInputException e) {
+ if (!handleInvalidToken(e))
+ throw e;
+ currentToken = 0; // this value is not modify when an exception is raised.
+ }
+ if (currentToken == TokenNameEOF)
+ break;
+
+ if (firstTokenOnLine == -1){
+ firstTokenOnLine = currentToken;
+ }
+
+
+ switch (currentToken) {
+ case TokenNameRBRACE:
+ case TokenNameRPAREN :
+ if (openParenthesisPositionCount > 0) {
+ if (openParenthesisPositionCount == 1 && lastOpenParenthesisPosition < openParenthesisPosition[0]) {
+ lastOpenParenthesisPosition = openParenthesisPosition[0];
+ } else
+ if ((splitTokenDepth == Integer.MAX_VALUE)
+ || (splitTokenDepth > openParenthesisPositionCount
+ && openParenthesisPositionCount == 1)) {
+ splitTokenType = 0;
+ splitTokenDepth = openParenthesisPositionCount;
+ splitTokenPriority = Integer.MAX_VALUE;
+ substringsStartPositions[0] = 0;
+ // better token means the whole line until now is the first substring
substringsCount = 1; // resets the count of substrings
- substringsEndPositions[0] = splitScanner.startPosition;
+ substringsEndPositions[0] = openParenthesisPosition[0];
// substring ends on operator start
- position = splitScanner.currentPosition;
- // next substring will start from operator end
+ position = openParenthesisPosition[0];
+ // the string mustn't be cut before the closing parenthesis but after the opening one.
splitOperatorsCount = 1; // resets the count of split operators
- splitOperators[0] = currentToken;
+ splitOperators[0] = 0;
}
+ openParenthesisPositionCount--;
+ }
+ break;
+ case TokenNameLBRACE:
+ case TokenNameLPAREN :
+ if (openParenthesisPositionCount == openParenthesisPosition.length) {
+ System.arraycopy(
+ openParenthesisPosition,
+ 0,
+ (openParenthesisPosition = new int[openParenthesisPositionCount * 2]),
+ 0,
+ openParenthesisPositionCount);
+ }
+ openParenthesisPosition[openParenthesisPositionCount++] = splitScanner.currentPosition;
+ if (currentToken == TokenNameLPAREN && previousToken == TokenNameRPAREN){
+ openParenthesisPosition[openParenthesisPositionCount - 1] = splitScanner.startPosition;
+ }
+ break;
+ case TokenNameSEMICOLON : // ;
+ case TokenNameCOMMA : // ,
+ case TokenNameEQUAL : // =
+ if (openParenthesisPositionCount < splitTokenDepth
+ || (openParenthesisPositionCount == splitTokenDepth
+ && splitTokenPriority > getTokenPriority(currentToken))) {
+ // the current token is better than the one we currently have
+ // (in level or in priority if same level)
+ // reset the substringsCount
+ splitTokenDepth = openParenthesisPositionCount;
+ splitTokenType = currentToken;
+ splitTokenPriority = getTokenPriority(currentToken);
+ substringsStartPositions[0] = 0;
+ // better token means the whole line until now is the first substring
+
+ if (separateFirstArgumentOn(firstTokenOnLine)
+ && openParenthesisPositionCount > 0) {
+ substringsCount = 2; // resets the count of substrings
+
+ substringsEndPositions[0] = openParenthesisPosition[splitTokenDepth - 1];
+ substringsStartPositions[1] = openParenthesisPosition[splitTokenDepth - 1];
+ substringsEndPositions[1] = splitScanner.startPosition;
+ splitOperatorsCount = 2; // resets the count of split operators
+ splitOperators[0] = 0;
+ splitOperators[1] = currentToken;
+ position = splitScanner.currentPosition;
+ // next substring will start from operator end
} else {
- if ((openParenthesisPositionCount == splitTokenDepth
+ substringsCount = 1; // resets the count of substrings
+
+ substringsEndPositions[0] = splitScanner.startPosition;
+ // substring ends on operator start
+ position = splitScanner.currentPosition;
+ // next substring will start from operator end
+ splitOperatorsCount = 1; // resets the count of split operators
+ splitOperators[0] = currentToken;
+ }
+ } else {
+ if ((openParenthesisPositionCount == splitTokenDepth
&& splitTokenPriority == getTokenPriority(currentToken))
- && splitTokenType != TokenNameEQUAL
- && currentToken != TokenNameEQUAL) {
- // fix for 1FG0BCN: LFCOM:WIN98 - Missing one indentation after split
- // take only the 1st = into account.
- // if another token with the same priority is found,
- // push the start position of the substring and
- // push the token into the stack.
- // create a new array object if the current one is full.
- if (substringsCount == substringsStartPositions.length) {
- System.arraycopy(
- substringsStartPositions,
- 0,
- (substringsStartPositions = new int[substringsCount * 2]),
- 0,
- substringsCount);
- System.arraycopy(
- substringsEndPositions,
- 0,
- (substringsEndPositions = new int[substringsCount * 2]),
- 0,
- substringsCount);
- }
- if (splitOperatorsCount == splitOperators.length) {
- System.arraycopy(
- splitOperators,
- 0,
- (splitOperators = new int[splitOperatorsCount * 2]),
- 0,
- splitOperatorsCount);
- }
- substringsStartPositions[substringsCount] = position;
- substringsEndPositions[substringsCount++] = splitScanner.startPosition;
- // substring ends on operator start
- position = splitScanner.currentPosition;
- // next substring will start from operator end
- splitOperators[splitOperatorsCount++] = currentToken;
+ && splitTokenType!=TokenNameEQUAL && currentToken != TokenNameEQUAL) {
+ // fix for 1FG0BCN: LFCOM:WIN98 - Missing one indentation after split
+ // take only the 1st = into account.
+ // if another token with the same priority is found,
+ // push the start position of the substring and
+ // push the token into the stack.
+ // create a new array object if the current one is full.
+ if (substringsCount == substringsStartPositions.length) {
+ System.arraycopy(
+ substringsStartPositions,
+ 0,
+ (substringsStartPositions = new int[substringsCount * 2]),
+ 0,
+ substringsCount);
+ System.arraycopy(
+ substringsEndPositions,
+ 0,
+ (substringsEndPositions = new int[substringsCount * 2]),
+ 0,
+ substringsCount);
+ }
+ if (splitOperatorsCount == splitOperators.length) {
+ System.arraycopy(
+ splitOperators,
+ 0,
+ (splitOperators = new int[splitOperatorsCount * 2]),
+ 0,
+ splitOperatorsCount);
}
+ substringsStartPositions[substringsCount] = position;
+ substringsEndPositions[substringsCount++] = splitScanner.startPosition;
+ // substring ends on operator start
+ position = splitScanner.currentPosition;
+ // next substring will start from operator end
+ splitOperators[splitOperatorsCount++] = currentToken;
}
+ }
+ break;
+
+ case TokenNameCOLON : // : (15.24)
+ // see 1FK7C5R, we only split on a colon, when it is associated with a question-mark.
+ // indeed it might appear also behind a case statement, and we do not to break at this point.
+ if ((splitOperatorsCount == 0) || splitOperators[splitOperatorsCount-1] != TokenNameQUESTION){
break;
+ }
+ case TokenNameextends :
+ case TokenNameimplements :
+ case TokenNamethrows :
+
+ case TokenNameDOT : // .
+ case TokenNameMULTIPLY : // * (15.16.1)
+ case TokenNameDIVIDE : // / (15.16.2)
+ case TokenNameREMAINDER : // % (15.16.3)
+ case TokenNamePLUS : // + (15.17, 15.17.2)
+ case TokenNameMINUS : // - (15.17.2)
+ case TokenNameLEFT_SHIFT : // << (15.18)
+ case TokenNameRIGHT_SHIFT : // >> (15.18)
+ case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18)
+ case TokenNameLESS : // < (15.19.1)
+ case TokenNameLESS_EQUAL : // <= (15.19.1)
+ case TokenNameGREATER : // > (15.19.1)
+ case TokenNameGREATER_EQUAL : // >= (15.19.1)
+ case TokenNameinstanceof : // instanceof
+ case TokenNameEQUAL_EQUAL : // == (15.20, 15.20.1, 15.20.2, 15.20.3)
+ case TokenNameNOT_EQUAL : // != (15.20, 15.20.1, 15.20.2, 15.20.3)
+ case TokenNameAND : // & (15.21, 15.21.1, 15.21.2)
+ case TokenNameOR : // | (15.21, 15.21.1, 15.21.2)
+ case TokenNameXOR : // ^ (15.21, 15.21.1, 15.21.2)
+ case TokenNameAND_AND : // && (15.22)
+ case TokenNameOR_OR : // || (15.23)
+ case TokenNameQUESTION : // ? (15.24)
+ case TokenNameMULTIPLY_EQUAL : // *= (15.25.2)
+ case TokenNameDIVIDE_EQUAL : // /= (15.25.2)
+ case TokenNameREMAINDER_EQUAL : // %= (15.25.2)
+ case TokenNamePLUS_EQUAL : // += (15.25.2)
+ case TokenNameMINUS_EQUAL : // -= (15.25.2)
+ case TokenNameLEFT_SHIFT_EQUAL : // <<= (15.25.2)
+ case TokenNameRIGHT_SHIFT_EQUAL : // >>= (15.25.2)
+ case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2)
+ case TokenNameAND_EQUAL : // &= (15.25.2)
+ case TokenNameXOR_EQUAL : // ^= (15.25.2)
+ case TokenNameOR_EQUAL : // |= (15.25.2)
+
+ if ((openParenthesisPositionCount < splitTokenDepth
+ || (openParenthesisPositionCount == splitTokenDepth
+ && splitTokenPriority > getTokenPriority(currentToken)))
+ &&
+ !((currentToken == TokenNamePLUS || currentToken == TokenNameMINUS)
+ && (previousToken == TokenNameLBRACE || previousToken == TokenNameLBRACKET || splitScanner.startPosition == 0))){
+ // the current token is better than the one we currently have
+ // (in level or in priority if same level)
+ // reset the substringsCount
+ splitTokenDepth = openParenthesisPositionCount;
+ splitTokenType = currentToken;
+ splitTokenPriority = getTokenPriority(currentToken);
+ substringsStartPositions[0] = 0;
+ // better token means the whole line until now is the first substring
+
+ if (separateFirstArgumentOn(firstTokenOnLine)
+ && openParenthesisPositionCount > 0) {
+ substringsCount = 2; // resets the count of substrings
+
+ substringsEndPositions[0] = openParenthesisPosition[splitTokenDepth - 1];
+ substringsStartPositions[1] = openParenthesisPosition[splitTokenDepth - 1];
+ substringsEndPositions[1] = splitScanner.startPosition;
+ splitOperatorsCount = 3; // resets the count of split operators
+ splitOperators[0] = 0;
+ splitOperators[1] = 0;
+ splitOperators[2] = currentToken;
+ position = splitScanner.currentPosition;
+ // next substring will start from operator end
+ } else {
+ substringsCount = 1; // resets the count of substrings
- case TokenNameCOLON : // : (15.24)
- // see 1FK7C5R, we only split on a colon, when it is associated with a question-mark.
- // indeed it might appear also behind a case statement, and we do not to break at this point.
- if ((splitOperatorsCount == 0)
- || splitOperators[splitOperatorsCount - 1] != TokenNameQUESTION) {
- break;
- }
- case TokenNameextends :
- case TokenNameimplements :
- case TokenNamethrows :
-
- case TokenNameDOT : // .
- case TokenNameMULTIPLY : // * (15.16.1)
- case TokenNameDIVIDE : // / (15.16.2)
- case TokenNameREMAINDER : // % (15.16.3)
- case TokenNamePLUS : // + (15.17, 15.17.2)
- case TokenNameMINUS : // - (15.17.2)
- case TokenNameLEFT_SHIFT : // << (15.18)
- case TokenNameRIGHT_SHIFT : // >> (15.18)
- case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18)
- case TokenNameLESS : // < (15.19.1)
- case TokenNameLESS_EQUAL : // <= (15.19.1)
- case TokenNameGREATER : // > (15.19.1)
- case TokenNameGREATER_EQUAL : // >= (15.19.1)
- case TokenNameinstanceof : // instanceof
- case TokenNameEQUAL_EQUAL : // == (15.20, 15.20.1, 15.20.2, 15.20.3)
- case TokenNameNOT_EQUAL : // != (15.20, 15.20.1, 15.20.2, 15.20.3)
- case TokenNameAND : // & (15.21, 15.21.1, 15.21.2)
- case TokenNameOR : // | (15.21, 15.21.1, 15.21.2)
- case TokenNameXOR : // ^ (15.21, 15.21.1, 15.21.2)
- case TokenNameAND_AND : // && (15.22)
- case TokenNameOR_OR : // || (15.23)
- case TokenNameQUESTION : // ? (15.24)
- case TokenNameMULTIPLY_EQUAL : // *= (15.25.2)
- case TokenNameDIVIDE_EQUAL : // /= (15.25.2)
- case TokenNameREMAINDER_EQUAL : // %= (15.25.2)
- case TokenNamePLUS_EQUAL : // += (15.25.2)
- case TokenNameMINUS_EQUAL : // -= (15.25.2)
- case TokenNameLEFT_SHIFT_EQUAL : // <<= (15.25.2)
- case TokenNameRIGHT_SHIFT_EQUAL : // >>= (15.25.2)
- case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2)
- case TokenNameAND_EQUAL : // &= (15.25.2)
- case TokenNameXOR_EQUAL : // ^= (15.25.2)
- case TokenNameOR_EQUAL : // |= (15.25.2)
-
- if ((openParenthesisPositionCount < splitTokenDepth
- || (openParenthesisPositionCount == splitTokenDepth
- && splitTokenPriority > getTokenPriority(currentToken)))
- && !((currentToken == TokenNamePLUS || currentToken == TokenNameMINUS)
- && (previousToken == TokenNameLBRACE
- || previousToken == TokenNameLBRACKET
- || splitScanner.startPosition == 0))) {
- // the current token is better than the one we currently have
- // (in level or in priority if same level)
- // reset the substringsCount
- splitTokenDepth = openParenthesisPositionCount;
- splitTokenType = currentToken;
- splitTokenPriority = getTokenPriority(currentToken);
- substringsStartPositions[0] = 0;
- // better token means the whole line until now is the first substring
-
- if (separateFirstArgumentOn(firstTokenOnLine)
- && openParenthesisPositionCount > 0) {
- substringsCount = 2; // resets the count of substrings
-
- substringsEndPositions[0] = openParenthesisPosition[splitTokenDepth - 1];
- substringsStartPositions[1] = openParenthesisPosition[splitTokenDepth - 1];
- substringsEndPositions[1] = splitScanner.startPosition;
- splitOperatorsCount = 3; // resets the count of split operators
- splitOperators[0] = 0;
- splitOperators[1] = 0;
- splitOperators[2] = currentToken;
- position = splitScanner.currentPosition;
- // next substring will start from operator end
- } else {
- substringsCount = 1; // resets the count of substrings
-
- substringsEndPositions[0] = splitScanner.startPosition;
- // substring ends on operator start
- position = splitScanner.currentPosition;
- // next substring will start from operator end
- splitOperatorsCount = 2; // resets the count of split operators
- splitOperators[0] = 0;
- // nothing for first operand since operator will be inserted in front of the second operand
- splitOperators[1] = currentToken;
+ substringsEndPositions[0] = splitScanner.startPosition;
+ // substring ends on operator start
+ position = splitScanner.currentPosition;
+ // next substring will start from operator end
+ splitOperatorsCount = 2; // resets the count of split operators
+ splitOperators[0] = 0;
+ // nothing for first operand since operator will be inserted in front of the second operand
+ splitOperators[1] = currentToken;
+ }
+ } else {
+ if (openParenthesisPositionCount == splitTokenDepth
+ && splitTokenPriority == getTokenPriority(currentToken)) {
+ // if another token with the same priority is found,
+ // push the start position of the substring and
+ // push the token into the stack.
+ // create a new array object if the current one is full.
+ if (substringsCount == substringsStartPositions.length) {
+ System.arraycopy(
+ substringsStartPositions,
+ 0,
+ (substringsStartPositions = new int[substringsCount * 2]),
+ 0,
+ substringsCount);
+ System.arraycopy(
+ substringsEndPositions,
+ 0,
+ (substringsEndPositions = new int[substringsCount * 2]),
+ 0,
+ substringsCount);
}
- } else {
- if (openParenthesisPositionCount == splitTokenDepth
- && splitTokenPriority == getTokenPriority(currentToken)) {
- // if another token with the same priority is found,
- // push the start position of the substring and
- // push the token into the stack.
- // create a new array object if the current one is full.
- if (substringsCount == substringsStartPositions.length) {
- System.arraycopy(
- substringsStartPositions,
- 0,
- (substringsStartPositions = new int[substringsCount * 2]),
- 0,
- substringsCount);
- System.arraycopy(
- substringsEndPositions,
- 0,
- (substringsEndPositions = new int[substringsCount * 2]),
- 0,
- substringsCount);
- }
- if (splitOperatorsCount == splitOperators.length) {
- System.arraycopy(
- splitOperators,
- 0,
- (splitOperators = new int[splitOperatorsCount * 2]),
- 0,
- splitOperatorsCount);
- }
- substringsStartPositions[substringsCount] = position;
- substringsEndPositions[substringsCount++] = splitScanner.startPosition;
- // substring ends on operator start
- position = splitScanner.currentPosition;
- // next substring will start from operator end
- splitOperators[splitOperatorsCount++] = currentToken;
+ if (splitOperatorsCount == splitOperators.length) {
+ System.arraycopy(
+ splitOperators,
+ 0,
+ (splitOperators = new int[splitOperatorsCount * 2]),
+ 0,
+ splitOperatorsCount);
}
+ substringsStartPositions[substringsCount] = position;
+ substringsEndPositions[substringsCount++] = splitScanner.startPosition;
+ // substring ends on operator start
+ position = splitScanner.currentPosition;
+ // next substring will start from operator end
+ splitOperators[splitOperatorsCount++] = currentToken;
}
+ }
default :
break;
- }
- if (isComment(currentToken)) {
- lastCommentStartPosition = splitScanner.startPosition;
- } else {
- lastCommentStartPosition = -1;
- }
}
- } catch (InvalidInputException e) {
- return null;
+ if (isComment(currentToken)) {
+ lastCommentStartPosition = splitScanner.startPosition;
+ } else {
+ lastCommentStartPosition = -1;
+ }
}
- // if the string cannot be split, return null.
- if (splitOperatorsCount == 0)
- return null;
-
- // ## SPECIAL CASES BEGIN
- if (((splitOperatorsCount == 2
- && splitOperators[1] == TokenNameDOT
- && splitTokenDepth == 0
- && lastOpenParenthesisPosition > -1)
- || (splitOperatorsCount > 2
- && splitOperators[1] == TokenNameDOT
- && splitTokenDepth == 0
- && lastOpenParenthesisPosition > -1
- && lastOpenParenthesisPosition <= options.maxLineLength)
- || (separateFirstArgumentOn(firstTokenOnLine)
- && splitTokenDepth > 0
- && lastOpenParenthesisPosition > -1))
- && (lastOpenParenthesisPosition < splitScanner.source.length
- && splitScanner.source[lastOpenParenthesisPosition] != ')')) {
+ } catch (InvalidInputException e) {
+ return null;
+ }
+ // if the string cannot be split, return null.
+ if (splitOperatorsCount == 0)
+ return null;
+
+ // ## SPECIAL CASES BEGIN
+ if (((splitOperatorsCount == 2 && splitOperators[1] == TokenNameDOT && splitTokenDepth == 0 && lastOpenParenthesisPosition > -1)
+ || (splitOperatorsCount > 2 && splitOperators[1] == TokenNameDOT && splitTokenDepth == 0 && lastOpenParenthesisPosition > -1 && lastOpenParenthesisPosition <= options.maxLineLength)
+ || (separateFirstArgumentOn(firstTokenOnLine) && splitTokenDepth > 0 && lastOpenParenthesisPosition > -1))
+ && (lastOpenParenthesisPosition<splitScanner.source.length && splitScanner.source[lastOpenParenthesisPosition]!=')')){
// fix for 1FH4J2H: LFCOM:WINNT - Formatter - Empty parenthesis should not be broken on two lines
- // only one split on a top level .
- // or more than one split on . and substring before open parenthesis fits one line.
- // or split inside parenthesis and first token is not a for/while/if
- SplitLine sl =
- split(
- stringToSplit.substring(lastOpenParenthesisPosition),
- lastOpenParenthesisPosition);
- if (sl == null || sl.operators[0] != TokenNameCOMMA) {
- // trim() is used to remove the extra blanks at the end of the substring. See PR 1FGYPI1
- return new SplitLine(
- new int[] { 0, 0 },
+ // only one split on a top level .
+ // or more than one split on . and substring before open parenthesis fits one line.
+ // or split inside parenthesis and first token is not a for/while/if
+ SplitLine sl = split(stringToSplit.substring(lastOpenParenthesisPosition), lastOpenParenthesisPosition);
+ if (sl == null || sl.operators[0] != TokenNameCOMMA) {
+ // trim() is used to remove the extra blanks at the end of the substring. See PR 1FGYPI1
+ return new SplitLine(
+ new int[] {0, 0},
new String[] {
- stringToSplit.substring(0, lastOpenParenthesisPosition).trim(),
+ stringToSplit.substring(0, lastOpenParenthesisPosition).trim(),
stringToSplit.substring(lastOpenParenthesisPosition)},
- new int[] {
- offsetInGlobalLine,
- lastOpenParenthesisPosition + offsetInGlobalLine });
- } else {
+ new int[] {offsetInGlobalLine, lastOpenParenthesisPosition + offsetInGlobalLine});
+ } else {
+
+ // right substring can be split and is split on comma
+ // copy substrings and operators
+ // except if the 1st string is empty.
- // right substring can be split and is split on comma
- // copy substrings and operators
- // except if the 1st string is empty.
-
- int startIndex = (sl.substrings[0].length() == 0) ? 1 : 0;
-
- int subStringsLength = sl.substrings.length + 1 - startIndex;
- String[] result = new String[subStringsLength];
- int[] startIndexes = new int[subStringsLength];
- int operatorsLength = sl.operators.length + 1 - startIndex;
- int[] operators = new int[operatorsLength];
-
- result[0] = stringToSplit.substring(0, lastOpenParenthesisPosition);
- operators[0] = 0;
-
- System.arraycopy(
- sl.startSubstringsIndexes,
- startIndex,
- startIndexes,
- 1,
- subStringsLength - 1);
- for (int i = subStringsLength - 1; i >= 0; i--) {
- startIndexes[i] += offsetInGlobalLine;
- }
- System.arraycopy(sl.substrings, startIndex, result, 1, subStringsLength - 1);
- System.arraycopy(sl.operators, startIndex, operators, 1, operatorsLength - 1);
+ int startIndex = (sl.substrings[0].length()==0)?1:0;
- return new SplitLine(operators, result, startIndexes);
- }
- }
+ int subStringsLength = sl.substrings.length + 1 - startIndex;
+ String[] result = new String[subStringsLength];
+ int[] startIndexes = new int[subStringsLength];
+ int operatorsLength = sl.operators.length + 1 - startIndex;
+ int[] operators = new int[operatorsLength];
- // if the last token is a comment and the substring before the comment fits on a line,
- // split before the comment and return the result.
- if (lastCommentStartPosition > -1
- && lastCommentStartPosition < options.maxLineLength
- && splitTokenPriority > 50) {
- int end = lastCommentStartPosition;
- int start = lastCommentStartPosition;
- if (stringToSplit.charAt(end - 1) == ' ') {
- end--;
- }
- if (start != end && stringToSplit.charAt(start) == ' ') {
- start++;
- }
- return new SplitLine(
- new int[] { 0, 0 },
- new String[] { stringToSplit.substring(0, end), stringToSplit.substring(start)},
- new int[] { 0, start });
- }
+ result[0] = stringToSplit.substring(0, lastOpenParenthesisPosition);
+ operators[0] = 0;
- if (position != stringToSplit.length()) {
-
- if (substringsCount == substringsStartPositions.length) {
- System.arraycopy(
- substringsStartPositions,
- 0,
- (substringsStartPositions = new int[substringsCount * 2]),
- 0,
- substringsCount);
- System.arraycopy(
- substringsEndPositions,
- 0,
- (substringsEndPositions = new int[substringsCount * 2]),
- 0,
- substringsCount);
+ System.arraycopy(sl.startSubstringsIndexes, startIndex, startIndexes, 1, subStringsLength - 1);
+ for (int i = subStringsLength - 1; i >= 0; i--) {
+ startIndexes[i] += offsetInGlobalLine;
}
- // avoid empty extra substring, e.g. line terminated with a semi-colon
- substringsStartPositions[substringsCount] = position;
- substringsEndPositions[substringsCount++] = stringToSplit.length();
- }
+ System.arraycopy(sl.substrings, startIndex, result, 1, subStringsLength - 1);
+ System.arraycopy(sl.operators, startIndex, operators, 1, operatorsLength - 1);
- if (splitOperatorsCount == splitOperators.length) {
- System.arraycopy(
- splitOperators,
- 0,
- (splitOperators = new int[splitOperatorsCount * 2]),
- 0,
- splitOperatorsCount);
+ return new SplitLine(operators, result, startIndexes);
}
+ }
- splitOperators[splitOperatorsCount] = 0;
-
- // the last element of the stack is the position of the end of StringToSPlit
- // +1 because the substring method excludes the last character
- String[] result = new String[substringsCount];
- for (int i = 0; i < substringsCount; i++) {
- int start = substringsStartPositions[i];
- int end = substringsEndPositions[i];
- if (stringToSplit.charAt(start) == ' ') {
- start++;
- substringsStartPositions[i]++;
- }
- if (end != start && stringToSplit.charAt(end - 1) == ' ') {
- end--;
- }
-
- result[i] = stringToSplit.substring(start, end);
- substringsStartPositions[i] += offsetInGlobalLine;
+ // if the last token is a comment and the substring before the comment fits on a line,
+ // split before the comment and return the result.
+ if (lastCommentStartPosition > -1
+ && lastCommentStartPosition < options.maxLineLength
+ && splitTokenPriority > 50) {
+ int end = lastCommentStartPosition;
+ int start = lastCommentStartPosition;
+ if (stringToSplit.charAt(end - 1) == ' ') {
+ end--;
}
- if (splitOperatorsCount > substringsCount) {
- System.arraycopy(
- substringsStartPositions,
- 0,
- (substringsStartPositions = new int[splitOperatorsCount]),
- 0,
- substringsCount);
- System.arraycopy(
- substringsEndPositions,
- 0,
- (substringsEndPositions = new int[splitOperatorsCount]),
- 0,
- substringsCount);
- for (int i = substringsCount; i < splitOperatorsCount; i++) {
- substringsStartPositions[i] = position;
- substringsEndPositions[i] = position;
- }
- System.arraycopy(
- splitOperators,
- 0,
- (splitOperators = new int[splitOperatorsCount]),
- 0,
- splitOperatorsCount);
- } else {
+ if (start != end && stringToSplit.charAt(start) == ' ') {
+ start++;
+ }
+ return new SplitLine(
+ new int[] {0, 0},
+ new String[] {
+ stringToSplit.substring(0, end),
+ stringToSplit.substring(start)},
+ new int[] {0, start});
+ }
+
+ if (position != stringToSplit.length()) {
+
+ if (substringsCount == substringsStartPositions.length) {
System.arraycopy(
- substringsStartPositions,
- 0,
- (substringsStartPositions = new int[substringsCount]),
- 0,
- substringsCount);
+ substringsStartPositions,
+ 0,
+ (substringsStartPositions = new int[substringsCount * 2]),
+ 0,
+ substringsCount);
System.arraycopy(
- substringsEndPositions,
- 0,
- (substringsEndPositions = new int[substringsCount]),
- 0,
- substringsCount);
- System.arraycopy(
- splitOperators,
- 0,
- (splitOperators = new int[substringsCount]),
- 0,
- substringsCount);
+ substringsEndPositions,
+ 0,
+ (substringsEndPositions = new int[substringsCount * 2]),
+ 0,
+ substringsCount);
}
+ // avoid empty extra substring, e.g. line terminated with a semi-colon
+ substringsStartPositions[substringsCount] = position;
+ substringsEndPositions[substringsCount++] = stringToSplit.length();
+ }
+
+ if (splitOperatorsCount == splitOperators.length) {
+ System.arraycopy(
+ splitOperators,
+ 0,
+ (splitOperators = new int[splitOperatorsCount * 2]),
+ 0,
+ splitOperatorsCount);
+ }
- SplitLine splitLine =
- new SplitLine(splitOperators, result, substringsStartPositions);
- return splitLine;
+ splitOperators[splitOperatorsCount] = 0;
+
+ // the last element of the stack is the position of the end of StringToSPlit
+ // +1 because the substring method excludes the last character
+ String[] result = new String[substringsCount];
+ for (int i = 0; i < substringsCount; i++) {
+ int start = substringsStartPositions[i];
+ int end = substringsEndPositions[i];
+ if (stringToSplit.charAt(start) == ' ') {
+ start++;
+ substringsStartPositions[i]++;
+ }
+ if (end != start && stringToSplit.charAt(end - 1) == ' ') {
+ end--;
+ }
+ result[i] = stringToSplit.substring(start, end);
+ substringsStartPositions[i] += offsetInGlobalLine;
}
-
- private void updateMappedPositions(int startPosition) {
- if (positionsToMap == null)
- return;
- char[] source = scanner.source;
- int sourceLength = source.length;
- while (indexToMap < positionsToMap.length
- && positionsToMap[indexToMap] <= startPosition) {
- int posToMap = positionsToMap[indexToMap];
- if (posToMap < 0
- || posToMap >= sourceLength) { // protection against out of bounds position
- indexToMap = positionsToMap.length; // no more mapping
- return;
- }
- if (Character.isWhitespace(source[posToMap])) {
- mappedPositions[indexToMap] = startPosition + globalDelta + lineDelta;
- } else {
- mappedPositions[indexToMap] = posToMap + globalDelta + lineDelta;
- }
- indexToMap++;
+ if (splitOperatorsCount > substringsCount) {
+ System.arraycopy(substringsStartPositions, 0, (substringsStartPositions = new int[splitOperatorsCount]), 0, substringsCount);
+ System.arraycopy(substringsEndPositions, 0, (substringsEndPositions = new int[splitOperatorsCount]), 0, substringsCount);
+ for (int i = substringsCount; i < splitOperatorsCount; i++) {
+ substringsStartPositions[i] = position;
+ substringsEndPositions[i] = position;
}
+ System.arraycopy(splitOperators, 0, (splitOperators = new int[splitOperatorsCount]), 0, splitOperatorsCount);
+ } else {
+ System.arraycopy(substringsStartPositions, 0, (substringsStartPositions = new int[substringsCount]), 0, substringsCount);
+ System.arraycopy(substringsEndPositions, 0, (substringsEndPositions = new int[substringsCount]), 0, substringsCount);
+ System.arraycopy(splitOperators, 0, (splitOperators = new int[substringsCount]), 0, substringsCount);
}
+
+ SplitLine splitLine = new SplitLine(splitOperators, result, substringsStartPositions);
+ return splitLine;
- private void updateMappedPositionsWhileSplitting(
- int startPosition,
- int endPosition) {
- if (mappedPositions == null || mappedPositions.length == indexInMap)
+}
+private void updateMappedPositions(int startPosition) {
+ if (positionsToMap == null) return;
+ char[] source = scanner.source;
+ int sourceLength = source.length;
+ while (indexToMap < positionsToMap.length && positionsToMap[indexToMap] <= startPosition) {
+ int posToMap = positionsToMap[indexToMap];
+ if (posToMap < 0 || posToMap >= sourceLength){ // protection against out of bounds position
+ indexToMap = positionsToMap.length; // no more mapping
return;
-
- while (indexInMap < mappedPositions.length
- && startPosition <= mappedPositions[indexInMap]
- && mappedPositions[indexInMap] < endPosition
- && indexInMap < indexToMap) {
- mappedPositions[indexInMap] += splitDelta;
- indexInMap++;
}
+ if (Character.isWhitespace(source[posToMap])) {
+ mappedPositions[indexToMap] = startPosition + globalDelta + lineDelta;
+ } else {
+ mappedPositions[indexToMap] = posToMap + globalDelta + lineDelta;
+ }
+ indexToMap++;
}
-
+}
+private void updateMappedPositionsWhileSplitting(int startPosition, int endPosition) {
+ if (mappedPositions == null || mappedPositions.length == indexInMap) return;
+
+ while(indexInMap < mappedPositions.length
+ && startPosition <= mappedPositions[indexInMap]
+ && mappedPositions[indexInMap] < endPosition
+ && indexInMap < indexToMap) {
+ mappedPositions[indexInMap]+= splitDelta;
+ indexInMap++;
+ }
+}
}
diff --git a/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/impl/FormatterOptions.java b/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/impl/FormatterOptions.java
index 54fa0388e3..fd6b7aeebf 100644
--- a/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/impl/FormatterOptions.java
+++ b/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/impl/FormatterOptions.java
@@ -18,238 +18,182 @@ public class FormatterOptions {
// by default, preserve one blank line per sequence of blank lines
public boolean clearAllBlankLinesMode = false;
-
+
// line splitting will occur when line exceeds this length
public int maxLineLength = 80;
- public boolean compactAssignmentMode = false;
- // if isTrue, assignments look like x= 12 (not like x = 12);
+ public boolean compactAssignmentMode = false; // if isTrue, assignments look like x= 12 (not like x = 12);
//number of consecutive spaces used to replace the tab char
public int tabSize = 4; // n spaces for one tab
public boolean indentWithTab = true;
- public boolean compactElseIfMode = false;
- // if true, else and if are kept on the same line.
- public boolean newLineInEmptyBlockMode = true;
- // if false, no new line in {} if it's empty.
-
- public char[] lineSeparatorSequence =
- System.getProperty("line.separator").toCharArray();
- /**
- * Initializing the formatter options with default settings
- */
- public FormatterOptions() {
- }
-
- /**
- * Initializing the formatter options with external settings
- */
- public FormatterOptions(ConfigurableOption[] settings) {
- if (settings == null)
- return;
- // filter options which are related to the compiler component
- String componentName = CodeFormatter.class.getName();
- for (int i = 0, max = settings.length; i < max; i++) {
- if (settings[i].getComponentName().equals(componentName)) {
- this.setOption(settings[i]);
- }
- }
- }
-
- /**
- * Returns all the options of the Code Formatter to be shown by the UI
- *
- * @param locale java.util.Locale
- * @return com.ibm.compiler.java.ConfigurableOption[]
- */
- public ConfigurableOption[] getConfigurableOptions(Locale locale) {
- String componentName = CodeFormatter.class.getName();
- return new ConfigurableOption[] {
- new ConfigurableOption(
- componentName,
- "newline.openingBrace",
- locale,
- newLineBeforeOpeningBraceMode ? 0 : 1),
- new ConfigurableOption(
- componentName,
- "newline.controlStatement",
- locale,
- newlineInControlStatementMode ? 0 : 1),
- new ConfigurableOption(
- componentName,
- "newline.clearAll",
- locale,
- clearAllBlankLinesMode ? 0 : 1),
- new ConfigurableOption(
- componentName,
- "newline.elseIf",
- locale,
- compactElseIfMode ? 0 : 1),
- new ConfigurableOption(
- componentName,
- "newline.emptyBlock",
- locale,
- newLineInEmptyBlockMode ? 0 : 1),
- new ConfigurableOption(componentName, "line.split", locale, maxLineLength),
- new ConfigurableOption(
- componentName,
- "style.compactAssignment",
- locale,
- compactAssignmentMode ? 0 : 1),
- new ConfigurableOption(
- componentName,
- "tabulation.char",
- locale,
- indentWithTab ? 0 : 1),
- new ConfigurableOption(componentName, "tabulation.size", locale, tabSize)};
- }
-
- /**
- *
- * @return int
- */
- public int getMaxLineLength() {
- return maxLineLength;
- }
-
- public int getTabSize() {
- return tabSize;
- }
-
- public boolean isAddingNewLineBeforeOpeningBrace() {
- return newLineBeforeOpeningBraceMode;
- }
-
- public boolean isAddingNewLineInControlStatement() {
- return newlineInControlStatementMode;
- }
-
- public boolean isAddingNewLineInEmptyBlock() {
- return newLineInEmptyBlockMode;
- }
-
- public boolean isClearingAllBlankLines() {
- return clearAllBlankLinesMode;
- }
-
- public boolean isCompactingAssignment() {
- return compactAssignmentMode;
- }
-
- public boolean isCompactingElseIf() {
- return compactElseIfMode;
- }
-
- public boolean isUsingTabForIndenting() {
- return indentWithTab;
- }
-
- public void setClearAllBlankLinesMode(boolean flag) {
- clearAllBlankLinesMode = flag;
- }
-
- /** Set the behaviour of the formatter about the braces.<br>
- * @param boolean newBraceIndentationLevel<ul>
- * <li>if true, the formatter add new line & indent before the opening brace.
- * <li>if false, the formatter leaves the brace on the same line.</ul>
- */
- public void setCompactAssignmentMode(boolean flag) {
- compactAssignmentMode = flag;
- }
-
- /** Set the behaviour of the formatter about else if.<br>
- * @param boolean flag<ul>
- * <li>if true, a <code>else if</code> sequence is kept on the same line.
- * <li>if false, <code>else if</code> is formatted like:
- <pre>
- else
- if
- </pre>
- </ul>
- */
- public void setCompactElseIfMode(boolean flag) {
- compactElseIfMode = flag;
- }
-
- /** Defines whether to use tab characters or sequence of spaces when indenting
- * @param boolean useTab <ul>
- * <li>if true, the formatter add new line & indent before the opening brace.
- * <li>if false, the formatter leaves the brace on the same line.</ul>
- */
- public void setIndentationUsesTab(boolean flag) {
- indentWithTab = flag;
- }
-
- public void setLineSeparator(String lineSeparator) {
- lineSeparatorSequence = lineSeparator.toCharArray();
- }
-
- public void setMaxLineLength(int maxLineLength) {
- this.maxLineLength = maxLineLength;
- }
-
- /** Set the behaviour of the formatter about the braces.<br>
- * @param boolean newBraceIndentationLevel<ul>
- * <li>if true, the formatter add new line & indent before the opening brace.
- * <li>if false, the formatter leaves the brace on the same line.</ul>
- */
- public void setNewLineBeforeOpeningBraceMode(boolean flag) {
- newLineBeforeOpeningBraceMode = flag;
- }
-
- public void setNewlineInControlStatementMode(boolean flag) {
- newlineInControlStatementMode = flag;
- }
-
- public void setNewLineInEmptyBlockMode(boolean flag) {
- newLineInEmptyBlockMode = flag;
- }
-
- /**
- * Change the value of the option corresponding to the option number
- *
- * @param optionNumber <CODE>int</CODE>
- * @param newValue <CODE>int</CODE>
- */
- public void setOption(ConfigurableOption setting) {
-
- switch (setting.getID()) {
- case 1 : // insert blank line before opening brace
- setNewLineBeforeOpeningBraceMode(setting.getCurrentValueIndex() == 0);
- break;
- case 2 : // insert blank line behind keywords (ELSE, CATCH, FINALLY,...) in control statements
- setNewlineInControlStatementMode(setting.getCurrentValueIndex() == 0);
- break;
- case 3 : // flush all blank lines
- setClearAllBlankLinesMode(setting.getCurrentValueIndex() == 0);
- break;
- case 4 : // puts else if on the same line
- setCompactElseIfMode(setting.getCurrentValueIndex() == 0);
- break;
- case 5 : // add a new line inside an empty block.
- setNewLineInEmptyBlockMode(setting.getCurrentValueIndex() == 0);
- break;
- case 6 : // line splitting will occur when line exceeds this length (0 -> no splitting)
- setMaxLineLength(setting.getCurrentValueIndex());
- break;
- case 7 : // if isTrue, assignments look like x= 12 (not like x = 12);
- setCompactAssignmentMode(setting.getCurrentValueIndex() == 0);
- break;
- case 9 : // should use tab or spaces to indent
- setIndentationUsesTab(setting.getCurrentValueIndex() == 0);
- break;
- case 10 : // amount of spaces for a tabulation
- setTabSize(setting.getCurrentValueIndex());
- break;
+ public boolean compactElseIfMode = false; // if true, else and if are kept on the same line.
+ public boolean newLineInEmptyBlockMode = true; // if false, no new line in {} if it's empty.
+
+ public char[] lineSeparatorSequence = System.getProperty("line.separator"/*nonNLS*/).toCharArray();
+/**
+ * Initializing the formatter options with default settings
+ */
+public FormatterOptions(){
+}
+/**
+ * Initializing the formatter options with external settings
+ */
+public FormatterOptions(ConfigurableOption[] settings){
+ if (settings == null) return;
+ // filter options which are related to the compiler component
+ String componentName = CodeFormatter.class.getName();
+ for (int i = 0, max = settings.length; i < max; i++){
+ if (settings[i].getComponentName().equals(componentName)){
+ this.setOption(settings[i]);
}
}
-
- public void setReuseExistingLayoutMode(boolean flag) {
- }
-
- public void setTabSize(int size) {
- this.tabSize = size;
+}
+/**
+ * Returns all the options of the Code Formatter to be shown by the UI
+ *
+ * @param locale java.util.Locale
+ * @return com.ibm.compiler.java.ConfigurableOption[]
+ */
+public ConfigurableOption[] getConfigurableOptions(Locale locale) {
+ String componentName = CodeFormatter.class.getName();
+ return new ConfigurableOption[] {
+ new ConfigurableOption(componentName, "newline.openingBrace"/*nonNLS*/, locale, newLineBeforeOpeningBraceMode ? 0 : 1),
+ new ConfigurableOption(componentName, "newline.controlStatement"/*nonNLS*/, locale, newlineInControlStatementMode ? 0 : 1),
+ new ConfigurableOption(componentName, "newline.clearAll"/*nonNLS*/, locale, clearAllBlankLinesMode ? 0 : 1),
+ new ConfigurableOption(componentName, "newline.elseIf"/*nonNLS*/, locale, compactElseIfMode ? 0 : 1),
+ new ConfigurableOption(componentName, "newline.emptyBlock"/*nonNLS*/, locale, newLineInEmptyBlockMode ? 0 : 1),
+ new ConfigurableOption(componentName, "line.split"/*nonNLS*/, locale, maxLineLength),
+ new ConfigurableOption(componentName, "style.compactAssignment"/*nonNLS*/, locale, compactAssignmentMode ? 0 : 1),
+ new ConfigurableOption(componentName, "tabulation.char"/*nonNLS*/, locale, indentWithTab ? 0 : 1),
+ new ConfigurableOption(componentName, "tabulation.size"/*nonNLS*/, locale, tabSize)
+ };
+}
+/**
+ *
+ * @return int
+ */
+public int getMaxLineLength() {
+ return maxLineLength;
+}
+public int getTabSize() {
+ return tabSize;
+}
+public boolean isAddingNewLineBeforeOpeningBrace() {
+ return newLineBeforeOpeningBraceMode;
+}
+public boolean isAddingNewLineInControlStatement() {
+ return newlineInControlStatementMode;
+}
+public boolean isAddingNewLineInEmptyBlock() {
+ return newLineInEmptyBlockMode;
+}
+public boolean isClearingAllBlankLines() {
+ return clearAllBlankLinesMode;
+}
+public boolean isCompactingAssignment() {
+ return compactAssignmentMode;
+}
+public boolean isCompactingElseIf() {
+ return compactElseIfMode;
+}
+public boolean isUsingTabForIndenting() {
+ return indentWithTab;
+}
+public void setClearAllBlankLinesMode(boolean flag) {
+ clearAllBlankLinesMode = flag;
+}
+/** Set the behaviour of the formatter about the braces.<br>
+ * @param boolean newBraceIndentationLevel<ul>
+ * <li>if true, the formatter add new line & indent before the opening brace.
+ * <li>if false, the formatter leaves the brace on the same line.</ul>
+ */
+public void setCompactAssignmentMode(boolean flag) {
+ compactAssignmentMode = flag;
+}
+/** Set the behaviour of the formatter about else if.<br>
+ * @param boolean flag<ul>
+ * <li>if true, a <code>else if</code> sequence is kept on the same line.
+ * <li>if false, <code>else if</code> is formatted like:
+ <pre>
+ else
+ if
+ </pre>
+ </ul>
+ */
+public void setCompactElseIfMode(boolean flag) {
+ compactElseIfMode = flag;
+}
+/** Defines whether to use tab characters or sequence of spaces when indenting
+ * @param boolean useTab <ul>
+ * <li>if true, the formatter add new line & indent before the opening brace.
+ * <li>if false, the formatter leaves the brace on the same line.</ul>
+ */
+public void setIndentationUsesTab(boolean flag) {
+ indentWithTab = flag;
+}
+public void setLineSeparator(String lineSeparator) {
+ lineSeparatorSequence = lineSeparator.toCharArray();
+}
+public void setMaxLineLength(int maxLineLength) {
+ this.maxLineLength = maxLineLength;
+}
+/** Set the behaviour of the formatter about the braces.<br>
+ * @param boolean newBraceIndentationLevel<ul>
+ * <li>if true, the formatter add new line & indent before the opening brace.
+ * <li>if false, the formatter leaves the brace on the same line.</ul>
+ */
+public void setNewLineBeforeOpeningBraceMode(boolean flag) {
+ newLineBeforeOpeningBraceMode = flag;
+}
+public void setNewlineInControlStatementMode(boolean flag) {
+ newlineInControlStatementMode = flag;
+}
+public void setNewLineInEmptyBlockMode(boolean flag) {
+ newLineInEmptyBlockMode = flag;
+}
+/**
+ * Change the value of the option corresponding to the option number
+ *
+ * @param optionNumber <CODE>int</CODE>
+ * @param newValue <CODE>int</CODE>
+ */
+public void setOption(ConfigurableOption setting) {
+
+ switch (setting.getID()) {
+ case 1 : // insert blank line before opening brace
+ setNewLineBeforeOpeningBraceMode(setting.getCurrentValueIndex() == 0);
+ break;
+ case 2 : // insert blank line behind keywords (ELSE, CATCH, FINALLY,...) in control statements
+ setNewlineInControlStatementMode(setting.getCurrentValueIndex() == 0);
+ break;
+ case 3 : // flush all blank lines
+ setClearAllBlankLinesMode(setting.getCurrentValueIndex() == 0);
+ break;
+ case 4 : // puts else if on the same line
+ setCompactElseIfMode(setting.getCurrentValueIndex() == 0);
+ break;
+ case 5 : // add a new line inside an empty block.
+ setNewLineInEmptyBlockMode(setting.getCurrentValueIndex() == 0);
+ break;
+ case 6 : // line splitting will occur when line exceeds this length (0 -> no splitting)
+ setMaxLineLength(setting.getCurrentValueIndex());
+ break;
+ case 7 : // if isTrue, assignments look like x= 12 (not like x = 12);
+ setCompactAssignmentMode(setting.getCurrentValueIndex() == 0);
+ break;
+ case 9 : // should use tab or spaces to indent
+ setIndentationUsesTab(setting.getCurrentValueIndex() == 0);
+ break;
+ case 10 : // amount of spaces for a tabulation
+ setTabSize(setting.getCurrentValueIndex());
+ break;
}
-
+}
+public void setReuseExistingLayoutMode(boolean flag) {
+}
+public void setTabSize(int size) {
+ this.tabSize = size;
+}
}
diff --git a/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/impl/SplitLine.java b/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/impl/SplitLine.java
index ae1d73608e..912da60e27 100644
--- a/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/impl/SplitLine.java
+++ b/org.eclipse.jdt.core/formatter/org/eclipse/jdt/internal/formatter/impl/SplitLine.java
@@ -8,203 +8,198 @@ import org.eclipse.jdt.internal.compiler.parser.*;
/** Represents a split line: contains an operator and all substrings
*/
-public class SplitLine implements TerminalSymbols {
+public class SplitLine implements TerminalSymbols{
public int[] operators; // the operator on which the string was split.
public String[] substrings;
public int[] startSubstringsIndexes;
- /**
- * SplitLine constructor comment.
- */
- public SplitLine(int[] operators, String[] substrings) {
- this(operators, substrings, null);
- }
-
- /**
- * SplitLine constructor comment.
- */
- public SplitLine(int[] operators, String[] substrings, int[] startIndexes) {
- super();
- this.operators = operators;
- this.substrings = substrings;
- this.startSubstringsIndexes = startIndexes;
+/**
+ * SplitLine constructor comment.
+ */
+public SplitLine(int[] operators, String[] substrings) {
+ this(operators, substrings, null);
+}
+/**
+ * SplitLine constructor comment.
+ */
+public SplitLine(int[] operators, String[] substrings, int[] startIndexes) {
+ super();
+ this.operators=operators;
+ this.substrings=substrings;
+ this.startSubstringsIndexes = startIndexes;
+}
+/**
+ * Prints a nice representation of the receiver
+ * @return java.lang.String
+ */
+public String toString() {
+ StringBuffer result=new StringBuffer();
+ String operatorString = new String();
+
+ for (int i=0,max=substrings.length;i<max;i++){
+ int currentOperator = operators[i];
+ String currentString = substrings[i];
+ boolean placeOperatorAhead = currentOperator != TerminalSymbols.TokenNameCOMMA && currentOperator != TerminalSymbols.TokenNameSEMICOLON;
+ boolean placeOperatorBehind = currentOperator == TerminalSymbols.TokenNameCOMMA || currentOperator == TerminalSymbols.TokenNameSEMICOLON;
+
+
+
+ switch (currentOperator){
+ case TokenNameextends:
+ operatorString="extends"/*nonNLS*/;
+ break;
+ case TokenNameimplements:
+ operatorString="implements"/*nonNLS*/;
+ break;
+ case TokenNamethrows:
+ operatorString="throws"/*nonNLS*/;
+ break;
+ case TokenNameSEMICOLON : // ;
+ operatorString=";"/*nonNLS*/;
+ break;
+ case TokenNameCOMMA : // ,
+ operatorString=","/*nonNLS*/;
+ break;
+ case TokenNameEQUAL : // =
+ operatorString="="/*nonNLS*/;
+ break;
+ case TokenNameAND_AND : // && (15.22)
+ operatorString="&&"/*nonNLS*/;
+ break;
+ case TokenNameOR_OR : // || (15.23)
+ operatorString="||"/*nonNLS*/;
+ break;
+ case TokenNameQUESTION : // ? (15.24)
+ operatorString="?"/*nonNLS*/;
+ break;
+
+ case TokenNameCOLON : // : (15.24)
+ operatorString=":"/*nonNLS*/;
+ break;
+ case TokenNameEQUAL_EQUAL : // == (15.20, 15.20.1, 15.20.2, 15.20.3)
+ operatorString="=="/*nonNLS*/;
+ break;
+
+ case TokenNameNOT_EQUAL : // != (15.20, 15.20.1, 15.20.2, 15.20.3)
+ operatorString="!="/*nonNLS*/;
+ break;
+
+ case TokenNameLESS : // < (15.19.1)
+ operatorString="<"/*nonNLS*/;
+ break;
+
+ case TokenNameLESS_EQUAL : // <= (15.19.1)
+ operatorString="<="/*nonNLS*/;
+ break;
+
+ case TokenNameGREATER : // > (15.19.1)
+ operatorString=">"/*nonNLS*/;
+ break;
+
+ case TokenNameGREATER_EQUAL : // >= (15.19.1)
+ operatorString=">="/*nonNLS*/;
+ break;
+
+ case TokenNameinstanceof : // instanceof
+ operatorString="instanceof"/*nonNLS*/;
+ break;
+ case TokenNamePLUS : // + (15.17, 15.17.2)
+ operatorString="+"/*nonNLS*/;
+ break;
+
+ case TokenNameMINUS : // - (15.17.2)
+ operatorString="-"/*nonNLS*/;
+ break;
+ case TokenNameMULTIPLY : // * (15.16.1)
+ operatorString="*"/*nonNLS*/;
+ break;
+
+ case TokenNameDIVIDE : // / (15.16.2)
+ operatorString="/"/*nonNLS*/;
+ break;
+
+ case TokenNameREMAINDER : // % (15.16.3)
+ operatorString="%"/*nonNLS*/;
+ break;
+ case TokenNameLEFT_SHIFT : // << (15.18)
+ operatorString="<<"/*nonNLS*/;
+ break;
+
+ case TokenNameRIGHT_SHIFT : // >> (15.18)
+ operatorString=">>"/*nonNLS*/;
+ break;
+
+ case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18)
+ operatorString=">>>"/*nonNLS*/;
+ break;
+ case TokenNameAND : // & (15.21, 15.21.1, 15.21.2)
+ operatorString="&"/*nonNLS*/;
+ break;
+
+ case TokenNameOR : // | (15.21, 15.21.1, 15.21.2)
+ operatorString="|"/*nonNLS*/;
+ break;
+
+ case TokenNameXOR : // ^ (15.21, 15.21.1, 15.21.2)
+ operatorString="^"/*nonNLS*/;
+ break;
+ case TokenNameMULTIPLY_EQUAL : // *= (15.25.2)
+ operatorString="*="/*nonNLS*/;
+ break;
+
+ case TokenNameDIVIDE_EQUAL : // /= (15.25.2)
+ operatorString="/="/*nonNLS*/;
+ break;
+ case TokenNameREMAINDER_EQUAL : // %= (15.25.2)
+ operatorString="%="/*nonNLS*/;
+ break;
+
+ case TokenNamePLUS_EQUAL : // += (15.25.2)
+ operatorString="+="/*nonNLS*/;
+ break;
+
+ case TokenNameMINUS_EQUAL : // -= (15.25.2)
+ operatorString="-="/*nonNLS*/;
+ break;
+
+ case TokenNameLEFT_SHIFT_EQUAL : // <<= (15.25.2)
+ operatorString="<<="/*nonNLS*/;
+ break;
+
+ case TokenNameRIGHT_SHIFT_EQUAL : // >>= (15.25.2)
+ operatorString=">>="/*nonNLS*/;
+ break;
+
+ case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2)
+ operatorString=">>>="/*nonNLS*/;
+ break;
+
+ case TokenNameAND_EQUAL : // &= (15.25.2)
+ operatorString="&="/*nonNLS*/;
+ break;
+
+ case TokenNameXOR_EQUAL : // ^= (15.25.2)
+ operatorString="^="/*nonNLS*/;
+ break;
+
+ case TokenNameOR_EQUAL : // |= (15.25.2)
+ operatorString="|="/*nonNLS*/;
+ break;
+ case TokenNameDOT : // .
+ operatorString="."/*nonNLS*/;
+ break;
+
+ default:
+ operatorString=""/*nonNLS*/;
}
-
- /**
- * Prints a nice representation of the receiver
- * @return java.lang.String
- */
- public String toString() {
- StringBuffer result = new StringBuffer();
- String operatorString = new String();
-
- for (int i = 0, max = substrings.length; i < max; i++) {
- int currentOperator = operators[i];
- String currentString = substrings[i];
- boolean placeOperatorAhead =
- currentOperator != TerminalSymbols.TokenNameCOMMA
- && currentOperator != TerminalSymbols.TokenNameSEMICOLON;
- boolean placeOperatorBehind =
- currentOperator == TerminalSymbols.TokenNameCOMMA
- || currentOperator == TerminalSymbols.TokenNameSEMICOLON;
-
- switch (currentOperator) {
- case TokenNameextends :
- operatorString = "extends";
- break;
- case TokenNameimplements :
- operatorString = "implements";
- break;
- case TokenNamethrows :
- operatorString = "throws";
- break;
- case TokenNameSEMICOLON : // ;
- operatorString = ";";
- break;
- case TokenNameCOMMA : // ,
- operatorString = ",";
- break;
- case TokenNameEQUAL : // =
- operatorString = "=";
- break;
- case TokenNameAND_AND : // && (15.22)
- operatorString = "&&";
- break;
- case TokenNameOR_OR : // || (15.23)
- operatorString = "||";
- break;
- case TokenNameQUESTION : // ? (15.24)
- operatorString = "?";
- break;
-
- case TokenNameCOLON : // : (15.24)
- operatorString = ":";
- break;
- case TokenNameEQUAL_EQUAL : // == (15.20, 15.20.1, 15.20.2, 15.20.3)
- operatorString = "==";
- break;
-
- case TokenNameNOT_EQUAL : // != (15.20, 15.20.1, 15.20.2, 15.20.3)
- operatorString = "!=";
- break;
-
- case TokenNameLESS : // < (15.19.1)
- operatorString = "<";
- break;
-
- case TokenNameLESS_EQUAL : // <= (15.19.1)
- operatorString = "<=";
- break;
-
- case TokenNameGREATER : // > (15.19.1)
- operatorString = ">";
- break;
-
- case TokenNameGREATER_EQUAL : // >= (15.19.1)
- operatorString = ">=";
- break;
-
- case TokenNameinstanceof : // instanceof
- operatorString = "instanceof";
- break;
- case TokenNamePLUS : // + (15.17, 15.17.2)
- operatorString = "+";
- break;
-
- case TokenNameMINUS : // - (15.17.2)
- operatorString = "-";
- break;
- case TokenNameMULTIPLY : // * (15.16.1)
- operatorString = "*";
- break;
-
- case TokenNameDIVIDE : // / (15.16.2)
- operatorString = "/";
- break;
-
- case TokenNameREMAINDER : // % (15.16.3)
- operatorString = "%";
- break;
- case TokenNameLEFT_SHIFT : // << (15.18)
- operatorString = "<<";
- break;
-
- case TokenNameRIGHT_SHIFT : // >> (15.18)
- operatorString = ">>";
- break;
-
- case TokenNameUNSIGNED_RIGHT_SHIFT : // >>> (15.18)
- operatorString = ">>>";
- break;
- case TokenNameAND : // & (15.21, 15.21.1, 15.21.2)
- operatorString = "&";
- break;
-
- case TokenNameOR : // | (15.21, 15.21.1, 15.21.2)
- operatorString = "|";
- break;
-
- case TokenNameXOR : // ^ (15.21, 15.21.1, 15.21.2)
- operatorString = "^";
- break;
- case TokenNameMULTIPLY_EQUAL : // *= (15.25.2)
- operatorString = "*=";
- break;
-
- case TokenNameDIVIDE_EQUAL : // /= (15.25.2)
- operatorString = "/=";
- break;
- case TokenNameREMAINDER_EQUAL : // %= (15.25.2)
- operatorString = "%=";
- break;
-
- case TokenNamePLUS_EQUAL : // += (15.25.2)
- operatorString = "+=";
- break;
-
- case TokenNameMINUS_EQUAL : // -= (15.25.2)
- operatorString = "-=";
- break;
-
- case TokenNameLEFT_SHIFT_EQUAL : // <<= (15.25.2)
- operatorString = "<<=";
- break;
-
- case TokenNameRIGHT_SHIFT_EQUAL : // >>= (15.25.2)
- operatorString = ">>=";
- break;
-
- case TokenNameUNSIGNED_RIGHT_SHIFT_EQUAL : // >>>= (15.25.2)
- operatorString = ">>>=";
- break;
-
- case TokenNameAND_EQUAL : // &= (15.25.2)
- operatorString = "&=";
- break;
-
- case TokenNameXOR_EQUAL : // ^= (15.25.2)
- operatorString = "^=";
- break;
-
- case TokenNameOR_EQUAL : // |= (15.25.2)
- operatorString = "|=";
- break;
- case TokenNameDOT : // .
- operatorString = ".";
- break;
-
- default :
- operatorString = "";
- }
- if (placeOperatorAhead) {
- result.append(operatorString);
- }
- result.append(currentString);
- if (placeOperatorBehind) {
- result.append(operatorString);
- }
- result.append('\n');
+ if (placeOperatorAhead){
+ result.append(operatorString);
+ }
+ result.append(currentString);
+ if (placeOperatorBehind){
+ result.append(operatorString);
}
- return "";
+ result.append('\n');
}
-
+ return ""/*nonNLS*/;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/BufferChangedEvent.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/BufferChangedEvent.java
index 54ba0fedfd..42eea3523e 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/BufferChangedEvent.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/BufferChangedEvent.java
@@ -54,59 +54,50 @@ public class BufferChangedEvent extends EventObject {
*/
private String text;
- /**
- * Creates a new buffer changed event indicating that the given buffer has changed.
- */
- public BufferChangedEvent(
- IBuffer buffer,
- int offset,
- int length,
- String text) {
- super(buffer);
- this.offset = offset;
- this.length = length;
- this.text = text;
- }
-
- /**
- * Returns the buffer which has changed.
- *
- * @return the buffer affected by the change
- */
- public IBuffer getBuffer() {
- return (IBuffer) source;
- }
-
- /**
- * Returns the length of text removed or replaced in the buffer, or
- * 0 if text has been inserted into the buffer.
- *
- * @return the length of the original text fragment modified by the
- * buffer change (<code> 0 </code> in case of insertion).
- */
- public int getLength() {
- return this.length;
- }
-
- /**
- * Returns the index of the first character inserted, removed, or replaced
- * in the buffer.
- *
- * @return the source offset of the textual manipulation in the buffer
- */
- public int getOffset() {
- return this.offset;
- }
-
- /**
- * Returns the text that was inserted, the replacement text,
- * or <code>null</code> if text has been removed.
- *
- * @return the text corresponding to the buffer change (<code> null </code>
- * in case of deletion).
- */
- public String getText() {
- return this.text;
- }
-
+/**
+ * Creates a new buffer changed event indicating that the given buffer has changed.
+ */
+public BufferChangedEvent(IBuffer buffer, int offset, int length, String text) {
+ super(buffer);
+ this.offset = offset;
+ this.length = length;
+ this.text = text;
+}
+/**
+ * Returns the buffer which has changed.
+ *
+ * @return the buffer affected by the change
+ */
+public IBuffer getBuffer() {
+ return (IBuffer) source;
+}
+/**
+ * Returns the length of text removed or replaced in the buffer, or
+ * 0 if text has been inserted into the buffer.
+ *
+ * @return the length of the original text fragment modified by the
+ * buffer change (<code> 0 </code> in case of insertion).
+ */
+public int getLength() {
+ return this.length;
+}
+/**
+ * Returns the index of the first character inserted, removed, or replaced
+ * in the buffer.
+ *
+ * @return the source offset of the textual manipulation in the buffer
+ */
+public int getOffset() {
+ return this.offset;
+}
+/**
+ * Returns the text that was inserted, the replacement text,
+ * or <code>null</code> if text has been removed.
+ *
+ * @return the text corresponding to the buffer change (<code> null </code>
+ * in case of deletion).
+ */
+public String getText() {
+ return this.text;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ElementChangedEvent.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ElementChangedEvent.java
index b408713c73..6192c852d4 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ElementChangedEvent.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ElementChangedEvent.java
@@ -19,22 +19,20 @@ import java.util.EventObject;
* @see IJavaElementDelta
*/
public class ElementChangedEvent extends EventObject {
- /**
- * Creates an new element changed event (based on a <code>IJavaElementDelta</code>).
- *
- * @param delta the Java element delta.
- */
- public ElementChangedEvent(IJavaElementDelta delta) {
- super(delta);
- }
-
- /**
- * Returns the delta describing the change.
- *
- * @return the delta describing the change
- */
- public IJavaElementDelta getDelta() {
- return (IJavaElementDelta) source;
- }
-
+/**
+ * Creates an new element changed event (based on a <code>IJavaElementDelta</code>).
+ *
+ * @param delta the Java element delta.
+ */
+public ElementChangedEvent(IJavaElementDelta delta) {
+ super(delta);
+}
+/**
+ * Returns the delta describing the change.
+ *
+ * @return the delta describing the change
+ */
+public IJavaElementDelta getDelta() {
+ return (IJavaElementDelta) source;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/Flags.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/Flags.java
index c4ea380943..fbcabf6c29 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/Flags.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/Flags.java
@@ -4,7 +4,7 @@ package org.eclipse.jdt.core;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
-
+
import org.eclipse.jdt.internal.compiler.env.IConstants;
/**
@@ -17,12 +17,10 @@ import org.eclipse.jdt.internal.compiler.env.IConstants;
* @see IMember#getFlags
*/
public final class Flags {
- /**
- * Not instantiable.
- */
- private Flags() {
- }
-
+/**
+ * Not instantiable.
+ */
+private Flags() {}
/**
* Returns whether the given integer includes the <code>abstract</code> modifier.
*
@@ -32,7 +30,6 @@ public final class Flags {
public static boolean isAbstract(int flags) {
return (flags & IConstants.AccAbstract) != 0;
}
-
/**
* Returns whether the given integer includes the indication that the
* element is deprecated (<code>@deprecated</code> tag in Javadoc comment).
@@ -43,7 +40,6 @@ public final class Flags {
public static boolean isDeprecated(int flags) {
return (flags & IConstants.AccDeprecated) != 0;
}
-
/**
* Returns whether the given integer includes the <code>final</code> modifier.
*
@@ -53,7 +49,6 @@ public final class Flags {
public static boolean isFinal(int flags) {
return (flags & IConstants.AccFinal) != 0;
}
-
/**
* Returns whether the given integer includes the <code>native</code> modifier.
*
@@ -63,7 +58,6 @@ public final class Flags {
public static boolean isNative(int flags) {
return (flags & IConstants.AccNative) != 0;
}
-
/**
* Returns whether the given integer includes the <code>private</code> modifier.
*
@@ -73,7 +67,6 @@ public final class Flags {
public static boolean isPrivate(int flags) {
return (flags & IConstants.AccPrivate) != 0;
}
-
/**
* Returns whether the given integer includes the <code>protected</code> modifier.
*
@@ -83,7 +76,6 @@ public final class Flags {
public static boolean isProtected(int flags) {
return (flags & IConstants.AccProtected) != 0;
}
-
/**
* Returns whether the given integer includes the <code>public</code> modifier.
*
@@ -93,7 +85,6 @@ public final class Flags {
public static boolean isPublic(int flags) {
return (flags & IConstants.AccPublic) != 0;
}
-
/**
* Returns whether the given integer includes the <code>static</code> modifier.
*
@@ -103,7 +94,6 @@ public final class Flags {
public static boolean isStatic(int flags) {
return (flags & IConstants.AccStatic) != 0;
}
-
/**
* Returns whether the given integer includes the <code>strictfp</code> modifier.
*
@@ -113,7 +103,6 @@ public final class Flags {
public static boolean isStrictfp(int flags) {
return (flags & IConstants.AccStrictfp) != 0;
}
-
/**
* Returns whether the given integer includes the <code>synchronized</code> modifier.
*
@@ -123,7 +112,6 @@ public final class Flags {
public static boolean isSynchronized(int flags) {
return (flags & IConstants.AccSynchronized) != 0;
}
-
/**
* Returns whether the given integer includes the indication that the
* element is synthetic.
@@ -134,7 +122,6 @@ public final class Flags {
public static boolean isSynthetic(int flags) {
return (flags & IConstants.AccSynthetic) != 0;
}
-
/**
* Returns whether the given integer includes the <code>transient</code> modifier.
*
@@ -142,9 +129,8 @@ public final class Flags {
* @return <code>true</code> if the <code>transient</code> modifier is included
*/
public static boolean isTransient(int flags) {
- return (flags & IConstants.AccTransient) != 0;
+ return (flags & IConstants.AccTransient) != 0;
}
-
/**
* Returns whether the given integer includes the <code>volatile</code> modifier.
*
@@ -154,7 +140,6 @@ public final class Flags {
public static boolean isVolatile(int flags) {
return (flags & IConstants.AccVolatile) != 0;
}
-
/**
* Returns a standard string describing the given modifier flags.
* Only modifier flags are included in the output; the deprecated and
@@ -184,34 +169,21 @@ public final class Flags {
public static String toString(int flags) {
StringBuffer sb = new StringBuffer();
- if (isPublic(flags))
- sb.append("public ");
- if (isProtected(flags))
- sb.append("protected ");
- if (isPrivate(flags))
- sb.append("private ");
- if (isStatic(flags))
- sb.append("static ");
- if (isAbstract(flags))
- sb.append("abstract ");
- if (isFinal(flags))
- sb.append("final ");
- if (isNative(flags))
- sb.append("native ");
- if (isSynchronized(flags))
- sb.append("synchronized ");
- if (isTransient(flags))
- sb.append("transient ");
- if (isVolatile(flags))
- sb.append("volatile ");
- if (isStrictfp(flags))
- sb.append("strictfp ");
+ if (isPublic(flags)) sb.append("public ");
+ if (isProtected(flags)) sb.append("protected ");
+ if (isPrivate(flags)) sb.append("private ");
+ if (isStatic(flags)) sb.append("static ");
+ if (isAbstract(flags)) sb.append("abstract ");
+ if (isFinal(flags)) sb.append("final ");
+ if (isNative(flags)) sb.append("native ");
+ if (isSynchronized(flags)) sb.append("synchronized ");
+ if (isTransient(flags)) sb.append("transient ");
+ if (isVolatile(flags)) sb.append("volatile ");
+ if (isStrictfp(flags)) sb.append("strictfp ");
int len = sb.length();
- if (len == 0)
- return "";
- sb.setLength(len - 1);
+ if (len == 0) return "";
+ sb.setLength(len-1);
return sb.toString();
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IBuffer.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IBuffer.java
index 5bb08875ab..31c9af6ff5 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IBuffer.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IBuffer.java
@@ -18,203 +18,202 @@ import org.eclipse.core.runtime.IProgressMonitor;
* </p>
*/
public interface IBuffer {
-
- /**
- * Adds the given listener for changes to this buffer.
- * Has no effect if an identical listener is already registered.
- *
- * @param listener the listener of buffer changes
- */
- public void addBufferChangedListener(IBufferChangedListener listener);
- /**
- * Appends the given character array to the contents of the buffer.
- * This buffer will now have unsaved changes.
- * Any client can append to the contents of the buffer, not just the owner of the buffer.
- * Reports a buffer changed event.
- *
- * <p>Has no effect if this buffer is read-only.
- *
- * @param text the given character array to append to contents of the buffer
- */
- public void append(char[] text);
- /**
- * Appends the given string to the contents of the buffer.
- * This buffer will now have unsaved changes.
- * Any client can append to the contents of the buffer, not just the owner of the buffer.
- * Reports a buffer changed event.
- *
- * <p>Has no effect if this buffer is read-only.
- *
- * @param text the <code>String</code> to append to the contents of the buffer
- */
- public void append(String text);
- /**
- * Closes the buffer. Any unsaved changes are lost. Reports a buffer changed event.
- * Further operations on the buffer are not allowed, except for close. If an
- * attempt is made to close an already closed buffer, the second attempt has no effect.
- */
- public void close();
- /**
- * Returns the character at the given position in this buffer.
- *
- * @param position a zero-based source offset in this buffer
- * @return the character at the given position in this buffer
- */
- public char getChar(int position);
- /**
- * Returns the contents of this buffer as a character array.
- * <p>
- * Callers should make no assumption about whether the returned character array
- * is or is not the genuine article or a copy. In other words, if the client
- * wishes to change this array, they should make a copy. Likewise, if the
- * client wishes to hang on to the array in its current state, they should
- * make a copy.
- * </p>
- *
- * @return the characters contained in this buffer
- */
- public char[] getCharacters();
- /**
- * Returns the contents of this buffer as a <code>String</code>. Like all strings,
- * the result is an immutable value object.
- *
- * @return the contents of this buffer as a <code>String</code>
- */
- public String getContents();
- /**
- * Returns number of characters stored in this buffer.
- *
- * @return the number of characters in this buffer
- */
- public int getLength();
- /**
- * Returns the Java openable element owning of this buffer.
- *
- * @return the openable element owning this buffer
- */
- public IOpenable getOwner();
- /**
- * Returns the given range of text in this buffer.
- *
- * @param offset the zero-based starting offset
- * @param length the number of characters to retrieve
- * @return the given range of text in this buffer
- */
- public String getText(int offset, int length);
- /**
- * Returns the underlying resource for which this buffer was opened,
- * or <code>null</code> if this buffer was not opened on a resource.
- *
- * @return the underlying resource for this buffer, or <code>null</code>
- * if none.
- */
- public IResource getUnderlyingResource();
- /**
- * Returns whether this buffer has been modified since it
- * was opened or since it was last saved.
- * If a buffer does not have an underlying resource, this method always
- * returns <code>true</code>.
- *
- * @return a <code>boolean</code> indicating presence of unsaved changes (in
- * the absence of any underlying resource, it will always return <code>true</code>).
- */
- public boolean hasUnsavedChanges();
- /**
- * Returns whether this buffer has been closed.
- *
- * @return a <code>boolean</code> indicating whether this buffer is closed.
- */
- public boolean isClosed();
- /**
- * Returns whether this buffer is read-only.
- *
- * @return a <code>boolean</code> indicating whether this buffer is read-only
- */
- public boolean isReadOnly();
- /**
- * Removes the given listener from this buffer.
- * Has no affect if an identical listener is not registered.
- *
- * @param listener the listener
- */
- public void removeBufferChangedListener(IBufferChangedListener listener);
- /**
- * Replaces the given range of characters in this buffer with the given text.
- * <code>position</code> and <code>position + length</code> must be in the range [0, getLength()].
- * <code>length</code> must not be negative.
- *
- * @param position the zero-based starting position of the affected text range in this buffer
- * @param length the length of the affected text range in this buffer
- * @param text the replacing text as a character array
- */
- public void replace(int position, int length, char[] text);
- /**
- * Replaces the given range of characters in this buffer with the given text.
- * <code>position</code> and <code>position + length</code> must be in the range [0, getLength()].
- * <code>length</code> must not be negative.
- *
- * @param position the zero-based starting position of the affected text range in this buffer
- * @param length the length of the affected text range in this buffer
- * @param text the replacing text as a <code>String</code>
- */
- public void replace(int position, int length, String text);
- /**
- * Saves the contents of this buffer to its underlying resource. If
- * successful, this buffer will have no unsaved changes.
- * The buffer is left open. Saving a buffer with no unsaved
- * changes has no effect - the underlying resource is not changed.
- * If the buffer does not have an underlying resource or is read-only, this
- * has no effect.
- * <p>
- * The <code>force</code> parameter controls how this method deals with
- * cases where the workbench is not completely in sync with the local file system.
- * If <code>false</code> is specified, this method will only attempt
- * to overwrite a corresponding file in the local file system provided
- * it is in sync with the workbench. This option ensures there is no
- * unintended data loss; it is the recommended setting.
- * However, if <code>true</code> is specified, an attempt will be made
- * to write a corresponding file in the local file system,
- * overwriting any existing one if need be.
- * In either case, if this method succeeds, the resource will be marked
- * as being local (even if it wasn't before).
- *
- * @param monitor the progress monitor to notify
- * @param force a <code> boolean </code> flag indicating how to deal with resource
- * inconsistencies.
- *
- * @exception JavaModelException if an error occurs writing the buffer
- * to the underlying resource
- *
- * @see org.eclipse.core.resources.IFile#setContents(InputStream, boolean, boolean, IProgressMonitor)
- */
- public void save(IProgressMonitor progress, boolean force)
- throws JavaModelException;
- /**
- * Sets the contents of this buffer to the given character array.
- * This buffer will now have unsaved changes.
- * Any client can set the contents of the buffer, not just the owner of the buffer.
- * Reports a buffer changed event.
- * <p>
- * Equivalent to <code>replace(0,getLength(),contents)</code>.
- * </p>
- *
- * <p>Has no effect if this buffer is read-only.
- *
- * @param contents the new contents of this buffer as a character array
- */
- public void setContents(char[] contents);
- /**
- * Sets the contents of this buffer to the given <code>String</code>.
- * This buffer will now have unsaved changes.
- * Any client can set the contents of the buffer, not just the owner of the buffer.
- * Reports a buffer changed event.
- * <p>
- * Equivalent to <code>replace(0,getLength(),contents)</code>.
- * </p>
- *
- * <p>Has no effect if this buffer is read-only.
- *
- * @param contents the new contents of this buffer as a <code>String</code>
- */
- public void setContents(String contents);
+
+/**
+ * Adds the given listener for changes to this buffer.
+ * Has no effect if an identical listener is already registered.
+ *
+ * @param listener the listener of buffer changes
+ */
+public void addBufferChangedListener(IBufferChangedListener listener);
+/**
+ * Appends the given character array to the contents of the buffer.
+ * This buffer will now have unsaved changes.
+ * Any client can append to the contents of the buffer, not just the owner of the buffer.
+ * Reports a buffer changed event.
+ *
+ * <p>Has no effect if this buffer is read-only.
+ *
+ * @param text the given character array to append to contents of the buffer
+ */
+public void append(char[] text);
+/**
+ * Appends the given string to the contents of the buffer.
+ * This buffer will now have unsaved changes.
+ * Any client can append to the contents of the buffer, not just the owner of the buffer.
+ * Reports a buffer changed event.
+ *
+ * <p>Has no effect if this buffer is read-only.
+ *
+ * @param text the <code>String</code> to append to the contents of the buffer
+ */
+public void append(String text);
+/**
+ * Closes the buffer. Any unsaved changes are lost. Reports a buffer changed event.
+ * Further operations on the buffer are not allowed, except for close. If an
+ * attempt is made to close an already closed buffer, the second attempt has no effect.
+ */
+public void close();
+/**
+ * Returns the character at the given position in this buffer.
+ *
+ * @param position a zero-based source offset in this buffer
+ * @return the character at the given position in this buffer
+ */
+public char getChar(int position);
+/**
+ * Returns the contents of this buffer as a character array.
+ * <p>
+ * Callers should make no assumption about whether the returned character array
+ * is or is not the genuine article or a copy. In other words, if the client
+ * wishes to change this array, they should make a copy. Likewise, if the
+ * client wishes to hang on to the array in its current state, they should
+ * make a copy.
+ * </p>
+ *
+ * @return the characters contained in this buffer
+ */
+public char[] getCharacters();
+/**
+ * Returns the contents of this buffer as a <code>String</code>. Like all strings,
+ * the result is an immutable value object.
+ *
+ * @return the contents of this buffer as a <code>String</code>
+ */
+public String getContents();
+/**
+ * Returns number of characters stored in this buffer.
+ *
+ * @return the number of characters in this buffer
+ */
+public int getLength();
+/**
+ * Returns the Java openable element owning of this buffer.
+ *
+ * @return the openable element owning this buffer
+ */
+public IOpenable getOwner();
+/**
+ * Returns the given range of text in this buffer.
+ *
+ * @param offset the zero-based starting offset
+ * @param length the number of characters to retrieve
+ * @return the given range of text in this buffer
+ */
+public String getText(int offset, int length);
+/**
+ * Returns the underlying resource for which this buffer was opened,
+ * or <code>null</code> if this buffer was not opened on a resource.
+ *
+ * @return the underlying resource for this buffer, or <code>null</code>
+ * if none.
+ */
+public IResource getUnderlyingResource();
+/**
+ * Returns whether this buffer has been modified since it
+ * was opened or since it was last saved.
+ * If a buffer does not have an underlying resource, this method always
+ * returns <code>true</code>.
+ *
+ * @return a <code>boolean</code> indicating presence of unsaved changes (in
+ * the absence of any underlying resource, it will always return <code>true</code>).
+ */
+public boolean hasUnsavedChanges();
+/**
+ * Returns whether this buffer has been closed.
+ *
+ * @return a <code>boolean</code> indicating whether this buffer is closed.
+ */
+public boolean isClosed();
+/**
+ * Returns whether this buffer is read-only.
+ *
+ * @return a <code>boolean</code> indicating whether this buffer is read-only
+ */
+public boolean isReadOnly();
+/**
+ * Removes the given listener from this buffer.
+ * Has no affect if an identical listener is not registered.
+ *
+ * @param listener the listener
+ */
+public void removeBufferChangedListener(IBufferChangedListener listener);
+/**
+ * Replaces the given range of characters in this buffer with the given text.
+ * <code>position</code> and <code>position + length</code> must be in the range [0, getLength()].
+ * <code>length</code> must not be negative.
+ *
+ * @param position the zero-based starting position of the affected text range in this buffer
+ * @param length the length of the affected text range in this buffer
+ * @param text the replacing text as a character array
+ */
+public void replace(int position, int length, char[] text);
+/**
+ * Replaces the given range of characters in this buffer with the given text.
+ * <code>position</code> and <code>position + length</code> must be in the range [0, getLength()].
+ * <code>length</code> must not be negative.
+ *
+ * @param position the zero-based starting position of the affected text range in this buffer
+ * @param length the length of the affected text range in this buffer
+ * @param text the replacing text as a <code>String</code>
+ */
+public void replace(int position, int length, String text);
+/**
+ * Saves the contents of this buffer to its underlying resource. If
+ * successful, this buffer will have no unsaved changes.
+ * The buffer is left open. Saving a buffer with no unsaved
+ * changes has no effect - the underlying resource is not changed.
+ * If the buffer does not have an underlying resource or is read-only, this
+ * has no effect.
+ * <p>
+ * The <code>force</code> parameter controls how this method deals with
+ * cases where the workbench is not completely in sync with the local file system.
+ * If <code>false</code> is specified, this method will only attempt
+ * to overwrite a corresponding file in the local file system provided
+ * it is in sync with the workbench. This option ensures there is no
+ * unintended data loss; it is the recommended setting.
+ * However, if <code>true</code> is specified, an attempt will be made
+ * to write a corresponding file in the local file system,
+ * overwriting any existing one if need be.
+ * In either case, if this method succeeds, the resource will be marked
+ * as being local (even if it wasn't before).
+ *
+ * @param monitor the progress monitor to notify
+ * @param force a <code> boolean </code> flag indicating how to deal with resource
+ * inconsistencies.
+ *
+ * @exception JavaModelException if an error occurs writing the buffer
+ * to the underlying resource
+ *
+ * @see org.eclipse.core.resources.IFile#setContents(InputStream, boolean, boolean, IProgressMonitor)
+ */
+public void save(IProgressMonitor progress, boolean force) throws JavaModelException;
+/**
+ * Sets the contents of this buffer to the given character array.
+ * This buffer will now have unsaved changes.
+ * Any client can set the contents of the buffer, not just the owner of the buffer.
+ * Reports a buffer changed event.
+ * <p>
+ * Equivalent to <code>replace(0,getLength(),contents)</code>.
+ * </p>
+ *
+ * <p>Has no effect if this buffer is read-only.
+ *
+ * @param contents the new contents of this buffer as a character array
+ */
+public void setContents(char[] contents);
+/**
+ * Sets the contents of this buffer to the given <code>String</code>.
+ * This buffer will now have unsaved changes.
+ * Any client can set the contents of the buffer, not just the owner of the buffer.
+ * Reports a buffer changed event.
+ * <p>
+ * Equivalent to <code>replace(0,getLength(),contents)</code>.
+ * </p>
+ *
+ * <p>Has no effect if this buffer is read-only.
+ *
+ * @param contents the new contents of this buffer as a <code>String</code>
+ */
+public void setContents(String contents);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IClassFile.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IClassFile.java
index e649ffcea0..12451debc4 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IClassFile.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IClassFile.java
@@ -1,49 +1,48 @@
package org.eclipse.jdt.core;
-public interface IClassFile
- extends IJavaElement, IParent, IOpenable, ISourceReference, ICodeAssist {
- /**
- * Returns the smallest element within this class file that
- * includes the given source position (a method, field, etc.), or
- * <code>null</code> if there is no element other than the class file
- * itself at the given position, or if the given position is not
- * within the source range of this class file.
- *
- * @param position a source position inside the class file
- * @return the innermost Java element enclosing a given source position or <code>null</code>
- * if none (excluding the class file).
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- IJavaElement getElementAt(int position) throws JavaModelException;
- /**
- * Returns the type contained in this class file.
- *
- * @return the type contained in this class file
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- IType getType() throws JavaModelException;
- /**
- * Returns whether this type represents a class. This is not guaranteed to be
- * instantaneous, as it may require parsing the underlying file.
- *
- * @return <code>true</code> if the class file represents a class.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- boolean isClass() throws JavaModelException;
- /**
- * Returns whether this type represents an interface. This is not guaranteed to
- * be instantaneous, as it may require parsing the underlying file.
- *
- * @return <code>true</code> if the class file represents an interface.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- boolean isInterface() throws JavaModelException;
+public interface IClassFile extends IJavaElement, IParent, IOpenable, ISourceReference, ICodeAssist {
+/**
+ * Returns the smallest element within this class file that
+ * includes the given source position (a method, field, etc.), or
+ * <code>null</code> if there is no element other than the class file
+ * itself at the given position, or if the given position is not
+ * within the source range of this class file.
+ *
+ * @param position a source position inside the class file
+ * @return the innermost Java element enclosing a given source position or <code>null</code>
+ * if none (excluding the class file).
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+IJavaElement getElementAt(int position) throws JavaModelException;
+/**
+ * Returns the type contained in this class file.
+ *
+ * @return the type contained in this class file
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+IType getType() throws JavaModelException;
+/**
+ * Returns whether this type represents a class. This is not guaranteed to be
+ * instantaneous, as it may require parsing the underlying file.
+ *
+ * @return <code>true</code> if the class file represents a class.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+boolean isClass() throws JavaModelException;
+/**
+ * Returns whether this type represents an interface. This is not guaranteed to
+ * be instantaneous, as it may require parsing the underlying file.
+ *
+ * @return <code>true</code> if the class file represents an interface.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+boolean isInterface() throws JavaModelException;
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IClasspathEntry.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IClasspathEntry.java
index 51847a64c3..16ff214f63 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IClasspathEntry.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IClasspathEntry.java
@@ -85,99 +85,99 @@ public interface IClasspathEntry {
* a path that begins with a classpath variable reference.
*/
public static final int CPE_VARIABLE = 4;
-
- /**
- * Returns the kind of files found in the package fragments identified by this
- * classpath entry.
- *
- * @return <code>IPackageFragmentRoot.K_SOURCE</code> for files containing
- * source code, and <code>IPackageFragmentRoot.K_BINARY</code> for binary
- * class files.
- * There is no specified value for an entry denoting a variable (<code>CPE_VARIABLE</code>)
- */
- int getContentKind();
- /**
- * Returns the kind of this classpath entry.
- *
- * @return one of:
- * <ul>
- * <li><code>CPE_SOURCE</code> - this entry describes a source root in
- its project
- * <li><code>CPE_LIBRARY</code> - this entry describes a folder or JAR
- containing binaries
- * <li><code>CPE_PROJECT</code> - this entry describes another project
- *
- * <li><code>CPE_VARIABLE</code> - this entry describes a project or library
- * indirectly via a classpath variable in the first segment of the path
- * </ul>
- */
- int getEntryKind();
- /**
- * Returns the path of this classpath entry.
- *
- * The meaning of the path of a classpath entry depends on its entry kind:<ul>
- * <li>Source code in the current project (<code>CPE_SOURCE</code>) -
- * The path associated with this entry is the absolute path to the root folder. </li>
- * <li>A binary library in the current project (<code>CPE_LIBRARY</code>) - the path
- * associated with this entry is the absolute path to the JAR (or root folder), and
- * in case it refers to an external JAR, then there is no associated resource in
- * the workbench.
- * <li>A required project (<code>CPE_PROJECT</code>) - the path of the entry denotes the
- * path to the corresponding project resource.</li>
- * <li>A variable entry (<code>CPE_VARIABLE</code>) - the first segment of the path
- * is the name of a classpath variable. If this classpath variable
- * is bound to the path <it>P</it>, the path of the corresponding classpath entry
- * is computed by appending to <it>P</it> the segments of the returned
- * path without the variable.</li>
- * </ul>
- *
- * @return the path of this classpath entry
- */
- IPath getPath();
- /**
- * This is a helper method which returns the resolved classpath entry denoted
- * by an entry (if it is a variable entry). It is obtained by resolving the variable
- * reference in the first segment. Returns <node>null</code> if unable to resolve using
- * the following algorithm:
- * <ul>
- * <li> if variable segment cannot be resolved, returns <code>null</code></li>
- * <li> finds a project, JAR or binary folder in the workspace at the resolved path location</li>
- * <li> if none finds an external JAR file or folder outside the workspace at the resolved path location </li>
- * <li> if none returns <code>null</code></li>
- * </ul>
- * <p>
- * Variable source attachment is also resolved and recorded in the resulting classpath entry.
- * <p>
- * @return the resolved library or project classpath entry, or <code>null</code>
- * if the given path could not be resolved to a classpath entry
- *
- * @deprecated - use JavaCore.getResolvedClasspathEntry(...)
- */
- IClasspathEntry getResolvedEntry();
- /**
- * Returns the path to the source archive associated with this
- * classpath entry, or <code>null</code> if this classpath entry has no
- * source attachment.
- * <p>
- * Only library and variable classpath entries may have source attachments.
- * For library classpath entries, the result path (if present) locates a source
- * archive. For variable classpath entries, the result path (if present) has
- * an analogous form and meaning as the variable path, namely the first segment
- * is the name of a classpath variable.
- * </p>
- *
- * @return the path to the source archive, or <code>null</code> if none
- */
- IPath getSourceAttachmentPath();
- /**
- * Returns the path within the source archive where package fragments
- * are located. An empty path indicates that packages are located at
- * the root of the source archive. Returns a non-<code>null</code> value
- * if and only if <code>getSourceAttachmentPath</code> returns
- * a non-<code>null</code> value.
- *
- * @return the path within the source archive, or <code>null</code> if
- * not applicable
- */
- IPath getSourceAttachmentRootPath();
+
+/**
+ * Returns the kind of files found in the package fragments identified by this
+ * classpath entry.
+ *
+ * @return <code>IPackageFragmentRoot.K_SOURCE</code> for files containing
+ * source code, and <code>IPackageFragmentRoot.K_BINARY</code> for binary
+ * class files.
+ * There is no specified value for an entry denoting a variable (<code>CPE_VARIABLE</code>)
+ */
+int getContentKind();
+/**
+ * Returns the kind of this classpath entry.
+ *
+ * @return one of:
+ * <ul>
+ * <li><code>CPE_SOURCE</code> - this entry describes a source root in
+ its project
+ * <li><code>CPE_LIBRARY</code> - this entry describes a folder or JAR
+ containing binaries
+ * <li><code>CPE_PROJECT</code> - this entry describes another project
+ *
+ * <li><code>CPE_VARIABLE</code> - this entry describes a project or library
+ * indirectly via a classpath variable in the first segment of the path
+ * </ul>
+ */
+int getEntryKind();
+/**
+ * Returns the path of this classpath entry.
+ *
+ * The meaning of the path of a classpath entry depends on its entry kind:<ul>
+ * <li>Source code in the current project (<code>CPE_SOURCE</code>) -
+ * The path associated with this entry is the absolute path to the root folder. </li>
+ * <li>A binary library in the current project (<code>CPE_LIBRARY</code>) - the path
+ * associated with this entry is the absolute path to the JAR (or root folder), and
+ * in case it refers to an external JAR, then there is no associated resource in
+ * the workbench.
+ * <li>A required project (<code>CPE_PROJECT</code>) - the path of the entry denotes the
+ * path to the corresponding project resource.</li>
+ * <li>A variable entry (<code>CPE_VARIABLE</code>) - the first segment of the path
+ * is the name of a classpath variable. If this classpath variable
+ * is bound to the path <it>P</it>, the path of the corresponding classpath entry
+ * is computed by appending to <it>P</it> the segments of the returned
+ * path without the variable.</li>
+ * </ul>
+ *
+ * @return the path of this classpath entry
+ */
+IPath getPath();
+/**
+ * This is a helper method which returns the resolved classpath entry denoted
+ * by an entry (if it is a variable entry). It is obtained by resolving the variable
+ * reference in the first segment. Returns <node>null</code> if unable to resolve using
+ * the following algorithm:
+ * <ul>
+ * <li> if variable segment cannot be resolved, returns <code>null</code></li>
+ * <li> finds a project, JAR or binary folder in the workspace at the resolved path location</li>
+ * <li> if none finds an external JAR file or folder outside the workspace at the resolved path location </li>
+ * <li> if none returns <code>null</code></li>
+ * </ul>
+ * <p>
+ * Variable source attachment is also resolved and recorded in the resulting classpath entry.
+ * <p>
+ * @return the resolved library or project classpath entry, or <code>null</code>
+ * if the given path could not be resolved to a classpath entry
+ *
+ * @deprecated - use JavaCore.getResolvedClasspathEntry(...)
+ */
+IClasspathEntry getResolvedEntry();
+/**
+ * Returns the path to the source archive associated with this
+ * classpath entry, or <code>null</code> if this classpath entry has no
+ * source attachment.
+ * <p>
+ * Only library and variable classpath entries may have source attachments.
+ * For library classpath entries, the result path (if present) locates a source
+ * archive. For variable classpath entries, the result path (if present) has
+ * an analogous form and meaning as the variable path, namely the first segment
+ * is the name of a classpath variable.
+ * </p>
+ *
+ * @return the path to the source archive, or <code>null</code> if none
+ */
+IPath getSourceAttachmentPath();
+/**
+ * Returns the path within the source archive where package fragments
+ * are located. An empty path indicates that packages are located at
+ * the root of the source archive. Returns a non-<code>null</code> value
+ * if and only if <code>getSourceAttachmentPath</code> returns
+ * a non-<code>null</code> value.
+ *
+ * @return the path within the source archive, or <code>null</code> if
+ * not applicable
+ */
+IPath getSourceAttachmentRootPath();
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ICodeAssist.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ICodeAssist.java
index 4b2615b749..921f25c173 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ICodeAssist.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ICodeAssist.java
@@ -1,35 +1,34 @@
package org.eclipse.jdt.core;
public interface ICodeAssist {
- /**
- * Performs code completion at the given offset position in this compilation unit,
- * reporting results to the given completion requestor. The <code>offset</code>
- * is the 0-based index of the character, after which code assist is desired.
- * An <code>offset</code> of -1 indicates to code assist at the beginning of this
- * compilation unit.
- *
- * @exception JavaModelException if code assist could not be performed. Reasons include:<ul>
- * <li>This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> The position specified is < -1 or is greater than this compilation unit's
- * source length (INDEX_OUT_OF_BOUNDS)
- * </ul>
- *
- * @exception IllegalArgumentException if <code>requestor</code> is <code>null</code>
- */
- void codeComplete(int offset, ICodeCompletionRequestor requestor)
- throws JavaModelException;
- /**
- * Performs code selection on the given selected text in this compilation unit,
- * reporting results to the given selection requestor. The <code>offset</code>
- * is the 0-based index of the first selected character. The <code>length</code>
- * is the number of selected characters.
- *
- * @exception JavaModelException if code resolve could not be performed. Reasons include:
- * <li>This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> The range specified is not within this element's
- * source range (INDEX_OUT_OF_BOUNDS)
- * </ul>
- *
- */
- IJavaElement[] codeSelect(int offset, int length) throws JavaModelException;
+/**
+ * Performs code completion at the given offset position in this compilation unit,
+ * reporting results to the given completion requestor. The <code>offset</code>
+ * is the 0-based index of the character, after which code assist is desired.
+ * An <code>offset</code> of -1 indicates to code assist at the beginning of this
+ * compilation unit.
+ *
+ * @exception JavaModelException if code assist could not be performed. Reasons include:<ul>
+ * <li>This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> The position specified is < -1 or is greater than this compilation unit's
+ * source length (INDEX_OUT_OF_BOUNDS)
+ * </ul>
+ *
+ * @exception IllegalArgumentException if <code>requestor</code> is <code>null</code>
+ */
+ void codeComplete(int offset, ICodeCompletionRequestor requestor) throws JavaModelException;
+/**
+ * Performs code selection on the given selected text in this compilation unit,
+ * reporting results to the given selection requestor. The <code>offset</code>
+ * is the 0-based index of the first selected character. The <code>length</code>
+ * is the number of selected characters.
+ *
+ * @exception JavaModelException if code resolve could not be performed. Reasons include:
+ * <li>This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> The range specified is not within this element's
+ * source range (INDEX_OUT_OF_BOUNDS)
+ * </ul>
+ *
+ */
+IJavaElement[] codeSelect(int offset, int length) throws JavaModelException;
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ICodeCompletionRequestor.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ICodeCompletionRequestor.java
index cbb150baf2..6fcfe3dd50 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ICodeCompletionRequestor.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ICodeCompletionRequestor.java
@@ -16,248 +16,245 @@ import org.eclipse.core.resources.IMarker;
* @see ICodeAssist
*/
public interface ICodeCompletionRequestor {
- /**
- * Code assist notification of a class completion.
- *
- * @return void - Nothing is answered back to code assist engine
- *
- * @param packageName char[] - Declaring package name of the class.
- * @param className char[] - Name of the class.
- * @param completionName char[] - The completion for the class.
- * Can include ';' for imported classes.
- * @param modifiers int - The modifiers of the class.
- * @param completionStart int - The start position of insertion of the name of the class.
- * @param completionEnd int - The end position of insertion of the name of the class.
- *
- * NOTE - All package and type names are presented in their readable form:
- * Package names are in the form "a.b.c".
- * Nested type names are in the qualified form "A.M".
- * The default package is represented by an empty array.
- */
- void acceptClass(
- char[] packageName,
- char[] className,
- char[] completionName,
- int modifiers,
- int completionStart,
- int completionEnd);
- /**
- * Code assist notification of a compilation error detected during completion.
- *
- * @return void - Nothing is answered back.
- *
- * @param error org.eclipse.core.resources.IMarker
- * Only problems which are categorized as errors are notified to the requestor,
- * warnings are silently ignored.
- * In case an error got signaled, no other completions might be available,
- * therefore the problem message should be presented to the user.
- * The source positions of the problem are related to the source where it was
- * detected (might be in another compilation unit, if it was indirectly requested
- * during the code assist process).
- * Note: the problem knows its originating file name.
- */
- void acceptError(IMarker marker);
- /**
- * Code assist notification of a field completion.
- *
- * @return void - Nothing is answered back to code assist engine
- *
- * @param declaringTypePackageName char[] - Name of the package in which the type that contains this field is declared.
- * @param declaringTypeName char[] - Name of the type declaring this new field.
- * @param name char[] - Name of the field.
- * @param typePackageName char[] - Name of the package in which the type of this field is declared.
- * @param typeName char[] - Name of the type of this field.
- * @param completionName char[] - The completion for the field.
- * @param modifiers int - The modifiers of this field.
- * @param completionStart int - The start position of insertion of the name of this field.
- * @param completionEnd int - The end position of insertion of the name of this field.
- * @see com.ibm.compiler.java.ast.Modifiers
- *
- * NOTE - All package and type names are presented in their readable form:
- * Package names are in the form "a.b.c".
- * Base types are in the form "int" or "boolean".
- * Array types are in the qualified form "M[]" or "int[]".
- * Nested type names are in the qualified form "A.M".
- * The default package is represented by an empty array.
- */
- void acceptField(
- char[] declaringTypePackageName,
- char[] declaringTypeName,
- char[] name,
- char[] typePackageName,
- char[] typeName,
- char[] completionName,
- int modifiers,
- int completionStart,
- int completionEnd);
- /**
- * Code assist notification of an interface completion.
- *
- * @return void - Nothing is answered back to code assist engine
- *
- * @param packageName char[] - Declaring package name of the interface.
- * @param className char[] - Name of the interface.
- * @param completionName char[] - The completion for the interface.
- * Can include ';' for imported interfaces.
- * @param modifiers int - The modifiers of the interface.
- * @param completionStart int - The start position of insertion of the name of the interface.
- * @param completionEnd int - The end position of insertion of the name of the interface.
- *
- * NOTE - All package and type names are presented in their readable form:
- * Package names are in the form "a.b.c".
- * Nested type names are in the qualified form "A.M".
- * The default package is represented by an empty array.
- */
- void acceptInterface(
- char[] packageName,
- char[] interfaceName,
- char[] completionName,
- int modifiers,
- int completionStart,
- int completionEnd);
- /**
- * Code assist notification of a keyword completion.
- *
- * @return void - Nothing is answered back to code assist engine
- *
- * @param keywordName char[] - The keyword source.
- * @param completionStart int - The start position of insertion of the name of this keyword.
- * @param completionEnd int - The end position of insertion of the name of this keyword.
- */
- void acceptKeyword(char[] keywordName, int completionStart, int completionEnd);
- /**
- * Code assist notification of a label completion.
- *
- * @return void - Nothing is answered back to code assist engine
- *
- * @param labelName char[] - The label source.
- * @param completionStart int - The start position of insertion of the name of this label.
- * @param completionEnd int - The end position of insertion of the name of this label.
- */
- void acceptLabel(char[] labelName, int completionStart, int completionEnd);
- /**
- * Code assist notification of a local variable completion.
- *
- * @return void - Nothing is answered back to code assist engine
- *
- * @param name char[] - Name of the new local variable.
- * @param typePackageName char[] - Name of the package in which the type of this new local variable is declared.
- * @param typeName char[] - Name of the type of this new local variable.
- * @param modifiers int - The modifiers of this new local variable.
- * @param completionStart int - The start position of insertion of the name of this new local variable.
- * @param completionEnd int - The end position of insertion of the name of this new local variable.
- * @see com.ibm.compiler.java.ast.Modifiers
- *
- * NOTE - All package and type names are presented in their readable form:
- * Package names are in the form "a.b.c".
- * Base types are in the form "int" or "boolean".
- * Array types are in the qualified form "M[]" or "int[]".
- * Nested type names are in the qualified form "A.M".
- * The default package is represented by an empty array.
- */
- void acceptLocalVariable(
- char[] name,
- char[] typePackageName,
- char[] typeName,
- int modifiers,
- int completionStart,
- int completionEnd);
- /**
- * Code assist notification of a method completion.
- *
- * @return void - Nothing is answered back to code assist engine
- *
- * @param declaringTypePackageName char[] - Name of the package in which the type that contains this new method is declared.
- * @param declaringTypeName char[] - Name of the type declaring this new method.
- * @param selector char[] - Name of the new method.
- * @param parameterPackageNames char[][] - Names of the packages in which the parameter types are declared.
- * Should contain as many elements as parameterTypeNames.
- * @param parameterTypeNames char[][] - Names of the parameters types.
- * Should contain as many elements as parameterPackageNames.
- * @param returnTypePackageName char[] - Name of the package in which the return type is declared.
- * @param returnTypeName char[] - Name of the return type of this new method, should be <code>null</code> for a constructor.
- * @param completionName char[] - The completion for the method.
- * Can include zero, one or two brackets. If the closing bracket is included, then the cursor should be placed before it.
- * @param modifiers int - The modifiers of this new method.
- * @param completionStart int - The start position of insertion of the name of this new method.
- * @param completionEnd int - The end position of insertion of the name of this new method.
- * @see com.ibm.compiler.java.ast.Modifiers
- *
- * NOTE - All package and type names are presented in their readable form:
- * Package names are in the form "a.b.c".
- * Base types are in the form "int" or "boolean".
- * Array types are in the qualified form "M[]" or "int[]".
- * Nested type names are in the qualified form "A.M".
- * The default package is represented by an empty array.
- *
- * NOTE: parameter names can be retrieved from the source model after the user selects a specific method.
- */
- void acceptMethod(
- char[] declaringTypePackageName,
- char[] declaringTypeName,
- char[] selector,
- char[][] parameterPackageNames,
- char[][] parameterTypeNames,
- char[] returnTypePackageName,
- char[] returnTypeName,
- char[] completionName,
- int modifiers,
- int completionStart,
- int completionEnd);
- /**
- * Code assist notification of a modifier completion.
- *
- * @return void - Nothing is answered back to code assist engine
- *
- * @param modifierName char[] - The new modifier.
- * @param completionStart int - The start position of insertion of the name of this new modifier.
- * @param completionEnd int - The end position of insertion of the name of this new modifier.
- */
- void acceptModifier(
- char[] modifierName,
- int completionStart,
- int completionEnd);
- /**
- * Code assist notification of a package completion.
- *
- * @return void - Nothing is answered back to code assist engine
- *
- * @param packageName char[] - The package name.
- * @param completionName char[] - The completion for the package.
- * Can include '.*;' for imports.
- * @param completionStart int - The start position of insertion of the name of this new package.
- * @param completionEnd int - The end position of insertion of the name of this new package.
- *
- * NOTE - All package names are presented in their readable form:
- * Package names are in the form "a.b.c".
- * The default package is represented by an empty array.
- */
- void acceptPackage(
- char[] packageName,
- char[] completionName,
- int completionStart,
- int completionEnd);
- /**
- * Code assist notification of a type completion.
- *
- * @return void - Nothing is answered back to code assist engine
- *
- * @param packageName char[] - Declaring package name of the type.
- * @param typeName char[] - Name of the type.
- * @param completionName char[] - The completion for the type.
- * Can include ';' for imported types.
- * @param completionStart int - The start position of insertion of the name of the type.
- * @param completionEnd int - The end position of insertion of the name of the type.
- *
- * NOTE - All package and type names are presented in their readable form:
- * Package names are in the form "a.b.c".
- * Nested type names are in the qualified form "A.M".
- * The default package is represented by an empty array.
- */
- void acceptType(
- char[] packageName,
- char[] typeName,
- char[] completionName,
- int completionStart,
- int completionEnd);
+/**
+ * Code assist notification of a class completion.
+ *
+ * @return void - Nothing is answered back to code assist engine
+ *
+ * @param packageName char[] - Declaring package name of the class.
+ * @param className char[] - Name of the class.
+ * @param completionName char[] - The completion for the class.
+ * Can include ';' for imported classes.
+ * @param modifiers int - The modifiers of the class.
+ * @param completionStart int - The start position of insertion of the name of the class.
+ * @param completionEnd int - The end position of insertion of the name of the class.
+ *
+ * NOTE - All package and type names are presented in their readable form:
+ * Package names are in the form "a.b.c".
+ * Nested type names are in the qualified form "A.M".
+ * The default package is represented by an empty array.
+ */
+void acceptClass(
+ char[] packageName,
+ char[] className,
+ char[] completionName,
+ int modifiers,
+ int completionStart,
+ int completionEnd);
+/**
+ * Code assist notification of a compilation error detected during completion.
+ *
+ * @return void - Nothing is answered back.
+ *
+ * @param error org.eclipse.core.resources.IMarker
+ * Only problems which are categorized as errors are notified to the requestor,
+ * warnings are silently ignored.
+ * In case an error got signaled, no other completions might be available,
+ * therefore the problem message should be presented to the user.
+ * The source positions of the problem are related to the source where it was
+ * detected (might be in another compilation unit, if it was indirectly requested
+ * during the code assist process).
+ * Note: the problem knows its originating file name.
+ */
+void acceptError(IMarker marker);
+/**
+ * Code assist notification of a field completion.
+ *
+ * @return void - Nothing is answered back to code assist engine
+ *
+ * @param declaringTypePackageName char[] - Name of the package in which the type that contains this field is declared.
+ * @param declaringTypeName char[] - Name of the type declaring this new field.
+ * @param name char[] - Name of the field.
+ * @param typePackageName char[] - Name of the package in which the type of this field is declared.
+ * @param typeName char[] - Name of the type of this field.
+ * @param completionName char[] - The completion for the field.
+ * @param modifiers int - The modifiers of this field.
+ * @param completionStart int - The start position of insertion of the name of this field.
+ * @param completionEnd int - The end position of insertion of the name of this field.
+ * @see com.ibm.compiler.java.ast.Modifiers
+ *
+ * NOTE - All package and type names are presented in their readable form:
+ * Package names are in the form "a.b.c".
+ * Base types are in the form "int" or "boolean".
+ * Array types are in the qualified form "M[]" or "int[]".
+ * Nested type names are in the qualified form "A.M".
+ * The default package is represented by an empty array.
+ */
+void acceptField(
+ char[] declaringTypePackageName,
+ char[] declaringTypeName,
+ char[] name,
+ char[] typePackageName,
+ char[] typeName,
+ char[] completionName,
+ int modifiers,
+ int completionStart,
+ int completionEnd);
+/**
+ * Code assist notification of an interface completion.
+ *
+ * @return void - Nothing is answered back to code assist engine
+ *
+ * @param packageName char[] - Declaring package name of the interface.
+ * @param className char[] - Name of the interface.
+ * @param completionName char[] - The completion for the interface.
+ * Can include ';' for imported interfaces.
+ * @param modifiers int - The modifiers of the interface.
+ * @param completionStart int - The start position of insertion of the name of the interface.
+ * @param completionEnd int - The end position of insertion of the name of the interface.
+ *
+ * NOTE - All package and type names are presented in their readable form:
+ * Package names are in the form "a.b.c".
+ * Nested type names are in the qualified form "A.M".
+ * The default package is represented by an empty array.
+ */
+void acceptInterface(
+ char[] packageName,
+ char[] interfaceName,
+ char[] completionName,
+ int modifiers,
+ int completionStart,
+ int completionEnd);
+/**
+ * Code assist notification of a keyword completion.
+ *
+ * @return void - Nothing is answered back to code assist engine
+ *
+ * @param keywordName char[] - The keyword source.
+ * @param completionStart int - The start position of insertion of the name of this keyword.
+ * @param completionEnd int - The end position of insertion of the name of this keyword.
+ */
+void acceptKeyword(char[] keywordName, int completionStart, int completionEnd);
+/**
+ * Code assist notification of a label completion.
+ *
+ * @return void - Nothing is answered back to code assist engine
+ *
+ * @param labelName char[] - The label source.
+ * @param completionStart int - The start position of insertion of the name of this label.
+ * @param completionEnd int - The end position of insertion of the name of this label.
+ */
+void acceptLabel(char[] labelName, int completionStart, int completionEnd);
+/**
+ * Code assist notification of a local variable completion.
+ *
+ * @return void - Nothing is answered back to code assist engine
+ *
+ * @param name char[] - Name of the new local variable.
+ * @param typePackageName char[] - Name of the package in which the type of this new local variable is declared.
+ * @param typeName char[] - Name of the type of this new local variable.
+ * @param modifiers int - The modifiers of this new local variable.
+ * @param completionStart int - The start position of insertion of the name of this new local variable.
+ * @param completionEnd int - The end position of insertion of the name of this new local variable.
+ * @see com.ibm.compiler.java.ast.Modifiers
+ *
+ * NOTE - All package and type names are presented in their readable form:
+ * Package names are in the form "a.b.c".
+ * Base types are in the form "int" or "boolean".
+ * Array types are in the qualified form "M[]" or "int[]".
+ * Nested type names are in the qualified form "A.M".
+ * The default package is represented by an empty array.
+ */
+void acceptLocalVariable(
+ char[] name,
+ char[] typePackageName,
+ char[] typeName,
+ int modifiers,
+ int completionStart,
+ int completionEnd);
+/**
+ * Code assist notification of a method completion.
+ *
+ * @return void - Nothing is answered back to code assist engine
+ *
+ * @param declaringTypePackageName char[] - Name of the package in which the type that contains this new method is declared.
+ * @param declaringTypeName char[] - Name of the type declaring this new method.
+ * @param selector char[] - Name of the new method.
+ * @param parameterPackageNames char[][] - Names of the packages in which the parameter types are declared.
+ * Should contain as many elements as parameterTypeNames.
+ * @param parameterTypeNames char[][] - Names of the parameters types.
+ * Should contain as many elements as parameterPackageNames.
+ * @param returnTypePackageName char[] - Name of the package in which the return type is declared.
+ * @param returnTypeName char[] - Name of the return type of this new method, should be <code>null</code> for a constructor.
+ * @param completionName char[] - The completion for the method.
+ * Can include zero, one or two brackets. If the closing bracket is included, then the cursor should be placed before it.
+ * @param modifiers int - The modifiers of this new method.
+ * @param completionStart int - The start position of insertion of the name of this new method.
+ * @param completionEnd int - The end position of insertion of the name of this new method.
+ * @see com.ibm.compiler.java.ast.Modifiers
+ *
+ * NOTE - All package and type names are presented in their readable form:
+ * Package names are in the form "a.b.c".
+ * Base types are in the form "int" or "boolean".
+ * Array types are in the qualified form "M[]" or "int[]".
+ * Nested type names are in the qualified form "A.M".
+ * The default package is represented by an empty array.
+ *
+ * NOTE: parameter names can be retrieved from the source model after the user selects a specific method.
+ */
+void acceptMethod(
+ char[] declaringTypePackageName,
+ char[] declaringTypeName,
+ char[] selector,
+ char[][] parameterPackageNames,
+ char[][] parameterTypeNames,
+ char[] returnTypePackageName,
+ char[] returnTypeName,
+ char[] completionName,
+ int modifiers,
+ int completionStart,
+ int completionEnd);
+/**
+ * Code assist notification of a modifier completion.
+ *
+ * @return void - Nothing is answered back to code assist engine
+ *
+ * @param modifierName char[] - The new modifier.
+ * @param completionStart int - The start position of insertion of the name of this new modifier.
+ * @param completionEnd int - The end position of insertion of the name of this new modifier.
+ */
+void acceptModifier(char[] modifierName, int completionStart, int completionEnd);
+/**
+ * Code assist notification of a package completion.
+ *
+ * @return void - Nothing is answered back to code assist engine
+ *
+ * @param packageName char[] - The package name.
+ * @param completionName char[] - The completion for the package.
+ * Can include '.*;' for imports.
+ * @param completionStart int - The start position of insertion of the name of this new package.
+ * @param completionEnd int - The end position of insertion of the name of this new package.
+ *
+ * NOTE - All package names are presented in their readable form:
+ * Package names are in the form "a.b.c".
+ * The default package is represented by an empty array.
+ */
+void acceptPackage(
+ char[] packageName,
+ char[] completionName,
+ int completionStart,
+ int completionEnd);
+/**
+ * Code assist notification of a type completion.
+ *
+ * @return void - Nothing is answered back to code assist engine
+ *
+ * @param packageName char[] - Declaring package name of the type.
+ * @param typeName char[] - Name of the type.
+ * @param completionName char[] - The completion for the type.
+ * Can include ';' for imported types.
+ * @param completionStart int - The start position of insertion of the name of the type.
+ * @param completionEnd int - The end position of insertion of the name of the type.
+ *
+ * NOTE - All package and type names are presented in their readable form:
+ * Package names are in the form "a.b.c".
+ * Nested type names are in the qualified form "A.M".
+ * The default package is represented by an empty array.
+ */
+void acceptType(
+ char[] packageName,
+ char[] typeName,
+ char[] completionName,
+ int completionStart,
+ int completionEnd);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ICompilationUnit.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ICompilationUnit.java
index 59d0537e24..9ee55c405a 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ICompilationUnit.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ICompilationUnit.java
@@ -19,202 +19,182 @@ import org.eclipse.core.runtime.IProgressMonitor;
* This interface is not intended to be implemented by clients.
* </p>
*/
-public interface ICompilationUnit
- extends
- IJavaElement,
- ISourceReference,
- IParent,
- IOpenable,
- IWorkingCopy,
- ISourceManipulation,
- ICodeAssist {
- /**
- * Creates and returns an import declaration in this compilation unit
- * with the given name.
- * <p>
- * Optionally, the new element can be positioned before the specified
- * sibling. If no sibling is specified, the element will be inserted
- * as the last import declaration in this compilation unit.
- * <p>
- * If the compilation unit already includes the specified import declaration,
- * the import is not generated (it does not generate duplicates).
- * Note that it is valid to specify both a single-type import and an on-demand import
- * for the same package, for example <code>"java.io.File"</code> and
- * <code>"java.io.*"</code>, in which case both are preserved since the semantics
- * of this are not the same as just importing <code>"java.io.*"</code>.
- * Importing <code>"java.lang.*"</code>, or the package in which the compilation unit
- * is defined, are not treated as special cases. If they are specified, they are
- * included in the result.
- *
- * @param name the name of the import declaration to add as defined by JLS2 7.5. (For example: <code>"java.io.File"</code> or
- * <code>"java.awt.*"</code>)
- * @param sibling the existing element which the import declaration will be inserted immediately before (if
- * <code> null </code>, then this import will be inserted as the last import declaration.
- * @param monitor the progress monitor to notify
- * @return the newly inserted import declaration (or the previously existing one in case attempting to create a duplicate)
- *
- * @exception JavaModelException if the element could not be created. Reasons include:
- * <ul>
- * <li> This Java element does not exist or the specified sibling does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> The specified sibling is not a child of this compilation unit (INVALID_SIBLING)
- * <li> The name is not a valid import name (INVALID_NAME)
- * </ul>
- */
- IImportDeclaration createImport(
- String name,
- IJavaElement sibling,
- IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Creates and returns a package declaration in this compilation unit
- * with the given package name.
- *
- * <p>If the compilation unit already includes the specified package declaration,
- * it is not generated (it does not generate duplicates).
- *
- * @param name the name of the package declaration to add as defined by JLS2 7.4. (For example, <code>"java.lang"</code>)
- * @param monitor the progress monitor to notify
- * @return the newly inserted package declaration (or the previously existing one in case attempting to create a duplicate)
- *
- * @exception JavaModelException if the element could not be created. Reasons include:
- * <ul>
- * <li>This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> The name is not a valid package name (INVALID_NAME)
- * </ul>
- */
- IPackageDeclaration createPackageDeclaration(
- String name,
- IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Creates and returns a type in this compilation unit with the
- * given contents. If this compilation unit does not exist, one
- * will be created with an appropriate package declaration.
- * <p>
- * Optionally, the new type can be positioned before the specified
- * sibling. If <code>sibling</code> is <code>null</code>, the type will be appended
- * to the end of this compilation unit.
- *
- * <p>It is possible that a type with the same name already exists in this compilation unit.
- * The value of the <code>force</code> parameter effects the resolution of
- * such a conflict:<ul>
- * <li> <code>true</code> - in this case the type is created with the new contents</li>
- * <li> <code>false</code> - in this case a <code>JavaModelException</code> is thrown</li>
- * </ul>
- *
- * @param contents the source contents of the type declaration to add.
- * @param sibling the existing element which the type will be inserted immediately before (if
- * <code> null </code>, then this type will be inserted as the last type declaration.
- * @param force a <code> boolean </code> flag indicating how to deal with duplicates
- * @param monitor the progress monitor to notify
- * @return the newly inserted type
- *
- * @exception JavaModelException if the element could not be created. Reasons include:
- * <ul>
- * <li>The specified sibling element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> The specified sibling is not a child of this compilation unit (INVALID_SIBLING)
- * <li> The contents could not be recognized as a type declaration (INVALID_CONTENTS)
- * <li> There was a naming collision with an existing type (NAME_COLLISION)
- * </ul>
- */
- IType createType(
- String contents,
- IJavaElement sibling,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Returns all types declared in this compilation unit in the order
- * in which they appear in the source.
- * This includes all top-level types and nested member types.
- * It does NOT include local types (types defined in methods).
- *
- * @return the array of toplevel and member types defined in a compilation unit, in declaration order.
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- IType[] getAllTypes() throws JavaModelException;
- /**
- * Returns the smallest element within this compilation unit that
- * includes the given source position (that is, a method, field, etc.), or
- * <code>null</code> if there is no element other than the compilation
- * unit itself at the given position, or if the given position is not
- * within the source range of this compilation unit.
- *
- * @param position a source position inside the compilation unit
- * @return the innermost Java element enclosing a given source position or <code>null</code>
- * if none (excluding the compilation unit).
- * @exception JavaModelException if the compilation unit does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- IJavaElement getElementAt(int position) throws JavaModelException;
- /**
- * Returns the first import declaration in this compilation unit with the given name.
- * This is a handle-only method. The import declaration may or may not exist. This
- * is a convenience method - imports can also be accessed from a compilation unit's
- * import container.
- *
- * @param the name of the import to find as defined by JLS2 7.5. (For example: <code>"java.io.File"</code>
- * or <code>"java.awt.*"</code>)
- * @return a handle onto the corresponding import declaration. The import declaration may or may not exist.
- */
- IImportDeclaration getImport(String name);
- /**
- * Returns the import container for this compilation unit.
- * This is a handle-only method. The import container may or
- * may not exist. The import container can used to access the
- * imports.
- *
- * @return a handle onto the corresponding import container. The
- * import contain may or may not exist.
- */
- IImportContainer getImportContainer();
- /**
- * Returns the import declarations in this compilation unit
- * in the order in which they appear in the source. This is
- * a convenience method - import declarations can also be
- * accessed from a compilation unit's import container.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- IImportDeclaration[] getImports() throws JavaModelException;
- /**
- * Returns the first package declaration in this compilation unit with the given package name
- * (there normally is at most one package declaration).
- * This is a handle-only method. The package declaration may or may not exist.
- *
- * @param name the name of the package declaration as defined by JLS2 7.4. (For example, <code>"java.lang"</code>)
- */
- IPackageDeclaration getPackageDeclaration(String name);
- /**
- * Returns the package declarations in this compilation unit
- * in the order in which they appear in the source.
- * There normally is at most one package declaration.
- *
- * @return an array of package declaration (normally of size one)
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- IPackageDeclaration[] getPackageDeclarations() throws JavaModelException;
- /**
- * Returns the top-level type declared in this compilation unit with the given simple type name.
- * This is a handle-only method. The type may or may not exist.
- *
- * @param name the simple name of the requested type in the compilation unit
- * @return a handle onto the corresponding type. The type may or may not exist.
- */
- IType getType(String name);
- /**
- * Returns the top-level types declared in this compilation unit
- * in the order in which they appear in the source.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- IType[] getTypes() throws JavaModelException;
+public interface ICompilationUnit extends IJavaElement, ISourceReference, IParent, IOpenable, IWorkingCopy, ISourceManipulation, ICodeAssist {
+/**
+ * Creates and returns an import declaration in this compilation unit
+ * with the given name.
+ * <p>
+ * Optionally, the new element can be positioned before the specified
+ * sibling. If no sibling is specified, the element will be inserted
+ * as the last import declaration in this compilation unit.
+ * <p>
+ * If the compilation unit already includes the specified import declaration,
+ * the import is not generated (it does not generate duplicates).
+ * Note that it is valid to specify both a single-type import and an on-demand import
+ * for the same package, for example <code>"java.io.File"</code> and
+ * <code>"java.io.*"</code>, in which case both are preserved since the semantics
+ * of this are not the same as just importing <code>"java.io.*"</code>.
+ * Importing <code>"java.lang.*"</code>, or the package in which the compilation unit
+ * is defined, are not treated as special cases. If they are specified, they are
+ * included in the result.
+ *
+ * @param name the name of the import declaration to add as defined by JLS2 7.5. (For example: <code>"java.io.File"</code> or
+ * <code>"java.awt.*"</code>)
+ * @param sibling the existing element which the import declaration will be inserted immediately before (if
+ * <code> null </code>, then this import will be inserted as the last import declaration.
+ * @param monitor the progress monitor to notify
+ * @return the newly inserted import declaration (or the previously existing one in case attempting to create a duplicate)
+ *
+ * @exception JavaModelException if the element could not be created. Reasons include:
+ * <ul>
+ * <li> This Java element does not exist or the specified sibling does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> A <code>CoreException</code> occurred while updating an underlying resource
+ * <li> The specified sibling is not a child of this compilation unit (INVALID_SIBLING)
+ * <li> The name is not a valid import name (INVALID_NAME)
+ * </ul>
+ */
+IImportDeclaration createImport(String name, IJavaElement sibling, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Creates and returns a package declaration in this compilation unit
+ * with the given package name.
+ *
+ * <p>If the compilation unit already includes the specified package declaration,
+ * it is not generated (it does not generate duplicates).
+ *
+ * @param name the name of the package declaration to add as defined by JLS2 7.4. (For example, <code>"java.lang"</code>)
+ * @param monitor the progress monitor to notify
+ * @return the newly inserted package declaration (or the previously existing one in case attempting to create a duplicate)
+ *
+ * @exception JavaModelException if the element could not be created. Reasons include:
+ * <ul>
+ * <li>This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> A <code>CoreException</code> occurred while updating an underlying resource
+ * <li> The name is not a valid package name (INVALID_NAME)
+ * </ul>
+ */
+ IPackageDeclaration createPackageDeclaration(String name, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Creates and returns a type in this compilation unit with the
+ * given contents. If this compilation unit does not exist, one
+ * will be created with an appropriate package declaration.
+ * <p>
+ * Optionally, the new type can be positioned before the specified
+ * sibling. If <code>sibling</code> is <code>null</code>, the type will be appended
+ * to the end of this compilation unit.
+ *
+ * <p>It is possible that a type with the same name already exists in this compilation unit.
+ * The value of the <code>force</code> parameter effects the resolution of
+ * such a conflict:<ul>
+ * <li> <code>true</code> - in this case the type is created with the new contents</li>
+ * <li> <code>false</code> - in this case a <code>JavaModelException</code> is thrown</li>
+ * </ul>
+ *
+ * @param contents the source contents of the type declaration to add.
+ * @param sibling the existing element which the type will be inserted immediately before (if
+ * <code> null </code>, then this type will be inserted as the last type declaration.
+ * @param force a <code> boolean </code> flag indicating how to deal with duplicates
+ * @param monitor the progress monitor to notify
+ * @return the newly inserted type
+ *
+ * @exception JavaModelException if the element could not be created. Reasons include:
+ * <ul>
+ * <li>The specified sibling element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> A <code>CoreException</code> occurred while updating an underlying resource
+ * <li> The specified sibling is not a child of this compilation unit (INVALID_SIBLING)
+ * <li> The contents could not be recognized as a type declaration (INVALID_CONTENTS)
+ * <li> There was a naming collision with an existing type (NAME_COLLISION)
+ * </ul>
+ */
+IType createType(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Returns all types declared in this compilation unit in the order
+ * in which they appear in the source.
+ * This includes all top-level types and nested member types.
+ * It does NOT include local types (types defined in methods).
+ *
+ * @return the array of toplevel and member types defined in a compilation unit, in declaration order.
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+IType[] getAllTypes() throws JavaModelException;
+/**
+ * Returns the smallest element within this compilation unit that
+ * includes the given source position (that is, a method, field, etc.), or
+ * <code>null</code> if there is no element other than the compilation
+ * unit itself at the given position, or if the given position is not
+ * within the source range of this compilation unit.
+ *
+ * @param position a source position inside the compilation unit
+ * @return the innermost Java element enclosing a given source position or <code>null</code>
+ * if none (excluding the compilation unit).
+ * @exception JavaModelException if the compilation unit does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+IJavaElement getElementAt(int position) throws JavaModelException;
+/**
+ * Returns the first import declaration in this compilation unit with the given name.
+ * This is a handle-only method. The import declaration may or may not exist. This
+ * is a convenience method - imports can also be accessed from a compilation unit's
+ * import container.
+ *
+ * @param the name of the import to find as defined by JLS2 7.5. (For example: <code>"java.io.File"</code>
+ * or <code>"java.awt.*"</code>)
+ * @return a handle onto the corresponding import declaration. The import declaration may or may not exist.
+ */
+IImportDeclaration getImport(String name) ;
+/**
+ * Returns the import container for this compilation unit.
+ * This is a handle-only method. The import container may or
+ * may not exist. The import container can used to access the
+ * imports.
+ *
+ * @return a handle onto the corresponding import container. The
+ * import contain may or may not exist.
+ */
+IImportContainer getImportContainer();
+/**
+ * Returns the import declarations in this compilation unit
+ * in the order in which they appear in the source. This is
+ * a convenience method - import declarations can also be
+ * accessed from a compilation unit's import container.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+IImportDeclaration[] getImports() throws JavaModelException;
+/**
+ * Returns the first package declaration in this compilation unit with the given package name
+ * (there normally is at most one package declaration).
+ * This is a handle-only method. The package declaration may or may not exist.
+ *
+ * @param name the name of the package declaration as defined by JLS2 7.4. (For example, <code>"java.lang"</code>)
+ */
+IPackageDeclaration getPackageDeclaration(String name);
+/**
+ * Returns the package declarations in this compilation unit
+ * in the order in which they appear in the source.
+ * There normally is at most one package declaration.
+ *
+ * @return an array of package declaration (normally of size one)
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+IPackageDeclaration[] getPackageDeclarations() throws JavaModelException;
+/**
+ * Returns the top-level type declared in this compilation unit with the given simple type name.
+ * This is a handle-only method. The type may or may not exist.
+ *
+ * @param name the simple name of the requested type in the compilation unit
+ * @return a handle onto the corresponding type. The type may or may not exist.
+ */
+IType getType(String name) ;
+/**
+ * Returns the top-level types declared in this compilation unit
+ * in the order in which they appear in the source.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+IType[] getTypes() throws JavaModelException;
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IElementChangedListener.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IElementChangedListener.java
index 26c6d3f811..3f2b6dc461 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IElementChangedListener.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IElementChangedListener.java
@@ -1,12 +1,12 @@
package org.eclipse.jdt.core;
public interface IElementChangedListener {
-
- /**
- * Notifies that one or more attributes of one or more Java elements have changed.
- * The specific details of the change are described by the given event.
- *
- * @param event the change event
- */
- public void elementChanged(ElementChangedEvent event);
+
+/**
+ * Notifies that one or more attributes of one or more Java elements have changed.
+ * The specific details of the change are described by the given event.
+ *
+ * @param event the change event
+ */
+public void elementChanged(ElementChangedEvent event);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IField.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IField.java
index bad3043857..184cdbd061 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IField.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IField.java
@@ -1,28 +1,28 @@
package org.eclipse.jdt.core;
public interface IField extends IMember {
- /**
- * Returns the constant value associated with this field
- * or <code>null</code> if this field has none.
- * Returns either a subclass of <code>Number</code>, or a <code>String</code>,
- * depending on the type of the field.
- * For example, if the field is of type <code>short</code>, this returns
- * a <code>Short</code>.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- public Object getConstant() throws JavaModelException;
- /**
- * Returns the simple name of this field.
- */
- String getElementName();
- /**
- * Returns the type signature of this field.
- *
- * @see Signature
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- String getTypeSignature() throws JavaModelException;
+/**
+ * Returns the constant value associated with this field
+ * or <code>null</code> if this field has none.
+ * Returns either a subclass of <code>Number</code>, or a <code>String</code>,
+ * depending on the type of the field.
+ * For example, if the field is of type <code>short</code>, this returns
+ * a <code>Short</code>.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+public Object getConstant() throws JavaModelException;
+/**
+ * Returns the simple name of this field.
+ */
+String getElementName();
+/**
+ * Returns the type signature of this field.
+ *
+ * @see Signature
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+String getTypeSignature() throws JavaModelException;
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IImportContainer.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IImportContainer.java
index 4da2605c74..735c7deefd 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IImportContainer.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IImportContainer.java
@@ -1,10 +1,9 @@
package org.eclipse.jdt.core;
-public interface IImportContainer
- extends IJavaElement, IParent, ISourceReference {
- /**
- * Returns the first import declaration in this import container with the given name.
- * This is a handle-only method. The import declaration may or may not exist.
- */
- IImportDeclaration getImport(String name);
+public interface IImportContainer extends IJavaElement, IParent, ISourceReference {
+/**
+ * Returns the first import declaration in this import container with the given name.
+ * This is a handle-only method. The import declaration may or may not exist.
+ */
+IImportDeclaration getImport(String name);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IImportDeclaration.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IImportDeclaration.java
index b881952da6..6eac7ea894 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IImportDeclaration.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IImportDeclaration.java
@@ -1,19 +1,18 @@
package org.eclipse.jdt.core;
-public interface IImportDeclaration
- extends IJavaElement, ISourceReference, ISourceManipulation {
- /**
- * Returns the name that has been imported.
- * For an on-demand import, this includes the trailing <code>".*"</code>.
- * For example, for the statement <code>"import java.util.*"</code>,
- * this returns <code>"java.util.*"</code>.
- * For the statement <code>"import java.util.Hashtable"</code>,
- * this returns <code>"java.util.Hashtable"</code>.
- */
- String getElementName();
- /**
- * Returns whether the import is on-demand. An import is on-demand if it ends
- * with <code>".*"</code>.
- */
- boolean isOnDemand();
+public interface IImportDeclaration extends IJavaElement, ISourceReference, ISourceManipulation {
+/**
+ * Returns the name that has been imported.
+ * For an on-demand import, this includes the trailing <code>".*"</code>.
+ * For example, for the statement <code>"import java.util.*"</code>,
+ * this returns <code>"java.util.*"</code>.
+ * For the statement <code>"import java.util.Hashtable"</code>,
+ * this returns <code>"java.util.Hashtable"</code>.
+ */
+String getElementName();
+/**
+ * Returns whether the import is on-demand. An import is on-demand if it ends
+ * with <code>".*"</code>.
+ */
+boolean isOnDemand();
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IInitializer.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IInitializer.java
index 10a8435f70..4d0c59629b 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IInitializer.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IInitializer.java
@@ -4,7 +4,7 @@ package org.eclipse.jdt.core;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
-
+
/**
* Represents a stand-alone instance or class (static) initializer in a type.
* <p>
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaElement.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaElement.java
index 1133cc090d..092c56dc5e 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaElement.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaElement.java
@@ -4,7 +4,7 @@ package org.eclipse.jdt.core;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
-
+
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
@@ -104,112 +104,112 @@ public interface IJavaElement extends IAdaptable {
*/
public static final int IMPORT_DECLARATION = 13;
- /**
- * Returns whether this Java element exists in the model.
- *
- * @return <code>true</code> if this element exists in the Java model
- */
- boolean exists();
- /**
- * Returns the resource that corresponds directly to this element,
- * or <code>null</code> if there is no resource that corresponds to
- * this element.
- * <p>
- * For example, the corresponding resource for an <code>ICompilationUnit</code>
- * is its underlying <code>IFile</code>. The corresponding resource for
- * an <code>IPackageFragment</code> that is not contained in an archive
- * is its underlying <code>IFolder</code>. An <code>IPackageFragment</code>
- * contained in an archive has no corresponding resource. Similarly, there
- * are no corresponding resources for <code>IMethods</code>,
- * <code>IFields</code>, etc.
- * <p>
- *
- * @return the corresponding resource, or <code>null</code> if none
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- IResource getCorrespondingResource() throws JavaModelException;
- /**
- * Returns the name of this element. This is a handle-only method.
- *
- * @return the element name
- */
- String getElementName();
- /**
- * Returns this element's kind encoded as an integer.
- * This is a handle-only method.
- *
- * @return the kind of element; one of the constants declared in
- * <code>IJavaElement</code>
- * @see IJavaElement
- */
- public int getElementType();
- /**
- * Returns a string representation of this element handle. The format of
- * the string is not specified; however, the identifier is stable across
- * workspace sessions, and can be used to recreate this handle via the
- * <code>JavaCore.create(String)</code> method.
- *
- * @return the string handle identifier
- * @see JavaCore#create(java.lang.String)
- */
- String getHandleIdentifier();
- /**
- * Returns the Java model.
- * This is a handle-only method.
- *
- * @return the Java model
- */
- IJavaModel getJavaModel();
- /**
- * Returns the Java project this element is contained in,
- * or <code>null</code> if this element is not contained in any Java project
- * (for instance, the <code>IJavaModel</code> is not contained in any Java
- * project).
- * This is a handle-only method.
- *
- * @return the containing Java project, or <code>null</code> if this element is
- * not contained in a Java project
- */
- IJavaProject getJavaProject();
- /**
- * Returns the element directly containing this element,
- * or <code>null</code> if this element has no parent.
- * This is a handle-only method.
- *
- * @return the parent element, or <code>null</code> if this element has no parent
- */
- IJavaElement getParent();
- /**
- * Returns the smallest underlying resource that contains
- * this element, or <code>null</code> if this element is not contained
- * in a resource.
- *
- * @return the underlying resource, or <code>null</code> if none
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its underlying resource
- */
- IResource getUnderlyingResource() throws JavaModelException;
- /**
- * Returns whether this Java element is read-only.
- * This is a handle-only method.
- *
- * @return <code>true</code> if this element is read-only
- */
- boolean isReadOnly();
- /**
- * Returns whether the structure of this element is known. For example, for a
- * compilation unit that could not be parsed, <code>false</code> is returned.
- * If the structure of an element is unknown, navigations will return reasonable
- * defaults. For example, <code>getChildren</code> will return an empty collection.
- * <p>
- * Note: This does not imply anything about consistency with the
- * underlying resource/buffer contents.
- * </p>
- *
- * @return <code>true</code> if the structure of this element is known
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- boolean isStructureKnown() throws JavaModelException;
+/**
+ * Returns whether this Java element exists in the model.
+ *
+ * @return <code>true</code> if this element exists in the Java model
+ */
+boolean exists();
+/**
+ * Returns the resource that corresponds directly to this element,
+ * or <code>null</code> if there is no resource that corresponds to
+ * this element.
+ * <p>
+ * For example, the corresponding resource for an <code>ICompilationUnit</code>
+ * is its underlying <code>IFile</code>. The corresponding resource for
+ * an <code>IPackageFragment</code> that is not contained in an archive
+ * is its underlying <code>IFolder</code>. An <code>IPackageFragment</code>
+ * contained in an archive has no corresponding resource. Similarly, there
+ * are no corresponding resources for <code>IMethods</code>,
+ * <code>IFields</code>, etc.
+ * <p>
+ *
+ * @return the corresponding resource, or <code>null</code> if none
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+IResource getCorrespondingResource() throws JavaModelException;
+/**
+ * Returns the name of this element. This is a handle-only method.
+ *
+ * @return the element name
+ */
+String getElementName();
+/**
+ * Returns this element's kind encoded as an integer.
+ * This is a handle-only method.
+ *
+ * @return the kind of element; one of the constants declared in
+ * <code>IJavaElement</code>
+ * @see IJavaElement
+ */
+public int getElementType();
+/**
+ * Returns a string representation of this element handle. The format of
+ * the string is not specified; however, the identifier is stable across
+ * workspace sessions, and can be used to recreate this handle via the
+ * <code>JavaCore.create(String)</code> method.
+ *
+ * @return the string handle identifier
+ * @see JavaCore#create(java.lang.String)
+ */
+String getHandleIdentifier();
+/**
+ * Returns the Java model.
+ * This is a handle-only method.
+ *
+ * @return the Java model
+ */
+IJavaModel getJavaModel();
+/**
+ * Returns the Java project this element is contained in,
+ * or <code>null</code> if this element is not contained in any Java project
+ * (for instance, the <code>IJavaModel</code> is not contained in any Java
+ * project).
+ * This is a handle-only method.
+ *
+ * @return the containing Java project, or <code>null</code> if this element is
+ * not contained in a Java project
+ */
+IJavaProject getJavaProject();
+/**
+ * Returns the element directly containing this element,
+ * or <code>null</code> if this element has no parent.
+ * This is a handle-only method.
+ *
+ * @return the parent element, or <code>null</code> if this element has no parent
+ */
+IJavaElement getParent();
+/**
+ * Returns the smallest underlying resource that contains
+ * this element, or <code>null</code> if this element is not contained
+ * in a resource.
+ *
+ * @return the underlying resource, or <code>null</code> if none
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its underlying resource
+ */
+IResource getUnderlyingResource() throws JavaModelException;
+/**
+ * Returns whether this Java element is read-only.
+ * This is a handle-only method.
+ *
+ * @return <code>true</code> if this element is read-only
+ */
+boolean isReadOnly();
+/**
+ * Returns whether the structure of this element is known. For example, for a
+ * compilation unit that could not be parsed, <code>false</code> is returned.
+ * If the structure of an element is unknown, navigations will return reasonable
+ * defaults. For example, <code>getChildren</code> will return an empty collection.
+ * <p>
+ * Note: This does not imply anything about consistency with the
+ * underlying resource/buffer contents.
+ * </p>
+ *
+ * @return <code>true</code> if the structure of this element is known
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+boolean isStructureKnown() throws JavaModelException;
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaElementDelta.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaElementDelta.java
index 7f1986235a..d26e00ce40 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaElementDelta.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaElementDelta.java
@@ -161,71 +161,71 @@ public interface IJavaElementDelta {
/**
* Change flag indicating that a source jar has been attached to a binary jar.
*/
- public int F_SOURCEATTACHED = 0x1000;
+ public int F_SOURCEATTACHED = 0x1000;
/**
* Change flag indicating that a source jar has been detached to a binary jar.
*/
- public int F_SOURCEDETACHED = 0x2000;
- /**
- * Returns deltas for the children that have been added.
- */
- public IJavaElementDelta[] getAddedChildren();
- /**
- * Returns deltas for the affected (added, removed, or changed) children.
- */
- public IJavaElementDelta[] getAffectedChildren();
- /**
- * Returns deltas for the children which have changed.
- */
- public IJavaElementDelta[] getChangedChildren();
- /**
- * Returns the element that this delta describes a change to.
- */
- public IJavaElement getElement();
- /**
- * Returns flags that describe how an element has changed.
- *
- * @see IJavaElementDelta#F_CHILDREN
- * @see IJavaElementDelta#F_CONTENT
- * @see IJavaElementDelta#F_MODIFIERS
- * @see IJavaElementDelta#F_MOVED_FROM
- * @see IJavaElementDelta#F_MOVED_TO
- * @see IJavaElementDelta#F_ADDED_TO_CLASSPATH
- * @see IJavaElementDelta#F_REMOVED_FROM_CLASSPATH
- * @see IJavaElementDelta#F_CLASSPATH_REORDER
- */
- public int getFlags();
- /**
- * Returns the kind of this delta - one of <code>ADDED</code>, <code>REMOVED</code>,
- * or <code>CHANGED</code>.
- */
- public int getKind();
- /**
- * Returns an element describing this element before it was moved
- * to its current location, or <code>null</code> if the
- * <code>F_MOVED_FROM</code> change flag is not set.
- */
- public IJavaElement getMovedFromElement();
- /**
- * Returns an element describing this element in its new location,
- * or <code>null</code> if the <code>F_MOVED_TO</code> change
- * flag is not set.
- */
- public IJavaElement getMovedToElement();
- /**
- * Returns deltas for the children which have been removed.
- */
- public IJavaElementDelta[] getRemovedChildren();
- /**
- * Returns the collection of resource deltas.
- * <p>
- * Note that resource deltas, like Java element deltas, are generally only valid
- * for the dynamic scope of an event notification. Clients must not hang on to
- * these objects.
- * </p>
- *
- * @return the underlying resource deltas, or <code>null</code> if none
- */
- public IResourceDelta[] getResourceDeltas();
+ public int F_SOURCEDETACHED = 0x2000;
+/**
+ * Returns deltas for the children that have been added.
+ */
+public IJavaElementDelta[] getAddedChildren();
+/**
+ * Returns deltas for the affected (added, removed, or changed) children.
+ */
+public IJavaElementDelta[] getAffectedChildren();
+/**
+ * Returns deltas for the children which have changed.
+ */
+public IJavaElementDelta[] getChangedChildren();
+/**
+ * Returns the element that this delta describes a change to.
+ */
+public IJavaElement getElement();
+/**
+ * Returns flags that describe how an element has changed.
+ *
+ * @see IJavaElementDelta#F_CHILDREN
+ * @see IJavaElementDelta#F_CONTENT
+ * @see IJavaElementDelta#F_MODIFIERS
+ * @see IJavaElementDelta#F_MOVED_FROM
+ * @see IJavaElementDelta#F_MOVED_TO
+ * @see IJavaElementDelta#F_ADDED_TO_CLASSPATH
+ * @see IJavaElementDelta#F_REMOVED_FROM_CLASSPATH
+ * @see IJavaElementDelta#F_CLASSPATH_REORDER
+ */
+public int getFlags();
+/**
+ * Returns the kind of this delta - one of <code>ADDED</code>, <code>REMOVED</code>,
+ * or <code>CHANGED</code>.
+ */
+public int getKind();
+/**
+ * Returns an element describing this element before it was moved
+ * to its current location, or <code>null</code> if the
+ * <code>F_MOVED_FROM</code> change flag is not set.
+ */
+public IJavaElement getMovedFromElement();
+/**
+ * Returns an element describing this element in its new location,
+ * or <code>null</code> if the <code>F_MOVED_TO</code> change
+ * flag is not set.
+ */
+public IJavaElement getMovedToElement();
+/**
+ * Returns deltas for the children which have been removed.
+ */
+public IJavaElementDelta[] getRemovedChildren();
+/**
+ * Returns the collection of resource deltas.
+ * <p>
+ * Note that resource deltas, like Java element deltas, are generally only valid
+ * for the dynamic scope of an event notification. Clients must not hang on to
+ * these objects.
+ * </p>
+ *
+ * @return the underlying resource deltas, or <code>null</code> if none
+ */
+public IResourceDelta[] getResourceDeltas();
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModel.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModel.java
index 0725beb7f6..b61681ab93 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModel.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModel.java
@@ -27,174 +27,153 @@ import org.eclipse.core.runtime.IProgressMonitor;
* @see JavaCore#create(org.eclipse.core.resources.IWorkspaceRoot)
*/
public interface IJavaModel extends IJavaElement, IOpenable, IParent {
- /**
- * Copies the given elements to the specified container(s).
- * If one container is specified, all elements are copied to that
- * container. If more than one container is specified, the number of
- * elements and containers must match, and each element is copied to
- * its associated container.
- * <p>
- * Optionally, each copy can positioned before a sibling
- * element. If <code>null</code> is specified for a given sibling, the copy
- * is inserted as the last child of its associated container.
- * </p>
- * <p>
- * Optionally, each copy can be renamed. If
- * <code>null</code> is specified for the new name, the copy
- * is not renamed.
- * </p>
- * <p>
- * Optionally, any existing child in the destination container with
- * the same name can be replaced by specifying <code>true</code> for
- * force. Otherwise an exception is thrown in the event that a name
- * collision occurs.
- * </p>
- *
- * @param elements the elements to copy
- * @param containers the container, or list of containers
- * @param siblings the list of siblings element any of which may be
- * <code>null</code>; or <code>null</code>
- * @param renamings the list of new names any of which may be
- * <code>null</code>; or <code>null</code>
- * @param replace <code>true</code> if any existing child in a target container
- * with the target name should be replaced, and <code>false</code> to throw an
- * exception in the event of a name collision
- * @param monitor a progress monitor
- * @exception JavaModelException if an element could not be copied. Reasons include:
- * <ul>
- * <li> A specified element, container, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> A container is of an incompatible type (<code>INVALID_DESTINATION</code>)
- * <li> A sibling is not a child of it associated container (<code>INVALID_SIBLING</code>)
- * <li> A new name is invalid (<code>INVALID_NAME</code>)
- * <li> A child in its associated container already exists with the same
- * name and <code>replace</code> has been specified as <code>false</code> (<code>NAME_COLLISION</code>)
- * <li> A container or element is read-only (<code>READ_ONLY</code>)
- * </ul>
- */
- void copy(
- IJavaElement[] elements,
- IJavaElement[] containers,
- IJavaElement[] siblings,
- String[] renamings,
- boolean replace,
- IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Deletes the given elements, forcing the operation if necessary and specified.
- *
- * @param elements the elements to delete
- * @param force a flag controlling whether underlying resources that are not
- * in sync with the local file system will be tolerated
- * @param monitor a progress monitor
- * @exception JavaModelException if an element could not be deleted. Reasons include:
- * <ul>
- * <li> A specified element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> An element is read-only (<code>READ_ONLY</code>)
- * </ul>
- */
- void delete(IJavaElement[] elements, boolean force, IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Returns the Java project with the given name. This is a handle-only method.
- * The project may or may not exist.
- */
- IJavaProject getJavaProject(String name);
- /**
- * Returns the Java projects in this Java model, or an empty array if there
- * are none.
- *
- * @exception JavaModelException if this request fails.
- */
- IJavaProject[] getJavaProjects() throws JavaModelException;
- /**
- * Returns the workspace associated with this Java model.
- */
- IWorkspace getWorkspace();
- /**
- * Moves the given elements to the specified container(s).
- * If one container is specified, all elements are moved to that
- * container. If more than one container is specified, the number of
- * elements and containers must match, and each element is moved to
- * its associated container.
- * <p>
- * Optionally, each element can positioned before a sibling
- * element. If <code>null</code> is specified for sibling, the element
- * is inserted as the last child of its associated container.
- * </p>
- * <p>
- * Optionally, each element can be renamed. If
- * <code>null</code> is specified for the new name, the element
- * is not renamed.
- * </p>
- * <p>
- * Optionally, any existing child in the destination container with
- * the same name can be replaced by specifying <code>true</code> for
- * force. Otherwise an exception is thrown in the event that a name
- * collision occurs.
- * </p>
- *
- * @param elements the elements to move
- * @param containers the container, or list of containers
- * @param siblings the list of siblings element any of which may be
- * <code>null</code>; or <code>null</code>
- * @param renamings the list of new names any of which may be
- * <code>null</code>; or <code>null</code>
- * @param replace <code>true</code> if any existing child in a target container
- * with the target name should be replaced, and <code>false</code> to throw an
- * exception in the event of a name collision
- * @param monitor a progress monitor
- * @exception JavaModelException if an element could not be moved. Reasons include:
- * <ul>
- * <li> A specified element, container, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> A container is of an incompatible type (<code>INVALID_DESTINATION</code>)
- * <li> A sibling is not a child of it associated container (<code>INVALID_SIBLING</code>)
- * <li> A new name is invalid (<code>INVALID_NAME</code>)
- * <li> A child in its associated container already exists with the same
- * name and <code>replace</code> has been specified as <code>false</code> (<code>NAME_COLLISION</code>)
- * <li> A container or element is read-only (<code>READ_ONLY</code>)
- * </ul>
- *
- * @exception IllegalArgumentException any element or container is <code>null</code>
- */
- void move(
- IJavaElement[] elements,
- IJavaElement[] containers,
- IJavaElement[] siblings,
- String[] renamings,
- boolean replace,
- IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Renames the given elements as specified.
- * If one container is specified, all elements are renamed within that
- * container. If more than one container is specified, the number of
- * elements and containers must match, and each element is renamed within
- * its associated container.
- *
- * @param elements the elements to rename
- * @param destinations the container, or list of containers
- * @param names the list of new names
- * @param replace <code>true</code> if an existing child in a target container
- * with the target name should be replaced, and <code>false</code> to throw an
- * exception in the event of a name collision
- * @param monitor a progress monitor
- * @exception JavaModelException if an element could not be renamed. Reasons include:
- * <ul>
- * <li> A specified element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> A new name is invalid (<code>INVALID_NAME</code>)
- * <li> A child already exists with the same name and <code>replace</code> has been specified as <code>false</code> (<code>NAME_COLLISION</code>)
- * <li> An element is read-only (<code>READ_ONLY</code>)
- * </ul>
- */
- void rename(
- IJavaElement[] elements,
- IJavaElement[] destinations,
- String[] names,
- boolean replace,
- IProgressMonitor monitor)
- throws JavaModelException;
+/**
+ * Copies the given elements to the specified container(s).
+ * If one container is specified, all elements are copied to that
+ * container. If more than one container is specified, the number of
+ * elements and containers must match, and each element is copied to
+ * its associated container.
+ * <p>
+ * Optionally, each copy can positioned before a sibling
+ * element. If <code>null</code> is specified for a given sibling, the copy
+ * is inserted as the last child of its associated container.
+ * </p>
+ * <p>
+ * Optionally, each copy can be renamed. If
+ * <code>null</code> is specified for the new name, the copy
+ * is not renamed.
+ * </p>
+ * <p>
+ * Optionally, any existing child in the destination container with
+ * the same name can be replaced by specifying <code>true</code> for
+ * force. Otherwise an exception is thrown in the event that a name
+ * collision occurs.
+ * </p>
+ *
+ * @param elements the elements to copy
+ * @param containers the container, or list of containers
+ * @param siblings the list of siblings element any of which may be
+ * <code>null</code>; or <code>null</code>
+ * @param renamings the list of new names any of which may be
+ * <code>null</code>; or <code>null</code>
+ * @param replace <code>true</code> if any existing child in a target container
+ * with the target name should be replaced, and <code>false</code> to throw an
+ * exception in the event of a name collision
+ * @param monitor a progress monitor
+ * @exception JavaModelException if an element could not be copied. Reasons include:
+ * <ul>
+ * <li> A specified element, container, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> A <code>CoreException</code> occurred while updating an underlying resource
+ * <li> A container is of an incompatible type (<code>INVALID_DESTINATION</code>)
+ * <li> A sibling is not a child of it associated container (<code>INVALID_SIBLING</code>)
+ * <li> A new name is invalid (<code>INVALID_NAME</code>)
+ * <li> A child in its associated container already exists with the same
+ * name and <code>replace</code> has been specified as <code>false</code> (<code>NAME_COLLISION</code>)
+ * <li> A container or element is read-only (<code>READ_ONLY</code>)
+ * </ul>
+ */
+void copy(IJavaElement[] elements, IJavaElement[] containers, IJavaElement[] siblings, String[] renamings, boolean replace, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Deletes the given elements, forcing the operation if necessary and specified.
+ *
+ * @param elements the elements to delete
+ * @param force a flag controlling whether underlying resources that are not
+ * in sync with the local file system will be tolerated
+ * @param monitor a progress monitor
+ * @exception JavaModelException if an element could not be deleted. Reasons include:
+ * <ul>
+ * <li> A specified element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> A <code>CoreException</code> occurred while updating an underlying resource
+ * <li> An element is read-only (<code>READ_ONLY</code>)
+ * </ul>
+ */
+void delete(IJavaElement[] elements, boolean force, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Returns the Java project with the given name. This is a handle-only method.
+ * The project may or may not exist.
+ */
+IJavaProject getJavaProject(String name);
+/**
+ * Returns the Java projects in this Java model, or an empty array if there
+ * are none.
+ *
+ * @exception JavaModelException if this request fails.
+ */
+IJavaProject[] getJavaProjects() throws JavaModelException;
+/**
+ * Returns the workspace associated with this Java model.
+ */
+IWorkspace getWorkspace();
+/**
+ * Moves the given elements to the specified container(s).
+ * If one container is specified, all elements are moved to that
+ * container. If more than one container is specified, the number of
+ * elements and containers must match, and each element is moved to
+ * its associated container.
+ * <p>
+ * Optionally, each element can positioned before a sibling
+ * element. If <code>null</code> is specified for sibling, the element
+ * is inserted as the last child of its associated container.
+ * </p>
+ * <p>
+ * Optionally, each element can be renamed. If
+ * <code>null</code> is specified for the new name, the element
+ * is not renamed.
+ * </p>
+ * <p>
+ * Optionally, any existing child in the destination container with
+ * the same name can be replaced by specifying <code>true</code> for
+ * force. Otherwise an exception is thrown in the event that a name
+ * collision occurs.
+ * </p>
+ *
+ * @param elements the elements to move
+ * @param containers the container, or list of containers
+ * @param siblings the list of siblings element any of which may be
+ * <code>null</code>; or <code>null</code>
+ * @param renamings the list of new names any of which may be
+ * <code>null</code>; or <code>null</code>
+ * @param replace <code>true</code> if any existing child in a target container
+ * with the target name should be replaced, and <code>false</code> to throw an
+ * exception in the event of a name collision
+ * @param monitor a progress monitor
+ * @exception JavaModelException if an element could not be moved. Reasons include:
+ * <ul>
+ * <li> A specified element, container, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> A <code>CoreException</code> occurred while updating an underlying resource
+ * <li> A container is of an incompatible type (<code>INVALID_DESTINATION</code>)
+ * <li> A sibling is not a child of it associated container (<code>INVALID_SIBLING</code>)
+ * <li> A new name is invalid (<code>INVALID_NAME</code>)
+ * <li> A child in its associated container already exists with the same
+ * name and <code>replace</code> has been specified as <code>false</code> (<code>NAME_COLLISION</code>)
+ * <li> A container or element is read-only (<code>READ_ONLY</code>)
+ * </ul>
+ *
+ * @exception IllegalArgumentException any element or container is <code>null</code>
+ */
+void move(IJavaElement[] elements, IJavaElement[] containers, IJavaElement[] siblings, String[] renamings, boolean replace, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Renames the given elements as specified.
+ * If one container is specified, all elements are renamed within that
+ * container. If more than one container is specified, the number of
+ * elements and containers must match, and each element is renamed within
+ * its associated container.
+ *
+ * @param elements the elements to rename
+ * @param destinations the container, or list of containers
+ * @param names the list of new names
+ * @param replace <code>true</code> if an existing child in a target container
+ * with the target name should be replaced, and <code>false</code> to throw an
+ * exception in the event of a name collision
+ * @param monitor a progress monitor
+ * @exception JavaModelException if an element could not be renamed. Reasons include:
+ * <ul>
+ * <li> A specified element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> A <code>CoreException</code> occurred while updating an underlying resource
+ * <li> A new name is invalid (<code>INVALID_NAME</code>)
+ * <li> A child already exists with the same name and <code>replace</code> has been specified as <code>false</code> (<code>NAME_COLLISION</code>)
+ * <li> An element is read-only (<code>READ_ONLY</code>)
+ * </ul>
+ */
+void rename(IJavaElement[] elements, IJavaElement[] destinations, String[] names, boolean replace, IProgressMonitor monitor) throws JavaModelException;
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelMarker.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelMarker.java
index 927dc7becb..e5a4757fed 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelMarker.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelMarker.java
@@ -7,8 +7,8 @@ public interface IJavaModelMarker {
* This can be used to recognize those markers in the workspace that flag problems
* detected by the Java tooling during compilation.
*/
- public static final String JAVA_MODEL_PROBLEM_MARKER =
- JavaCore.PLUGIN_ID + ".problem";
+ public static final String JAVA_MODEL_PROBLEM_MARKER = JavaCore.PLUGIN_ID + ".problem";
+
/**
* Java model transient problem marker type (value <code>"org.eclipse.jdt.core.transient_problem"</code>).
@@ -16,20 +16,19 @@ public interface IJavaModelMarker {
* problems detected by the Java tooling (such as a cycle in the build path, a problem
* detected by the outliner, or a problem detected during a code completion)
*/
- public static final String TRANSIENT_PROBLEM =
- JavaCore.PLUGIN_ID + ".transient_problem";
-
+ public static final String TRANSIENT_PROBLEM = JavaCore.PLUGIN_ID + ".transient_problem";
+
/**
* Id marker attribute (value <code>"id"</code>).
* Reserved for future use.
*/
- public static final String ID = "id";
+ public static final String ID = "id";
/**
* Flags marker attribute (value <code>"flags"</code>).
* Reserved for future use.
*/
- public static final String FLAGS = "flags";
+ public static final String FLAGS = "flags";
/**
* Cycle detected marker attribute (value <code>"cycleDetected"</code>).
@@ -37,5 +36,11 @@ public interface IJavaModelMarker {
* The value of this attribute is the name of the project that caused a
* cycle in the projects classpaths.
*/
- public static final String CYCLE_DETECTED = "cycleDetected";
+ public static final String CYCLE_DETECTED = "cycleDetected";
+ /**
+ * Build path problem marker type (value <code>"org.eclipse.jdt.core.buildpath_problem"</code>).
+ * This can be used to recognize those markers in the workspace that flag problems
+ * detected by the Java tooling during classpath setting.
+ */
+ public static final String BUILDPATH_PROBLEM_MARKER = JavaCore.PLUGIN_ID + ".buildpath_problem";
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelStatus.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelStatus.java
index 898ef0e6c2..be78f23b58 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelStatus.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelStatus.java
@@ -32,45 +32,45 @@ import org.eclipse.core.runtime.IStatus;
* @see IJavaModelStatusConstants
*/
public interface IJavaModelStatus extends IStatus {
- /**
- * Returns any Java elements associated with the failure (see specification
- * of the status code), or an empty array if no elements are related to this
- * particular status code.
- *
- * @return the list of Java element culprits
- * @see IJavaModelStatusConstants
- */
- IJavaElement[] getElements();
- /**
- * Returns the path associated with the failure (see specification
- * of the status code), or <code>null</code> if the failure is not
- * one of <code>DEVICE_PATH</code>, <code>INVALID_PATH</code>,
- * <code>PATH_OUTSIDE_PROJECT</code>, or <code>RELATIVE_PATH</code>.
- *
- * @return the path that caused the failure, or <code>null</code> if none
- * @see IJavaModelStatusConstants#DEVICE_PATH
- * @see IJavaModelStatusConstants#INVALID_PATH
- * @see IJavaModelStatusConstants#PATH_OUTSIDE_PROJECT
- * @see IJavaModelStatusConstants#RELATIVE_PATH
- */
- IPath getPath();
- /**
- * Returns the string associated with the failure (see specification
- * of the status code), or <code>null</code> if no string is related to this
- * particular status code.
- *
- * @return the string culprit, or <code>null</code> if none
- * @see IJavaModelStatusConstants
- */
- String getString();
- /**
- * Returns whether this status indicates that a Java model element does not exist.
- * This convenience method is equivalent to
- * <code>getCode() == IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST</code>.
- *
- * @return <code>true</code> if the status code indicates that a Java model
- * element does not exist
- * @see IJavaModelStatusConstants#ELEMENT_DOES_NOT_EXIST
- */
- boolean isDoesNotExist();
+/**
+ * Returns any Java elements associated with the failure (see specification
+ * of the status code), or an empty array if no elements are related to this
+ * particular status code.
+ *
+ * @return the list of Java element culprits
+ * @see IJavaModelStatusConstants
+ */
+IJavaElement[] getElements();
+/**
+ * Returns the path associated with the failure (see specification
+ * of the status code), or <code>null</code> if the failure is not
+ * one of <code>DEVICE_PATH</code>, <code>INVALID_PATH</code>,
+ * <code>PATH_OUTSIDE_PROJECT</code>, or <code>RELATIVE_PATH</code>.
+ *
+ * @return the path that caused the failure, or <code>null</code> if none
+ * @see IJavaModelStatusConstants#DEVICE_PATH
+ * @see IJavaModelStatusConstants#INVALID_PATH
+ * @see IJavaModelStatusConstants#PATH_OUTSIDE_PROJECT
+ * @see IJavaModelStatusConstants#RELATIVE_PATH
+ */
+IPath getPath();
+/**
+ * Returns the string associated with the failure (see specification
+ * of the status code), or <code>null</code> if no string is related to this
+ * particular status code.
+ *
+ * @return the string culprit, or <code>null</code> if none
+ * @see IJavaModelStatusConstants
+ */
+String getString();
+/**
+ * Returns whether this status indicates that a Java model element does not exist.
+ * This convenience method is equivalent to
+ * <code>getCode() == IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST</code>.
+ *
+ * @return <code>true</code> if the status code indicates that a Java model
+ * element does not exist
+ * @see IJavaModelStatusConstants#ELEMENT_DOES_NOT_EXIST
+ */
+boolean isDoesNotExist();
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelStatusConstants.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelStatusConstants.java
index 2ca618de78..5f9e63b95a 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelStatusConstants.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaModelStatusConstants.java
@@ -14,7 +14,7 @@ public interface IJavaModelStatusConstants {
* Use <code>getException</code> to retrieve a <code>CoreException</code>.
*/
public static final int CORE_EXCEPTION = 966;
-
+
/**
* Status constant indicating one or more of the elements
* supplied are not of a valid type for the operation to
@@ -43,14 +43,14 @@ public interface IJavaModelStatusConstants {
* supplied to the operation.
*/
public static final int NULL_PATH = 970;
-
+
/**
* Status constant indicating that a path outside of the
* project was supplied to the operation. The path can be retrieved using
* <code>getPath</code> on the status object.
*/
public static final int PATH_OUTSIDE_PROJECT = 971;
-
+
/**
* Status constant indicating that a relative path
* was supplied to the operation when an absolute path is
@@ -58,7 +58,7 @@ public interface IJavaModelStatusConstants {
* status object.
*/
public static final int RELATIVE_PATH = 972;
-
+
/**
* Status constant indicating that a path specifying a device
* was supplied to the operation when a path with no device is
@@ -66,45 +66,45 @@ public interface IJavaModelStatusConstants {
* status object.
*/
public static final int DEVICE_PATH = 973;
-
+
/**
* Status constant indicating that a string
* was supplied to the operation that was <code>null</code>.
*/
public static final int NULL_STRING = 974;
-
+
/**
* Status constant indicating that the operation encountered
* a read-only element.
* The element(s) can be retrieved using <code>getElements</code> on the status object.
*/
public static final int READ_ONLY = 976;
-
+
/**
* Status constant indicating that a naming collision would occur
* if the operation proceeded.
*/
public static final int NAME_COLLISION = 977;
-
+
/**
* Status constant indicating that a destination provided for a copy/move/rename operation
* is invalid.
* The destination element can be retrieved using <code>getElements</code> on the status object.
*/
public static final int INVALID_DESTINATION = 978;
-
+
/**
* Status constant indicating that a path provided to an operation
* is invalid. The path can be retrieved using <code>getPath</code> on the
* status object.
*/
public static final int INVALID_PATH = 979;
-
+
/**
* Status constant indicating the given source position is out of bounds.
*/
public static final int INDEX_OUT_OF_BOUNDS = 980;
-
+
/**
* Status constant indicating there is an update conflict
* for a working copy. The compilation unit on which the
@@ -177,21 +177,21 @@ public interface IJavaModelStatusConstants {
* the underlying resource is invalid.
* @see JavaCore
*/
- public static final int INVALID_RESOURCE = 995;
+ public static final int INVALID_RESOURCE = 995;
- /**
- * Status indicating that a Java element could not be created because
- * the underlying resource is not of an appropriate type.
- * @see JavaCore
- */
- public static final int INVALID_RESOURCE_TYPE = 996;
+ /**
+ * Status indicating that a Java element could not be created because
+ * the underlying resource is not of an appropriate type.
+ * @see JavaCore
+ */
+ public static final int INVALID_RESOURCE_TYPE = 996;
- /**
- * Status indicating that a Java element could not be created because
- * the project owning underlying resource does not have the Java nature.
- * @see JavaCore
- */
- public static final int INVALID_PROJECT = 997;
+ /**
+ * Status indicating that a Java element could not be created because
+ * the project owning underlying resource does not have the Java nature.
+ * @see JavaCore
+ */
+ public static final int INVALID_PROJECT = 997;
/**
* Status indicating that the package declaration in a <code>ICompilationUnit</code>
@@ -200,12 +200,16 @@ public interface IJavaModelStatusConstants {
* gives the name of the package in which the <code>ICompilationUnit</code> is
* declared.
*/
- public static final int INVALID_PACKAGE = 998;
+ public static final int INVALID_PACKAGE = 998;
/**
* Status indicating that the corresponding resource has no local contents yet.
* This might happen when attempting to use a resource before its contents
* has been made locally available.
*/
- public static final int NO_LOCAL_CONTENTS = 999;
+ public static final int NO_LOCAL_CONTENTS = 999;
+ /**
+ * Status constant indicating that a classpath entry was invalid
+ */
+ public static final int INVALID_CLASSPATH = 964;
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaProject.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaProject.java
index d69b0a3fe0..c2434d349b 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaProject.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IJavaProject.java
@@ -4,7 +4,7 @@ package org.eclipse.jdt.core;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
-
+
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
@@ -45,327 +45,248 @@ import org.eclipse.jdt.core.eval.IEvaluationContext;
*/
public interface IJavaProject extends IParent, IJavaElement, IOpenable {
- /**
- * Returns the <code>IJavaElement</code> corresponding to the given
- * classpath-relative path, or <code>null</code> if no such
- * <code>IJavaElement</code> is found. The result is one of an
- * <code>ICompilationUnit</code>, <code>IClassFile</code>, or
- * <code>IPackageFragment</code>.
- *
- * <p>For example, the path "java/lang/Object.java", would result in the
- * <code>ICompilationUnit</code> or <code>IClassFile</code> corresponding to
- * "java.lang.Object". The path "java/lang" would result in the
- * <code>IPackageFragment</code> for "java.lang".
- *
- * @exception JavaModelException if the given path is <code>null</code>
- * or absolute
- */
- IJavaElement findElement(IPath path) throws JavaModelException;
- /**
- * Returns the first existing package fragment on this project's classpath
- * whose path matches the given (absolute) path, or <code>null</code> if none
- * exist.
- * The path can be:
- * - internal to the workbench: "/Project/src"
- * - external to the workbench: "c:/jdk/classes.zip/java/lang"
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- IPackageFragment findPackageFragment(IPath path) throws JavaModelException;
- /**
- * Returns the existing package fragment root on this project's classpath
- * whose path matches the given (absolute) path, or <code>null</code> if
- * one does not exist.
- * The path can be:
- * - internal to the workbench: "/Compiler/src"
- * - external to the workbench: "c:/jdk/classes.zip"
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- IPackageFragmentRoot findPackageFragmentRoot(IPath path)
- throws JavaModelException;
- /**
- * Returns all of the existing package fragment roots that exist
- * on the classpath, in the order they are defined by the classpath.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- IPackageFragmentRoot[] getAllPackageFragmentRoots() throws JavaModelException;
- /**
- * Returns the classpath for the project, as a list of classpath
- * entries.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- *
- * @deprecated - since classpath variable support was added either use #getRawClasspath or #getResolvedClasspath
- */
- IClasspathEntry[] getClasspath() throws JavaModelException;
- /**
- * Returns an array of non-Java resources directly contained in this project.
- * It does not transitively answer non-Java resources contained in folders;
- * these would have to be explicitly iterated over.
- */
- Object[] getNonJavaResources() throws JavaModelException;
- /**
- * Returns the full path to the location where the builder writes
- * <code>.class</code> files.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- IPath getOutputLocation() throws JavaModelException;
- /**
- * Returns a package fragment root for the JAR at the specified file system path.
- * This is a handle-only method. The underlying <code>java.io.File</code>
- * may or may not exist. No resource is associated with this local JAR
- * package fragment root.
- */
- IPackageFragmentRoot getPackageFragmentRoot(String jarPath);
- /**
- * Returns a package fragment root for the given resource, which
- * must either be a folder representing the top of a package hierarchy,
- * or a <code>.jar</code> or <code>.zip</code> file.
- * This is a handle-only method. The underlying resource may or may not exist.
- */
- IPackageFragmentRoot getPackageFragmentRoot(IResource resource);
- /**
- * Returns all of the package fragment roots contained in this
- * project, identified on this project's resolved classpath. The result
- * does not include package fragment roots in other projects referenced
- * on this project's classpath.
- *
- * <p>NOTE: This is equivalent to <code>getChildren()</code>.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- IPackageFragmentRoot[] getPackageFragmentRoots() throws JavaModelException;
- /**
- * Returns the existing package fragment roots identified by the given entry.
- * Note that a classpath entry that refers to another project may
- * have more than one root (if that project has more than on root
- * containing source), and classpath entries within the current
- * project identify a single root.
- *
- * If the classpath entry denotes a variable, it will be resolved and returning
- * the roots of the target entry (empty if not resolvable).
- */
- IPackageFragmentRoot[] getPackageFragmentRoots(IClasspathEntry entry);
- /**
- * Returns all package fragments in all package fragment roots contained
- * in this project. This is a convenience method.
- *
- * Note that the package fragment roots corresponds to the resolved
- * classpath of the project.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- IPackageFragment[] getPackageFragments() throws JavaModelException;
- /**
- * Returns the <code>IProject</code> on which this <code>IJavaProject</code>
- * was created. This is handle-only method.
- */
- IProject getProject();
- /**
- * Returns the raw classpath for the project, as a list of classpath entries. This corresponds to the exact set
- * of entries which were assigned using <code>setRawClasspath</code>, in particular such a classpath may contain
- * classpath variable entries. Classpath variable entries can be resolved individually (see <code>JavaCore#getClasspathVariable</code>),
- * or the full classpath can be resolved at once using the helper method <code>getResolvedClasspath</code>.
- * <p>
- * A classpath variable provides an indirection level for better sharing a classpath. As an example, it allows
- * a classpath to no longer refer directly to external JARs located in some user specific location. The classpath
- * can simply refer to some variables defining the proper locations of these external JARs.
- * <p>
- * @exception JavaModelException in one of the corresponding situation:
- * <ul>
- * <li> this element does not exist </li>
- * <li> an exception occurs while accessing its corresponding resource </li>
- * </ul>
- * @see IClasspathEntry
- */
- IClasspathEntry[] getRawClasspath() throws JavaModelException;
- /**
- * Returns the names of the projects that are directly required by this
- * project. A project is required if it is in its classpath.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- String[] getRequiredProjectNames() throws JavaModelException;
- /**
- * This is a helper method returning the resolved classpath for the project, as a list of classpath entries,
- * where all classpath variable entries have been resolved and substituted with their final target entries.
- * <p>
- * A resolved classpath corresponds to a particular instance of the raw classpath bound in the context of
- * the current values of the referred variables, and thus should not be persisted.
- * <p>
- * A classpath variable provides an indirection level for better sharing a classpath. As an example, it allows
- * a classpath to no longer refer directly to external JARs located in some user specific location. The classpath
- * can simply refer to some variables defining the proper locations of these external JARs.
- * <p>
- * The boolean argument <code>ignoreUnresolvedVariable</code> allows to specify how to handle unresolvable variables,
- * when set to <code>true</code>, missing variables are simply ignored, the resulting path is then only formed of the
- * resolvable entries, without any indication about which variable(s) was ignored. When set to <code>false</code>, a
- * JavaModelException will be thrown for the first unresolved variable (from left to right).
- *
- * @exception JavaModelException in one of the corresponding situation:
- * <ul>
- * <li> this element does not exist </li>
- * <li> an exception occurs while accessing its corresponding resource </li>
- * <li> a classpath variable was not resolvable and <code>ignoreUnresolvedVariable</code> was set to <code>false</code>. </li>
- * </ul>
- * @see IClasspathEntry
- */
- IClasspathEntry[] getResolvedClasspath(boolean ignoreUnresolvedVariable)
- throws JavaModelException;
- /**
- * Returns whether this project has been built at least once and thus whether it has a build state.
- */
- public boolean hasBuildState();
- /**
- * Returns whether setting this projec's classpath to the given classpath entries
- * would result in a cycle.
- *
- * If the set of entries contains some variables, these are resolved in order to determine
- * cycles.
- */
- public boolean hasClasspathCycle(IClasspathEntry[] entries);
- /**
- * Creates a new evaluation context.
- */
- IEvaluationContext newEvaluationContext();
- /**
- * Creates and returns a new classpath entry of kind <code>K_BINARY</code> for the JAR
- * or folder identified by the given absolute path. This specifies that
- * all package fragments within the root will have children of type
- * <code>IClassFile</code>.
- * The path can be:
- * - internal to the workbench: "/Project/binary"
- * - external to the workbench: "c:/jdk/classes.zip"
- *
- * @deprecated - use JavaCore#newLibraryEntry
- */
- public IClasspathEntry newLibraryEntry(IPath path);
- /**
- * Creates and returns a new classpath entry of kind <code>K_SOURCE</code>
- * for the project identified by the given absolute path. This
- * identifies all the source code of the given project to be
- * used in the Java model, and the output location of the project
- * to be used when building.
- * The path can be:
- * - internal to the workbench: "/Project/binary"
- * - external to the workbench: "c:/jdk/classes.zip"
- *
- * @deprecated - use JavaCore#newProjectEntry
- */
- public IClasspathEntry newProjectEntry(IPath path);
- /**
- * Creates and returns a new classpath entry of kind <code>K_SOURCE</code>
- * for folder identified by the given absolute path. This specifies that
- * all package fragments within the root will have children of type
- * <code>ICompilationUnit</code>.
- * The path can be:
- * - internal to the workbench: "/Project/binary"
- * - external to the workbench: "c:/jdk/classes.zip"
- *
- * @deprecated - use JavaCore#newSourceEntry
- */
- public IClasspathEntry newSourceEntry(IPath path);
- /**
- * Creates and returns a type hierarchy for all types in the given
- * region, considering subtypes within that region.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- *
- * @exception IllegalArgumentException if region is <code>null</code>
- */
- ITypeHierarchy newTypeHierarchy(IRegion region, IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Creates and returns a type hierarchy for the given type considering
- * subtypes in the specified region.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- *
- * @exception IllegalArgumentException if type or region is <code>null</code>
- */
- ITypeHierarchy newTypeHierarchy(
- IType type,
- IRegion region,
- IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Sets the classpath of this project.
- * <p>
- * Setting the classpath to <code>null</code> specifies a default classpath
- * (the project root). Setting the classpath to an empty array specifies an
- * empty classpath.
- * <p>
- * If a cycle is detected while setting this classpath, an error marker will be added
- * to the project closing the cycle.
- * To avoid this problem, use <code>hasClasspathCycle(IClasspathEntry[] entries)</code>
- * before setting the classpath.
- *
- * @exception JavaModelException if the classpath could not be set. Reasons include:
- * <ul>
- * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> Two or more entries specify source roots with the same or overlapping paths (NAME_COLLISION)
- * <li> A entry of kind <code>CPE_PROJECT</code> refers to this project (INVALID_PATH)
- * <li> The classpath is being modified during resource change event notification (CORE_EXCEPTION)
- * </ul>
- * @deprecated - was renamed to #setRawClasspath
- */
- void setClasspath(IClasspathEntry[] entries, IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Sets the output location of this project to the location
- * described by the given absolute path.
- * <p>
- *
- * @exception JavaModelException if the classpath could not be set. Reasons include:
- * <ul>
- * <li>This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li>The path refers to a location not contained in this project (<code>PATH_OUTSIDE_PROJECT</code>)
- * <li>The path is not an absolute path (<code>RELATIVE_PATH</code>)
- * <li>The path is nested inside a package fragment root of this project (<code>INVALID_PATH</code>)
- * </ul>
- */
- void setOutputLocation(IPath path, IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Sets the classpath of this project using a list of classpath entries. In particular such a classpath may contain
- * classpath variable entries. Classpath variable entries can be resolved individually (see <code>JavaCore#getClasspathVariable</code>),
- * or the full classpath can be resolved at once using the helper method <code>getResolvedClasspath</code>.
- * <p>
- * A classpath variable provides an indirection level for better sharing a classpath. As an example, it allows
- * a classpath to no longer refer directly to external JARs located in some user specific location. The classpath
- * can simply refer to some variables defining the proper locations of these external JARs.
- * <p>
- * Setting the classpath to <code>null</code> specifies a default classpath
- * (the project root). Setting the classpath to an empty array specifies an
- * empty classpath.
- * <p>
- * If a cycle is detected while setting this classpath, an error marker will be added
- * to the project closing the cycle.
- * To avoid this problem, use <code>hasClasspathCycle(IClasspathEntry[] entries)</code>
- * before setting the classpath.
- *
- * @exception JavaModelException if the classpath could not be set. Reasons include:
- * <ul>
- * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> Two or more entries specify source roots with the same or overlapping paths (NAME_COLLISION)
- * <li> A entry of kind <code>CPE_PROJECT</code> refers to this project (INVALID_PATH)
- * <li> The classpath is being modified during resource change event notification (CORE_EXCEPTION)
- * </ul>
- * @see IClasspathEntry
- */
- void setRawClasspath(IClasspathEntry[] entries, IProgressMonitor monitor)
- throws JavaModelException;
+/**
+ * Returns the <code>IJavaElement</code> corresponding to the given
+ * classpath-relative path, or <code>null</code> if no such
+ * <code>IJavaElement</code> is found. The result is one of an
+ * <code>ICompilationUnit</code>, <code>IClassFile</code>, or
+ * <code>IPackageFragment</code>.
+ *
+ * <p>For example, the path "java/lang/Object.java", would result in the
+ * <code>ICompilationUnit</code> or <code>IClassFile</code> corresponding to
+ * "java.lang.Object". The path "java/lang" would result in the
+ * <code>IPackageFragment</code> for "java.lang".
+ *
+ * @exception JavaModelException if the given path is <code>null</code>
+ * or absolute
+ */
+IJavaElement findElement(IPath path) throws JavaModelException;
+/**
+ * Returns the first existing package fragment on this project's classpath
+ * whose path matches the given (absolute) path, or <code>null</code> if none
+ * exist.
+ * The path can be:
+ * - internal to the workbench: "/Project/src"
+ * - external to the workbench: "c:/jdk/classes.zip/java/lang"
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+IPackageFragment findPackageFragment(IPath path) throws JavaModelException;
+/**
+ * Returns the existing package fragment root on this project's classpath
+ * whose path matches the given (absolute) path, or <code>null</code> if
+ * one does not exist.
+ * The path can be:
+ * - internal to the workbench: "/Compiler/src"
+ * - external to the workbench: "c:/jdk/classes.zip"
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+IPackageFragmentRoot findPackageFragmentRoot(IPath path) throws JavaModelException;
+/**
+ * Returns all of the existing package fragment roots that exist
+ * on the classpath, in the order they are defined by the classpath.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+IPackageFragmentRoot[] getAllPackageFragmentRoots() throws JavaModelException;
+/**
+ * Returns an array of non-Java resources directly contained in this project.
+ * It does not transitively answer non-Java resources contained in folders;
+ * these would have to be explicitly iterated over.
+ */
+Object[] getNonJavaResources() throws JavaModelException;
+/**
+ * Returns the full path to the location where the builder writes
+ * <code>.class</code> files.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+IPath getOutputLocation() throws JavaModelException;
+/**
+ * Returns a package fragment root for the JAR at the specified file system path.
+ * This is a handle-only method. The underlying <code>java.io.File</code>
+ * may or may not exist. No resource is associated with this local JAR
+ * package fragment root.
+ */
+IPackageFragmentRoot getPackageFragmentRoot(String jarPath);
+/**
+ * Returns a package fragment root for the given resource, which
+ * must either be a folder representing the top of a package hierarchy,
+ * or a <code>.jar</code> or <code>.zip</code> file.
+ * This is a handle-only method. The underlying resource may or may not exist.
+ */
+IPackageFragmentRoot getPackageFragmentRoot(IResource resource);
+/**
+ * Returns all of the package fragment roots contained in this
+ * project, identified on this project's resolved classpath. The result
+ * does not include package fragment roots in other projects referenced
+ * on this project's classpath.
+ *
+ * <p>NOTE: This is equivalent to <code>getChildren()</code>.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+IPackageFragmentRoot[] getPackageFragmentRoots() throws JavaModelException;
+/**
+ * Returns the existing package fragment roots identified by the given entry.
+ * Note that a classpath entry that refers to another project may
+ * have more than one root (if that project has more than on root
+ * containing source), and classpath entries within the current
+ * project identify a single root.
+ *
+ * If the classpath entry denotes a variable, it will be resolved and returning
+ * the roots of the target entry (empty if not resolvable).
+ */
+IPackageFragmentRoot[] getPackageFragmentRoots(IClasspathEntry entry);
+/**
+ * Returns all package fragments in all package fragment roots contained
+ * in this project. This is a convenience method.
+ *
+ * Note that the package fragment roots corresponds to the resolved
+ * classpath of the project.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+IPackageFragment[] getPackageFragments() throws JavaModelException;
+/**
+ * Returns the <code>IProject</code> on which this <code>IJavaProject</code>
+ * was created. This is handle-only method.
+ */
+IProject getProject();
+/**
+ * Returns the raw classpath for the project, as a list of classpath entries. This corresponds to the exact set
+ * of entries which were assigned using <code>setRawClasspath</code>, in particular such a classpath may contain
+ * classpath variable entries. Classpath variable entries can be resolved individually (see <code>JavaCore#getClasspathVariable</code>),
+ * or the full classpath can be resolved at once using the helper method <code>getResolvedClasspath</code>.
+ * <p>
+ * A classpath variable provides an indirection level for better sharing a classpath. As an example, it allows
+ * a classpath to no longer refer directly to external JARs located in some user specific location. The classpath
+ * can simply refer to some variables defining the proper locations of these external JARs.
+ * <p>
+ * @exception JavaModelException in one of the corresponding situation:
+ * <ul>
+ * <li> this element does not exist </li>
+ * <li> an exception occurs while accessing its corresponding resource </li>
+ * </ul>
+ * @see IClasspathEntry
+ */
+IClasspathEntry[] getRawClasspath() throws JavaModelException;
+/**
+ * Returns the names of the projects that are directly required by this
+ * project. A project is required if it is in its classpath.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+String[] getRequiredProjectNames() throws JavaModelException;
+/**
+ * This is a helper method returning the resolved classpath for the project, as a list of classpath entries,
+ * where all classpath variable entries have been resolved and substituted with their final target entries.
+ * <p>
+ * A resolved classpath corresponds to a particular instance of the raw classpath bound in the context of
+ * the current values of the referred variables, and thus should not be persisted.
+ * <p>
+ * A classpath variable provides an indirection level for better sharing a classpath. As an example, it allows
+ * a classpath to no longer refer directly to external JARs located in some user specific location. The classpath
+ * can simply refer to some variables defining the proper locations of these external JARs.
+ * <p>
+ * The boolean argument <code>ignoreUnresolvedVariable</code> allows to specify how to handle unresolvable variables,
+ * when set to <code>true</code>, missing variables are simply ignored, the resulting path is then only formed of the
+ * resolvable entries, without any indication about which variable(s) was ignored. When set to <code>false</code>, a
+ * JavaModelException will be thrown for the first unresolved variable (from left to right).
+ *
+ * @exception JavaModelException in one of the corresponding situation:
+ * <ul>
+ * <li> this element does not exist </li>
+ * <li> an exception occurs while accessing its corresponding resource </li>
+ * <li> a classpath variable was not resolvable and <code>ignoreUnresolvedVariable</code> was set to <code>false</code>. </li>
+ * </ul>
+ * @see IClasspathEntry
+ */
+IClasspathEntry[] getResolvedClasspath(boolean ignoreUnresolvedVariable) throws JavaModelException;
+/**
+ * Returns whether this project has been built at least once and thus whether it has a build state.
+ */
+public boolean hasBuildState();
+/**
+ * Returns whether setting this projec's classpath to the given classpath entries
+ * would result in a cycle.
+ *
+ * If the set of entries contains some variables, these are resolved in order to determine
+ * cycles.
+ */
+public boolean hasClasspathCycle(IClasspathEntry[] entries);
+/**
+ * Creates a new evaluation context.
+ */
+IEvaluationContext newEvaluationContext();
+/**
+ * Creates and returns a type hierarchy for all types in the given
+ * region, considering subtypes within that region.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ *
+ * @exception IllegalArgumentException if region is <code>null</code>
+ */
+ITypeHierarchy newTypeHierarchy(IRegion region, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Creates and returns a type hierarchy for the given type considering
+ * subtypes in the specified region.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ *
+ * @exception IllegalArgumentException if type or region is <code>null</code>
+ */
+ITypeHierarchy newTypeHierarchy(IType type, IRegion region, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Sets the output location of this project to the location
+ * described by the given absolute path.
+ * <p>
+ *
+ * @exception JavaModelException if the classpath could not be set. Reasons include:
+ * <ul>
+ * <li>This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li>The path refers to a location not contained in this project (<code>PATH_OUTSIDE_PROJECT</code>)
+ * <li>The path is not an absolute path (<code>RELATIVE_PATH</code>)
+ * <li>The path is nested inside a package fragment root of this project (<code>INVALID_PATH</code>)
+ * </ul>
+ */
+void setOutputLocation(IPath path, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Sets the classpath of this project using a list of classpath entries. In particular such a classpath may contain
+ * classpath variable entries. Classpath variable entries can be resolved individually (see <code>JavaCore#getClasspathVariable</code>),
+ * or the full classpath can be resolved at once using the helper method <code>getResolvedClasspath</code>.
+ * <p>
+ * A classpath variable provides an indirection level for better sharing a classpath. As an example, it allows
+ * a classpath to no longer refer directly to external JARs located in some user specific location. The classpath
+ * can simply refer to some variables defining the proper locations of these external JARs.
+ * <p>
+ * Setting the classpath to <code>null</code> specifies a default classpath
+ * (the project root). Setting the classpath to an empty array specifies an
+ * empty classpath.
+ * <p>
+ * If a cycle is detected while setting this classpath, an error marker will be added
+ * to the project closing the cycle.
+ * To avoid this problem, use <code>hasClasspathCycle(IClasspathEntry[] entries)</code>
+ * before setting the classpath.
+ *
+ * @exception JavaModelException if the classpath could not be set. Reasons include:
+ * <ul>
+ * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> Two or more entries specify source roots with the same or overlapping paths (NAME_COLLISION)
+ * <li> A entry of kind <code>CPE_PROJECT</code> refers to this project (INVALID_PATH)
+ * <li> The classpath is being modified during resource change event notification (CORE_EXCEPTION)
+ * </ul>
+ * @see IClasspathEntry
+ */
+void setRawClasspath(IClasspathEntry[] entries, IProgressMonitor monitor) throws JavaModelException;
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IMember.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IMember.java
index f3e3d0eea3..8aee2fe2f5 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IMember.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IMember.java
@@ -1,51 +1,50 @@
package org.eclipse.jdt.core;
-public interface IMember
- extends IJavaElement, ISourceReference, ISourceManipulation {
- /**
- * Returns the class file in which this member is declared, or <code>null</code>
- * if this member is not declared in a class file (for example, a source type).
- * This is a handle-only method.
- */
- IClassFile getClassFile();
- /**
- * Returns the compilation unit in which this member is declared, or <code>null</code>
- * if this member is not declared in a compilation unit (for example, a binary type).
- * This is a handle-only method.
- */
- ICompilationUnit getCompilationUnit();
- /**
- * Returns the type in which this member is declared, or <code>null</code>
- * if this member is not declared in a type (for example, a top-level type).
- * This is a handle-only method.
- */
- IType getDeclaringType();
- /**
- * Returns the modifier flags for this member. The flags can be examined using class
- * <code>Flags</code>.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- *
- * @see Flags
- */
- int getFlags() throws JavaModelException;
- /**
- * Returns the source range of this member's simple name,
- * or <code>null</code> if this member does not have a name
- * (for example, an initializer), or if this member does not have
- * associated source code (for example, a binary type).
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- ISourceRange getNameRange() throws JavaModelException;
- /**
- * Returns whether this member is from a class file.
- * This is a handle-only method.
- *
- * @return <code>true</code> if from a class file, and <code>false</code> if
- * from a compilation unit
- */
- boolean isBinary();
+public interface IMember extends IJavaElement, ISourceReference, ISourceManipulation {
+/**
+ * Returns the class file in which this member is declared, or <code>null</code>
+ * if this member is not declared in a class file (for example, a source type).
+ * This is a handle-only method.
+ */
+IClassFile getClassFile();
+/**
+ * Returns the compilation unit in which this member is declared, or <code>null</code>
+ * if this member is not declared in a compilation unit (for example, a binary type).
+ * This is a handle-only method.
+ */
+ICompilationUnit getCompilationUnit();
+/**
+ * Returns the type in which this member is declared, or <code>null</code>
+ * if this member is not declared in a type (for example, a top-level type).
+ * This is a handle-only method.
+ */
+IType getDeclaringType();
+/**
+ * Returns the modifier flags for this member. The flags can be examined using class
+ * <code>Flags</code>.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ *
+ * @see Flags
+ */
+int getFlags() throws JavaModelException;
+/**
+ * Returns the source range of this member's simple name,
+ * or <code>null</code> if this member does not have a name
+ * (for example, an initializer), or if this member does not have
+ * associated source code (for example, a binary type).
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ */
+ISourceRange getNameRange() throws JavaModelException;
+/**
+ * Returns whether this member is from a class file.
+ * This is a handle-only method.
+ *
+ * @return <code>true</code> if from a class file, and <code>false</code> if
+ * from a compilation unit
+ */
+boolean isBinary();
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IMethod.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IMethod.java
index bd176f9e80..8cc01a6165 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IMethod.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IMethod.java
@@ -1,90 +1,90 @@
package org.eclipse.jdt.core;
public interface IMethod extends IMember {
- /**
- * Returns the simple name of this method.
- * For a constructor, this returns the simple name of the declaring type.
- * Note: This holds whether the constructor appears in a source or binary type
- * (even though class files internally define constructor names to be <code>"&lt;init&gt;"</code>).
- * For the class initialization methods in binary types, this returns
- * the special name <code>"&lt;clinit&gt;"</code>.
- * This is a handle-only method.
- */
- String getElementName();
- /**
- * Returns the type signatures of the exceptions this method throws,
- * in the order declared in the source. Returns an empty array
- * if this method throws no exceptions.
- *
- * <p>For example, a source method declaring <code>"throws IOException"</code>,
- * would return the array <code>{"QIOException;"}</code>.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- *
- * @see Signature
- */
- String[] getExceptionTypes() throws JavaModelException;
- /**
- * Returns the number of parameters of this method.
- * This is a handle-only method.
- */
- int getNumberOfParameters();
- /**
- * Returns the names of parameters in this method.
- * For binary types, these names are invented as "arg"+i, where i starts at 1
- * (even if source is associated with the binary).
- * Returns an empty array if this method has no parameters.
- *
- * <p>For example, a method declared as <code>public void foo(String text, int length)</code>
- * would return the array <code>{"text","length"}</code>.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- String[] getParameterNames() throws JavaModelException;
- /**
- * Returns the type signatures for the parameters of this method.
- * Returns an empty array if this method has no parameters.
- * This is a handle-only method.
- *
- * <p>For example, a source method declared as <code>public void foo(String text, int length)</code>
- * would return the array <code>{"QString;","I"}</code>.
- *
- * @see Signature
- */
- String[] getParameterTypes();
- /**
- * Returns the type signature of the return value of this method.
- * For constructors, this returns the signature for void.
- *
- * <p>For example, a source method declared as <code>public String getName()</code>
- * would return <code>"QString;"</code>.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- *
- * @see Signature
- */
- String getReturnType() throws JavaModelException;
- /**
- * Returns the signature of the method. This includes the signatures for the parameter
- * types and return type, but does not include the method name or exception types.
- *
- * <p>For example, a source method declared as <code>public void foo(String text, int length)</code>
- * would return <code>"(QString;I)V"</code>.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- *
- * @see Signature
- */
- String getSignature() throws JavaModelException;
- /**
- * Returns whether this method is a constructor.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- boolean isConstructor() throws JavaModelException;
+/**
+ * Returns the simple name of this method.
+ * For a constructor, this returns the simple name of the declaring type.
+ * Note: This holds whether the constructor appears in a source or binary type
+ * (even though class files internally define constructor names to be <code>"&lt;init&gt;"</code>).
+ * For the class initialization methods in binary types, this returns
+ * the special name <code>"&lt;clinit&gt;"</code>.
+ * This is a handle-only method.
+ */
+String getElementName();
+/**
+ * Returns the type signatures of the exceptions this method throws,
+ * in the order declared in the source. Returns an empty array
+ * if this method throws no exceptions.
+ *
+ * <p>For example, a source method declaring <code>"throws IOException"</code>,
+ * would return the array <code>{"QIOException;"}</code>.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ *
+ * @see Signature
+ */
+String[] getExceptionTypes() throws JavaModelException;
+/**
+ * Returns the number of parameters of this method.
+ * This is a handle-only method.
+ */
+int getNumberOfParameters();
+/**
+ * Returns the names of parameters in this method.
+ * For binary types, these names are invented as "arg"+i, where i starts at 1
+ * (even if source is associated with the binary).
+ * Returns an empty array if this method has no parameters.
+ *
+ * <p>For example, a method declared as <code>public void foo(String text, int length)</code>
+ * would return the array <code>{"text","length"}</code>.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ */
+String[] getParameterNames() throws JavaModelException;
+/**
+ * Returns the type signatures for the parameters of this method.
+ * Returns an empty array if this method has no parameters.
+ * This is a handle-only method.
+ *
+ * <p>For example, a source method declared as <code>public void foo(String text, int length)</code>
+ * would return the array <code>{"QString;","I"}</code>.
+ *
+ * @see Signature
+ */
+String[] getParameterTypes();
+/**
+ * Returns the type signature of the return value of this method.
+ * For constructors, this returns the signature for void.
+ *
+ * <p>For example, a source method declared as <code>public String getName()</code>
+ * would return <code>"QString;"</code>.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ *
+ * @see Signature
+ */
+String getReturnType() throws JavaModelException;
+/**
+ * Returns the signature of the method. This includes the signatures for the parameter
+ * types and return type, but does not include the method name or exception types.
+ *
+ * <p>For example, a source method declared as <code>public void foo(String text, int length)</code>
+ * would return <code>"(QString;I)V"</code>.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ *
+ * @see Signature
+ */
+String getSignature() throws JavaModelException;
+/**
+ * Returns whether this method is a constructor.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ */
+boolean isConstructor() throws JavaModelException;
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IOpenable.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IOpenable.java
index cd58a42b79..76490b5e1f 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IOpenable.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IOpenable.java
@@ -4,7 +4,7 @@ package org.eclipse.jdt.core;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
-
+
import org.eclipse.core.runtime.IProgressMonitor;
/**
@@ -38,112 +38,111 @@ import org.eclipse.core.runtime.IProgressMonitor;
*/
public interface IOpenable {
- /**
- * Closes this element and its buffer (if any).
- * Closing an element which is not open has no effect.
- *
- * <p>Note: although <code>close</code> is exposed in the API, clients are
- * not expected to open and close elements - the Java model does this automatically
- * as elements are accessed.
- *
- * @exception JavaModelException if an error occurs closing this element
- */
- public void close() throws JavaModelException;
- /**
- * Returns the buffer opened for this element, or <code>null</code>
- * if this element does not have a buffer.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- public IBuffer getBuffer() throws JavaModelException;
- /**
- * Returns <code>true</code> if this element is open and:
- * <ul>
- * <li>its buffer has unsaved changes, or
- * <li>one of its descendants has unsaved changes, or
- * <li>a working copy has been created on one of this
- * element's children and has not yet destroyed
- * </ul>
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- boolean hasUnsavedChanges() throws JavaModelException;
- /**
- * Returns whether the element is consistent with its underlying resource or buffer.
- * The element is consistent when opened, and is consistent if the underlying resource
- * or buffer has not been modified since it was last consistent.
- *
- * <p>NOTE: Child consistency is not considered. For example, a package fragment
- * responds <code>true</code> when it knows about all of its
- * compilation units present in its underlying folder. However, one or more of
- * the compilation units could be inconsistent.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- *
- * @see IOpenable#makeConsistent
- */
- boolean isConsistent() throws JavaModelException;
- /**
- * Returns whether this openable is open. This is a handle-only method.
- */
- boolean isOpen();
- /**
- * Makes this element consistent with its underlying resource or buffer
- * by updating the element's structure and properties as necessary.
- *
- * @exception JavaModelException if the element is unable to access the contents
- * of its underlying resource. Reasons include:
- * <ul>
- * <li>This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * </ul>
- * @see IOpenable#isConsistent
- */
- void makeConsistent(IProgressMonitor progress) throws JavaModelException;
- /**
- * Opens this element and all parent elements that are not already open.
- * For compilation units, a buffer is opened on the contents of the underlying resource.
- *
- * <p>Note: although <code>open</code> is exposed in the API, clients are
- * not expected to open and close elements - the Java model does this automatically
- * as elements are accessed.
- *
- * @exception JavaModelException if an error occurs accessing the contents
- * of its underlying resource. Reasons include:
- * <ul>
- * <li>This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * </ul>
- */
- public void open(IProgressMonitor progress) throws JavaModelException;
- /**
- * Saves any changes in this element's buffer to its underlying resource
- * via a workspace resource operation. This has no effect if the element has no underlying
- * buffer, or if there are no unsaved changed in the buffer.
- * <p>
- * The <code>force</code> parameter controls how this method deals with
- * cases where the workbench is not completely in sync with the local file system.
- * If <code>false</code> is specified, this method will only attempt
- * to overwrite a corresponding file in the local file system provided
- * it is in sync with the workbench. This option ensures there is no
- * unintended data loss; it is the recommended setting.
- * However, if <code>true</code> is specified, an attempt will be made
- * to write a corresponding file in the local file system,
- * overwriting any existing one if need be.
- * In either case, if this method succeeds, the resource will be marked
- * as being local (even if it wasn't before).
- * <p>
- * As a result of this operation, the element is consistent with its underlying
- * resource or buffer.
- *
- * @exception JavaModelException if an error occurs accessing the contents
- * of its underlying resource. Reasons include:
- * <ul>
- * <li>This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li>This Java element is read-only (READ_ONLY)</li>
- * </ul>
- */
- public void save(IProgressMonitor progress, boolean force)
- throws JavaModelException;
+/**
+ * Closes this element and its buffer (if any).
+ * Closing an element which is not open has no effect.
+ *
+ * <p>Note: although <code>close</code> is exposed in the API, clients are
+ * not expected to open and close elements - the Java model does this automatically
+ * as elements are accessed.
+ *
+ * @exception JavaModelException if an error occurs closing this element
+ */
+public void close() throws JavaModelException;
+/**
+ * Returns the buffer opened for this element, or <code>null</code>
+ * if this element does not have a buffer.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ */
+public IBuffer getBuffer() throws JavaModelException;
+/**
+ * Returns <code>true</code> if this element is open and:
+ * <ul>
+ * <li>its buffer has unsaved changes, or
+ * <li>one of its descendants has unsaved changes, or
+ * <li>a working copy has been created on one of this
+ * element's children and has not yet destroyed
+ * </ul>
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ */
+boolean hasUnsavedChanges() throws JavaModelException;
+/**
+ * Returns whether the element is consistent with its underlying resource or buffer.
+ * The element is consistent when opened, and is consistent if the underlying resource
+ * or buffer has not been modified since it was last consistent.
+ *
+ * <p>NOTE: Child consistency is not considered. For example, a package fragment
+ * responds <code>true</code> when it knows about all of its
+ * compilation units present in its underlying folder. However, one or more of
+ * the compilation units could be inconsistent.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ *
+ * @see IOpenable#makeConsistent
+ */
+boolean isConsistent() throws JavaModelException;
+/**
+ * Returns whether this openable is open. This is a handle-only method.
+ */
+boolean isOpen();
+/**
+ * Makes this element consistent with its underlying resource or buffer
+ * by updating the element's structure and properties as necessary.
+ *
+ * @exception JavaModelException if the element is unable to access the contents
+ * of its underlying resource. Reasons include:
+ * <ul>
+ * <li>This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * </ul>
+ * @see IOpenable#isConsistent
+ */
+void makeConsistent(IProgressMonitor progress) throws JavaModelException;
+/**
+ * Opens this element and all parent elements that are not already open.
+ * For compilation units, a buffer is opened on the contents of the underlying resource.
+ *
+ * <p>Note: although <code>open</code> is exposed in the API, clients are
+ * not expected to open and close elements - the Java model does this automatically
+ * as elements are accessed.
+ *
+ * @exception JavaModelException if an error occurs accessing the contents
+ * of its underlying resource. Reasons include:
+ * <ul>
+ * <li>This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * </ul>
+ */
+public void open(IProgressMonitor progress) throws JavaModelException;
+/**
+ * Saves any changes in this element's buffer to its underlying resource
+ * via a workspace resource operation. This has no effect if the element has no underlying
+ * buffer, or if there are no unsaved changed in the buffer.
+ * <p>
+ * The <code>force</code> parameter controls how this method deals with
+ * cases where the workbench is not completely in sync with the local file system.
+ * If <code>false</code> is specified, this method will only attempt
+ * to overwrite a corresponding file in the local file system provided
+ * it is in sync with the workbench. This option ensures there is no
+ * unintended data loss; it is the recommended setting.
+ * However, if <code>true</code> is specified, an attempt will be made
+ * to write a corresponding file in the local file system,
+ * overwriting any existing one if need be.
+ * In either case, if this method succeeds, the resource will be marked
+ * as being local (even if it wasn't before).
+ * <p>
+ * As a result of this operation, the element is consistent with its underlying
+ * resource or buffer.
+ *
+ * @exception JavaModelException if an error occurs accessing the contents
+ * of its underlying resource. Reasons include:
+ * <ul>
+ * <li>This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li>This Java element is read-only (READ_ONLY)</li>
+ * </ul>
+ */
+public void save(IProgressMonitor progress, boolean force) throws JavaModelException;
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IPackageDeclaration.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IPackageDeclaration.java
index 771053e061..b3723df89d 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IPackageDeclaration.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IPackageDeclaration.java
@@ -1,9 +1,9 @@
package org.eclipse.jdt.core;
public interface IPackageDeclaration extends IJavaElement, ISourceReference {
- /**
- * Returns the name of the package the statement refers to.
- * This is a handle-only method.
- */
- String getElementName();
+/**
+ * Returns the name of the package the statement refers to.
+ * This is a handle-only method.
+ */
+String getElementName();
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IPackageFragment.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IPackageFragment.java
index 6c46fdc30f..4f5c0f3074 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IPackageFragment.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IPackageFragment.java
@@ -4,7 +4,7 @@ package org.eclipse.jdt.core;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
-
+
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.resources.IResource;
@@ -23,118 +23,112 @@ import org.eclipse.core.resources.IResource;
* This interface is not intended to be implemented by clients.
* </p>
*/
-public interface IPackageFragment
- extends IParent, IJavaElement, IOpenable, ISourceManipulation {
+public interface IPackageFragment extends IParent, IJavaElement, IOpenable, ISourceManipulation {
/**
* <p>
* The name of package fragment for the default package (value: the empty
* string, <code>""</code>).
* </p>
- */
+ */
public static final String DEFAULT_PACKAGE_NAME = "";
- /**
- * Returns whether this fragment contains at least one Java resource.
- */
- boolean containsJavaResources() throws JavaModelException;
- /**
- * Creates and returns a compilation unit in this package fragment
- * with the specified name and contents. No verification is performed
- * on the contents.
- *
- * <p>It is possible that a compilation unit with the same name already exists in this
- * package fragment.
- * The value of the <code>force</code> parameter effects the resolution of
- * such a conflict:<ul>
- * <li> <code>true</code> - in this case the compilation is created with the new contents</li>
- * <li> <code>false</code> - in this case a <code>JavaModelException</code> is thrown</li>
- * </ul>
- *
- * @exception JavaModelException if the element could not be created. Reasons include:
- * <ul>
- * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while creating an underlying resource
- * <li> The name is not a valid compilation unit name (INVALID_NAME)
- * <li> The contents are <code>null</code> (INVALID_CONTENTS)
- * </ul>
- */
- ICompilationUnit createCompilationUnit(
- String name,
- String contents,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Returns the class file with the specified name
- * in this package (for example, <code>"Object.class"</code>).
- * The ".class" suffix is required.
- * This is a handle-only method. The class file may or may not be present.
- */
- IClassFile getClassFile(String name);
- /**
- * Returns all of the class files in this package fragment.
- *
- * <p>Note: it is possible that a package fragment contains only
- * compilation units (i.e. its kind is <code>K_SOURCE</code>), in
- * which case this method returns an empty collection.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- IClassFile[] getClassFiles() throws JavaModelException;
- /**
- * Returns the compilation unit with the specified name
- * in this package (for example, <code>"Object.java"</code>).
- * The ".java" suffix is required.
- * This is a handle-only method. The compilation unit may or may not be present.
- */
- ICompilationUnit getCompilationUnit(String name);
- /**
- * Returns all of the compilation units in this package fragment.
- *
- * <p>Note: it is possible that a package fragment contains only
- * class files (i.e. its kind is <code>K_BINARY</code>), in which
- * case this method returns an empty collection.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- ICompilationUnit[] getCompilationUnits() throws JavaModelException;
- /**
- * Returns the dot-separated package name of this fragment, for example
- * <code>"java.lang"</code>, or <code>""</code> (the empty string),
- * for the default package.
- */
- String getElementName();
- /**
- * Returns this package fragment's root kind encoded as an integer.
- * A package fragment can contain <code>.java</code> source files,
- * or <code>.class</code> files. This is a convenience method.
- *
- * @see IPackageFragmentRoot#K_SOURCE
- * @see IPackageFragmentRoot#K_BINARY
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- *
- */
- int getKind() throws JavaModelException;
- /**
- * Returns an array of non-Java resources contained in this package fragment.
- */
- Object[] getNonJavaResources() throws JavaModelException;
- /**
- * Returns whether this package fragment's name is
- * a prefix of other package fragments in this package fragment's
- * root.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- boolean hasSubpackages() throws JavaModelException;
- /**
- * Returns whether this package fragment is a default package.
- * This is a handle-only method.
- */
- boolean isDefaultPackage();
+/**
+ * Returns whether this fragment contains at least one Java resource.
+ */
+boolean containsJavaResources() throws JavaModelException;
+/**
+ * Creates and returns a compilation unit in this package fragment
+ * with the specified name and contents. No verification is performed
+ * on the contents.
+ *
+ * <p>It is possible that a compilation unit with the same name already exists in this
+ * package fragment.
+ * The value of the <code>force</code> parameter effects the resolution of
+ * such a conflict:<ul>
+ * <li> <code>true</code> - in this case the compilation is created with the new contents</li>
+ * <li> <code>false</code> - in this case a <code>JavaModelException</code> is thrown</li>
+ * </ul>
+ *
+ * @exception JavaModelException if the element could not be created. Reasons include:
+ * <ul>
+ * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> A <code>CoreException</code> occurred while creating an underlying resource
+ * <li> The name is not a valid compilation unit name (INVALID_NAME)
+ * <li> The contents are <code>null</code> (INVALID_CONTENTS)
+ * </ul>
+ */
+ICompilationUnit createCompilationUnit(String name, String contents, boolean force, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Returns the class file with the specified name
+ * in this package (for example, <code>"Object.class"</code>).
+ * The ".class" suffix is required.
+ * This is a handle-only method. The class file may or may not be present.
+ */
+IClassFile getClassFile(String name);
+/**
+ * Returns all of the class files in this package fragment.
+ *
+ * <p>Note: it is possible that a package fragment contains only
+ * compilation units (i.e. its kind is <code>K_SOURCE</code>), in
+ * which case this method returns an empty collection.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ */
+IClassFile[] getClassFiles() throws JavaModelException;
+/**
+ * Returns the compilation unit with the specified name
+ * in this package (for example, <code>"Object.java"</code>).
+ * The ".java" suffix is required.
+ * This is a handle-only method. The compilation unit may or may not be present.
+ */
+ICompilationUnit getCompilationUnit(String name);
+/**
+ * Returns all of the compilation units in this package fragment.
+ *
+ * <p>Note: it is possible that a package fragment contains only
+ * class files (i.e. its kind is <code>K_BINARY</code>), in which
+ * case this method returns an empty collection.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ */
+ICompilationUnit[] getCompilationUnits() throws JavaModelException;
+/**
+ * Returns the dot-separated package name of this fragment, for example
+ * <code>"java.lang"</code>, or <code>""</code> (the empty string),
+ * for the default package.
+ */
+String getElementName();
+/**
+ * Returns this package fragment's root kind encoded as an integer.
+ * A package fragment can contain <code>.java</code> source files,
+ * or <code>.class</code> files. This is a convenience method.
+ *
+ * @see IPackageFragmentRoot#K_SOURCE
+ * @see IPackageFragmentRoot#K_BINARY
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ *
+ */
+int getKind() throws JavaModelException;
+/**
+ * Returns an array of non-Java resources contained in this package fragment.
+ */
+Object[] getNonJavaResources() throws JavaModelException;
+/**
+ * Returns whether this package fragment's name is
+ * a prefix of other package fragments in this package fragment's
+ * root.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ */
+boolean hasSubpackages() throws JavaModelException;
+/**
+ * Returns whether this package fragment is a default package.
+ * This is a handle-only method.
+ */
+boolean isDefaultPackage();
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IPackageFragmentRoot.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IPackageFragmentRoot.java
index 473eb5f6e3..4304ae83c4 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IPackageFragmentRoot.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IPackageFragmentRoot.java
@@ -4,7 +4,7 @@ package org.eclipse.jdt.core;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
-
+
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
@@ -24,15 +24,14 @@ import org.eclipse.core.runtime.IProgressMonitor;
* This interface is not intended to be implemented by clients.
* </p>
*/
-public interface IPackageFragmentRoot
- extends IParent, IJavaElement, IOpenable {
-
+public interface IPackageFragmentRoot extends IParent, IJavaElement, IOpenable {
+
/**
* Kind constant for a source path root. Indicates this root
* only contains source files.
*/
int K_SOURCE = 1;
-
+
/**
* Kind constant for a binary path root. Indicates this
* root only contains binary files.
@@ -43,118 +42,113 @@ public interface IPackageFragmentRoot
*/
String DEFAULT_PACKAGEROOT_PATH = "";
- /**
- * Attaches the source archive identified by the given absolute path to this
- * JAR package fragment root. <code>rootPath</code> specifies the location
- * of the root within the archive (<code>null</code> or empty specifies the default root).
- * Once a source archive is attached to the JAR,
- * the <code>getSource</code> and <code>getSourceRange</code>
- * methods become operational for binary types/members.
- * To detach a source archive from a JAR, specify <code>null</code> as the
- * archivePath.
- *
- * @exception JavaModelException if this operation fails. Reasons include:
- * <ul>
- * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating a server property
- * <li> This package fragment root is not a JAR (INVALID_ELEMENT_TYPES)
- * <li> The path provided is not absolute (RELATIVE_PATH)
- * </ul>
- * @deprecated - source attachment is to be specified using classpath entries.
- */
- void attachSource(IPath archivePath, IPath rootPath, IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Creates and returns a package fragment in this root with the
- * given dot-separated package name. An empty string specifies the default package.
- * This has the side effect of creating all package
- * fragments that are a prefix of the new package fragment which
- * do not exist yet. If the package fragment already exists, this
- * has no effect.
- *
- * For a descrption of the <code>force</code> flag, see <code>IFolder.create</code>.
- *
- * @exception JavaModelException if the element could not be created. Reasons include:
- * <ul>
- * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while creating an underlying resource
- * <li> This package fragment root is read only (READ_ONLY)
- * <li> The name is not a valid package name (INVALID_NAME)
- * </ul>
- * @see org.eclipse.core.resources.IFolder#create
- */
- IPackageFragment createPackageFragment(
- String name,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Returns this package fragment root's kind encoded as an integer.
- * A package fragment root can contain <code>.java</code> source files,
- * or <code>.class</code> files, but not both.
- * If the underlying folder or archive contains other kinds of files, they are ignored.
- * In particular, <code>.class</code> files are ignored under a source package fragment root,
- * and <code>.java</code> files are ignored under a binary package fragment root.
- *
- * @see IPackageFragmentRoot#K_SOURCE
- * @see IPackageFragmentRoot#K_BINARY
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- int getKind() throws JavaModelException;
- /**
- * Returns an array of non-Java resources contained in this package fragment root.
- */
- Object[] getNonJavaResources() throws JavaModelException;
- /**
- * Returns the package fragment with the given package name.
- * An empty string indicates the default package.
- * This is a handle-only operation. The package fragment
- * may or may not exist.
- */
- IPackageFragment getPackageFragment(String packageName);
- /**
- * Returns the path of this package fragment root. If this
- * package fragment root is not external, the path returned is the
- * full, absolute path to this package fragment root, relative to the
- * workbench. If this package fragment root is external, the path
- * returned is the absolute path to this package fragment root's
- * archive in the file system.
- */
- IPath getPath();
- /**
- * Returns the absolute path to the source archive attached to
- * this package fragment root's binary archive.
- *
- * @return the absolute path to the corresponding source archive,
- * or <code>null</code> if this package fragment root's binary archive
- * has no corresponding source archive, or if this package fragment root
- * is not a binary archive
- * @exception JavaModelException if this operation fails
- */
- IPath getSourceAttachmentPath() throws JavaModelException;
- /**
- * Returns the path within this package fragment root's source archive.
- * An empty path indicates that packages are located at the root of the
- * source archive.
- *
- * @return the path within the corresponding source archive,
- * or <code>null</code> if this package fragment root's binary archive
- * has no corresponding source archive, or if this package fragment root
- * is not a binary archive
- * @exception JavaModelException if this operation fails
- */
- IPath getSourceAttachmentRootPath() throws JavaModelException;
- /**
- * Returns whether this package fragment root's underlying
- * resource is a binary archive (a JAR or zip file).
- */
- public boolean isArchive();
- /**
- * Returns whether this package fragment root is external
- * to the workbench (that is, a local file), and has no
- * underlying resource.
- */
- boolean isExternal();
+/**
+ * Attaches the source archive identified by the given absolute path to this
+ * JAR package fragment root. <code>rootPath</code> specifies the location
+ * of the root within the archive (<code>null</code> or empty specifies the default root).
+ * Once a source archive is attached to the JAR,
+ * the <code>getSource</code> and <code>getSourceRange</code>
+ * methods become operational for binary types/members.
+ * To detach a source archive from a JAR, specify <code>null</code> as the
+ * archivePath.
+ *
+ * @exception JavaModelException if this operation fails. Reasons include:
+ * <ul>
+ * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> A <code>CoreException</code> occurred while updating a server property
+ * <li> This package fragment root is not a JAR (INVALID_ELEMENT_TYPES)
+ * <li> The path provided is not absolute (RELATIVE_PATH)
+ * </ul>
+ * @deprecated - source attachment is to be specified using classpath entries.
+ */
+void attachSource(IPath archivePath, IPath rootPath, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Creates and returns a package fragment in this root with the
+ * given dot-separated package name. An empty string specifies the default package.
+ * This has the side effect of creating all package
+ * fragments that are a prefix of the new package fragment which
+ * do not exist yet. If the package fragment already exists, this
+ * has no effect.
+ *
+ * For a descrption of the <code>force</code> flag, see <code>IFolder.create</code>.
+ *
+ * @exception JavaModelException if the element could not be created. Reasons include:
+ * <ul>
+ * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> A <code>CoreException</code> occurred while creating an underlying resource
+ * <li> This package fragment root is read only (READ_ONLY)
+ * <li> The name is not a valid package name (INVALID_NAME)
+ * </ul>
+ * @see org.eclipse.core.resources.IFolder#create
+ */
+IPackageFragment createPackageFragment(String name, boolean force, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Returns this package fragment root's kind encoded as an integer.
+ * A package fragment root can contain <code>.java</code> source files,
+ * or <code>.class</code> files, but not both.
+ * If the underlying folder or archive contains other kinds of files, they are ignored.
+ * In particular, <code>.class</code> files are ignored under a source package fragment root,
+ * and <code>.java</code> files are ignored under a binary package fragment root.
+ *
+ * @see IPackageFragmentRoot#K_SOURCE
+ * @see IPackageFragmentRoot#K_BINARY
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ */
+int getKind() throws JavaModelException;
+/**
+ * Returns an array of non-Java resources contained in this package fragment root.
+ */
+Object[] getNonJavaResources() throws JavaModelException;
+/**
+ * Returns the package fragment with the given package name.
+ * An empty string indicates the default package.
+ * This is a handle-only operation. The package fragment
+ * may or may not exist.
+ */
+IPackageFragment getPackageFragment(String packageName);
+/**
+ * Returns the path of this package fragment root. If this
+ * package fragment root is not external, the path returned is the
+ * full, absolute path to this package fragment root, relative to the
+ * workbench. If this package fragment root is external, the path
+ * returned is the absolute path to this package fragment root's
+ * archive in the file system.
+ */
+IPath getPath();
+/**
+ * Returns the absolute path to the source archive attached to
+ * this package fragment root's binary archive.
+ *
+ * @return the absolute path to the corresponding source archive,
+ * or <code>null</code> if this package fragment root's binary archive
+ * has no corresponding source archive, or if this package fragment root
+ * is not a binary archive
+ * @exception JavaModelException if this operation fails
+ */
+IPath getSourceAttachmentPath() throws JavaModelException;
+/**
+ * Returns the path within this package fragment root's source archive.
+ * An empty path indicates that packages are located at the root of the
+ * source archive.
+ *
+ * @return the path within the corresponding source archive,
+ * or <code>null</code> if this package fragment root's binary archive
+ * has no corresponding source archive, or if this package fragment root
+ * is not a binary archive
+ * @exception JavaModelException if this operation fails
+ */
+IPath getSourceAttachmentRootPath() throws JavaModelException;
+/**
+ * Returns whether this package fragment root's underlying
+ * resource is a binary archive (a JAR or zip file).
+ */
+public boolean isArchive();
+/**
+ * Returns whether this package fragment root is external
+ * to the workbench (that is, a local file), and has no
+ * underlying resource.
+ */
+boolean isExternal();
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IParent.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IParent.java
index 161850017e..ef06f37ea7 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IParent.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IParent.java
@@ -1,22 +1,22 @@
package org.eclipse.jdt.core;
public interface IParent {
- /**
- * Returns the immediate children of this element.
- * Unless otherwise specified by the implementing element,
- * the children are in no particular order.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- IJavaElement[] getChildren() throws JavaModelException;
- /**
- * Returns whether this element has one or more immediate children.
- * This is a convenience method, and may be more efficient than
- * testing whether <code>getChildren</code> is an empty array.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- boolean hasChildren() throws JavaModelException;
+/**
+ * Returns the immediate children of this element.
+ * Unless otherwise specified by the implementing element,
+ * the children are in no particular order.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+IJavaElement[] getChildren() throws JavaModelException;
+/**
+ * Returns whether this element has one or more immediate children.
+ * This is a convenience method, and may be more efficient than
+ * testing whether <code>getChildren</code> is an empty array.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+boolean hasChildren() throws JavaModelException;
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IRegion.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IRegion.java
index 460d89db85..aedb33f9b8 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IRegion.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IRegion.java
@@ -1,29 +1,29 @@
package org.eclipse.jdt.core;
public interface IRegion {
- /**
- * Adds the given element and all of its descendents to this region.
- * If the specified element is already included, or one of its
- * ancestors is already included, this has no effect. If the element
- * being added is an ancestor of an element already contained in this
- * region, the ancestor subsumes the descendent.
- */
- void add(IJavaElement element);
- /**
- * Returns whether the given element is contained in this region.
- */
- boolean contains(IJavaElement element);
- /**
- * Returns the top level elements in this region.
- * All descendents of these elements are also included in this region.
- */
- IJavaElement[] getElements();
- /**
- * Removes the specified element from the region and returns
- * <code>true</code> if successful, <code>false</code> if the remove
- * fails. If an ancestor of the given element is included, the
- * remove fails (i.e. not possible to selectively
- * exclude descendants of included ancestors).
- */
- boolean remove(IJavaElement element);
+/**
+ * Adds the given element and all of its descendents to this region.
+ * If the specified element is already included, or one of its
+ * ancestors is already included, this has no effect. If the element
+ * being added is an ancestor of an element already contained in this
+ * region, the ancestor subsumes the descendent.
+ */
+void add(IJavaElement element);
+/**
+ * Returns whether the given element is contained in this region.
+ */
+boolean contains(IJavaElement element);
+/**
+ * Returns the top level elements in this region.
+ * All descendents of these elements are also included in this region.
+ */
+IJavaElement[] getElements();
+/**
+ * Removes the specified element from the region and returns
+ * <code>true</code> if successful, <code>false</code> if the remove
+ * fails. If an ancestor of the given element is included, the
+ * remove fails (i.e. not possible to selectively
+ * exclude descendants of included ancestors).
+ */
+boolean remove(IJavaElement element);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ISourceManipulation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ISourceManipulation.java
index 6915e56e3e..c8b79d6586 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ISourceManipulation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ISourceManipulation.java
@@ -4,7 +4,7 @@ package org.eclipse.jdt.core;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
-
+
import org.eclipse.core.runtime.IProgressMonitor;
/**
@@ -15,107 +15,94 @@ import org.eclipse.core.runtime.IProgressMonitor;
* </p>
*/
public interface ISourceManipulation {
- /**
- * Copies this element to the given container.
- *
- * @param container the container
- * @param sibling the sibling element before which the copy should be inserted,
- * or <code>null</code> if the copy should be inserted as the last child of
- * the container
- * @param rename the new name for the element, or <code>null</code> if the copy
- * retains the name of this element
- * @param replace <code>true</code> if any existing child in the container with
- * the target name should be replaced, and <code>false</code> to throw an
- * exception in the event of a name collision
- * @param monitor a progress monitor
- * @exception JavaModelException if this element could not be copied. Reasons include:
- * <ul>
- * <li> This Java element, container element, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> The container is of an incompatible type (INVALID_DESTINATION)
- * <li> The sibling is not a child of the given container (INVALID_SIBLING)
- * <li> The new name is invalid (INVALID_NAME)
- * <li> A child in the container already exists with the same name (NAME_COLLISION)
- * and <code>replace</code> has been specified as <code>false</code>
- * <li> The container or this element is read-only (READ_ONLY)
- * </ul>
- *
- * @exception IllegalArgumentException if container is <code>null</code>
- */
- void copy(
- IJavaElement container,
- IJavaElement sibling,
- String rename,
- boolean replace,
- IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Deletes this element, forcing if specified and necessary.
- *
- * @param force a flag controlling whether underlying resources that are not
- * in sync with the local file system will be tolerated (same as the force flag
- * in IResource operations).
- * @param monitor a progress monitor
- * @exception JavaModelException if this element could not be deleted. Reasons include:
- * <ul>
- * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource (CORE_EXCEPTION)</li>
- * <li> This element is read-only (READ_ONLY)</li>
- * </ul>
- */
- void delete(boolean force, IProgressMonitor monitor) throws JavaModelException;
- /**
- * Moves this element to the given container.
- *
- * @param container the container
- * @param sibling the sibling element before which the element should be inserted,
- * or <code>null</code> if the element should be inserted as the last child of
- * the container
- * @param rename the new name for the element, or <code>null</code> if the
- * element retains its name
- * @param replace <code>true</code> if any existing child in the container with
- * the target name should be replaced, and <code>false</code> to throw an
- * exception in the event of a name collision
- * @param monitor a progress monitor
- * @exception JavaModelException if this element could not be moved. Reasons include:
- * <ul>
- * <li> This Java element, container element, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> The container is of an incompatible type (INVALID_DESTINATION)
- * <li> The sibling is not a child of the given container (INVALID_SIBLING)
- * <li> The new name is invalid (INVALID_NAME)
- * <li> A child in the container already exists with the same name (NAME_COLLISION)
- * and <code>replace</code> has been specified as <code>false</code>
- * <li> The container or this element is read-only (READ_ONLY)
- * </ul>
- *
- * @exception IllegalArgumentException if container is <code>null</code>
- */
- void move(
- IJavaElement container,
- IJavaElement sibling,
- String rename,
- boolean replace,
- IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Renames this element to the given name.
- *
- * @param name the new name for the element
- * @param replace <code>true</code> if any existing element with the target name
- * should be replaced, and <code>false</code> to throw an exception in the
- * event of a name collision
- * @param monitor a progress monitor
- * @exception JavaModelException if this element could not be renamed. Reasons include:
- * <ul>
- * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> The new name is invalid (INVALID_NAME)
- * <li> A child in the container already exists with the same name (NAME_COLLISION)
- * and <code>replace</code> has been specified as <code>false</code>
- * <li> This element is read-only (READ_ONLY)
- * </ul>
- */
- void rename(String name, boolean replace, IProgressMonitor monitor)
- throws JavaModelException;
+/**
+ * Copies this element to the given container.
+ *
+ * @param container the container
+ * @param sibling the sibling element before which the copy should be inserted,
+ * or <code>null</code> if the copy should be inserted as the last child of
+ * the container
+ * @param rename the new name for the element, or <code>null</code> if the copy
+ * retains the name of this element
+ * @param replace <code>true</code> if any existing child in the container with
+ * the target name should be replaced, and <code>false</code> to throw an
+ * exception in the event of a name collision
+ * @param monitor a progress monitor
+ * @exception JavaModelException if this element could not be copied. Reasons include:
+ * <ul>
+ * <li> This Java element, container element, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> A <code>CoreException</code> occurred while updating an underlying resource
+ * <li> The container is of an incompatible type (INVALID_DESTINATION)
+ * <li> The sibling is not a child of the given container (INVALID_SIBLING)
+ * <li> The new name is invalid (INVALID_NAME)
+ * <li> A child in the container already exists with the same name (NAME_COLLISION)
+ * and <code>replace</code> has been specified as <code>false</code>
+ * <li> The container or this element is read-only (READ_ONLY)
+ * </ul>
+ *
+ * @exception IllegalArgumentException if container is <code>null</code>
+ */
+void copy(IJavaElement container, IJavaElement sibling, String rename, boolean replace, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Deletes this element, forcing if specified and necessary.
+ *
+ * @param force a flag controlling whether underlying resources that are not
+ * in sync with the local file system will be tolerated (same as the force flag
+ * in IResource operations).
+ * @param monitor a progress monitor
+ * @exception JavaModelException if this element could not be deleted. Reasons include:
+ * <ul>
+ * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> A <code>CoreException</code> occurred while updating an underlying resource (CORE_EXCEPTION)</li>
+ * <li> This element is read-only (READ_ONLY)</li>
+ * </ul>
+ */
+void delete(boolean force, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Moves this element to the given container.
+ *
+ * @param container the container
+ * @param sibling the sibling element before which the element should be inserted,
+ * or <code>null</code> if the element should be inserted as the last child of
+ * the container
+ * @param rename the new name for the element, or <code>null</code> if the
+ * element retains its name
+ * @param replace <code>true</code> if any existing child in the container with
+ * the target name should be replaced, and <code>false</code> to throw an
+ * exception in the event of a name collision
+ * @param monitor a progress monitor
+ * @exception JavaModelException if this element could not be moved. Reasons include:
+ * <ul>
+ * <li> This Java element, container element, or sibling does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> A <code>CoreException</code> occurred while updating an underlying resource
+ * <li> The container is of an incompatible type (INVALID_DESTINATION)
+ * <li> The sibling is not a child of the given container (INVALID_SIBLING)
+ * <li> The new name is invalid (INVALID_NAME)
+ * <li> A child in the container already exists with the same name (NAME_COLLISION)
+ * and <code>replace</code> has been specified as <code>false</code>
+ * <li> The container or this element is read-only (READ_ONLY)
+ * </ul>
+ *
+ * @exception IllegalArgumentException if container is <code>null</code>
+ */
+void move(IJavaElement container, IJavaElement sibling, String rename, boolean replace, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Renames this element to the given name.
+ *
+ * @param name the new name for the element
+ * @param replace <code>true</code> if any existing element with the target name
+ * should be replaced, and <code>false</code> to throw an exception in the
+ * event of a name collision
+ * @param monitor a progress monitor
+ * @exception JavaModelException if this element could not be renamed. Reasons include:
+ * <ul>
+ * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> A <code>CoreException</code> occurred while updating an underlying resource
+ * <li> The new name is invalid (INVALID_NAME)
+ * <li> A child in the container already exists with the same name (NAME_COLLISION)
+ * and <code>replace</code> has been specified as <code>false</code>
+ * <li> This element is read-only (READ_ONLY)
+ * </ul>
+ */
+void rename(String name, boolean replace, IProgressMonitor monitor) throws JavaModelException;
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ISourceRange.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ISourceRange.java
index 1a9eb62aa4..9fced6406b 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ISourceRange.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ISourceRange.java
@@ -2,14 +2,14 @@ package org.eclipse.jdt.core;
public interface ISourceRange {
- /**
- * Returns the number of characters of the source code for this element,
- * relative to the source buffer in which this element is contained.
- */
- int getLength();
- /**
- * Returns the 0-based index of the first character of the source code for this element,
- * relative to the source buffer in which this element is contained.
- */
- int getOffset();
+/**
+ * Returns the number of characters of the source code for this element,
+ * relative to the source buffer in which this element is contained.
+ */
+int getLength();
+/**
+ * Returns the 0-based index of the first character of the source code for this element,
+ * relative to the source buffer in which this element is contained.
+ */
+int getOffset();
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ISourceReference.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ISourceReference.java
index d92a6de117..0228695227 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ISourceReference.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ISourceReference.java
@@ -1,33 +1,33 @@
package org.eclipse.jdt.core;
public interface ISourceReference {
- /**
- * Returns the source code associated with this element.
- * This extracts the substring from the source buffer containing this source
- * element. This corresponds to the source range that would be returned by
- * <code>getSourceRange</code>.
- * <p>
- * For class files, this returns the source of the entire compilation unit
- * associated with the class file (if there is one).
- * </p>
- *
- * @return the source code, or <code>null</code> if this element has no
- * associated source code
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- String getSource() throws JavaModelException;
- /**
- * Returns the source range associated with this element.
- * <p>
- * For class files, this returns the range of the entire compilation unit
- * associated with the class file (if there is one).
- * </p>
- *
- * @return the source range, or <code>null</code> if if this element has no
- * associated source code
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource
- */
- ISourceRange getSourceRange() throws JavaModelException;
+/**
+ * Returns the source code associated with this element.
+ * This extracts the substring from the source buffer containing this source
+ * element. This corresponds to the source range that would be returned by
+ * <code>getSourceRange</code>.
+ * <p>
+ * For class files, this returns the source of the entire compilation unit
+ * associated with the class file (if there is one).
+ * </p>
+ *
+ * @return the source code, or <code>null</code> if this element has no
+ * associated source code
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+String getSource() throws JavaModelException;
+/**
+ * Returns the source range associated with this element.
+ * <p>
+ * For class files, this returns the range of the entire compilation unit
+ * associated with the class file (if there is one).
+ * </p>
+ *
+ * @return the source range, or <code>null</code> if if this element has no
+ * associated source code
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource
+ */
+ISourceRange getSourceRange() throws JavaModelException;
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IType.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IType.java
index 422560fa0b..e97251c0db 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IType.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IType.java
@@ -24,296 +24,274 @@ import org.eclipse.core.runtime.IProgressMonitor;
* </p>
*/
public interface IType extends IMember, IParent {
-
- /**
- * Creates and returns a field in this type with the
- * given contents.
- * <p>
- * Optionally, the new element can be positioned before the specified
- * sibling. If no sibling is specified, the element will be inserted
- * as the last field declaration in this type.
- *
- * <p>It is possible that a field with the same name already exists in this type.
- * The value of the <code>force</code> parameter effects the resolution of
- * such a conflict:<ul>
- * <li> <code>true</code> - in this case the field is created with the new contents</li>
- * <li> <code>false</code> - in this case a <code>JavaModelException</code> is thrown</li>
- *
- * @exception JavaModelException if the element could not be created. Reasons include:
- * <ul>
- * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> The specified sibling is not a child of this type (INVALID_SIBLING)
- * <li> The contents could not be recognized as a field declaration (INVALID_CONTENTS)
- * <li> This type is read-only (binary) (READ_ONLY)
- * <li> There was a naming collision with an existing field (NAME_COLLISION)
- * </ul>
- */
- IField createField(
- String contents,
- IJavaElement sibling,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Creates and returns a static initializer in this type with the
- * given contents.
- * <p>
- * Optionally, the new element can be positioned before the specified
- * sibling. If no sibling is specified, the new initializer is positioned
- * after the last existing initializer declaration, or as the first member
- * in the type if there are no
- * initializers.
- *
- * @exception JavaModelException if the element could not be created. Reasons include:
- * <ul>
- * <li> This element does not exist
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> The specified sibling is not a child of this type (INVALID_SIBLING)
- * <li> The contents could not be recognized as an initializer declaration (INVALID_CONTENTS)
- * <li> This type is read-only (binary) (READ_ONLY)
- * </ul>
- */
- IInitializer createInitializer(
- String contents,
- IJavaElement sibling,
- IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Creates and returns a method or constructor in this type with the
- * given contents.
- * <p>
- * Optionally, the new element can be positioned before the specified
- * sibling. If no sibling is specified, the element will be appended
- * to this type.
- *
- * <p>It is possible that a method with the same signature already exists in this type.
- * The value of the <code>force</code> parameter effects the resolution of
- * such a conflict:<ul>
- * <li> <code>true</code> - in this case the method is created with the new contents</li>
- * <li> <code>false</code> - in this case a <code>JavaModelException</code> is thrown</li>
- *
- * @exception JavaModelException if the element could not be created. Reasons include:
- * <ul>
- * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> The specified sibling is not a child of this type (INVALID_SIBLING)
- * <li> The contents could not be recognized as a method or constructor
- * declaration (INVALID_CONTENTS)
- * <li> This type is read-only (binary) (READ_ONLY)
- * <li> There was a naming collision with an existing method (NAME_COLLISION)
- * </ul>
- */
- IMethod createMethod(
- String contents,
- IJavaElement sibling,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Creates and returns a type in this type with the
- * given contents.
- * <p>
- * Optionally, the new type can be positioned before the specified
- * sibling. If no sibling is specified, the type will be appended
- * to this type.
- *
- * <p>It is possible that a type with the same name already exists in this type.
- * The value of the <code>force</code> parameter effects the resolution of
- * such a conflict:<ul>
- * <li> <code>true</code> - in this case the type is created with the new contents</li>
- * <li> <code>false</code> - in this case a <code>JavaModelException</code> is thrown</li>
- *
- * @exception JavaModelException if the element could not be created. Reasons include:
- * <ul>
- * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> The specified sibling is not a child of this type (INVALID_SIBLING)
- * <li> The contents could not be recognized as a type declaration (INVALID_CONTENTS)
- * <li> This type is read-only (binary) (READ_ONLY)
- * <li> There was a naming collision with an existing field (NAME_COLLISION)
- * </ul>
- */
- IType createType(
- String contents,
- IJavaElement sibling,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Returns the simple name of this type, unqualified by package or enclosing type.
- * This is a handle-only method.
- */
- String getElementName();
- /**
- * Returns the field with the specified name
- * in this type (for example, <code>"bar"</code>).
- * This is a handle-only method. The field may or may not exist.
- */
- IField getField(String name);
- /**
- * Returns the fields declared by this type.
- * If this is a source type, the results are listed in the order
- * in which they appear in the source, otherwise, the results are
- * in no particular order. For binary types, this includes synthetic fields.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- IField[] getFields() throws JavaModelException;
- /**
- * Returns the fully qualified name of this type,
- * including qualification for any containing types and packages.
- * This is the name of the package, followed by <code>'.'</code>,
- * followed by the type-qualified name.
- * This is a handle-only method.
- *
- * @see IType#getTypeQualifiedName()
- */
- String getFullyQualifiedName();
- /**
- * Returns the Initializer with the specified position relative to
- * the order they are defined in the source.
- * Numbering starts at 1 (i.e. the first occurrence is occurrence 1, not occurrence 0).
- * This is a handle-only method. The initializer may or may not be present.
- */
- IInitializer getInitializer(int occurrenceCount);
- /**
- * Returns the initializers declared by this type.
- * For binary types this is an empty collection.
- * If this is a source type, the results are listed in the order
- * in which they appear in the source.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- IInitializer[] getInitializers() throws JavaModelException;
- /**
- * Returns the method with the specified name and parameter types
- * in this type (for example, <code>"foo", {"I", "QString;"}</code>). To get the
- * handle for a constructor, the name specified must be the simple
- * name of the enclosing type.
- * This is a handle-only method. The method may or may not be present.
- */
- IMethod getMethod(String name, String[] parameterTypeSignatures);
- /**
- * Returns the methods and constructors declared by this type.
- * For binary types, this may include the special <code>&lt;clinit&gt</code>; method
- * and synthetic methods.
- * If this is a source type, the results are listed in the order
- * in which they appear in the source, otherwise, the results are
- * in no particular order.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- IMethod[] getMethods() throws JavaModelException;
- /**
- * Returns the package fragment in which this element is defined.
- * This is a handle-only method.
- */
- IPackageFragment getPackageFragment();
- /**
- * Returns the name of this type's superclass, or <code>null</code>
- * for source types that do not specify a superclass.
- * For interfaces, the superclass name is always <code>"java.lang.Object"</code>.
- * For source types, the name as declared is returned, for binary types,
- * the resolved, qualified name is returned.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- String getSuperclassName() throws JavaModelException;
- /**
- * Returns the names of interfaces that this type implements or extends,
- * in the order in which they are listed in the source.
- * For classes, this gives the interfaces that this class implements.
- * For interfaces, this gives the interfaces that this interface extends.
- * An empty collection is returned if this type does not implement or
- * extend any interfaces. For source types, simples name are returned,
- * for binary types, qualified names are returned.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- String[] getSuperInterfaceNames() throws JavaModelException;
- /**
- * Returns the member type declared in this type with the given simple name.
- * This is a handle-only method. The type may or may not exist.
- */
- IType getType(String name);
- /**
- * Returns the type-qualified name of this type,
- * including qualification for any enclosing types,
- * but not including package qualification.
- * For source types, this consists of the simple names of
- * any enclosing types, separated by <code>"$"</code>, followed by the simple name of this type.
- * For binary types, this is the name of the class file without the ".class" suffix.
- * This is a handle-only method.
- */
- String getTypeQualifiedName();
- /**
- * Returns the immediate member types declared by this type.
- * The results are listed in the order in which they appear in the source or class file.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- IType[] getTypes() throws JavaModelException;
- /**
- * Returns whether this type represents a class.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- boolean isClass() throws JavaModelException;
- /**
- * Returns whether this type represents an interface.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- boolean isInterface() throws JavaModelException;
- /**
- * Creates and returns a type hierarchy for this type containing
- * this type and all of its supertypes.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- ITypeHierarchy newSupertypeHierarchy(IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Creates and returns a type hierarchy for this type containing
- * this type, all of its supertypes, and all its subtypes in the workspace.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- ITypeHierarchy newTypeHierarchy(IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Creates and returns a type hierarchy for this type containing
- * this type, all of its supertypes, and all its subtypes
- * in the context of the given project.
- *
- * @exception JavaModelException if this element does not exist or if an
- * exception occurs while accessing its corresponding resource.
- */
- ITypeHierarchy newTypeHierarchy(IJavaProject project, IProgressMonitor monitor)
- throws JavaModelException;
- /**
- * Resolves the given type name within the context of this type (depending on the type hierarchy
- * and its imports). Multiple answers might be found in case there are ambiguous matches.
- *
- * Each matching type name is decomposed as an array of two strings, the first denoting the package
- * name (dot-separated) and the second being the type name.
- * Returns <code>null</code> if unable to find any matching type.
- *
- * For example, resolution of <code>"Object"</code> would typically return
- * <code>{{"java.lang", "Object"}}</code>.
- *
- * @exception JavaModelException if code resolve could not be performed.
- */
- String[][] resolveType(String typeName) throws JavaModelException;
+
+/**
+ * Creates and returns a field in this type with the
+ * given contents.
+ * <p>
+ * Optionally, the new element can be positioned before the specified
+ * sibling. If no sibling is specified, the element will be inserted
+ * as the last field declaration in this type.
+ *
+ * <p>It is possible that a field with the same name already exists in this type.
+ * The value of the <code>force</code> parameter effects the resolution of
+ * such a conflict:<ul>
+ * <li> <code>true</code> - in this case the field is created with the new contents</li>
+ * <li> <code>false</code> - in this case a <code>JavaModelException</code> is thrown</li>
+ *
+ * @exception JavaModelException if the element could not be created. Reasons include:
+ * <ul>
+ * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> A <code>CoreException</code> occurred while updating an underlying resource
+ * <li> The specified sibling is not a child of this type (INVALID_SIBLING)
+ * <li> The contents could not be recognized as a field declaration (INVALID_CONTENTS)
+ * <li> This type is read-only (binary) (READ_ONLY)
+ * <li> There was a naming collision with an existing field (NAME_COLLISION)
+ * </ul>
+ */
+IField createField(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Creates and returns a static initializer in this type with the
+ * given contents.
+ * <p>
+ * Optionally, the new element can be positioned before the specified
+ * sibling. If no sibling is specified, the new initializer is positioned
+ * after the last existing initializer declaration, or as the first member
+ * in the type if there are no
+ * initializers.
+ *
+ * @exception JavaModelException if the element could not be created. Reasons include:
+ * <ul>
+ * <li> This element does not exist
+ * <li> A <code>CoreException</code> occurred while updating an underlying resource
+ * <li> The specified sibling is not a child of this type (INVALID_SIBLING)
+ * <li> The contents could not be recognized as an initializer declaration (INVALID_CONTENTS)
+ * <li> This type is read-only (binary) (READ_ONLY)
+ * </ul>
+ */
+IInitializer createInitializer(String contents, IJavaElement sibling, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Creates and returns a method or constructor in this type with the
+ * given contents.
+ * <p>
+ * Optionally, the new element can be positioned before the specified
+ * sibling. If no sibling is specified, the element will be appended
+ * to this type.
+ *
+ * <p>It is possible that a method with the same signature already exists in this type.
+ * The value of the <code>force</code> parameter effects the resolution of
+ * such a conflict:<ul>
+ * <li> <code>true</code> - in this case the method is created with the new contents</li>
+ * <li> <code>false</code> - in this case a <code>JavaModelException</code> is thrown</li>
+ *
+ * @exception JavaModelException if the element could not be created. Reasons include:
+ * <ul>
+ * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> A <code>CoreException</code> occurred while updating an underlying resource
+ * <li> The specified sibling is not a child of this type (INVALID_SIBLING)
+ * <li> The contents could not be recognized as a method or constructor
+ * declaration (INVALID_CONTENTS)
+ * <li> This type is read-only (binary) (READ_ONLY)
+ * <li> There was a naming collision with an existing method (NAME_COLLISION)
+ * </ul>
+ */
+IMethod createMethod(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Creates and returns a type in this type with the
+ * given contents.
+ * <p>
+ * Optionally, the new type can be positioned before the specified
+ * sibling. If no sibling is specified, the type will be appended
+ * to this type.
+ *
+ * <p>It is possible that a type with the same name already exists in this type.
+ * The value of the <code>force</code> parameter effects the resolution of
+ * such a conflict:<ul>
+ * <li> <code>true</code> - in this case the type is created with the new contents</li>
+ * <li> <code>false</code> - in this case a <code>JavaModelException</code> is thrown</li>
+ *
+ * @exception JavaModelException if the element could not be created. Reasons include:
+ * <ul>
+ * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> A <code>CoreException</code> occurred while updating an underlying resource
+ * <li> The specified sibling is not a child of this type (INVALID_SIBLING)
+ * <li> The contents could not be recognized as a type declaration (INVALID_CONTENTS)
+ * <li> This type is read-only (binary) (READ_ONLY)
+ * <li> There was a naming collision with an existing field (NAME_COLLISION)
+ * </ul>
+ */
+IType createType(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Returns the simple name of this type, unqualified by package or enclosing type.
+ * This is a handle-only method.
+ */
+String getElementName();
+/**
+ * Returns the field with the specified name
+ * in this type (for example, <code>"bar"</code>).
+ * This is a handle-only method. The field may or may not exist.
+ */
+IField getField(String name);
+/**
+ * Returns the fields declared by this type.
+ * If this is a source type, the results are listed in the order
+ * in which they appear in the source, otherwise, the results are
+ * in no particular order. For binary types, this includes synthetic fields.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ */
+IField[] getFields() throws JavaModelException;
+/**
+ * Returns the fully qualified name of this type,
+ * including qualification for any containing types and packages.
+ * This is the name of the package, followed by <code>'.'</code>,
+ * followed by the type-qualified name.
+ * This is a handle-only method.
+ *
+ * @see IType#getTypeQualifiedName()
+ */
+String getFullyQualifiedName();
+/**
+ * Returns the Initializer with the specified position relative to
+ * the order they are defined in the source.
+ * Numbering starts at 1 (i.e. the first occurrence is occurrence 1, not occurrence 0).
+ * This is a handle-only method. The initializer may or may not be present.
+ */
+IInitializer getInitializer(int occurrenceCount);
+/**
+ * Returns the initializers declared by this type.
+ * For binary types this is an empty collection.
+ * If this is a source type, the results are listed in the order
+ * in which they appear in the source.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ */
+IInitializer[] getInitializers() throws JavaModelException;
+/**
+ * Returns the method with the specified name and parameter types
+ * in this type (for example, <code>"foo", {"I", "QString;"}</code>). To get the
+ * handle for a constructor, the name specified must be the simple
+ * name of the enclosing type.
+ * This is a handle-only method. The method may or may not be present.
+ */
+IMethod getMethod(String name, String[] parameterTypeSignatures);
+/**
+ * Returns the methods and constructors declared by this type.
+ * For binary types, this may include the special <code>&lt;clinit&gt</code>; method
+ * and synthetic methods.
+ * If this is a source type, the results are listed in the order
+ * in which they appear in the source, otherwise, the results are
+ * in no particular order.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ */
+IMethod[] getMethods() throws JavaModelException;
+/**
+ * Returns the package fragment in which this element is defined.
+ * This is a handle-only method.
+ */
+IPackageFragment getPackageFragment();
+/**
+ * Returns the name of this type's superclass, or <code>null</code>
+ * for source types that do not specify a superclass.
+ * For interfaces, the superclass name is always <code>"java.lang.Object"</code>.
+ * For source types, the name as declared is returned, for binary types,
+ * the resolved, qualified name is returned.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ */
+String getSuperclassName() throws JavaModelException;
+/**
+ * Returns the names of interfaces that this type implements or extends,
+ * in the order in which they are listed in the source.
+ * For classes, this gives the interfaces that this class implements.
+ * For interfaces, this gives the interfaces that this interface extends.
+ * An empty collection is returned if this type does not implement or
+ * extend any interfaces. For source types, simples name are returned,
+ * for binary types, qualified names are returned.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ */
+String[] getSuperInterfaceNames() throws JavaModelException;
+/**
+ * Returns the member type declared in this type with the given simple name.
+ * This is a handle-only method. The type may or may not exist.
+ */
+IType getType(String name) ;
+/**
+ * Returns the type-qualified name of this type,
+ * including qualification for any enclosing types,
+ * but not including package qualification.
+ * For source types, this consists of the simple names of
+ * any enclosing types, separated by <code>"$"</code>, followed by the simple name of this type.
+ * For binary types, this is the name of the class file without the ".class" suffix.
+ * This is a handle-only method.
+ */
+String getTypeQualifiedName();
+/**
+ * Returns the immediate member types declared by this type.
+ * The results are listed in the order in which they appear in the source or class file.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ */
+IType[] getTypes() throws JavaModelException;
+/**
+ * Returns whether this type represents a class.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ */
+boolean isClass() throws JavaModelException;
+/**
+ * Returns whether this type represents an interface.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ */
+boolean isInterface() throws JavaModelException;
+/**
+ * Creates and returns a type hierarchy for this type containing
+ * this type and all of its supertypes.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ */
+ITypeHierarchy newSupertypeHierarchy(IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Creates and returns a type hierarchy for this type containing
+ * this type, all of its supertypes, and all its subtypes in the workspace.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ */
+ITypeHierarchy newTypeHierarchy(IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Creates and returns a type hierarchy for this type containing
+ * this type, all of its supertypes, and all its subtypes
+ * in the context of the given project.
+ *
+ * @exception JavaModelException if this element does not exist or if an
+ * exception occurs while accessing its corresponding resource.
+ */
+ITypeHierarchy newTypeHierarchy(IJavaProject project, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Resolves the given type name within the context of this type (depending on the type hierarchy
+ * and its imports). Multiple answers might be found in case there are ambiguous matches.
+ *
+ * Each matching type name is decomposed as an array of two strings, the first denoting the package
+ * name (dot-separated) and the second being the type name.
+ * Returns <code>null</code> if unable to find any matching type.
+ *
+ * For example, resolution of <code>"Object"</code> would typically return
+ * <code>{{"java.lang", "Object"}}</code>.
+ *
+ * @exception JavaModelException if code resolve could not be performed.
+ */
+String[][] resolveType(String typeName) throws JavaModelException;
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ITypeHierarchy.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ITypeHierarchy.java
index aca73213be..bb9cfe4aae 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ITypeHierarchy.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ITypeHierarchy.java
@@ -33,167 +33,167 @@ import org.eclipse.core.runtime.IProgressMonitor;
* </p>
*/
public interface ITypeHierarchy {
- /**
- * Adds the given listener for changes to this type hierarchy. Listeners are
- * notified when this type hierarchy changes and needs to be refreshed.
- * Has no effect if an identical listener is already registered.
- *
- * @param listener the listener
- */
- void addTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener);
- /**
- * Returns whether the given type is part of this hierarchy.
- */
- boolean contains(IType type);
- /**
- * Returns whether the type and project this hierarchy was created on exist.
- */
- boolean exists();
- /**
- * Returns all classes in this type hierarchy's graph, in no particular
- * order. Any classes in the creation region which were not resolved to
- * have any subtypes or supertypes are not included in the result.
- */
- IType[] getAllClasses();
- /**
- * Returns all interfaces in this type hierarchy's graph, in no particular
- * order. Any interfaces in the creation region which were not resolved to
- * have any subtypes or supertypes are not included in the result.
- */
- IType[] getAllInterfaces();
- /**
- * Returns all resolved subtypes (direct and indirect) of the
- * given type, in no particular order, limited to the
- * types in this type hierarchy's graph. An empty array
- * is returned if there are no resolved subtypes for the
- * given type.
- */
- IType[] getAllSubtypes(IType type);
- /**
- * Returns all resolved superclasses of the
- * given class, in bottom-up order. An empty array
- * is returned if there are no resolved superclasses for the
- * given class.
- *
- * <p>NOTE: once a type hierarchy has been created, it is more efficient to
- * query the hierarchy for superclasses than to query a class recursively up
- * the superclass chain. Querying an element performs a dynamic resolution,
- * whereas the hierarchy returns a pre-computed result.
- */
- IType[] getAllSuperclasses(IType type);
- /**
- * Returns all resolved superinterfaces (direct and indirect) of the given type.
- * If the given type is a class, this includes all superinterfaces of all superclasses.
- * An empty array is returned if there are no resolved superinterfaces for the
- * given type.
- *
- * <p>NOTE: once a type hierarchy has been created, it is more efficient to
- * query the hierarchy for superinterfaces than to query a type recursively.
- * Querying an element performs a dynamic resolution,
- * whereas the hierarchy returns a pre-computed result.
- */
- IType[] getAllSuperInterfaces(IType type);
- /**
- * Returns all resolved supertypes of the
- * given class, in bottom-up order. An empty array
- * is returned if there are no resolved supertypes for the
- * given class.
- *
- * <p>NOTE: once a type hierarchy has been created, it is more efficient to
- * query the hierarchy for supertypes than to query a type recursively up
- * the supertype chain. Querying an element performs a dynamic resolution,
- * whereas the hierarchy returns a pre-computed result.
- */
- IType[] getAllSupertypes(IType type);
- /**
- * Returns all types in this type hierarchy's graph, in no particular
- * order. Any types in the creation region which were not resolved to
- * have any subtypes or supertypes are not included in the result.
- */
- IType[] getAllTypes();
- /**
- * Returns all interfaces resolved to extend the given interface,
- * in no particular order, limited to the interfaces in this
- * hierarchy's graph.
- * Returns an empty collection if the given type is a class, or
- * if no interfaces were resolved to extend the given interface.
- */
- IType[] getExtendingInterfaces(IType type);
- /**
- * Returns all classes resolved to implement the given interface,
- * in no particular order, limited to the classes in this type
- * hierarchy's graph. Returns an empty collection if the given type is a
- * class, or if no classes were resolved to implement the given
- * interface.
- */
- IType[] getImplementingClasses(IType type);
- /**
- * Returns all classes in the graph which have no resolved superclass,
- * in no particular order.
- */
- IType[] getRootClasses();
- /**
- * Returns all interfaces in the graph which have no resolved superinterfaces,
- * in no particular order.
- */
- IType[] getRootInterfaces();
- /**
- * Returns the direct resolved subclasses of the given class,
- * in no particular order, limited to the classes in this
- * type hierarchy's graph.
- * Returns an empty collection if the given type is an interface,
- * or if no classes were resolved to be subclasses of the given
- * class.
- */
- IType[] getSubclasses(IType type);
- /**
- * Returns the direct resolved subtypes of the given type,
- * in no particular order, limited to the types in this
- * type hierarchy's graph.
- * If the type is a class, this returns the resolved subclasses.
- * If the type is an interface, this returns both the classes which implement
- * the interface and the interfaces which extend it.
- */
- IType[] getSubtypes(IType type);
- /**
- * Returns the resolved superclass of the given class,
- * or <code>null</code> if the given class has no superclass,
- * the superclass could not be resolved, or if the given
- * type is an interface.
- */
- IType getSuperclass(IType type);
- /**
- * Returns the direct resolved interfaces that the given type implements or extends,
- * in no particular order, limited to the interfaces in this type
- * hierarchy's graph.
- * For classes, this gives the interfaces that the class implements.
- * For interfaces, this gives the interfaces that the interface extends.
- */
- IType[] getSuperInterfaces(IType type);
- /**
- * Returns the resolved supertypes of the given type,
- * in no particular order, limited to the types in this
- * type hierarchy's graph.
- * For classes, this returns its superclass and the interfaces that the class implements.
- * For interfaces, this returns the interfaces that the interface extends.
- */
- IType[] getSupertypes(IType type);
- /**
- * Returns the type this hierarchy was computed for.
- * Returns <code>null</code> if this hierarchy was computed for a region.
- */
- IType getType();
- /**
- * Re-computes the type hierarchy reporting progess.
- *
- * @exception JavaModelException if unable to refresh the hierarchy
- */
- void refresh(IProgressMonitor monitor) throws JavaModelException;
- /**
- * Removes the given listener from this type hierarchy.
- * Has no affect if an identical listener is not registered.
- *
- * @param listener the listener
- */
- void removeTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener);
+/**
+ * Adds the given listener for changes to this type hierarchy. Listeners are
+ * notified when this type hierarchy changes and needs to be refreshed.
+ * Has no effect if an identical listener is already registered.
+ *
+ * @param listener the listener
+ */
+void addTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener);
+/**
+ * Returns whether the given type is part of this hierarchy.
+ */
+boolean contains(IType type);
+/**
+ * Returns whether the type and project this hierarchy was created on exist.
+ */
+boolean exists();
+/**
+ * Returns all classes in this type hierarchy's graph, in no particular
+ * order. Any classes in the creation region which were not resolved to
+ * have any subtypes or supertypes are not included in the result.
+ */
+IType[] getAllClasses();
+/**
+ * Returns all interfaces in this type hierarchy's graph, in no particular
+ * order. Any interfaces in the creation region which were not resolved to
+ * have any subtypes or supertypes are not included in the result.
+ */
+IType[] getAllInterfaces();
+/**
+ * Returns all resolved subtypes (direct and indirect) of the
+ * given type, in no particular order, limited to the
+ * types in this type hierarchy's graph. An empty array
+ * is returned if there are no resolved subtypes for the
+ * given type.
+ */
+IType[] getAllSubtypes(IType type);
+/**
+ * Returns all resolved superclasses of the
+ * given class, in bottom-up order. An empty array
+ * is returned if there are no resolved superclasses for the
+ * given class.
+ *
+ * <p>NOTE: once a type hierarchy has been created, it is more efficient to
+ * query the hierarchy for superclasses than to query a class recursively up
+ * the superclass chain. Querying an element performs a dynamic resolution,
+ * whereas the hierarchy returns a pre-computed result.
+ */
+IType[] getAllSuperclasses(IType type);
+/**
+ * Returns all resolved superinterfaces (direct and indirect) of the given type.
+ * If the given type is a class, this includes all superinterfaces of all superclasses.
+ * An empty array is returned if there are no resolved superinterfaces for the
+ * given type.
+ *
+ * <p>NOTE: once a type hierarchy has been created, it is more efficient to
+ * query the hierarchy for superinterfaces than to query a type recursively.
+ * Querying an element performs a dynamic resolution,
+ * whereas the hierarchy returns a pre-computed result.
+ */
+IType[] getAllSuperInterfaces(IType type);
+/**
+ * Returns all resolved supertypes of the
+ * given class, in bottom-up order. An empty array
+ * is returned if there are no resolved supertypes for the
+ * given class.
+ *
+ * <p>NOTE: once a type hierarchy has been created, it is more efficient to
+ * query the hierarchy for supertypes than to query a type recursively up
+ * the supertype chain. Querying an element performs a dynamic resolution,
+ * whereas the hierarchy returns a pre-computed result.
+ */
+IType[] getAllSupertypes(IType type);
+/**
+ * Returns all types in this type hierarchy's graph, in no particular
+ * order. Any types in the creation region which were not resolved to
+ * have any subtypes or supertypes are not included in the result.
+ */
+IType[] getAllTypes();
+/**
+ * Returns all interfaces resolved to extend the given interface,
+ * in no particular order, limited to the interfaces in this
+ * hierarchy's graph.
+ * Returns an empty collection if the given type is a class, or
+ * if no interfaces were resolved to extend the given interface.
+ */
+IType[] getExtendingInterfaces(IType type);
+/**
+ * Returns all classes resolved to implement the given interface,
+ * in no particular order, limited to the classes in this type
+ * hierarchy's graph. Returns an empty collection if the given type is a
+ * class, or if no classes were resolved to implement the given
+ * interface.
+ */
+IType[] getImplementingClasses(IType type);
+/**
+ * Returns all classes in the graph which have no resolved superclass,
+ * in no particular order.
+ */
+IType[] getRootClasses();
+/**
+ * Returns all interfaces in the graph which have no resolved superinterfaces,
+ * in no particular order.
+ */
+IType[] getRootInterfaces();
+/**
+ * Returns the direct resolved subclasses of the given class,
+ * in no particular order, limited to the classes in this
+ * type hierarchy's graph.
+ * Returns an empty collection if the given type is an interface,
+ * or if no classes were resolved to be subclasses of the given
+ * class.
+ */
+IType[] getSubclasses(IType type);
+/**
+ * Returns the direct resolved subtypes of the given type,
+ * in no particular order, limited to the types in this
+ * type hierarchy's graph.
+ * If the type is a class, this returns the resolved subclasses.
+ * If the type is an interface, this returns both the classes which implement
+ * the interface and the interfaces which extend it.
+ */
+IType[] getSubtypes(IType type);
+/**
+ * Returns the resolved superclass of the given class,
+ * or <code>null</code> if the given class has no superclass,
+ * the superclass could not be resolved, or if the given
+ * type is an interface.
+ */
+IType getSuperclass(IType type);
+/**
+ * Returns the direct resolved interfaces that the given type implements or extends,
+ * in no particular order, limited to the interfaces in this type
+ * hierarchy's graph.
+ * For classes, this gives the interfaces that the class implements.
+ * For interfaces, this gives the interfaces that the interface extends.
+ */
+IType[] getSuperInterfaces(IType type);
+/**
+ * Returns the resolved supertypes of the given type,
+ * in no particular order, limited to the types in this
+ * type hierarchy's graph.
+ * For classes, this returns its superclass and the interfaces that the class implements.
+ * For interfaces, this returns the interfaces that the interface extends.
+ */
+IType[] getSupertypes(IType type);
+/**
+ * Returns the type this hierarchy was computed for.
+ * Returns <code>null</code> if this hierarchy was computed for a region.
+ */
+IType getType();
+/**
+ * Re-computes the type hierarchy reporting progess.
+ *
+ * @exception JavaModelException if unable to refresh the hierarchy
+ */
+void refresh(IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Removes the given listener from this type hierarchy.
+ * Has no affect if an identical listener is not registered.
+ *
+ * @param listener the listener
+ */
+void removeTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ITypeHierarchyChangedListener.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ITypeHierarchyChangedListener.java
index d95b2d90f0..cf59398365 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ITypeHierarchyChangedListener.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/ITypeHierarchyChangedListener.java
@@ -1,10 +1,10 @@
package org.eclipse.jdt.core;
public interface ITypeHierarchyChangedListener {
- /**
- * Notifies that the given type hierarchy has changed in some way and should
- * be refreshed at some point to make it consistent with the current state of
- * the Java model.
- */
- void typeHierarchyChanged(ITypeHierarchy typeHierarchy);
+/**
+ * Notifies that the given type hierarchy has changed in some way and should
+ * be refreshed at some point to make it consistent with the current state of
+ * the Java model.
+ */
+void typeHierarchyChanged(ITypeHierarchy typeHierarchy);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IWorkingCopy.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IWorkingCopy.java
index a6b48e04c1..3a2bef6d6d 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IWorkingCopy.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/IWorkingCopy.java
@@ -4,7 +4,7 @@ package org.eclipse.jdt.core;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
-
+
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
@@ -46,102 +46,102 @@ import org.eclipse.core.runtime.IProgressMonitor;
* </p>
*/
public interface IWorkingCopy {
- /**
- * Commits the contents of this working copy to its original element
- * and underlying resource, bringing the Java model up-to-date with
- * the current contents of the working copy.
- *
- * <p>It is possible that the contents of the original resource have changed
- * since this working copy was created, in which case there is an update conflict.
- * The value of the <code>force</code> parameter effects the resolution of
- * such a conflict:<ul>
- * <li> <code>true</code> - in this case the contents of this working copy are applied to
- * the underlying resource even though this working copy was created before
- * a subsequent change in the resource</li>
- * <li> <code>false</code> - in this case a <code>JavaModelException</code> is thrown</li>
- * </ul>
- *
- * @exception JavaModelException if this working copy could not commit. Reasons include:
- * <ul>
- * <li> The original Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * <li> A <code>CoreException</code> occurred while updating an underlying resource
- * <li> This element is not a working copy (INVALID_ELEMENT_TYPES)
- * <li> A update conflict (described above) (UPDATE_CONFLICT)
- * </ul>
- */
- void commit(boolean force, IProgressMonitor monitor) throws JavaModelException;
- /**
- * Destroys this working copy, closing its buffer and discarding
- * its structure. Subsequent attempts to access non-handle information
- * for this working copy will result in <code>IJavaModelException</code>s. Has
- * no effect if this element is not a working copy.
- */
- void destroy();
- /**
- * Returns the original element the specified working copy element was created from,
- * or <code>null</code> if this is not a working copy element. This is a handle
- * only method, the returned element may or may not exist.
- */
- IJavaElement getOriginal(IJavaElement workingCopyElement);
- /**
- * Returns the original element this working copy was created from,
- * or <code>null</code> if this is not a working copy.
- */
- IJavaElement getOriginalElement();
- /**
- * Returns a working copy of this element if this element is not
- * a working copy, or this element if this element is a working copy.
- *
- * @exception JavaModelException if the contents of this element can
- * not be determined. Reasons include:
- * <ul>
- * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * </ul>
- */
- IJavaElement getWorkingCopy() throws JavaModelException;
- /**
- * Returns whether this working copy's original element's content
- * has not changed since the inception of this working copy.
- */
- boolean isBasedOn(IResource resource);
- /**
- * Returns whether this element is a working copy.
- */
- boolean isWorkingCopy();
- /**
- * Reconciles the contents of this working copy.
- * It performs the reconciliation by locally caching the contents of
- * the working copy, updating the contents, then creating a delta
- * over the cached contents and the new contents, and finally firing
- * this delta.
- * <p>
- * Returns the syntax problems found in the new contents as transient markers
- * associated with the original element. Returns <code>null</code> if no problems were found.
- * <p>
- * Note: It has been assumed that added inner types should
- * not generate change deltas. The implementation has been
- * modified to reflect this assumption.
- *
- * @exception JavaModelException if the contents of the original element
- * cannot be accessed. Reasons include:
- * <ul>
- * <li> The original Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * </ul>
- */
- IMarker[] reconcile() throws JavaModelException;
- /**
- * Restores the contents of this working copy to the current contents of
- * this working copy's original element. Has no effect if this element
- * is not a working copy.
- *
- * <p>Note: This is the inverse of committing the content of the
- * working copy to the original element with <code>commit(boolean, IProgressMonitor)</code>.
- *
- * @exception JavaModelException if the contents of the original element
- * cannot be accessed. Reasons include:
- * <ul>
- * <li> The original Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
- * </ul>
- */
- void restore() throws JavaModelException;
+/**
+ * Commits the contents of this working copy to its original element
+ * and underlying resource, bringing the Java model up-to-date with
+ * the current contents of the working copy.
+ *
+ * <p>It is possible that the contents of the original resource have changed
+ * since this working copy was created, in which case there is an update conflict.
+ * The value of the <code>force</code> parameter effects the resolution of
+ * such a conflict:<ul>
+ * <li> <code>true</code> - in this case the contents of this working copy are applied to
+ * the underlying resource even though this working copy was created before
+ * a subsequent change in the resource</li>
+ * <li> <code>false</code> - in this case a <code>JavaModelException</code> is thrown</li>
+ * </ul>
+ *
+ * @exception JavaModelException if this working copy could not commit. Reasons include:
+ * <ul>
+ * <li> The original Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * <li> A <code>CoreException</code> occurred while updating an underlying resource
+ * <li> This element is not a working copy (INVALID_ELEMENT_TYPES)
+ * <li> A update conflict (described above) (UPDATE_CONFLICT)
+ * </ul>
+ */
+void commit(boolean force, IProgressMonitor monitor) throws JavaModelException;
+/**
+ * Destroys this working copy, closing its buffer and discarding
+ * its structure. Subsequent attempts to access non-handle information
+ * for this working copy will result in <code>IJavaModelException</code>s. Has
+ * no effect if this element is not a working copy.
+ */
+void destroy();
+/**
+ * Returns the original element the specified working copy element was created from,
+ * or <code>null</code> if this is not a working copy element. This is a handle
+ * only method, the returned element may or may not exist.
+ */
+IJavaElement getOriginal(IJavaElement workingCopyElement);
+/**
+ * Returns the original element this working copy was created from,
+ * or <code>null</code> if this is not a working copy.
+ */
+IJavaElement getOriginalElement();
+/**
+ * Returns a working copy of this element if this element is not
+ * a working copy, or this element if this element is a working copy.
+ *
+ * @exception JavaModelException if the contents of this element can
+ * not be determined. Reasons include:
+ * <ul>
+ * <li> This Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * </ul>
+ */
+IJavaElement getWorkingCopy() throws JavaModelException;
+/**
+ * Returns whether this working copy's original element's content
+ * has not changed since the inception of this working copy.
+ */
+boolean isBasedOn(IResource resource);
+/**
+ * Returns whether this element is a working copy.
+ */
+boolean isWorkingCopy();
+/**
+ * Reconciles the contents of this working copy.
+ * It performs the reconciliation by locally caching the contents of
+ * the working copy, updating the contents, then creating a delta
+ * over the cached contents and the new contents, and finally firing
+ * this delta.
+ * <p>
+ * Returns the syntax problems found in the new contents as transient markers
+ * associated with the original element. Returns <code>null</code> if no problems were found.
+ * <p>
+ * Note: It has been assumed that added inner types should
+ * not generate change deltas. The implementation has been
+ * modified to reflect this assumption.
+ *
+ * @exception JavaModelException if the contents of the original element
+ * cannot be accessed. Reasons include:
+ * <ul>
+ * <li> The original Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * </ul>
+ */
+IMarker[] reconcile() throws JavaModelException;
+/**
+ * Restores the contents of this working copy to the current contents of
+ * this working copy's original element. Has no effect if this element
+ * is not a working copy.
+ *
+ * <p>Note: This is the inverse of committing the content of the
+ * working copy to the original element with <code>commit(boolean, IProgressMonitor)</code>.
+ *
+ * @exception JavaModelException if the contents of the original element
+ * cannot be accessed. Reasons include:
+ * <ul>
+ * <li> The original Java element does not exist (ELEMENT_DOES_NOT_EXIST)</li>
+ * </ul>
+ */
+void restore() throws JavaModelException;
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaConventions.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaConventions.java
index 1e10089075..682d8686d1 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaConventions.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaConventions.java
@@ -4,10 +4,7 @@ package org.eclipse.jdt.core;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Status;
+
import org.eclipse.jdt.internal.compiler.parser.InvalidInputException;
import org.eclipse.jdt.internal.compiler.parser.Scanner;
@@ -17,6 +14,12 @@ import org.eclipse.jdt.internal.compiler.util.CharOperation;
import java.util.StringTokenizer;
+import org.eclipse.jdt.internal.core.JavaModelStatus;
+import org.eclipse.core.runtime.*;
+import java.io.File;
+import org.eclipse.jdt.internal.core.*;
+import org.eclipse.core.resources.*;
+
/**
* Provides methods for checking Java-specific conventions such as name syntax.
* <p>
@@ -25,374 +28,443 @@ import java.util.StringTokenizer;
* </p>
*/
public final class JavaConventions {
- private final static char fgDot = '.';
- private final static String fgJAVA = "JAVA";
- /**
- * Not instantiable.
- */
- private JavaConventions() {
+ private final static char fgDot= '.';
+ private final static String fgJAVA= "JAVA";
+/**
+ * Not instantiable.
+ */
+private JavaConventions() {}
+/**
+ * Returns whether the given package fragment root paths are considered
+ * to overlap.
+ * <p>
+ * Two root paths overlap if one is a prefix of the other, or they point to
+ * the same location. However, a JAR is allowed to be nested in a root.
+ *
+ */
+public static boolean isOverlappingRoots(IPath rootPath1, IPath rootPath2) {
+ if (rootPath1 == null || rootPath2 == null) {
+ return false;
}
-
- /**
- * Returns whether the given package fragment root paths are considered
- * to overlap.
- * <p>
- * Two root paths overlap if one is a prefix of the other, or they point to
- * the same location. However, a JAR is allowed to be nested in a root.
- *
- */
- public static boolean isOverlappingRoots(IPath rootPath1, IPath rootPath2) {
- if (rootPath1 == null || rootPath2 == null) {
- return false;
- }
- String extension1 = rootPath1.getFileExtension();
- String extension2 = rootPath2.getFileExtension();
- String jarExtension = "JAR";
- String zipExtension = "ZIP";
- if (extension1 != null
- && (extension1.equalsIgnoreCase(jarExtension)
- || extension1.equalsIgnoreCase(zipExtension))) {
- return false;
- }
- if (extension2 != null
- && (extension2.equalsIgnoreCase(jarExtension)
- || extension2.equalsIgnoreCase(zipExtension))) {
- return false;
- }
- return rootPath1.isPrefixOf(rootPath2) || rootPath2.isPrefixOf(rootPath1);
+ String extension1 = rootPath1.getFileExtension();
+ String extension2 = rootPath2.getFileExtension();
+ String jarExtension = "JAR";
+ String zipExtension = "ZIP";
+ if (extension1 != null && (extension1.equalsIgnoreCase(jarExtension) || extension1.equalsIgnoreCase(zipExtension))) {
+ return false;
+ }
+ if (extension2 != null && (extension2.equalsIgnoreCase(jarExtension) || extension2.equalsIgnoreCase(zipExtension))) {
+ return false;
}
-
- /**
- * Returns the current identifier extracted by the scanner (ie. without unicodes)
- * from the given id.
- * Returns <code>null</code> if the id was not valid.
- */
- private static char[] scannedIdentifier(String id) {
- if (id == null) {
+ return rootPath1.isPrefixOf(rootPath2) || rootPath2.isPrefixOf(rootPath1);
+}
+/**
+ * Returns the current identifier extracted by the scanner (ie. without unicodes)
+ * from the given id.
+ * Returns <code>null</code> if the id was not valid.
+ */
+private static char[] scannedIdentifier(String id) {
+ if (id == null) {
+ return null;
+ }
+ String trimmed = id.trim();
+ if (!trimmed.equals(id)) {
+ return null;
+ }
+ try {
+ Scanner scanner = new Scanner();
+ scanner.setSourceBuffer(id.toCharArray());
+ int token = scanner.getNextToken();
+ char[] currentIdentifier;
+ try {
+ currentIdentifier = scanner.getCurrentIdentifierSource();
+ } catch (ArrayIndexOutOfBoundsException e) {
return null;
}
- String trimmed = id.trim();
- if (!trimmed.equals(id)) {
+ int nextToken= scanner.getNextToken();
+ if (token == TerminalSymbols.TokenNameIdentifier
+ && nextToken == TerminalSymbols.TokenNameEOF
+ && scanner.startPosition == scanner.source.length) { // to handle case where we had an ArrayIndexOutOfBoundsException
+ // while reading the last token
+ return currentIdentifier;
+ } else {
return null;
}
- try {
- Scanner scanner = new Scanner();
- scanner.setSourceBuffer(id.toCharArray());
- int token = scanner.getNextToken();
- char[] currentIdentifier;
- try {
- currentIdentifier = scanner.getCurrentIdentifierSource();
- } catch (ArrayIndexOutOfBoundsException e) {
- return null;
- }
- int nextToken = scanner.getNextToken();
- if (token == TerminalSymbols.TokenNameIdentifier
- && nextToken == TerminalSymbols.TokenNameEOF
- && scanner.startPosition == scanner.source.length) {
- // to handle case where we had an ArrayIndexOutOfBoundsException
- // while reading the last token
- return currentIdentifier;
- } else {
- return null;
- }
- } catch (InvalidInputException e) {
- return null;
+ }
+ catch (InvalidInputException e) {
+ return null;
+ }
+}
+/**
+ * Validate the given compilation unit name.
+ * A compilation unit name must obey the following rules:
+ * <ul>
+ * <li> it must not be null
+ * <li> it must include the <code>".java"</code> suffix
+ * <li> its prefix must be a valid identifier
+ * </ul>
+ * </p>
+ * @param name the name of a compilation unit
+ * @return a status object with code <code>IStatus.OK</code> if
+ * the given name is valid as a compilation unit name, otherwise a status
+ * object indicating what is wrong with the name
+ */
+public static IStatus validateCompilationUnitName(String name) {
+ if (name == null) {
+ return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, "Compilation unit name must not be null", null);
+ }
+ String extension;
+ String identifier;
+ int index;
+ index = name.indexOf('.');
+ if (index == -1) {
+ return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, "Compilation unit name must include the \".java\" suffix", null);
+ }
+ identifier = name.substring(0, index);
+ extension = name.substring(index + 1);
+ IStatus status = validateIdentifier(identifier);
+ if (!status.isOK()) {
+ return status;
+ }
+ if (!Util.isJavaFileName(name)) {
+ return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, "Compilation unit name must include the \".java\" suffix", null);
+ }
+ return new Status(IStatus.OK, JavaCore.PLUGIN_ID, -1, "OK", null);
+}
+/**
+ * Validate the given field name.
+ * <p>
+ * Syntax of a field name corresponds to VariableDeclaratorId (JLS2 8.3).
+ * For example, <code>"x"</code>.
+ *
+ * @param name the name of a field
+ * @return a status object with code <code>IStatus.OK</code> if
+ * the given name is valid as a field name, otherwise a status
+ * object indicating what is wrong with the name
+ */
+public static IStatus validateFieldName(String name) {
+ return validateIdentifier(name);
+}
+/**
+ * Validate the given Java identifier.
+ * The identifier must have the same spelling as a Java keyword,
+ * boolean literal (<code>"true"</code>, <code>"false"</code>), or null literal (<code>"null"</code>).
+ * See section 3.8 of the <em>Java Language Specification, Second Edition</em> (JLS2).
+ * A valid identifier can act as a simple type name, method name or field name.
+ *
+ * @param id the Java identifier
+ * @return a status object with code <code>IStatus.OK</code> if
+ * the given identifier is a valid Java idetifier, otherwise a status
+ * object indicating what is wrong with the identifier
+ */
+public static IStatus validateIdentifier(String id) {
+ if (scannedIdentifier(id) != null) {
+ return new Status(IStatus.OK, JavaCore.PLUGIN_ID, -1, "OK", null);
+ } else {
+ return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, id + " is not a valid Java identifier", null);
+ }
+}
+/**
+ * Validate the given import declaration name.
+ * <p>
+ * The name of an import corresponds to a fully qualified type name
+ * or an on-demand package name as defined by ImportDeclaration (JLS2 7.5).
+ * For example, <code>"java.util.*"</code> or <code>"java.util.Hashtable"</code>.
+ *
+ * @param name the import declaration
+ * @return a status object with code <code>IStatus.OK</code> if
+ * the given name is valid as an import declaration, otherwise a status
+ * object indicating what is wrong with the name
+ */
+public static IStatus validateImportDeclaration(String name) {
+ if (name == null || name.length() == 0) {
+ return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, "An import declaration must not be null", null);;
+ }
+ if (name.charAt(name.length() - 1) == '*') {
+ if (name.charAt(name.length() - 2) == '.') {
+ return validatePackageName(name.substring(0, name.length() - 2));
+ } else {
+ return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, "An import declaration must not end with an unqualified *", null);;
+ }
+ }
+ return validatePackageName(name);
+}
+/**
+ * Validate the given Java type name, either simple or qualified.
+ * For example, <code>"java.lang.Object"</code>, or <code>"Object"</code>.
+ * <p>
+ *
+ * @param name the name of a type
+ * @return a status object with code <code>IStatus.OK</code> if
+ * the given name is valid as a Java type name,
+ * a status with code <code>IStatus.WARNING</code>
+ * indicating why the given name is discouraged,
+ * otherwise a status object indicating what is wrong with
+ * the name
+ */
+public static IStatus validateJavaTypeName(String name) {
+ if (name == null) {
+ return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, "A Java type name must not be null", null);
+ }
+ String trimmed = name.trim();
+ if (!name.equals(trimmed)) {
+ return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, "A Java type name must not start or end with a blank.", null);;
+ }
+ int index = name.lastIndexOf('.');
+ char[] scannedID;
+ if (index == -1) {
+ // simple name
+ scannedID = scannedIdentifier(name);
+ } else {
+ // qualified name
+ String pkg = name.substring(0, index).trim();
+ IStatus status = validatePackageName(pkg);
+ if (!status.isOK()) {
+ return status;
}
+ String type = name.substring(index + 1).trim();
+ scannedID = scannedIdentifier(type);
}
- /**
- * Validate the given compilation unit name.
- * A compilation unit name must obey the following rules:
- * <ul>
- * <li> it must not be null
- * <li> it must include the <code>".java"</code> suffix
- * <li> its prefix must be a valid identifier
- * </ul>
- * </p>
- * @param name the name of a compilation unit
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as a compilation unit name, otherwise a status
- * object indicating what is wrong with the name
- */
- public static IStatus validateCompilationUnitName(String name) {
- if (name == null) {
- return new Status(
- IStatus.ERROR,
- JavaCore.PLUGIN_ID,
- -1,
- "Compilation unit name must not be null",
- null);
+ if (scannedID != null) {
+ if (CharOperation.contains('$', scannedID)) {
+ return new Status(IStatus.WARNING, JavaCore.PLUGIN_ID, -1, "By convention, Java type names usually don't contain the $ character.", null);
}
- String extension;
- String identifier;
- int index;
- index = name.indexOf('.');
- if (index == -1) {
- return new Status(
- IStatus.ERROR,
- JavaCore.PLUGIN_ID,
- -1,
- "Compilation unit name must include the \".java\" suffix",
- null);
+ if ((scannedID.length > 0 && Character.isLowerCase(scannedID[0]))) {
+ return new Status(IStatus.WARNING, JavaCore.PLUGIN_ID, -1, "By convention, Java type names usually start with an uppercase letter.", null);
}
- identifier = name.substring(0, index);
- extension = name.substring(index + 1);
- IStatus status = validateIdentifier(identifier);
+ return new Status(IStatus.OK, JavaCore.PLUGIN_ID, -1, "OK", null);
+ } else {
+ return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, "The type name " + name + " is not a valid identifier.", null);
+ }
+}
+/**
+ * Validate the given method name.
+ * The special names "&lt;init&gt;" and "&lt;clinit&gt;" are not valid.
+ * <p>
+ * The syntax for a method name is defined by Identifer
+ * of MethodDeclarator (JLS2 8.4). For example "println".
+ *
+ * @param name the name of a method
+ * @return a status object with code <code>IStatus.OK</code> if
+ * the given name is valid as a method name, otherwise a status
+ * object indicating what is wrong with the name
+ */
+public static IStatus validateMethodName(String name) {
+ return validateIdentifier(name);
+}
+/**
+ * Validate the given package name.
+ * <p>
+ * The syntax of a package name corresponds to PackageName as
+ * defined by PackageDeclaration (JLS2 7.4). For example, <code>"java.lang"</code>.
+ *
+ * @param name the name of a package
+ * @return a status object with code <code>IStatus.OK</code> if
+ * the given name is valid as a package name, otherwise a status
+ * object indicating what is wrong with the name
+ */
+public static IStatus validatePackageName(String name) {
+ if (name == null) {
+ return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, "A package name must not be null", null);
+ }
+ int length;
+ if ((length = name.length()) == 0) {
+ return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, "A package name must not be empty", null);
+ }
+ if (name.charAt(0) == fgDot || name.charAt(length-1) == fgDot) {
+ return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, "A package name cannot start or end with a dot", null);
+ }
+ if (Character.isWhitespace(name.charAt(0)) || Character.isWhitespace(name.charAt(name.length() - 1))) {
+ return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, "A package name must not start or end with a blank", null);;
+ }
+ int dot = 0;
+ while (dot != -1 && dot < length-1) {
+ if ((dot = name.indexOf(fgDot, dot+1)) != -1 && dot < length-1 && name.charAt(dot+1) == fgDot) {
+ return new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, "A package name must not contain two consecutive dots", null);
+ }
+ }
+ StringTokenizer st = new StringTokenizer(name, new String(new char[] {fgDot}));
+ while (st.hasMoreTokens()) {
+ String typeName = st.nextToken();
+ typeName = typeName.trim(); // grammar allows spaces
+ IStatus status = validateIdentifier(typeName);
if (!status.isOK()) {
return status;
}
- if (!extension.toUpperCase().equals(fgJAVA)) {
- return new Status(
- IStatus.ERROR,
- JavaCore.PLUGIN_ID,
- -1,
- "Compilation unit name must include the \".java\" suffix",
- null);
- }
- return new Status(IStatus.OK, JavaCore.PLUGIN_ID, -1, "OK", null);
}
+ return new Status(IStatus.OK, JavaCore.PLUGIN_ID, -1, "OK", null);
+}
- /**
- * Validate the given field name.
- * <p>
- * Syntax of a field name corresponds to VariableDeclaratorId (JLS2 8.3).
- * For example, <code>"x"</code>.
- *
- * @param name the name of a field
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as a field name, otherwise a status
- * object indicating what is wrong with the name
- */
- public static IStatus validateFieldName(String name) {
- return validateIdentifier(name);
- }
+/**
+ * Validate the given classpath and output location.
+ * - Source folders cannot be nested inside the binary output, and reciprocally. They can coincidate.
+ * - Source folders cannot be nested in each other.
+ * - Output location must be nested inside project.
+
+ * @param classpath a given classpath
+ * @param outputLocation a given output location
+ * @return a status object with code <code>IStatus.OK</code> if
+ * the given classpath and output location are compatible, otherwise a status
+ * object indicating what is wrong with the classpath or output location
+ */
+public static IJavaModelStatus validateClasspath(IJavaProject javaProject, IClasspathEntry[] classpath, IPath outputLocation) {
- /**
- * Validate the given Java identifier.
- * The identifier must have the same spelling as a Java keyword,
- * boolean literal (<code>"true"</code>, <code>"false"</code>), or null literal (<code>"null"</code>).
- * See section 3.8 of the <em>Java Language Specification, Second Edition</em> (JLS2).
- * A valid identifier can act as a simple type name, method name or field name.
- *
- * @param id the Java identifier
- * @return a status object with code <code>IStatus.OK</code> if
- * the given identifier is a valid Java idetifier, otherwise a status
- * object indicating what is wrong with the identifier
- */
- public static IStatus validateIdentifier(String id) {
- if (scannedIdentifier(id) != null) {
- return new Status(IStatus.OK, JavaCore.PLUGIN_ID, -1, "OK", null);
- } else {
- return new Status(
- IStatus.ERROR,
- JavaCore.PLUGIN_ID,
- -1,
- id + " is not a valid Java identifier",
- null);
+ IProject project = javaProject.getProject();
+ IPath projectPath= project.getFullPath();
+
+ /* validate output location */
+ if (outputLocation == null) {
+ return new JavaModelStatus(IJavaModelStatusConstants.NULL_PATH);
+ }
+ if (outputLocation.isAbsolute()) {
+ if (!projectPath.isPrefixOf(outputLocation)) {
+ return new JavaModelStatus(IJavaModelStatusConstants.PATH_OUTSIDE_PROJECT, javaProject, outputLocation.toString());
}
+ } else {
+ return new JavaModelStatus(IJavaModelStatusConstants.RELATIVE_PATH, outputLocation);
}
- /**
- * Validate the given import declaration name.
- * <p>
- * The name of an import corresponds to a fully qualified type name
- * or an on-demand package name as defined by ImportDeclaration (JLS2 7.5).
- * For example, <code>"java.util.*"</code> or <code>"java.util.Hashtable"</code>.
- *
- * @param name the import declaration
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as an import declaration, otherwise a status
- * object indicating what is wrong with the name
- */
- public static IStatus validateImportDeclaration(String name) {
- if (name == null || name.length() == 0) {
- return new Status(
- IStatus.ERROR,
- JavaCore.PLUGIN_ID,
- -1,
- "An import declaration must not be null",
- null);
- ;
- }
- if (name.charAt(name.length() - 1) == '*') {
- if (name.charAt(name.length() - 2) == '.') {
- return validatePackageName(name.substring(0, name.length() - 2));
- } else {
- return new Status(
- IStatus.ERROR,
- JavaCore.PLUGIN_ID,
- -1,
- "An import declaration must not end with an unqualified *",
- null);
- ;
- }
+
+
+ // check if any source entries coincidates with binary output - in which case nesting inside output is legal
+ boolean allowNestingInOutput = false;
+ boolean hasSource = false;
+ for (int i = 0 ; i < classpath.length; i++) {
+ if (classpath[i].getEntryKind() == IClasspathEntry.CPE_SOURCE) hasSource = true;
+ if (classpath[i].getPath().equals(outputLocation)){
+ allowNestingInOutput = true;
+ break;
}
- return validatePackageName(name);
}
+ if (!hasSource) allowNestingInOutput = true; // if no source, then allowed
+
+ // check all entries
+ for (int i = 0 ; i < classpath.length; i++) {
+ IClasspathEntry entry = classpath[i];
+ IPath entryPath = entry.getPath();
- /**
- * Validate the given Java type name, either simple or qualified.
- * For example, <code>"java.lang.Object"</code>, or <code>"Object"</code>.
- * <p>
- *
- * @param name the name of a type
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as a Java type name,
- * a status with code <code>IStatus.WARNING</code>
- * indicating why the given name is discouraged,
- * otherwise a status object indicating what is wrong with
- * the name
- */
- public static IStatus validateJavaTypeName(String name) {
- if (name == null) {
- return new Status(
- IStatus.ERROR,
- JavaCore.PLUGIN_ID,
- -1,
- "A Java type name must not be null",
- null);
- }
- String trimmed = name.trim();
- if (!name.equals(trimmed)) {
- return new Status(
- IStatus.ERROR,
- JavaCore.PLUGIN_ID,
- -1,
- "A Java type name must not start or end with a blank.",
- null);
- ;
- }
- int index = name.lastIndexOf('.');
- char[] scannedID;
- if (index == -1) {
- // simple name
- scannedID = scannedIdentifier(name);
- } else {
- // qualified name
- String pkg = name.substring(0, index).trim();
- IStatus status = validatePackageName(pkg);
- if (!status.isOK()) {
- return status;
+ // no further check if entry coincidates with project or output location
+ if (entryPath.equals(projectPath)) continue;
+ if (entryPath.equals(outputLocation)) continue;
+
+ // prevent nesting source entries in each other
+ if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE){
+ for (int j = 0; j < classpath.length; j++){
+ IClasspathEntry otherEntry = classpath[j];
+ if (entry != otherEntry && otherEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE){
+ if (entryPath.isPrefixOf(otherEntry.getPath())){
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.cannotNestSourceFolderInSource"/*nonNLS*/,entryPath.toString(), otherEntry.getPath().toString()));
+ }
+ }
}
- String type = name.substring(index + 1).trim();
- scannedID = scannedIdentifier(type);
+ }
+ // prevent nesting output location inside entry
+ if (entryPath.isPrefixOf(outputLocation)) {
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.cannotNestSourceFolderInOutput"/*nonNLS*/,entryPath.toString(), outputLocation.toString()));
}
- if (scannedID != null) {
- if (CharOperation.contains('$', scannedID)) {
- return new Status(
- IStatus.WARNING,
- JavaCore.PLUGIN_ID,
- -1,
- "By convention, Java type names usually don't contain the $ character.",
- null);
- }
- if ((scannedID.length > 0 && Character.isLowerCase(scannedID[0]))) {
- return new Status(
- IStatus.WARNING,
- JavaCore.PLUGIN_ID,
- -1,
- "By convention, Java type names usually start with an uppercase letter.",
- null);
- }
- return new Status(IStatus.OK, JavaCore.PLUGIN_ID, -1, "OK", null);
- } else {
- return new Status(
- IStatus.ERROR,
- JavaCore.PLUGIN_ID,
- -1,
- "The type name " + name + " is not a valid identifier.",
- null);
+ // prevent nesting entry inside output location - when distinct from project or a source folder
+ if (!allowNestingInOutput && outputLocation.isPrefixOf(entryPath)) {
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.cannotNestOuputInSourceFolder"/*nonNLS*/, outputLocation.toString(), entryPath.toString()));
}
}
+ return JavaModelStatus.VERIFIED_OK;
+}
/**
- * Validate the given method name.
- * The special names "&lt;init&gt;" and "&lt;clinit&gt;" are not valid.
- * <p>
- * The syntax for a method name is defined by Identifer
- * of MethodDeclarator (JLS2 8.4). For example "println".
- *
- * @param name the name of a method
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as a method name, otherwise a status
- * object indicating what is wrong with the name
+ * Returns a message describing the problem related to this classpath entry if any, or null if entry is fine
+ * (i.e. if the given classpath entry denotes a valid element to be referenced onto a classpath).
*/
- public static IStatus validateMethodName(String name) {
- return validateIdentifier(name);
- }
+ public static IJavaModelStatus validateClasspathEntry(IJavaProject javaProject, IClasspathEntry entry, boolean checkSourceAttachment){
+
+ IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
+ IPath path = entry.getPath();
+
+ switch(entry.getEntryKind()){
- /**
- * Validate the given package name.
- * <p>
- * The syntax of a package name corresponds to PackageName as
- * defined by PackageDeclaration (JLS2 7.4). For example, <code>"java.lang"</code>.
- *
- * @param name the name of a package
- * @return a status object with code <code>IStatus.OK</code> if
- * the given name is valid as a package name, otherwise a status
- * object indicating what is wrong with the name
- */
- public static IStatus validatePackageName(String name) {
- if (name == null) {
- return new Status(
- IStatus.ERROR,
- JavaCore.PLUGIN_ID,
- -1,
- "A package name must not be null",
- null);
- }
- int length;
- if ((length = name.length()) == 0) {
- return new Status(
- IStatus.ERROR,
- JavaCore.PLUGIN_ID,
- -1,
- "A package name must not be empty",
- null);
- }
- if (name.charAt(0) == fgDot || name.charAt(length - 1) == fgDot) {
- return new Status(
- IStatus.ERROR,
- JavaCore.PLUGIN_ID,
- -1,
- "A package name cannot start or end with a dot",
- null);
- }
- if (Character.isWhitespace(name.charAt(0))
- || Character.isWhitespace(name.charAt(name.length() - 1))) {
- return new Status(
- IStatus.ERROR,
- JavaCore.PLUGIN_ID,
- -1,
- "A package name must not start or end with a blank",
- null);
- ;
- }
- int dot = 0;
- while (dot != -1 && dot < length - 1) {
- if ((dot = name.indexOf(fgDot, dot + 1)) != -1
- && dot < length - 1
- && name.charAt(dot + 1) == fgDot) {
- return new Status(
- IStatus.ERROR,
- JavaCore.PLUGIN_ID,
- -1,
- "A package name must not contain two consecutive dots",
- null);
- }
- }
- StringTokenizer st =
- new StringTokenizer(name, new String(new char[] { fgDot }));
- while (st.hasMoreTokens()) {
- String typeName = st.nextToken();
- typeName = typeName.trim(); // grammar allows spaces
- IStatus status = validateIdentifier(typeName);
- if (!status.isOK()) {
- return status;
- }
- }
- return new Status(IStatus.OK, JavaCore.PLUGIN_ID, -1, "OK", null);
- }
+ // variable entry check
+ case IClasspathEntry.CPE_VARIABLE :
+ if (path != null && path.segmentCount() >= 1){
+ entry = JavaCore.getResolvedClasspathEntry(entry);
+ if (entry == null){
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.unboundVariablePath"/*nonNLS*/, path.toString()));
+ }
+ return validateClasspathEntry(javaProject, entry, checkSourceAttachment);
+ } else {
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.illegalVariablePath"/*nonNLS*/, path.toString()));
+ }
+
+ // library entry check
+ case IClasspathEntry.CPE_LIBRARY :
+ if (path != null && path.isAbsolute() && !path.isEmpty()) {
+ IPath sourceAttachment = entry.getSourceAttachmentPath();
+ Object target = JavaModel.getTarget(workspaceRoot, path, true);
+ if (target instanceof IResource){
+ IResource resolvedResource = (IResource) target;
+ switch(resolvedResource.getType()){
+ case IResource.FILE :
+ String extension = resolvedResource.getFileExtension();
+ if ("jar"/*nonNLS*/.equalsIgnoreCase(extension) || "zip"/*nonNLS*/.equalsIgnoreCase(extension)){ // internal binary archive
+ if (checkSourceAttachment
+ && sourceAttachment != null
+ && !sourceAttachment.isEmpty()
+ && JavaModel.getTarget(workspaceRoot, sourceAttachment, true) == null){
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.unboundSourceAttachment"/*nonNLS*/, sourceAttachment.toString()));
+ }
+ }
+ break;
+ case IResource.FOLDER : // internal binary folder
+ if (checkSourceAttachment
+ && sourceAttachment != null
+ && !sourceAttachment.isEmpty()
+ && JavaModel.getTarget(workspaceRoot, sourceAttachment, true) == null){
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.unboundSourceAttachment"/*nonNLS*/, sourceAttachment.toString()));
+ }
+ }
+ } else if (target instanceof File){
+ if (checkSourceAttachment
+ && sourceAttachment != null
+ && !sourceAttachment.isEmpty()
+ && JavaModel.getTarget(workspaceRoot, sourceAttachment, true) == null){
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.unboundSourceAttachment"/*nonNLS*/, sourceAttachment.toString()));
+ }
+ } else {
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.unboundLibrary"/*nonNLS*/, path.toString()));
+ }
+ } else {
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.illegalLibraryPath"/*nonNLS*/, path.toString()));
+ }
+ break;
+ // project entry check
+ case IClasspathEntry.CPE_PROJECT :
+ if (path != null && path.isAbsolute() && !path.isEmpty()) {
+ IProject project = workspaceRoot.getProject(path.segment(0));
+ try {
+ if (!project.exists() || !project.hasNature(JavaCore.NATURE_ID)){
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.unboundProject"/*nonNLS*/, path.segment(0).toString()));
+ }
+ } catch (CoreException e){
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.unboundProject"/*nonNLS*/, path.segment(0).toString()));
+ }
+ } else {
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.illegalProjectPath"/*nonNLS*/, path.segment(0).toString()));
+ }
+ break;
+
+ // project source folder
+ case IClasspathEntry.CPE_SOURCE :
+ if (path != null && path.isAbsolute() && !path.isEmpty()) {
+ IPath projectPath= javaProject.getProject().getFullPath();
+ if (!projectPath.isPrefixOf(path) || JavaModel.getTarget(workspaceRoot, path, true) == null){
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.unboundSourceFolder"/*nonNLS*/, path.toString()));
+ }
+ } else {
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CLASSPATH, Util.bind("classpath.illegalSourceFolderPath"/*nonNLS*/, path.toString()));
+ }
+ break;
+ }
+ return JavaModelStatus.VERIFIED_OK;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaCore.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaCore.java
index fe8ccc1c76..1618786bf8 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaCore.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaCore.java
@@ -4,7 +4,7 @@ package org.eclipse.jdt.core;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
-
+
import org.eclipse.core.runtime.*;
import org.eclipse.core.resources.*;
@@ -38,25 +38,25 @@ import org.eclipse.jdt.internal.core.search.indexing.*;
*/
public final class JavaCore extends Plugin implements IExecutableExtension {
+
private static Plugin JAVA_CORE_PLUGIN = null;
/**
* The plug-in identifier of the Java core support
* (value <code>"org.eclipse.jdt.core"</code>).
*/
- public static final String PLUGIN_ID = "org.eclipse.jdt.core";
- // getPlugin().getDescriptor().getUniqueIdentifier();
+ public static final String PLUGIN_ID = "org.eclipse.jdt.core"/*nonNLS*/; // getPlugin().getDescriptor().getUniqueIdentifier();
/**
* The identifier for the Java builder
* (value <code>"org.eclipse.jdt.core.javabuilder"</code>).
*/
- public static final String BUILDER_ID = PLUGIN_ID + ".javabuilder";
+ public static final String BUILDER_ID = PLUGIN_ID + ".javabuilder"/*nonNLS*/;
/**
* The identifier for the Java model
* (value <code>"org.eclipse.jdt.core.javamodel"</code>).
*/
- public static final String MODEL_ID = PLUGIN_ID + ".javamodel";
+ public static final String MODEL_ID = PLUGIN_ID + ".javamodel"/*nonNLS*/;
/**
* The identifier for the Java nature
@@ -66,1133 +66,1012 @@ public final class JavaCore extends Plugin implements IExecutableExtension {
*
* @see org.eclipse.core.resources.IProject#hasNature
*/
- public static final String NATURE_ID = PLUGIN_ID + ".javanature";
+ public static final String NATURE_ID = PLUGIN_ID + ".javanature"/*nonNLS*/;
/**
* Name of the handle id attribute in a Java marker
*/
- private static final String ATT_HANDLE_ID =
- "org.eclipse.jdt.internal.core.JavaModelManager.handleId";
+ private static final String ATT_HANDLE_ID= "org.eclipse.jdt.internal.core.JavaModelManager.handleId"/*nonNLS*/;
/**
* Names of recognized configurable options
*/
- public static final String COMPILER_LOCAL_VARIABLE_ATTR =
- PLUGIN_ID + ".compiler.debug.localVariable";
- // possible values are GENERATE or DO_NOT_GENERATE (default is DO_NOT_GENERATE)
-
- public static final String COMPILER_LINE_NUMBER_ATTR =
- PLUGIN_ID + ".compiler.debug.lineNumber";
- // possible values are GENERATE or DO_NOT_GENERATE (default is GENERATE)
-
- public static final String COMPILER_SOURCE_FILE_ATTR =
- PLUGIN_ID + ".compiler.debug.sourceFile";
- // possible values are GENERATE or DO_NOT_GENERATE (default is GENERATE)
-
- public static final String COMPILER_CODEGEN_UNUSED_LOCAL =
- PLUGIN_ID + ".compiler.codegen.unusedLocal";
- // possible values are PRESERVE or OPTIMIZE_OUT (default is OPTIMIZE_OUT)
-
- public static final String COMPILER_CODEGEN_TARGET_PLATFORM =
- PLUGIN_ID + ".compiler.codegen.targetPlatform";
- // possible values are VERSION_1_1 or VERSION_1_2 (default is VERSION_1_1)
-
- public static final String COMPILER_PB_UNREACHABLE_CODE =
- PLUGIN_ID + ".compiler.problem.unreachableCode";
- // possible values are ERROR or WARNING (default is ERROR)
-
- public static final String COMPILER_PB_INVALID_IMPORT =
- PLUGIN_ID + ".compiler.problem.invalidImport";
- // possible values are ERROR or WARNING (default is ERROR)
-
- public static final String COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD =
- PLUGIN_ID + ".compiler.problem.overridingPackageDefaultMethod";
- // possible values are WARNING or IGNORE (default is WARNING)
-
- public static final String COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME =
- PLUGIN_ID + ".compiler.problem.methodWithConstructorName";
- // possible values are WARNING or IGNORE (default is WARNING)
-
- public static final String COMPILER_PB_DEPRECATION =
- PLUGIN_ID + ".compiler.problem.deprecation";
- // possible values are WARNING or IGNORE (default is WARNING)
-
- public static final String COMPILER_PB_HIDDEN_CATCH_BLOCK =
- PLUGIN_ID + ".compiler.problem.hiddenCatchBlock";
- // possible values are WARNING or IGNORE (default is WARNING)
-
- public static final String COMPILER_PB_UNUSED_LOCAL =
- PLUGIN_ID + ".compiler.problem.unusedLocal";
- // possible values are WARNING or IGNORE (default is WARNING)
-
- public static final String COMPILER_PB_UNUSED_PARAMETER =
- PLUGIN_ID + ".compiler.problem.unusedParameter";
- // possible values are WARNING or IGNORE (default is WARNING)
-
- public static final String COMPILER_PB_SYNTHETIC_ACCESS_EMULATION =
- PLUGIN_ID + ".compiler.problem.syntheticAccessEmulation";
- // possible values are WARNING or IGNORE (default is IGNORE)
-
- public static final String CORE_JAVA_BUILD_ORDER =
- PLUGIN_ID + ".computeJavaBuildOrder";
- // possible values are COMPUTE or IGNORE (default is COMPUTE)
+ public static final String COMPILER_LOCAL_VARIABLE_ATTR = PLUGIN_ID + ".compiler.debug.localVariable"/*nonNLS*/;
+ // possible values are GENERATE or DO_NOT_GENERATE (default is DO_NOT_GENERATE)
+
+ public static final String COMPILER_LINE_NUMBER_ATTR = PLUGIN_ID + ".compiler.debug.lineNumber"/*nonNLS*/;
+ // possible values are GENERATE or DO_NOT_GENERATE (default is GENERATE)
+
+ public static final String COMPILER_SOURCE_FILE_ATTR = PLUGIN_ID + ".compiler.debug.sourceFile"/*nonNLS*/;
+ // possible values are GENERATE or DO_NOT_GENERATE (default is GENERATE)
+
+ public static final String COMPILER_CODEGEN_UNUSED_LOCAL = PLUGIN_ID + ".compiler.codegen.unusedLocal"/*nonNLS*/;
+ // possible values are PRESERVE or OPTIMIZE_OUT (default is OPTIMIZE_OUT)
+
+ public static final String COMPILER_CODEGEN_TARGET_PLATFORM = PLUGIN_ID + ".compiler.codegen.targetPlatform"/*nonNLS*/;
+ // possible values are VERSION_1_1 or VERSION_1_2 (default is VERSION_1_1)
+
+ public static final String COMPILER_PB_UNREACHABLE_CODE = PLUGIN_ID + ".compiler.problem.unreachableCode"/*nonNLS*/;
+ // possible values are ERROR or WARNING (default is ERROR)
+
+ public static final String COMPILER_PB_INVALID_IMPORT = PLUGIN_ID + ".compiler.problem.invalidImport"/*nonNLS*/;
+ // possible values are ERROR or WARNING (default is ERROR)
+
+ public static final String COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD = PLUGIN_ID + ".compiler.problem.overridingPackageDefaultMethod"/*nonNLS*/;
+ // possible values are WARNING or IGNORE (default is WARNING)
+
+ public static final String COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME = PLUGIN_ID + ".compiler.problem.methodWithConstructorName"/*nonNLS*/;
+ // possible values are WARNING or IGNORE (default is WARNING)
+
+ public static final String COMPILER_PB_DEPRECATION = PLUGIN_ID + ".compiler.problem.deprecation"/*nonNLS*/;
+ // possible values are WARNING or IGNORE (default is WARNING)
+
+ public static final String COMPILER_PB_HIDDEN_CATCH_BLOCK = PLUGIN_ID + ".compiler.problem.hiddenCatchBlock"/*nonNLS*/;
+ // possible values are WARNING or IGNORE (default is WARNING)
+
+ public static final String COMPILER_PB_UNUSED_LOCAL = PLUGIN_ID + ".compiler.problem.unusedLocal"/*nonNLS*/;
+ // possible values are WARNING or IGNORE (default is WARNING)
+
+ public static final String COMPILER_PB_UNUSED_PARAMETER = PLUGIN_ID + ".compiler.problem.unusedParameter"/*nonNLS*/;
+ // possible values are WARNING or IGNORE (default is WARNING)
+
+ public static final String COMPILER_PB_SYNTHETIC_ACCESS_EMULATION = PLUGIN_ID + ".compiler.problem.syntheticAccessEmulation"/*nonNLS*/;
+ // possible values are WARNING or IGNORE (default is IGNORE)
+
+ public static final String CORE_JAVA_BUILD_ORDER = PLUGIN_ID + ".computeJavaBuildOrder"/*nonNLS*/;
+ // possible values are COMPUTE or IGNORE (default is COMPUTE)
/**
* Possible values for configurable options
*/
- public static final String GENERATE = "generate";
- public static final String DO_NOT_GENERATE = "do not generate";
- public static final String PRESERVE = "preserve";
- public static final String OPTIMIZE_OUT = "optimize out";
- public static final String VERSION_1_1 = "1.1";
- public static final String VERSION_1_2 = "1.2";
- public static final String ERROR = "error";
- public static final String WARNING = "warning";
- public static final String IGNORE = "ignore";
- public static final String COMPUTE = "compute";
-
+ public static final String GENERATE = "generate"/*nonNLS*/;
+ public static final String DO_NOT_GENERATE = "do not generate"/*nonNLS*/;
+ public static final String PRESERVE = "preserve"/*nonNLS*/;
+ public static final String OPTIMIZE_OUT = "optimize out"/*nonNLS*/;
+ public static final String VERSION_1_1 = "1.1"/*nonNLS*/;
+ public static final String VERSION_1_2 = "1.2"/*nonNLS*/;
+ public static final String ERROR = "error"/*nonNLS*/;
+ public static final String WARNING = "warning"/*nonNLS*/;
+ public static final String IGNORE = "ignore"/*nonNLS*/;
+ public static final String COMPUTE = "compute"/*nonNLS*/;
+
private static Hashtable ConfigurableOptions;
private static Hashtable Variables = new Hashtable(5);
- /**
- * Creates the Java core plug-in.
- */
- public JavaCore(IPluginDescriptor pluginDescriptor) {
- super(pluginDescriptor);
- JAVA_CORE_PLUGIN = this;
- }
+ // possible values are WARNING or IGNORE (default is IGNORE)
- /**
- * Adds the given listener for changes to Java elements.
- * Has no effect if an identical listener is already registered.
- *
- * @param listener the listener
- */
- public static void addElementChangedListener(IElementChangedListener listener) {
- JavaModelManager.getJavaModelManager().addElementChangedListener(listener);
- }
+ public static final String COMPILER_PB_NON_EXTERNALIZED_STRING_LITERAL = PLUGIN_ID + ".compiler.problem.nonExternalizedStringLiteral"/*nonNLS*/;
- /**
- * Configures the given marker attribute map for the given Java element.
- * Used for markers which denote a Java element rather than a resource.
- *
- * @param attributes the mutable marker attribute map (key type: <code>String</code>,
- * value type: <code>String</code>)
- * @param element the Java element for which the marker needs to be configured
- */
- public static void addJavaElementMarkerAttributes(
- Map attributes,
- IJavaElement element) {
- if (element instanceof IMember)
- element = ((IMember) element).getClassFile();
- if (attributes != null && element != null)
- attributes.put(ATT_HANDLE_ID, element.getHandleIdentifier());
+/**
+ * Creates the Java core plug-in.
+ */
+public JavaCore(IPluginDescriptor pluginDescriptor) {
+ super(pluginDescriptor);
+ JAVA_CORE_PLUGIN = this;
+}
+/**
+ * Adds the given listener for changes to Java elements.
+ * Has no effect if an identical listener is already registered.
+ *
+ * @param listener the listener
+ */
+public static void addElementChangedListener(IElementChangedListener listener) {
+ JavaModelManager.getJavaModelManager().addElementChangedListener(listener);
+}
+/**
+ * Configures the given marker attribute map for the given Java element.
+ * Used for markers which denote a Java element rather than a resource.
+ *
+ * @param attributes the mutable marker attribute map (key type: <code>String</code>,
+ * value type: <code>String</code>)
+ * @param element the Java element for which the marker needs to be configured
+ */
+public static void addJavaElementMarkerAttributes(Map attributes, IJavaElement element) {
+ if (element instanceof IMember)
+ element= ((IMember) element).getClassFile();
+ if (attributes != null && element != null)
+ attributes.put(ATT_HANDLE_ID, element.getHandleIdentifier());
+}
+/**
+ * Configures the given marker for the given Java element.
+ * Used for markers which denote a Java element rather than a resource.
+ *
+ * @param marker the marker to be configured
+ * @param element the Java element for which the marker needs to be configured
+ * @exception CoreException if the <code>IMarker.setAttribute</code> on the marker fails
+ */
+public void configureJavaElementMarker(IMarker marker, IJavaElement element) throws CoreException {
+ if (element instanceof IMember)
+ element= ((IMember)element).getClassFile();
+ if (marker != null && element != null)
+ marker.setAttribute(ATT_HANDLE_ID, element.getHandleIdentifier());
+}
+/**
+ * Returns the Java model element corresponding to the given handle identifier
+ * generated by <code>IJavaElement.getHandleIdentifier()</code>, or
+ * <code>null</code> if unable to create the associated element.
+ */
+public static IJavaElement create(String handleIdentifier) {
+ if (handleIdentifier == null) {
+ return null;
}
-
- /**
- * Configures the given marker for the given Java element.
- * Used for markers which denote a Java element rather than a resource.
- *
- * @param marker the marker to be configured
- * @param element the Java element for which the marker needs to be configured
- * @exception CoreException if the <code>IMarker.setAttribute</code> on the marker fails
- */
- public void configureJavaElementMarker(IMarker marker, IJavaElement element)
- throws CoreException {
- if (element instanceof IMember)
- element = ((IMember) element).getClassFile();
- if (marker != null && element != null)
- marker.setAttribute(ATT_HANDLE_ID, element.getHandleIdentifier());
+ try {
+ return JavaModelManager.getJavaModelManager().getHandleFromMemento(handleIdentifier);
+ } catch (JavaModelException e) {
+ return null;
}
-
- /**
- * Returns the Java model element corresponding to the given handle identifier
- * generated by <code>IJavaElement.getHandleIdentifier()</code>, or
- * <code>null</code> if unable to create the associated element.
- */
- public static IJavaElement create(String handleIdentifier) {
- if (handleIdentifier == null) {
- return null;
- }
- try {
- return JavaModelManager.getJavaModelManager().getHandleFromMemento(
- handleIdentifier);
- } catch (JavaModelException e) {
- return null;
- }
+}
+/**
+ * Returns the Java element corresponding to the given file, or
+ * <code>null</code> if unable to associate the given file
+ * with a Java element.
+ *
+ * <p>The file must be one of:<ul>
+ * <li>a <code>.java</code> file - the element returned is the corresponding <code>ICompilationUnit</code></li>
+ * <li>a <code>.class</code> file - the element returned is the corresponding <code>IClassFile</code></li>
+ * <li>a <code>.jar</code> file - the element returned is the corresponding <code>IPackageFragmentRoot</code></li>
+ * </ul>
+ * <p>
+ * Creating a Java element has the side effect of creating and opening all of the
+ * element's parents if they are not yet open.
+ */
+public static IJavaElement create(IFile file) {
+ if (file == null) {
+ return null;
}
-
- /**
- * Returns the Java element corresponding to the given file, or
- * <code>null</code> if unable to associate the given file
- * with a Java element.
- *
- * <p>The file must be one of:<ul>
- * <li>a <code>.java</code> file - the element returned is the corresponding <code>ICompilationUnit</code></li>
- * <li>a <code>.class</code> file - the element returned is the corresponding <code>IClassFile</code></li>
- * <li>a <code>.jar</code> file - the element returned is the corresponding <code>IPackageFragmentRoot</code></li>
- * </ul>
- * <p>
- * Creating a Java element has the side effect of creating and opening all of the
- * element's parents if they are not yet open.
- */
- public static IJavaElement create(IFile file) {
- if (file == null) {
- return null;
- }
- String extension = file.getProjectRelativePath().getFileExtension();
- if (extension != null) {
- extension = extension.toLowerCase();
- if (extension.equals("java")) {
- return createCompilationUnitFrom(file);
- } else
- if (extension.equals("class")) {
- return createClassFileFrom(file);
- } else
- if (extension.equals("jar") || extension.equals("zip")) {
- return createJarPackageFragmentRootFrom(file);
- }
+ String extension= file.getProjectRelativePath().getFileExtension();
+ if (extension != null) {
+ extension= extension.toLowerCase();
+ if (extension.equals("java"/*nonNLS*/)) {
+ return createCompilationUnitFrom(file);
+ } else if (extension.equals("class"/*nonNLS*/)) {
+ return createClassFileFrom(file);
+ } else if (extension.equals("jar"/*nonNLS*/) || extension.equals("zip"/*nonNLS*/)) {
+ return createJarPackageFragmentRootFrom(file);
}
+ }
+ return null;
+}
+/**
+ * Returns the package fragment or package fragment root corresponding to the given folder, or
+ * <code>null</code> if unable to associate the given folder with a Java element.
+ * <p>
+ * Note that a package fragment root is returned rather than a default package.
+ * <p>
+ * Creating a Java element has the side effect of creating and opening all of the
+ * element's parents if they are not yet open.
+ */
+public static IJavaElement create(IFolder folder) {
+ if (folder == null) {
return null;
}
-
- /**
- * Returns the package fragment or package fragment root corresponding to the given folder, or
- * <code>null</code> if unable to associate the given folder with a Java element.
- * <p>
- * Note that a package fragment root is returned rather than a default package.
- * <p>
- * Creating a Java element has the side effect of creating and opening all of the
- * element's parents if they are not yet open.
- */
- public static IJavaElement create(IFolder folder) {
- if (folder == null) {
- return null;
- }
- if (folder.getName().indexOf('.') < 0) {
- JavaProject project = (JavaProject) create(folder.getProject());
- if (project == null)
- return null;
- IJavaElement element = determineIfOnClasspath(folder, project);
- try {
- IPath outputLocation = project.getOutputLocation();
- if (outputLocation == null)
- return null;
- if (outputLocation.isPrefixOf(folder.getFullPath())) {
- if (project.getClasspathEntryFor(outputLocation) != null) {
- // if the output location is the same as an input location, return the element
- return element;
- } else {
- // otherwise, do not create elements for folders in the output location
- return null;
- }
- } else {
+ if (folder.getName().indexOf('.') < 0) {
+ JavaProject project = (JavaProject) create(folder.getProject());
+ if (project == null) return null;
+ IJavaElement element = determineIfOnClasspath(folder, project);
+ try {
+ IPath outputLocation = project.getOutputLocation();
+ if (outputLocation == null) return null;
+ if (outputLocation.isPrefixOf(folder.getFullPath())) {
+ if (project.getClasspathEntryFor(outputLocation) != null) {
+ // if the output location is the same as an input location, return the element
return element;
+ } else {
+ // otherwise, do not create elements for folders in the output location
+ return null;
}
- } catch (JavaModelException e) {
- return null;
+ } else {
+ return element;
}
+ } catch (JavaModelException e) {
+ return null;
}
+ }
+ return null;
+}
+/**
+ * Returns the Java project corresponding to the given project, or
+ * <code>null</code> if unable to associate the given project
+ * with a Java project.
+ * <p>
+ * Creating a Java Project has the side effect of creating and opening all of the
+ * project's parents if they are not yet open.
+ */
+public static IJavaProject create(IProject project) {
+ if (project == null) {
return null;
}
-
- /**
- * Returns the Java project corresponding to the given project, or
- * <code>null</code> if unable to associate the given project
- * with a Java project.
- * <p>
- * Creating a Java Project has the side effect of creating and opening all of the
- * project's parents if they are not yet open.
- */
- public static IJavaProject create(IProject project) {
- if (project == null) {
- return null;
- }
- JavaModel javaModel = JavaModelManager.getJavaModel(project.getWorkspace());
- return javaModel.getJavaProject(project);
+ JavaModel javaModel= JavaModelManager.getJavaModel(project.getWorkspace());
+ return javaModel.getJavaProject(project);
+}
+/**
+ * Returns the Java element corresponding to the given resource, or
+ * <code>null</code> if unable to associate the given resource
+ * with a Java element.
+ * <p>
+ * The resource must be one of:<ul>
+ * <li>a project - the element returned is the corresponding <code>IJavaProject</code></li>
+ * <li>a <code>.java</code> file - the element returned is the corresponding <code>ICompilationUnit</code></li>
+ * <li>a <code>.class</code> file - the element returned is the corresponding <code>IClassFile</code></li>
+ * <li>a <code>.jar</code> file - the element returned is the corresponding <code>IPackageFragmentRoot</code></li>
+ * <li>a folder - the element returned is the corresponding <code>IPackageFragmentRoot</code>
+ * or <code>IPackageFragment</code></li>
+ * <li>the workspace root resource - the element returned is the <code>IJavaModel</code></li>
+ * </ul>
+ * <p>
+ * Creating a Java element has the side effect of creating and opening all of the
+ * element's parents if they are not yet open.
+ */
+public static IJavaElement create(IResource resource) {
+ if (resource == null) {
+ return null;
}
-
- /**
- * Returns the Java element corresponding to the given resource, or
- * <code>null</code> if unable to associate the given resource
- * with a Java element.
- * <p>
- * The resource must be one of:<ul>
- * <li>a project - the element returned is the corresponding <code>IJavaProject</code></li>
- * <li>a <code>.java</code> file - the element returned is the corresponding <code>ICompilationUnit</code></li>
- * <li>a <code>.class</code> file - the element returned is the corresponding <code>IClassFile</code></li>
- * <li>a <code>.jar</code> file - the element returned is the corresponding <code>IPackageFragmentRoot</code></li>
- * <li>a folder - the element returned is the corresponding <code>IPackageFragmentRoot</code>
- * or <code>IPackageFragment</code></li>
- * <li>the workspace root resource - the element returned is the <code>IJavaModel</code></li>
- * </ul>
- * <p>
- * Creating a Java element has the side effect of creating and opening all of the
- * element's parents if they are not yet open.
- */
- public static IJavaElement create(IResource resource) {
- if (resource == null) {
+ int type= resource.getType();
+ switch (type) {
+ case IResource.PROJECT:
+ return create((IProject)resource);
+ case IResource.FILE:
+ return create((IFile)resource);
+ case IResource.FOLDER:
+ return create((IFolder)resource);
+ case IResource.ROOT:
+ return create((IWorkspaceRoot)resource);
+ default:
return null;
- }
- int type = resource.getType();
- switch (type) {
- case IResource.PROJECT :
- return create((IProject) resource);
- case IResource.FILE :
- return create((IFile) resource);
- case IResource.FOLDER :
- return create((IFolder) resource);
- case IResource.ROOT :
- return create((IWorkspaceRoot) resource);
- default :
- return null;
- }
}
-
- /**
- * Returns the Java model.
- */
- public static IJavaModel create(IWorkspaceRoot root) {
- if (root == null) {
- return null;
- }
- return JavaModelManager.getJavaModel(root.getWorkspace());
- }
-
- /**
- * Creates and returns a class file element for
- * the given <code>.class</code> file. Returns <code>null</code> if unable
- * to recognize the class file.
- */
- public static IClassFile createClassFileFrom(IFile file) {
- IJavaProject project = (IJavaProject) create(file.getProject());
- IPackageFragment pkg = (IPackageFragment) determineIfOnClasspath(file, project);
- if (pkg == null) {
- // fix for 1FVS7WE
- // not on classpath - make the root its folder, and a default package
- IPackageFragmentRoot root = project.getPackageFragmentRoot(file.getParent());
- pkg = root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
- }
- return pkg.getClassFile(file.getName());
+}
+/**
+ * Returns the Java model.
+ */
+public static IJavaModel create(IWorkspaceRoot root) {
+ if (root == null) {
+ return null;
}
-
- /**
- * Creates and returns a compilation unit element for
- * the given <code>.java</code> file. Returns <code>null</code> if unable
- * to recognize the compilation unit.
- */
- public static ICompilationUnit createCompilationUnitFrom(IFile file) {
- IProject fileProject = file.getProject();
- IJavaProject project = (IJavaProject) create(fileProject);
- IPackageFragment pkg = (IPackageFragment) determineIfOnClasspath(file, project);
- if (pkg == null) {
- // fix for 1FVS7WE
- // not on classpath - make the root its folder, and a default package
- IPackageFragmentRoot root = project.getPackageFragmentRoot(file.getParent());
- pkg = root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
- }
- return pkg.getCompilationUnit(file.getName());
+ return JavaModelManager.getJavaModel(root.getWorkspace());
+}
+/**
+ * Creates and returns a class file element for
+ * the given <code>.class</code> file. Returns <code>null</code> if unable
+ * to recognize the class file.
+ */
+public static IClassFile createClassFileFrom(IFile file) {
+ IJavaProject project = (IJavaProject) create(file.getProject());
+ IPackageFragment pkg = (IPackageFragment) determineIfOnClasspath(file, project);
+ if (pkg == null) {
+ // fix for 1FVS7WE
+ // not on classpath - make the root its folder, and a default package
+ IPackageFragmentRoot root= project.getPackageFragmentRoot(file.getParent());
+ pkg= root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
}
-
- /**
- * Creates and returns a handle for the given JAR file.
- * The Java model associated with the JAR's project may be
- * created as a side effect.
- * Returns <code>null</code> if unable to create a JAR package fragment root.
- * (for example, if the JAR file represents a non-Java resource)
- */
- public static IPackageFragmentRoot createJarPackageFragmentRootFrom(IFile file) {
- IJavaProject project = (IJavaProject) create(file.getProject());
-
- // Create a jar package fragment root only if on the classpath
- IPath resourcePath = file.getFullPath();
- try {
- IClasspathEntry[] entries = project.getResolvedClasspath(true);
- for (int i = 0, length = entries.length; i < length; i++) {
- IClasspathEntry entry = entries[i];
- IPath rootPath = entry.getPath();
- if (rootPath.equals(resourcePath)) {
- return project.getPackageFragmentRoot(file);
- }
+ return pkg.getClassFile(file.getName());
+}
+/**
+ * Creates and returns a compilation unit element for
+ * the given <code>.java</code> file. Returns <code>null</code> if unable
+ * to recognize the compilation unit.
+ */
+public static ICompilationUnit createCompilationUnitFrom(IFile file) {
+ IProject fileProject = file.getProject();
+ IJavaProject project = (IJavaProject) create(fileProject);
+ IPackageFragment pkg= (IPackageFragment)determineIfOnClasspath(file, project);
+ if (pkg == null) {
+ // fix for 1FVS7WE
+ // not on classpath - make the root its folder, and a default package
+ IPackageFragmentRoot root= project.getPackageFragmentRoot(file.getParent());
+ pkg= root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
+ }
+ return pkg.getCompilationUnit(file.getName());
+}
+/**
+ * Creates and returns a handle for the given JAR file.
+ * The Java model associated with the JAR's project may be
+ * created as a side effect.
+ * Returns <code>null</code> if unable to create a JAR package fragment root.
+ * (for example, if the JAR file represents a non-Java resource)
+ */
+public static IPackageFragmentRoot createJarPackageFragmentRootFrom(IFile file) {
+ IJavaProject project= (IJavaProject)create(file.getProject());
+
+ // Create a jar package fragment root only if on the classpath
+ IPath resourcePath = file.getFullPath();
+ try {
+ IClasspathEntry[] entries = project.getResolvedClasspath(true);
+ for (int i = 0, length = entries.length; i < length; i++) {
+ IClasspathEntry entry = entries[i];
+ IPath rootPath = entry.getPath();
+ if (rootPath.equals(resourcePath)) {
+ return project.getPackageFragmentRoot(file);
}
- } catch (JavaModelException e) {
}
- return null;
+ } catch (JavaModelException e) {
}
-
- /**
- * Returns the package fragment root represented by the resource, or
- * the package fragment the given resource is located in, or <code>null</code>
- * if the given resource is not on the classpath of the given project.
- */
- private static IJavaElement determineIfOnClasspath(
- IResource resource,
- IJavaProject project) {
- IPath resourcePath = resource.getFullPath();
- try {
- IClasspathEntry[] entries = project.getResolvedClasspath(true);
- for (int i = 0; i < entries.length; i++) {
- IClasspathEntry entry = entries[i];
- IPath rootPath = entry.getPath();
- if (rootPath.equals(resourcePath)) {
- return project.getPackageFragmentRoot(resource);
- } else
- if (rootPath.isPrefixOf(resourcePath)) {
- IPackageFragmentRoot root =
- ((JavaProject) project).getPackageFragmentRoot(rootPath);
- IPath pkgPath = resourcePath.removeFirstSegments(rootPath.segmentCount());
- if (resource.getType() == IResource.FILE) {
- // if the resource is a file, then remove the last segment which
- // is the file name in the package
- pkgPath = pkgPath.removeLastSegments(1);
+ return null;
+}
+/**
+ * Returns the package fragment root represented by the resource, or
+ * the package fragment the given resource is located in, or <code>null</code>
+ * if the given resource is not on the classpath of the given project.
+ */
+private static IJavaElement determineIfOnClasspath(IResource resource, IJavaProject project) {
+ IPath resourcePath = resource.getFullPath();
+ try {
+ IClasspathEntry[] entries = project.getResolvedClasspath(true);
+ for (int i = 0; i < entries.length; i++) {
+ IClasspathEntry entry = entries[i];
+ IPath rootPath = entry.getPath();
+ if (rootPath.equals(resourcePath)) {
+ return project.getPackageFragmentRoot(resource);
+ } else
+ if (rootPath.isPrefixOf(resourcePath)) {
+ IPackageFragmentRoot root = ((JavaProject)project).getPackageFragmentRoot(rootPath);
+ IPath pkgPath = resourcePath.removeFirstSegments(rootPath.segmentCount());
+ if (resource.getType() == IResource.FILE) {
+ // if the resource is a file, then remove the last segment which
+ // is the file name in the package
+ pkgPath= pkgPath.removeLastSegments(1);
+ }
+ StringBuffer pkgName = new StringBuffer(IPackageFragment.DEFAULT_PACKAGE_NAME);
+ for (int j = 0, max = pkgPath.segmentCount(); j < max; j++) {
+ String segment = pkgPath.segment(j);
+ if (segment.indexOf('.') >= 0) {
+ return null;
}
- StringBuffer pkgName = new StringBuffer(IPackageFragment.DEFAULT_PACKAGE_NAME);
- for (int j = 0, max = pkgPath.segmentCount(); j < max; j++) {
- String segment = pkgPath.segment(j);
- if (segment.indexOf('.') >= 0) {
- return null;
- }
- pkgName.append(segment);
- if (j < pkgPath.segmentCount() - 1) {
- pkgName.append(".");
- }
+ pkgName.append(segment);
+ if (j < pkgPath.segmentCount() - 1) {
+ pkgName.append("."/*nonNLS*/);
}
- return root.getPackageFragment(pkgName.toString());
}
- }
- } catch (JavaModelException npe) {
- return null;
+ return root.getPackageFragment(pkgName.toString());
+ }
}
+ } catch (JavaModelException npe) {
return null;
}
-
- /**
- * Returns the path held in the given classpath variable.
- * Returns <node>null</code> if unable to bind.
- * <p>
- * Classpath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- * <p>
- *
- * @param variableName the name of the classpath variable
- * @return the path, or <code>null</code> if none
- * @see #setClasspathVariable
- */
- public static IPath getClasspathVariable(String variableName) {
- return (IPath) Variables.get(variableName);
- }
-
- /**
- * Returns the names of all known classpath variables.
- * <p>
- * Classpath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- * <p>
- *
- * @return the list of classpath variable names
- * @see #setClasspathVariable
- */
- public static String[] getClasspathVariableNames() {
- int length = Variables.size();
- String[] result = new String[length];
- Enumeration vars = Variables.keys();
- int index = 0;
- while (vars.hasMoreElements()) {
- result[index++] = (String) vars.nextElement();
- }
- return result;
- }
-
- /**
- * Answers a set of configurable options with their default values.
- * These options allow to configure the behavior of the underlying components.
- *
- * Recognized options are listed below, optionName = possibleValue1 / possibleValue2
- * where [] are enclosing the default value of the corresponding option.
- *
- * Note: more options might be added in further releases.
- *
- * RECOGNIZED OPTIONS:
- *
- * COMPILER_LOCAL_VARIABLE_ATTR = [GENERATE] | DO_NOT_GENERATE
- * When generated, this attribute will enable local variable names to be displayed
- * in debugger, only in place where variables are definitely assigned
- * (.class file is then bigger)
- *
- * COMPILER_LINE_NUMBER_ATTR = [GENERATE] | DO_NOT_GENERATE
- * When generated, this attribute will enable source code highlighting in debugger
- * (.class file is then bigger).
- *
- * COMPILER_SOURCE_FILE_ATTR = [GENERATE] | DO_NOT_GENERATE
- * When generated, this attribute will enable the debugger to present the
- * corresponding source code.
- *
- * COMPILER_CODEGEN_UNUSED_LOCAL = [PRESERVE] | OPTIMIZE_OUT
- * Unless requested to preserve unused local variables (i.e. never read), the
- * compiler will optimize them out, potentially altering debugging
- *
- * COMPILER_CODEGEN_TARGET_PLATFORM = [VERSION_1_1] | VERSION_1_2
- * Generate .class files either backward compatible with JVM 1.1 or only executable
- * on JVM 1.2 and later
- *
- * COMPILER_PB_UNREACHABLE_CODE = [ERROR] | WARNING
- * Unreachable code can either be reported as an error or a warning
- *
- * COMPILER_PB_INVALID_IMPORT = [ERROR] | WARNING
- * An import statement that cannot be resolved might either be reported
- * either as an error or as a warning
- *
- * COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD = [WARNING] | IGNORE
- * A package default method is not visible in a different package, and thus
- * cannot be overriden. When enabling this option, the compiler will signal
- * such scenarii.
- *
- * COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME = [WARNING] | IGNORE
- * Naming a method with a constructor name is generally considered poor
- * style programming. When enabling this option, the compiler will signal such
- * scenarii
- *
- * COMPILER_PB_DEPRECATION = [WARNING] | IGNORE
- * When enabled, the compiler will signal use of deprecated API.
- *
- * COMPILER_PB_HIDDEN_CATCH_BLOCK = [WARNING] | IGNORE
- * Locally to a try statement, some catch blocks may hide others
- * (e.g. try { throw new java.io.CharConversionException();
- * } catch (java.io.CharConversionException e) {
- * } catch (java.io.IOException e) {}).
- * When enabling this option, the compiler will issue a warning for hidden catch
- * blocks corresponding to checked exceptions
- *
- * COMPILER_PB_UNUSED_LOCAL = WARNING | [IGNORE]
- * When enabled, the compiler will issue a warning for unused local variables
- * (i.e. variables never read from)
- *
- * COMPILER_PB_UNUSED_PARAMETER = WARNING | [IGNORE]
- * When enabled, the compiler will issue a warning for unused method parameters
- * (i.e. parameters never read from)
- *
- * COMPILER_PB_SYNTHETIC_ACCESS_EMULATION = WARNING | [IGNORE]
- * When enabled, the compiler will issue a warning whenever it emulates access
- * to a non-accessible member of an enclosing type
- *
- * CORE_JAVA_BUILD_ORDER = [COMPUTE] | IGNORE
- * When enabled, the build order is automatically reflecting the classpath on each
- * classpath change action. It can still be modified manually afterwards.
- */
-
- public static Hashtable getDefaultOptions() {
-
- Hashtable defaultOptions = new Hashtable(10);
-
- // Compiler settings
- defaultOptions.put(COMPILER_LOCAL_VARIABLE_ATTR, GENERATE);
- defaultOptions.put(COMPILER_LINE_NUMBER_ATTR, GENERATE);
- defaultOptions.put(COMPILER_SOURCE_FILE_ATTR, GENERATE);
- defaultOptions.put(COMPILER_CODEGEN_UNUSED_LOCAL, PRESERVE);
- defaultOptions.put(COMPILER_CODEGEN_TARGET_PLATFORM, VERSION_1_1);
- defaultOptions.put(COMPILER_PB_UNREACHABLE_CODE, ERROR);
- defaultOptions.put(COMPILER_PB_INVALID_IMPORT, ERROR);
- defaultOptions.put(COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, WARNING);
- defaultOptions.put(COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME, WARNING);
- defaultOptions.put(COMPILER_PB_DEPRECATION, WARNING);
- defaultOptions.put(COMPILER_PB_HIDDEN_CATCH_BLOCK, WARNING);
- defaultOptions.put(COMPILER_PB_UNUSED_LOCAL, IGNORE);
- defaultOptions.put(COMPILER_PB_UNUSED_PARAMETER, IGNORE);
- defaultOptions.put(COMPILER_PB_SYNTHETIC_ACCESS_EMULATION, IGNORE);
-
- // JavaCore settings
- defaultOptions.put(CORE_JAVA_BUILD_ORDER, IGNORE);
-
- return defaultOptions;
- }
-
- /**
- * Returns the single instance of the Java core plug-in runtime class.
- * Equivalent to <code>(JavaCore) getPlugin()</code>.
- */
- public static JavaCore getJavaCore() {
- return (JavaCore) getPlugin();
+ return null;
+}
+/**
+ * Returns the path held in the given classpath variable.
+ * Returns <node>null</code> if unable to bind.
+ * <p>
+ * Classpath variable values are persisted locally to the workspace, and
+ * are preserved from session to session.
+ * <p>
+ *
+ * @param variableName the name of the classpath variable
+ * @return the path, or <code>null</code> if none
+ * @see #setClasspathVariable
+ */
+public static IPath getClasspathVariable(String variableName) {
+ return (IPath)Variables.get(variableName);
+}
+/**
+ * Returns the names of all known classpath variables.
+ * <p>
+ * Classpath variable values are persisted locally to the workspace, and
+ * are preserved from session to session.
+ * <p>
+ *
+ * @return the list of classpath variable names
+ * @see #setClasspathVariable
+ */
+public static String[] getClasspathVariableNames() {
+ int length = Variables.size();
+ String[] result = new String[length];
+ Enumeration vars = Variables.keys();
+ int index = 0;
+ while (vars.hasMoreElements()){
+ result[index++] = (String)vars.nextElement();
}
-
- /**
- * Returns the <code>IJavaProject</code> associated with the
- * given <code>IProject</code>, or <code>null</code> if the
- * project does not have a Java nature.
- */
- private IJavaProject getJavaProject(IProject project) {
- try {
- if (project.hasNature(NATURE_ID)) {
- JavaModel model = JavaModelManager.getJavaModel(project.getWorkspace());
- if (model != null) {
- return model.getJavaProject(project);
- }
+ return result;
+}
+/**
+ * Answers a set of configurable options with their default values.
+ * These options allow to configure the behavior of the underlying components.
+ *
+ * Recognized options are listed below, optionName = possibleValue1 / possibleValue2
+ * where [] are enclosing the default value of the corresponding option.
+ *
+ * Note: more options might be added in further releases.
+ *
+ * RECOGNIZED OPTIONS:
+ *
+ * COMPILER_LOCAL_VARIABLE_ATTR = [GENERATE] | DO_NOT_GENERATE
+ * When generated, this attribute will enable local variable names to be displayed
+ * in debugger, only in place where variables are definitely assigned
+ * (.class file is then bigger)
+ *
+ * COMPILER_LINE_NUMBER_ATTR = [GENERATE] | DO_NOT_GENERATE
+ * When generated, this attribute will enable source code highlighting in debugger
+ * (.class file is then bigger).
+ *
+ * COMPILER_SOURCE_FILE_ATTR = [GENERATE] | DO_NOT_GENERATE
+ * When generated, this attribute will enable the debugger to present the
+ * corresponding source code.
+ *
+ * COMPILER_CODEGEN_UNUSED_LOCAL = [PRESERVE] | OPTIMIZE_OUT
+ * Unless requested to preserve unused local variables (i.e. never read), the
+ * compiler will optimize them out, potentially altering debugging
+ *
+ * COMPILER_CODEGEN_TARGET_PLATFORM = [VERSION_1_1] | VERSION_1_2
+ * Generate .class files either backward compatible with JVM 1.1 or only executable
+ * on JVM 1.2 and later
+ *
+ * COMPILER_PB_UNREACHABLE_CODE = [ERROR] | WARNING
+ * Unreachable code can either be reported as an error or a warning
+ *
+ * COMPILER_PB_INVALID_IMPORT = [ERROR] | WARNING
+ * An import statement that cannot be resolved might either be reported
+ * either as an error or as a warning
+ *
+ * COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD = [WARNING] | IGNORE
+ * A package default method is not visible in a different package, and thus
+ * cannot be overriden. When enabling this option, the compiler will signal
+ * such scenarii.
+ *
+ * COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME = [WARNING] | IGNORE
+ * Naming a method with a constructor name is generally considered poor
+ * style programming. When enabling this option, the compiler will signal such
+ * scenarii
+ *
+ * COMPILER_PB_DEPRECATION = [WARNING] | IGNORE
+ * When enabled, the compiler will signal use of deprecated API.
+ *
+ * COMPILER_PB_HIDDEN_CATCH_BLOCK = [WARNING] | IGNORE
+ * Locally to a try statement, some catch blocks may hide others
+ * (e.g. try { throw new java.io.CharConversionException();
+ * } catch (java.io.CharConversionException e) {
+ * } catch (java.io.IOException e) {}).
+ * When enabling this option, the compiler will issue a warning for hidden catch
+ * blocks corresponding to checked exceptions
+ *
+ * COMPILER_PB_UNUSED_LOCAL = WARNING | [IGNORE]
+ * When enabled, the compiler will issue a warning for unused local variables
+ * (i.e. variables never read from)
+ *
+ * COMPILER_PB_UNUSED_PARAMETER = WARNING | [IGNORE]
+ * When enabled, the compiler will issue a warning for unused method parameters
+ * (i.e. parameters never read from)
+ *
+ * COMPILER_PB_SYNTHETIC_ACCESS_EMULATION = WARNING | [IGNORE]
+ * When enabled, the compiler will issue a warning whenever it emulates access
+ * to a non-accessible member of an enclosing type
+ *
+ * CORE_JAVA_BUILD_ORDER = [COMPUTE] | IGNORE
+ * When enabled, the build order is automatically reflecting the classpath on each
+ * classpath change action. It can still be modified manually afterwards.
+ */
+
+public static Hashtable getDefaultOptions(){
+
+ Hashtable defaultOptions = new Hashtable(10);
+
+ // Compiler settings
+ defaultOptions.put(COMPILER_LOCAL_VARIABLE_ATTR, GENERATE);
+ defaultOptions.put(COMPILER_LINE_NUMBER_ATTR, GENERATE);
+ defaultOptions.put(COMPILER_SOURCE_FILE_ATTR, GENERATE);
+ defaultOptions.put(COMPILER_CODEGEN_UNUSED_LOCAL, PRESERVE);
+ defaultOptions.put(COMPILER_CODEGEN_TARGET_PLATFORM, VERSION_1_1);
+ defaultOptions.put(COMPILER_PB_UNREACHABLE_CODE, ERROR);
+ defaultOptions.put(COMPILER_PB_INVALID_IMPORT, ERROR);
+ defaultOptions.put(COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, WARNING);
+ defaultOptions.put(COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME, WARNING);
+ defaultOptions.put(COMPILER_PB_DEPRECATION, WARNING);
+ defaultOptions.put(COMPILER_PB_HIDDEN_CATCH_BLOCK, WARNING);
+ defaultOptions.put(COMPILER_PB_UNUSED_LOCAL, IGNORE);
+ defaultOptions.put(COMPILER_PB_UNUSED_PARAMETER, IGNORE);
+ defaultOptions.put(COMPILER_PB_SYNTHETIC_ACCESS_EMULATION, IGNORE);
+ defaultOptions.put(COMPILER_PB_NON_EXTERNALIZED_STRING_LITERAL, WARNING);
+
+ // JavaCore settings
+ defaultOptions.put(CORE_JAVA_BUILD_ORDER, IGNORE);
+
+ return defaultOptions;
+}
+/**
+ * Returns the single instance of the Java core plug-in runtime class.
+ * Equivalent to <code>(JavaCore) getPlugin()</code>.
+ */
+public static JavaCore getJavaCore() {
+ return (JavaCore) getPlugin();
+}
+/**
+ * Returns the <code>IJavaProject</code> associated with the
+ * given <code>IProject</code>, or <code>null</code> if the
+ * project does not have a Java nature.
+ */
+private IJavaProject getJavaProject(IProject project) {
+ try {
+ if (project.hasNature(NATURE_ID)) {
+ JavaModel model= JavaModelManager.getJavaModel(project.getWorkspace());
+ if (model != null) {
+ return model.getJavaProject(project);
}
- } catch (CoreException e) {
}
- return null;
- }
-
- /**
- * Answers a copy of the current set of configurable options supported by the Java core.
- * These options allow to configure the behavior of the underlying components.
- *
- * Changes on the set of options are not committed until invoking <code>JavaCore.setOptions</code>
- *
- * For a list of recognized options, refer to <code>JavaCore.getDefaultOptions</code>
- */
- public static Hashtable getOptions() {
-
- if (ConfigurableOptions == null)
- return ConfigurableOptions = getDefaultOptions();
- return (Hashtable) ConfigurableOptions.clone();
- }
-
- /**
- * Returns the single instance of the Java core plug-in runtime class.
- */
- public static Plugin getPlugin() {
- return JAVA_CORE_PLUGIN;
+ } catch (CoreException e) {
}
+ return null;
+}
+/**
+ * Answers a copy of the current set of configurable options supported by the Java core.
+ * These options allow to configure the behavior of the underlying components.
+ *
+ * Changes on the set of options are not committed until invoking <code>JavaCore.setOptions</code>
+ *
+ * For a list of recognized options, refer to <code>JavaCore.getDefaultOptions</code>
+ */
+public static Hashtable getOptions(){
- /**
- * This is a helper method which returns the resolved classpath entry denoted
- * by a given entry (if it is a variable entry). It is obtained by resolving the variable
- * reference in the first segment. Returns <node>null</code> if unable to resolve using
- * the following algorithm:
- * <ul>
- * <li> if variable segment cannot be resolved, returns <code>null</code></li>
- * <li> finds a project, JAR or binary folder in the workspace at the resolved path location</li>
- * <li> if none finds an external JAR file or folder outside the workspace at the resolved path location </li>
- * <li> if none returns <code>null</code></li>
- * </ul>
- * <p>
- * Variable source attachment path and root path are also resolved and recorded in the resulting classpath entry.
- * <p>
- * @return the resolved library or project classpath entry, or <code>null</code>
- * if the given variable entry could not be resolved to a valid classpath entry
- */
- public static IClasspathEntry getResolvedClasspathEntry(IClasspathEntry entry) {
-
- if (entry.getEntryKind() != IClasspathEntry.CPE_VARIABLE)
- return entry;
-
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- IPath resolvedPath = JavaCore.getResolvedVariablePath(entry.getPath());
- if (resolvedPath == null)
- return null;
-
- Object target = JavaModel.getTarget(workspaceRoot, resolvedPath);
- if (target == null)
- return null;
-
- // inside the workspace
- if (target instanceof IResource) {
- IResource resolvedResource = (IResource) target;
- if (resolvedResource != null) {
- switch (resolvedResource.getType()) {
- case IResource.PROJECT :
- return JavaCore.newProjectEntry(resolvedPath); // internal project
- case IResource.FILE :
- String extension = resolvedResource.getFileExtension();
- if ("jar".equalsIgnoreCase(extension)
- || "zip".equalsIgnoreCase(extension)) { // internal binary archive
- return JavaCore.newLibraryEntry(
+ if (ConfigurableOptions == null) return ConfigurableOptions = getDefaultOptions();
+ return (Hashtable)ConfigurableOptions.clone();
+}
+/**
+ * Returns the single instance of the Java core plug-in runtime class.
+ */
+public static Plugin getPlugin() {
+ return JAVA_CORE_PLUGIN;
+}
+/**
+ * This is a helper method which returns the resolved classpath entry denoted
+ * by a given entry (if it is a variable entry). It is obtained by resolving the variable
+ * reference in the first segment. Returns <node>null</code> if unable to resolve using
+ * the following algorithm:
+ * <ul>
+ * <li> if variable segment cannot be resolved, returns <code>null</code></li>
+ * <li> finds a project, JAR or binary folder in the workspace at the resolved path location</li>
+ * <li> if none finds an external JAR file or folder outside the workspace at the resolved path location </li>
+ * <li> if none returns <code>null</code></li>
+ * </ul>
+ * <p>
+ * Variable source attachment path and root path are also resolved and recorded in the resulting classpath entry.
+ * <p>
+ * @return the resolved library or project classpath entry, or <code>null</code>
+ * if the given variable entry could not be resolved to a valid classpath entry
+ */
+public static IClasspathEntry getResolvedClasspathEntry(IClasspathEntry entry) {
+
+ if (entry.getEntryKind() != IClasspathEntry.CPE_VARIABLE) return entry;
+
+ IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
+ IPath resolvedPath = JavaCore.getResolvedVariablePath(entry.getPath());
+ if (resolvedPath == null) return null;
+
+ Object target = JavaModel.getTarget(workspaceRoot, resolvedPath, false);
+ if (target == null) return null;
+
+ // inside the workspace
+ if (target instanceof IResource){
+ IResource resolvedResource = (IResource) target;
+ if (resolvedResource != null){
+ switch(resolvedResource.getType()){
+ case IResource.PROJECT :
+ return JavaCore.newProjectEntry(resolvedPath); // internal project
+ case IResource.FILE :
+ String extension = resolvedResource.getFileExtension();
+ if ("jar"/*nonNLS*/.equalsIgnoreCase(extension) || "zip"/*nonNLS*/.equalsIgnoreCase(extension)){ // internal binary archive
+ return JavaCore.newLibraryEntry(
resolvedPath,
getResolvedVariablePath(entry.getSourceAttachmentPath()),
- getResolvedVariablePath(entry.getSourceAttachmentRootPath()));
- }
- break;
- case IResource.FOLDER : // internal binary folder
- return JavaCore.newLibraryEntry(
+ getResolvedVariablePath(entry.getSourceAttachmentRootPath()));
+ }
+ break;
+ case IResource.FOLDER : // internal binary folder
+ return JavaCore.newLibraryEntry(
resolvedPath,
getResolvedVariablePath(entry.getSourceAttachmentPath()),
- getResolvedVariablePath(entry.getSourceAttachmentRootPath()));
- }
+ getResolvedVariablePath(entry.getSourceAttachmentRootPath()));
}
}
- // outside the workspace
- if (target instanceof File) {
- File externalFile = (File) target;
- if (externalFile.isFile()) {
- String fileName = externalFile.getName().toLowerCase();
- if (fileName.endsWith(".jar")
- || fileName.endsWith(".zip")) { // external binary archive
- return JavaCore.newLibraryEntry(
+ }
+ // outside the workspace
+ if (target instanceof File){
+ File externalFile = (File) target;
+ if (externalFile.isFile()){
+ String fileName = externalFile.getName().toLowerCase();
+ if (fileName.endsWith(".jar"/*nonNLS*/) || fileName.endsWith(".zip"/*nonNLS*/)){ // external binary archive
+ return JavaCore.newLibraryEntry(
resolvedPath,
getResolvedVariablePath(entry.getSourceAttachmentPath()),
- getResolvedVariablePath(entry.getSourceAttachmentRootPath()));
- }
- } else { // external binary folder
- return JavaCore.newLibraryEntry(
- resolvedPath,
- getResolvedVariablePath(entry.getSourceAttachmentPath()),
- getResolvedVariablePath(entry.getSourceAttachmentRootPath()));
+ getResolvedVariablePath(entry.getSourceAttachmentRootPath()));
}
+ } else { // external binary folder
+ return JavaCore.newLibraryEntry(
+ resolvedPath,
+ getResolvedVariablePath(entry.getSourceAttachmentPath()),
+ getResolvedVariablePath(entry.getSourceAttachmentRootPath()));
}
- return null;
}
+ return null;
+}
+/**
+ * Resolve a variable path (helper method)
+ */
+public static IPath getResolvedVariablePath(IPath variablePath) {
- /**
- * Resolve a variable path (helper method)
- */
- public static IPath getResolvedVariablePath(IPath variablePath) {
-
- if (variablePath == null)
- return null;
- int count = variablePath.segmentCount();
- if (count == 0)
- return null;
-
- // lookup variable
- String variableName = variablePath.segment(0);
- IPath resolvedPath = JavaCore.getClasspathVariable(variableName);
- if (resolvedPath == null || resolvedPath.isEmpty())
- return null;
+ if (variablePath == null) return null;
+ int count = variablePath.segmentCount();
+ if (count == 0) return null;
- // append path suffix
- if (count > 1) {
- resolvedPath = resolvedPath.append(variablePath.removeFirstSegments(1));
- }
- return resolvedPath;
- }
+ // lookup variable
+ String variableName = variablePath.segment(0);
+ IPath resolvedPath = JavaCore.getClasspathVariable(variableName);
+ if (resolvedPath == null || resolvedPath.isEmpty()) return null;
- /**
- * Returns whether the given marker references the given Java element.
- * Used for markers which denote a Java element rather than a resource.
- *
- * @param element the element
- * @param marker the marker
- * @return <code>true</code> if the marker references the element
- * @exception CoreException if the <code>IMarker.getAttribute</code> on the marker fails
- */
- public static boolean isReferencedBy(IJavaElement element, IMarker marker)
- throws CoreException {
- if (element instanceof IMember)
- element = ((IMember) element).getClassFile();
- return (
- element != null
- && marker != null
- && element.getHandleIdentifier().equals(marker.getAttribute(ATT_HANDLE_ID)));
+ // append path suffix
+ if (count > 1){
+ resolvedPath = resolvedPath.append(variablePath.removeFirstSegments(1));
}
-
- /**
- * Returns whether the given marker delta references the given Java element.
- * Used for markers deltas which denote a Java element rather than a resource.
- *
- * @param element the element
- * @param markerDelta the marker delta
- * @return <code>true</code> if the marker delta references the element
- * @exception CoreException if the <code>IMarkerDelta.getAttribute</code> on the marker delta fails
- */
- public static boolean isReferencedBy(
- IJavaElement element,
- IMarkerDelta markerDelta)
- throws CoreException {
- if (element instanceof IMember)
- element = ((IMember) element).getClassFile();
- return element != null
- && markerDelta != null
+ return resolvedPath;
+}
+/**
+ * Returns whether the given marker references the given Java element.
+ * Used for markers which denote a Java element rather than a resource.
+ *
+ * @param element the element
+ * @param marker the marker
+ * @return <code>true</code> if the marker references the element
+ * @exception CoreException if the <code>IMarker.getAttribute</code> on the marker fails
+ */
+ public static boolean isReferencedBy(IJavaElement element, IMarker marker) throws CoreException {
+ if (element instanceof IMember)
+ element= ((IMember)element).getClassFile();
+ return (element != null
+ && marker != null
+ && element.getHandleIdentifier().equals(marker.getAttribute(ATT_HANDLE_ID)));
+}
+/**
+ * Returns whether the given marker delta references the given Java element.
+ * Used for markers deltas which denote a Java element rather than a resource.
+ *
+ * @param element the element
+ * @param markerDelta the marker delta
+ * @return <code>true</code> if the marker delta references the element
+ * @exception CoreException if the <code>IMarkerDelta.getAttribute</code> on the marker delta fails
+ */
+public static boolean isReferencedBy(IJavaElement element, IMarkerDelta markerDelta) throws CoreException {
+ if (element instanceof IMember) element= ((IMember) element).getClassFile();
+ return element != null
+ && markerDelta != null
&& element.getHandleIdentifier().equals(markerDelta.getAttribute(ATT_HANDLE_ID));
- }
-
- /**
- * Creates and returns a new classpath entry of kind <code>CPE_LIBRARY</code> for the JAR or folder
- * identified by the given absolute path. This specifies that all package fragments within the root
- * will have children of type <code>IClassFile</code>.
- * <p>
- * A library entry is used to denote a prerequisite JAR or root folder containing binaries.
- * The target JAR or folder can either be defined internally to the workspace (absolute path relative
- * to the workspace root) or externally to the workspace (absolute path in the file system).
- *
- * e.g. Here are some examples of binary path usage<ul>
- * <li><code> "c:/jdk1.2.2/jre/lib/rt.jar" </code> - reference to an external JAR</li>
- * <li><code> "/Project/someLib.jar" </code> - reference to an internal JAR </li>
- * <li><code> "c:/classes/" </code> - reference to an external binary folder</li>
- * </ul>
- * Note that this operation does not attempt to validate or access the
- * resources at the given paths.
- * <p>
- * @param path the absolute path of the binary archive
- * @param sourceAttachmentPath the absolute path of the corresponding source archive,
- * or <code>null</code> if none
- * @param sourceAttachmentRootPath the location of the root within the source archive
- * or <code>null</code> if <code>archivePath</code> is also <code>null</code>
- */
-
- public static IClasspathEntry newLibraryEntry(
- IPath path,
- IPath sourceAttachmentPath,
- IPath sourceAttachmentRootPath) {
- Assert.isTrue(path.isAbsolute(), "path for IClasspathEntry must be absolute");
- return new ClasspathEntry(
- IPackageFragmentRoot.K_BINARY,
- IClasspathEntry.CPE_LIBRARY,
+}
+/**
+ * Creates and returns a new classpath entry of kind <code>CPE_LIBRARY</code> for the JAR or folder
+ * identified by the given absolute path. This specifies that all package fragments within the root
+ * will have children of type <code>IClassFile</code>.
+ * <p>
+ * A library entry is used to denote a prerequisite JAR or root folder containing binaries.
+ * The target JAR or folder can either be defined internally to the workspace (absolute path relative
+ * to the workspace root) or externally to the workspace (absolute path in the file system).
+ *
+ * e.g. Here are some examples of binary path usage<ul>
+ * <li><code> "c:/jdk1.2.2/jre/lib/rt.jar" </code> - reference to an external JAR</li>
+ * <li><code> "/Project/someLib.jar" </code> - reference to an internal JAR </li>
+ * <li><code> "c:/classes/" </code> - reference to an external binary folder</li>
+ * </ul>
+ * Note that this operation does not attempt to validate or access the
+ * resources at the given paths.
+ * <p>
+ * @param path the absolute path of the binary archive
+ * @param sourceAttachmentPath the absolute path of the corresponding source archive,
+ * or <code>null</code> if none
+ * @param sourceAttachmentRootPath the location of the root within the source archive
+ * or <code>null</code> if <code>archivePath</code> is also <code>null</code>
+ */
+
+public static IClasspathEntry newLibraryEntry(IPath path, IPath sourceAttachmentPath, IPath sourceAttachmentRootPath) {
+ Assert.isTrue(path.isAbsolute(), "path for IClasspathEntry must be absolute");
+ return new ClasspathEntry(
+ IPackageFragmentRoot.K_BINARY,
+ IClasspathEntry.CPE_LIBRARY,
JavaProject.canonicalizedPath(path),
sourceAttachmentPath,
sourceAttachmentRootPath);
- }
-
- /**
- * Creates and returns a new classpath entry of kind <code>CPE_PROJECT</code>
- * for the project identified by the given absolute path.
- * <p>
- * A project entry is used to denote a prerequisite project on a classpath.
- * The referenced project will be contributed as a whole, either as sources (in the Java Model, it
- * contributes all its package fragment roots) or as binaries (when building, it contributes its
- * whole output location).
- * <p>
- * A project reference allows to indirect through another project, independently from its internal layout.
- * <p>
- * The prerequisite project is referred to using an absolute path relative to the workspace root.
- */
- public static IClasspathEntry newProjectEntry(IPath path) {
- Assert.isTrue(path.isAbsolute(), "path for IClasspathEntry must be absolute");
- return new ClasspathEntry(
- IPackageFragmentRoot.K_SOURCE,
- IClasspathEntry.CPE_PROJECT,
- path,
- null,
- null);
- }
+}
+/**
+ * Creates and returns a new classpath entry of kind <code>CPE_PROJECT</code>
+ * for the project identified by the given absolute path.
+ * <p>
+ * A project entry is used to denote a prerequisite project on a classpath.
+ * The referenced project will be contributed as a whole, either as sources (in the Java Model, it
+ * contributes all its package fragment roots) or as binaries (when building, it contributes its
+ * whole output location).
+ * <p>
+ * A project reference allows to indirect through another project, independently from its internal layout.
+ * <p>
+ * The prerequisite project is referred to using an absolute path relative to the workspace root.
+ */
+public static IClasspathEntry newProjectEntry(IPath path){
+ Assert.isTrue(path.isAbsolute(), "path for IClasspathEntry must be absolute");
+ return new ClasspathEntry(IPackageFragmentRoot.K_SOURCE, IClasspathEntry.CPE_PROJECT, path, null, null);
+}
+/**
+ * Returns a new empty region.
+ */
+public static IRegion newRegion() {
+ return new Region();
+}
+/**
+ * Creates and returns a new classpath entry of kind <code>CPE_SOURCE</code> for the project's source folder
+ * identified by the given absolute path. This specifies that all package fragments within the root will
+ * have children of type <code>ICompilationUnit</code>.
+ * <p>
+ * The source folder is referred to using an absolute path relative to the workspace root, e.g. <code>"/Project/src"</code>.
+ * <p>
+ * A source entry is used to setup the internal source layout of a project, and cannot be used out of the
+ * context of the containing project (a source entry "Proj1/src" cannot be used on the classpath of Proj2).
+ */
+public static IClasspathEntry newSourceEntry(IPath path){
+ Assert.isTrue(path.isAbsolute(), "path for IClasspathEntry must be absolute");
+ return new ClasspathEntry(IPackageFragmentRoot.K_SOURCE, IClasspathEntry.CPE_SOURCE, path, null, null);
+}
+/**
+ * Creates and returns a new classpath entry of kind <code>CPE_VARIABLE</code>
+ * for the given path. The first segment of the the path is the name of a classpath variable.
+ * The trailing segments of the path will be appended to resolved variable path.
+ * <p>
+ * A variable entry allows to express indirect references on a classpath to other projects or libraries,
+ * depending on what the classpath variable is referring.
+ * <p>
+ * e.g. Here are some examples of variable path usage<ul>
+ * <li><"JDTCORE" where variable <code>JDTCORE</code> is
+ * bound to "c:/jars/jdtcore.jar". The resoved classpath entry is denoting the library "c:\jars\jdtcore.jar"</li>
+ * <li> "JDTCORE" where variable <code>JDTCORE</code> is
+ * bound to "/Project_JDTCORE". The resoved classpath entry is denoting the project "/Project_JDTCORE"</li>
+ * <li> "PLUGINS/com.example/example.jar" where variable <code>PLUGINS</code>
+ * is bound to "c:/eclipse/plugins". The resolved classpath entry is denoting the library "c:/eclipse/plugins/com.example/example.jar"</li>
+ * </ul>
+ * <p>
+ * Note that this operation does not attempt to validate classpath variables
+ * or access the resources at the given paths.
+ * <p>
+ * @param variablePath the path of the binary archive; first segment is the
+ * name of a classpath variable
+ * @param variableSourceAttachmentPath the path of the corresponding source archive,
+ * or <code>null</code> if none; if present, the first segment is the
+ * name of a classpath variable (not necessarily the same variable
+ * as the one that begins <code>variablePath</code>)
+ * @param sourceAttachmentRootPath the location of the root within the source archive
+ * or <code>null</code> if <code>archivePath</code> is also <code>null</code>
+ */
+public static IClasspathEntry newVariableEntry(IPath variablePath, IPath variableSourceAttachmentPath, IPath sourceAttachmentRootPath){
+ Assert.isTrue(variablePath != null && variablePath.segmentCount() >= 1, "invalid variable path");
+ return new ClasspathEntry(
+ IPackageFragmentRoot.K_SOURCE,
+ IClasspathEntry.CPE_VARIABLE,
+ variablePath,
+ variableSourceAttachmentPath,
+ sourceAttachmentRootPath);
+}
+/**
+ * Removed the given classpath variable. Does nothing if no value was
+ * set for this classpath variable.
+ * <p>
+ * This functionality cannot be used while the resource tree is locked.
+ * <p>
+ * Classpath variable values are persisted locally to the workspace, and
+ * are preserved from session to session.
+ * <p>
+ *
+ * @param variableName the name of the classpath variable
+ * @see #setClasspathVariable
+ *
+ * @deprecated - use version with extra IProgressMonitor
+ */
+public static void removeClasspathVariable(String variableName) {
- /**
- * Returns a new empty region.
- */
- public static IRegion newRegion() {
- return new Region();
- }
+ removeClasspathVariable(variableName, null);
+}
+/**
+ * Removed the given classpath variable. Does nothing if no value was
+ * set for this classpath variable.
+ * <p>
+ * This functionality cannot be used while the resource tree is locked.
+ * <p>
+ * Classpath variable values are persisted locally to the workspace, and
+ * are preserved from session to session.
+ * <p>
+ *
+ * @param variableName the name of the classpath variable
+ * @param monitor the progress monitor to report progress
+ * @see #setClasspathVariable
+ */
+public static void removeClasspathVariable(String variableName, IProgressMonitor monitor) {
- /**
- * Creates and returns a new classpath entry of kind <code>CPE_SOURCE</code> for the project's source folder
- * identified by the given absolute path. This specifies that all package fragments within the root will
- * have children of type <code>ICompilationUnit</code>.
- * <p>
- * The source folder is referred to using an absolute path relative to the workspace root, e.g. <code>"/Project/src"</code>.
- * <p>
- * A source entry is used to setup the internal source layout of a project, and cannot be used out of the
- * context of the containing project (a source entry "Proj1/src" cannot be used on the classpath of Proj2).
- */
- public static IClasspathEntry newSourceEntry(IPath path) {
- Assert.isTrue(path.isAbsolute(), "path for IClasspathEntry must be absolute");
- return new ClasspathEntry(
- IPackageFragmentRoot.K_SOURCE,
- IClasspathEntry.CPE_SOURCE,
- path,
- null,
- null);
- }
-
- /**
- * Creates and returns a new classpath entry of kind <code>CPE_VARIABLE</code>
- * for the given path. The first segment of the the path is the name of a classpath variable.
- * The trailing segments of the path will be appended to resolved variable path.
- * <p>
- * A variable entry allows to express indirect references on a classpath to other projects or libraries,
- * depending on what the classpath variable is referring.
- * <p>
- * e.g. Here are some examples of variable path usage<ul>
- * <li><"JDTCORE" where variable <code>JDTCORE</code> is
- * bound to "c:/jars/jdtcore.jar". The resoved classpath entry is denoting the library "c:\jars\jdtcore.jar"</li>
- * <li> "JDTCORE" where variable <code>JDTCORE</code> is
- * bound to "/Project_JDTCORE". The resoved classpath entry is denoting the project "/Project_JDTCORE"</li>
- * <li> "PLUGINS/com.example/example.jar" where variable <code>PLUGINS</code>
- * is bound to "c:/eclipse/plugins". The resolved classpath entry is denoting the library "c:/eclipse/plugins/com.example/example.jar"</li>
- * </ul>
- * <p>
- * Note that this operation does not attempt to validate classpath variables
- * or access the resources at the given paths.
- * <p>
- * @param variablePath the path of the binary archive; first segment is the
- * name of a classpath variable
- * @param variableSourceAttachmentPath the path of the corresponding source archive,
- * or <code>null</code> if none; if present, the first segment is the
- * name of a classpath variable (not necessarily the same variable
- * as the one that begins <code>variablePath</code>)
- * @param sourceAttachmentRootPath the location of the root within the source archive
- * or <code>null</code> if <code>archivePath</code> is also <code>null</code>
- */
- public static IClasspathEntry newVariableEntry(
- IPath variablePath,
- IPath variableSourceAttachmentPath,
- IPath sourceAttachmentRootPath) {
- Assert.isTrue(
- variablePath != null && variablePath.segmentCount() >= 1,
- "invalid variable path");
- return new ClasspathEntry(
- IPackageFragmentRoot.K_SOURCE,
- IClasspathEntry.CPE_VARIABLE,
- variablePath,
- variableSourceAttachmentPath,
- sourceAttachmentRootPath);
+ try {
+ updateVariableValue(variableName, null, monitor);
+ } catch(JavaModelException e){
}
+}
+/**
+ * Removes the given element changed listener.
+ * Has no affect if an identical listener is not registered.
+ *
+ * @param listener the listener
+ */
+public static void removeElementChangedListener(IElementChangedListener listener) {
+ JavaModelManager.getJavaModelManager().removeElementChangedListener(listener);
+}
+/**
+ * Sets the value of the given classpath variable.
+ * The path must have at least one segment.
+ * <p>
+ * This functionality cannot be used while the resource tree is locked.
+ * <p>
+ * Classpath variable values are persisted locally to the workspace, and
+ * are preserved from session to session.
+ * <p>
+ *
+ * @param variableName the name of the classpath variable
+ * @param path the path
+ * @see #getClasspathVariable
+ *
+ * @deprecated - use API with IProgressMonitor
+ */
+public static void setClasspathVariable(String variableName, IPath path) throws JavaModelException {
- /**
- * Removed the given classpath variable. Does nothing if no value was
- * set for this classpath variable.
- * <p>
- * This functionality cannot be used while the resource tree is locked.
- * <p>
- * Classpath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- * <p>
- *
- * @param variableName the name of the classpath variable
- * @see #setClasspathVariable
- *
- * @deprecated - use version with extra IProgressMonitor
- */
- public static void removeClasspathVariable(String variableName) {
+ setClasspathVariable(variableName, path, null);
+}
+/**
+ * Sets the value of the given classpath variable.
+ * The path must have at least one segment.
+ * <p>
+ * This functionality cannot be used while the resource tree is locked.
+ * <p>
+ * Classpath variable values are persisted locally to the workspace, and
+ * are preserved from session to session.
+ * <p>
+ *
+ * @param variableName the name of the classpath variable
+ * @param path the path
+ * @param monitor a monitor to report progress
+ * @see #getClasspathVariable
+ */
+public static void setClasspathVariable(String variableName, IPath path, IProgressMonitor monitor) throws JavaModelException {
- removeClasspathVariable(variableName, null);
- }
+ Assert.isTrue(path != null, "variable path cannot be null");
+ updateVariableValue(variableName, path, monitor);
+}
+/* (non-Javadoc)
+ * Method declared on IExecutableExtension.
+ * Record any necessary initialization data from the plugin.
+ */
+public void setInitializationData(IConfigurationElement cfig, String propertyName, Object data) throws CoreException {}
+/**
+ * Set current set of configurable options supported by the Java core.
+ * These options allow to configure the behavior of the underlying components.
+ *
+ * For a list of recognized options, refer to <code>JavaCore.getDefaultOptions</code>
+ */
+public static void setOptions(Hashtable configurableOptions){
+ ConfigurableOptions = (Hashtable) configurableOptions.clone();
+}
+/**
+ * Shutdown the JavaCore plugin
+ * <p>
+ * De-registers the JavaModelManager as a resource changed listener and save participant.
+ * <p>
+ * @see Plugin#shutdown
+ */
+public void shutdown() {
- /**
- * Removed the given classpath variable. Does nothing if no value was
- * set for this classpath variable.
- * <p>
- * This functionality cannot be used while the resource tree is locked.
- * <p>
- * Classpath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- * <p>
- *
- * @param variableName the name of the classpath variable
- * @param monitor the progress monitor to report progress
- * @see #setClasspathVariable
- */
- public static void removeClasspathVariable(
- String variableName,
- IProgressMonitor monitor) {
+ IWorkspace workspace = ResourcesPlugin.getWorkspace();
+ workspace.removeResourceChangeListener(JavaModelManager.getJavaModelManager());
+ workspace.removeSaveParticipant(this);
- try {
- updateVariableValue(variableName, null, monitor);
- } catch (JavaModelException e) {
+ ((JavaModelManager) JavaModelManager.getJavaModelManager()).shutdown();
+}
+/**
+ * Initiate the background indexing process.
+ * This should be deferred after the plugin activation.
+ */
+private void startIndexing() {
+
+ JavaModelManager manager = (JavaModelManager) JavaModelManager.getJavaModelManager();
+ IndexManager indexManager = manager.getIndexManager();
+ if (indexManager != null) indexManager.reset();
+ /*
+ // if there is a desktop defer the start of the indexing by posting a runnable
+ if (getDesktopPlugin() != null) {
+ IDesktop desktop= getDesktop();
+ ApplicationWindow window= (ApplicationWindow) desktop.getActiveDesktopWindow();
+ Display display= null;
+ if (window != null)
+ display= window.getDisplay();
+ if (display != null) {
+ display.asyncExec(start);
+ return;
+ }
}
- }
-
- /**
- * Removes the given element changed listener.
- * Has no affect if an identical listener is not registered.
- *
- * @param listener the listener
- */
- public static void removeElementChangedListener(IElementChangedListener listener) {
- JavaModelManager.getJavaModelManager().removeElementChangedListener(listener);
- }
-
- /**
- * Sets the value of the given classpath variable.
- * The path must have at least one segment.
- * <p>
- * This functionality cannot be used while the resource tree is locked.
- * <p>
- * Classpath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- * <p>
- *
- * @param variableName the name of the classpath variable
- * @param path the path
- * @see #getClasspathVariable
- *
- * @deprecated - use API with IProgressMonitor
- */
- public static void setClasspathVariable(String variableName, IPath path)
- throws JavaModelException {
-
- setClasspathVariable(variableName, path, null);
- }
-
- /**
- * Sets the value of the given classpath variable.
- * The path must have at least one segment.
- * <p>
- * This functionality cannot be used while the resource tree is locked.
- * <p>
- * Classpath variable values are persisted locally to the workspace, and
- * are preserved from session to session.
- * <p>
- *
- * @param variableName the name of the classpath variable
- * @param path the path
- * @param monitor a monitor to report progress
- * @see #getClasspathVariable
- */
- public static void setClasspathVariable(
- String variableName,
- IPath path,
- IProgressMonitor monitor)
- throws JavaModelException {
-
- Assert.isTrue(path != null, "variable path cannot be null");
- updateVariableValue(variableName, path, monitor);
- }
-
- /* (non-Javadoc)
- * Method declared on IExecutableExtension.
- * Record any necessary initialization data from the plugin.
- */
- public void setInitializationData(
- IConfigurationElement cfig,
- String propertyName,
- Object data)
- throws CoreException {
- }
-
- /**
- * Set current set of configurable options supported by the Java core.
- * These options allow to configure the behavior of the underlying components.
- *
- * For a list of recognized options, refer to <code>JavaCore.getDefaultOptions</code>
- */
- public static void setOptions(Hashtable configurableOptions) {
- ConfigurableOptions = (Hashtable) configurableOptions.clone();
- }
-
- /**
- * Shutdown the JavaCore plugin
- * <p>
- * De-registers the JavaModelManager as a resource changed listener and save participant.
- * <p>
- * @see Plugin#shutdown
- */
- public void shutdown() {
-
+ */
+}
+/**
+ * Startup of the JavaCore plugin
+ * <p>
+ * Registers the JavaModelManager as a resource changed listener and save participant.
+ * Starts the background indexing, and restore saved classpath variable values.
+ * <p>
+ * @see Plugin#startup
+ */
+public void startup() {
+ JavaModelManager manager = JavaModelManager.getJavaModelManager();
+ try {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
- workspace.removeResourceChangeListener(JavaModelManager.getJavaModelManager());
- workspace.removeSaveParticipant(this);
-
- ((JavaModelManager) JavaModelManager.getJavaModelManager()).shutdown();
- }
-
- /**
- * Initiate the background indexing process.
- * This should be deferred after the plugin activation.
- */
- private void startIndexing() {
-
- JavaModelManager manager =
- (JavaModelManager) JavaModelManager.getJavaModelManager();
IndexManager indexManager = manager.getIndexManager();
- if (indexManager != null)
- indexManager.reset();
- /*
- // if there is a desktop defer the start of the indexing by posting a runnable
- if (getDesktopPlugin() != null) {
- IDesktop desktop= getDesktop();
- ApplicationWindow window= (ApplicationWindow) desktop.getActiveDesktopWindow();
- Display display= null;
- if (window != null)
- display= window.getDisplay();
- if (display != null) {
- display.asyncExec(start);
- return;
- }
- }
- */
- }
-
- /**
- * Startup of the JavaCore plugin
- * <p>
- * Registers the JavaModelManager as a resource changed listener and save participant.
- * Starts the background indexing, and restore saved classpath variable values.
- * <p>
- * @see Plugin#startup
- */
- public void startup() {
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- try {
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IndexManager indexManager = manager.getIndexManager();
- if (indexManager != null) {
- // need to initialize workbench now since a query may be done before indexing starts
- indexManager.workspace = workspace;
- }
- workspace.addResourceChangeListener(
- manager,
- IResourceChangeEvent.PRE_AUTO_BUILD
- | IResourceChangeEvent.POST_CHANGE
- | IResourceChangeEvent.PRE_DELETE
- | IResourceChangeEvent.PRE_CLOSE);
-
- startIndexing();
-
- workspace.addSaveParticipant(this, manager);
- manager.loadVariables();
- } catch (CoreException e) {
- } catch (RuntimeException e) {
- manager.shutdown();
- throw e;
+ if (indexManager != null) {
+ // need to initialize workbench now since a query may be done before indexing starts
+ indexManager.workspace = workspace;
}
+ workspace.addResourceChangeListener(
+ manager,
+ IResourceChangeEvent.PRE_AUTO_BUILD | IResourceChangeEvent.POST_CHANGE
+ | IResourceChangeEvent.PRE_DELETE | IResourceChangeEvent.PRE_CLOSE);
+
+ startIndexing();
+
+ workspace.addSaveParticipant(this, manager);
+ manager.loadVariables();
+ } catch(CoreException e) {
+ } catch(RuntimeException e){
+ manager.shutdown();
+ throw e;
}
-
- /**
- * Internal updating of a variable value (null path meaning removal).
- */
- private static void updateVariableValue(
- String variableName,
- IPath path,
- IProgressMonitor monitor)
- throws JavaModelException {
-
- // gather classpath information for updating
- Hashtable affectedProjects = new Hashtable(5);
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- try {
- IJavaModel model = manager.getJavaModel();
- if (model != null) {
- IJavaProject[] projects = model.getJavaProjects();
- nextProject : for (int i = 0, max = projects.length; i < max; i++) {
- IClasspathEntry[] entries = projects[i].getRawClasspath();
- for (int j = 0, cplength = entries.length; j < cplength; j++) {
- IClasspathEntry oldEntry = entries[j];
- if (oldEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
- IPath sourcePath, sourceRootPath;
- if (oldEntry.getPath().segment(0).equals(variableName)
- || ((sourcePath = oldEntry.getSourceAttachmentPath()) != null
- && sourcePath.segment(0).equals(variableName))
- || ((sourceRootPath = oldEntry.getSourceAttachmentRootPath()) != null
- && sourceRootPath.segment(0).equals(variableName))) {
- affectedProjects.put(projects[i], projects[i].getResolvedClasspath(true));
- continue nextProject;
- }
+}
+/**
+ * Internal updating of a variable value (null path meaning removal).
+ */
+private static void updateVariableValue(String variableName, IPath path, IProgressMonitor monitor) throws JavaModelException {
+
+ // gather classpath information for updating
+ Hashtable affectedProjects = new Hashtable(5);
+ JavaModelManager manager = JavaModelManager.getJavaModelManager();
+ try {
+ IJavaModel model = manager.getJavaModel();
+ if (model != null){
+ IJavaProject[] projects = model.getJavaProjects();
+ nextProject: for (int i = 0, max = projects.length; i < max; i++){
+ IClasspathEntry[] entries = projects[i].getRawClasspath();
+ for (int j = 0, cplength = entries.length; j < cplength; j++){
+ IClasspathEntry oldEntry = entries[j];
+ if (oldEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE){
+ IPath sourcePath, sourceRootPath;
+ if (oldEntry.getPath().segment(0).equals(variableName)
+ || ((sourcePath = oldEntry.getSourceAttachmentPath()) != null && sourcePath.segment(0).equals(variableName))
+ || ((sourceRootPath = oldEntry.getSourceAttachmentRootPath()) != null && sourceRootPath.segment(0).equals(variableName))) {
+ affectedProjects.put(projects[i], projects[i].getResolvedClasspath(true));
+ continue nextProject;
}
}
}
}
- } catch (JavaModelException e) {
}
+ } catch(JavaModelException e){
+ }
- if (path == null) {
- Variables.remove(variableName);
- } else {
- // new variable value is assigned
- Variables.put(variableName, path);
- }
+ if (path == null){
+ Variables.remove(variableName);
+ } else {
+ // new variable value is assigned
+ Variables.put(variableName, path);
+ }
- if (!affectedProjects.isEmpty()) {
- boolean wasFiring = manager.isFiring();
- try {
- if (wasFiring)
- manager.stopDeltas();
- // propagate classpath change
- Enumeration projectsToUpdate = affectedProjects.keys();
- while (projectsToUpdate.hasMoreElements()) {
- JavaProject project = (JavaProject) projectsToUpdate.nextElement();
- project
- .setRawClasspath(
- project.getRawClasspath(),
- monitor,
- project.getWorkspace().isAutoBuilding(),
- // force build if in auto build mode
- (IClasspathEntry[]) affectedProjects.get(project));
- }
- } finally {
- manager.mergeDeltas();
- if (wasFiring) {
- manager.startDeltas();
- manager.fire();
- }
+ if (!affectedProjects.isEmpty()){
+ boolean wasFiring = manager.isFiring();
+ try {
+ if (wasFiring) manager.stopDeltas();
+ // propagate classpath change
+ Enumeration projectsToUpdate = affectedProjects.keys();
+ while (projectsToUpdate.hasMoreElements()){
+ JavaProject project = (JavaProject)projectsToUpdate.nextElement();
+ project.setRawClasspath(
+ project.getRawClasspath(),
+ monitor,
+ project.getWorkspace().isAutoBuilding(), // force build if in auto build mode
+ (IClasspathEntry[])affectedProjects.get(project));
+ }
+ } finally {
+ manager.mergeDeltas();
+ if (wasFiring){
+ manager.startDeltas();
+ manager.fire();
}
}
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaModelException.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaModelException.java
index 336ff45d97..e7017e5071 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaModelException.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/JavaModelException.java
@@ -4,7 +4,7 @@ package org.eclipse.jdt.core;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
-
+
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
@@ -24,101 +24,94 @@ import org.eclipse.jdt.internal.core.JavaModelStatus;
* @see IJavaModelStatusConstants
*/
public class JavaModelException extends CoreException {
- /**
- * Creates a Java model exception that wrappers the given <code>Throwable</code>.
- * The exception contains a Java-specific status object with severity
- * <code>IStatus.ERROR</code> and the given status code.
- *
- * @param exception the <code>Throwable</code>
- * @param code one of the Java-specific status codes declared in
- * <code>IJavaModelStatusConstants</code>
- * @return the new Java model exception
- * @see IJavaModelStatusConstants
- * @see org.eclipse.core.runtime.IStatus#ERROR
- */
- public JavaModelException(Throwable e, int code) {
- this(new JavaModelStatus(code, e));
- }
-
- /**
- * Creates a Java model exception for the given <code>CoreException</code>.
- * Equivalent to
- * <code>JavaModelException(exception,IJavaModelStatusConstants.CORE_EXCEPTION</code>.
- *
- * @param exception the <code>CoreException</code>
- * @return the new Java model exception
- */
- public JavaModelException(CoreException exception) {
- this(new JavaModelStatus(exception));
- }
-
- /**
- * Creates a Java model exception for the given Java-specific status object.
- *
- * @param status the Java-specific status object
- * @return the new Java model exception
- */
- public JavaModelException(IJavaModelStatus status) {
- super(status);
- }
-
- /**
- * Returns the underlying <code>Throwable</code> that caused the failure.
- *
- * @return the wrappered <code>Throwable</code>, or <code>null</code> if the
- * direct case of the failure was at the Java model layer
- */
- public Throwable getException() {
- return getStatus().getException();
- }
-
- /**
- * Returns the Java model status object for this exception.
- * Equivalent to <code>(IJavaModelStatus) getStatus()</code>.
- *
- * @return a status object
- */
- public IJavaModelStatus getJavaModelStatus() {
- return (IJavaModelStatus) getStatus();
- }
-
- /**
- * Returns whether this exception indicates that a Java model element does not
- * exist. Such exceptions have a status with a code of
- * <code>IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST</code>.
- * This is a convenience method.
- *
- * @return <code>true</code> if this exception indicates that a Java model
- * element does not exist
- * @see IJavaModelStatus#isDoesNotExist
- * @see IJavaModelStatusConstants#ELEMENT_DOES_NOT_EXIST
- */
- public boolean isDoesNotExist() {
- IJavaModelStatus javaModelStatus = getJavaModelStatus();
- return javaModelStatus != null && javaModelStatus.isDoesNotExist();
- }
-
- /**
- * Returns a printable representation of this exception suitable for debugging
- * purposes only.
- */
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append("Java Model Exception: ");
- if (getException() != null) {
- if (getException() instanceof CoreException) {
- CoreException c = (CoreException) getException();
- buffer.append("Core Exception [code ");
- buffer.append(c.getStatus().getCode());
- buffer.append("] ");
- buffer.append(c.getStatus().getMessage());
- } else {
- buffer.append(getException().toString());
- }
+/**
+ * Creates a Java model exception that wrappers the given <code>Throwable</code>.
+ * The exception contains a Java-specific status object with severity
+ * <code>IStatus.ERROR</code> and the given status code.
+ *
+ * @param exception the <code>Throwable</code>
+ * @param code one of the Java-specific status codes declared in
+ * <code>IJavaModelStatusConstants</code>
+ * @return the new Java model exception
+ * @see IJavaModelStatusConstants
+ * @see org.eclipse.core.runtime.IStatus#ERROR
+ */
+public JavaModelException(Throwable e, int code) {
+ this(new JavaModelStatus(code, e));
+}
+/**
+ * Creates a Java model exception for the given <code>CoreException</code>.
+ * Equivalent to
+ * <code>JavaModelException(exception,IJavaModelStatusConstants.CORE_EXCEPTION</code>.
+ *
+ * @param exception the <code>CoreException</code>
+ * @return the new Java model exception
+ */
+public JavaModelException(CoreException exception) {
+ this(new JavaModelStatus(exception));
+}
+/**
+ * Creates a Java model exception for the given Java-specific status object.
+ *
+ * @param status the Java-specific status object
+ * @return the new Java model exception
+ */
+public JavaModelException(IJavaModelStatus status) {
+ super(status);
+}
+/**
+ * Returns the underlying <code>Throwable</code> that caused the failure.
+ *
+ * @return the wrappered <code>Throwable</code>, or <code>null</code> if the
+ * direct case of the failure was at the Java model layer
+ */
+public Throwable getException() {
+ return getStatus().getException();
+}
+/**
+ * Returns the Java model status object for this exception.
+ * Equivalent to <code>(IJavaModelStatus) getStatus()</code>.
+ *
+ * @return a status object
+ */
+public IJavaModelStatus getJavaModelStatus() {
+ return (IJavaModelStatus) getStatus();
+}
+/**
+ * Returns whether this exception indicates that a Java model element does not
+ * exist. Such exceptions have a status with a code of
+ * <code>IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST</code>.
+ * This is a convenience method.
+ *
+ * @return <code>true</code> if this exception indicates that a Java model
+ * element does not exist
+ * @see IJavaModelStatus#isDoesNotExist
+ * @see IJavaModelStatusConstants#ELEMENT_DOES_NOT_EXIST
+ */
+public boolean isDoesNotExist() {
+ IJavaModelStatus javaModelStatus = getJavaModelStatus();
+ return javaModelStatus != null && javaModelStatus.isDoesNotExist();
+}
+/**
+ * Returns a printable representation of this exception suitable for debugging
+ * purposes only.
+ */
+public String toString() {
+ StringBuffer buffer= new StringBuffer();
+ buffer.append("Java Model Exception: "/*nonNLS*/);
+ if (getException() != null) {
+ if (getException() instanceof CoreException) {
+ CoreException c= (CoreException)getException();
+ buffer.append("Core Exception [code "/*nonNLS*/);
+ buffer.append(c.getStatus().getCode());
+ buffer.append("] "/*nonNLS*/);
+ buffer.append(c.getStatus().getMessage());
} else {
- buffer.append(getStatus().toString());
+ buffer.append(getException().toString());
}
- return buffer.toString();
+ } else {
+ buffer.append(getStatus().toString());
}
-
+ return buffer.toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/Signature.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/Signature.java
index fdec35ba68..7a870dd705 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/Signature.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/Signature.java
@@ -4,7 +4,7 @@ package org.eclipse.jdt.core;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
-
+
import org.eclipse.jdt.internal.compiler.parser.InvalidInputException;
import org.eclipse.jdt.internal.compiler.parser.Scanner;
import org.eclipse.jdt.internal.compiler.parser.TerminalSymbols;
@@ -65,844 +65,794 @@ public final class Signature {
* Character constant indicating the primitive type boolean in a signature.
* Value is <code>'Z'</code>.
*/
- public static final char C_BOOLEAN = 'Z';
+ public static final char C_BOOLEAN = 'Z';
/**
* Character constant indicating the primitive type byte in a signature.
* Value is <code>'B'</code>.
*/
- public static final char C_BYTE = 'B';
+ public static final char C_BYTE = 'B';
/**
* Character constant indicating the primitive type char in a signature.
* Value is <code>'C'</code>.
*/
- public static final char C_CHAR = 'C';
+ public static final char C_CHAR = 'C';
/**
* Character constant indicating the primitive type double in a signature.
* Value is <code>'D'</code>.
*/
- public static final char C_DOUBLE = 'D';
+ public static final char C_DOUBLE = 'D';
/**
* Character constant indicating the primitive type float in a signature.
* Value is <code>'F'</code>.
*/
- public static final char C_FLOAT = 'F';
+ public static final char C_FLOAT = 'F';
/**
* Character constant indicating the primitive type int in a signature.
* Value is <code>'I'</code>.
*/
- public static final char C_INT = 'I';
-
+ public static final char C_INT = 'I';
+
/**
* Character constant indicating the semicolon in a signature.
* Value is <code>';'</code>.
*/
- public static final char C_SEMICOLON = ';';
+ public static final char C_SEMICOLON = ';';
/**
* Character constant indicating the primitive type long in a signature.
* Value is <code>'J'</code>.
*/
- public static final char C_LONG = 'J';
-
+ public static final char C_LONG = 'J';
+
/**
* Character constant indicating the primitive type short in a signature.
* Value is <code>'S'</code>.
*/
- public static final char C_SHORT = 'S';
-
+ public static final char C_SHORT = 'S';
+
/**
* Character constant indicating result type void in a signature.
* Value is <code>'V'</code>.
*/
- public static final char C_VOID = 'V';
-
+ public static final char C_VOID = 'V';
+
/**
* Character constant indicating the dot in a signature.
* Value is <code>'.'</code>.
*/
- public static final char C_DOT = '.';
-
+ public static final char C_DOT = '.';
+
/**
* Character constant indicating the dollar in a signature.
* Value is <code>'$'</code>.
*/
- public static final char C_DOLLAR = '$';
+ public static final char C_DOLLAR = '$';
/**
* Character constant indicating an array type in a signature.
* Value is <code>'['</code>.
*/
- public static final char C_ARRAY = '[';
+ public static final char C_ARRAY = '[';
/**
* Character constant indicating the start of a resolved, named type in a
* signature. Value is <code>'L'</code>.
*/
- public static final char C_RESOLVED = 'L';
+ public static final char C_RESOLVED = 'L';
/**
* Character constant indicating the start of an unresolved, named type in a
* signature. Value is <code>'Q'</code>.
*/
- public static final char C_UNRESOLVED = 'Q';
+ public static final char C_UNRESOLVED = 'Q';
/**
* Character constant indicating the end of a named type in a signature.
* Value is <code>';'</code>.
*/
- public static final char C_NAME_END = ';';
+ public static final char C_NAME_END = ';';
/**
* Character constant indicating the start of a parameter type list in a
* signature. Value is <code>'('</code>.
*/
- public static final char C_PARAM_START = '(';
+ public static final char C_PARAM_START = '(';
/**
* Character constant indicating the end of a parameter type list in a
* signature. Value is <code>')'</code>.
*/
- public static final char C_PARAM_END = ')';
+ public static final char C_PARAM_END = ')';
/**
* String constant for the signature of the primitive type boolean.
* Value is <code>"Z"</code>.
*/
- public static final String SIG_BOOLEAN = "Z";
+ public static final String SIG_BOOLEAN = "Z"/*nonNLS*/;
/**
* String constant for the signature of the primitive type byte.
* Value is <code>"B"</code>.
*/
- public static final String SIG_BYTE = "B";
+ public static final String SIG_BYTE = "B"/*nonNLS*/;
/**
* String constant for the signature of the primitive type char.
* Value is <code>"C"</code>.
*/
- public static final String SIG_CHAR = "C";
+ public static final String SIG_CHAR = "C"/*nonNLS*/;
/**
* String constant for the signature of the primitive type double.
* Value is <code>"D"</code>.
*/
- public static final String SIG_DOUBLE = "D";
+ public static final String SIG_DOUBLE = "D"/*nonNLS*/;
/**
* String constant for the signature of the primitive type float.
* Value is <code>"F"</code>.
*/
- public static final String SIG_FLOAT = "F";
+ public static final String SIG_FLOAT = "F"/*nonNLS*/;
/**
* String constant for the signature of the primitive type int.
* Value is <code>"I"</code>.
*/
- public static final String SIG_INT = "I";
+ public static final String SIG_INT = "I"/*nonNLS*/;
/**
* String constant for the signature of the primitive type long.
* Value is <code>"J"</code>.
*/
- public static final String SIG_LONG = "J";
+ public static final String SIG_LONG = "J"/*nonNLS*/;
/**
* String constant for the signature of the primitive type short.
* Value is <code>"S"</code>.
*/
- public static final String SIG_SHORT = "S";
+ public static final String SIG_SHORT = "S"/*nonNLS*/;
/** String constant for the signature of result type void.
* Value is <code>"V"</code>.
*/
- public static final String SIG_VOID = "V";
-
- /**
- * Not instantiable.
- */
- private Signature() {
+ public static final String SIG_VOID = "V"/*nonNLS*/;
+
+/**
+ * Not instantiable.
+ */
+private Signature() {}
+/**
+ * Internal - Adds array brackets to a readable type name.
+ */
+private static String arrayIfy(String typeName, int arrayCount) {
+ if (arrayCount == 0) {
+ return typeName;
}
-
- /**
- * Internal - Adds array brackets to a readable type name.
- */
- private static String arrayIfy(String typeName, int arrayCount) {
- if (arrayCount == 0) {
- return typeName;
- }
- StringBuffer sb = new StringBuffer(typeName.length() + arrayCount * 2);
- sb.append(typeName);
- for (int i = 0; i < arrayCount; ++i) {
- sb.append("[]");
- }
- return sb.toString();
+ StringBuffer sb = new StringBuffer(typeName.length() + arrayCount * 2);
+ sb.append(typeName);
+ for (int i = 0; i < arrayCount; ++i) {
+ sb.append("[]"/*nonNLS*/);
}
-
- /**
- * Creates a new type signature with the given amount of array nesting added
- * to the given type signature.
- *
- * @param typeSignature the type signature
- * @param arrayCount the desired number of levels of array nesting
- * @return the encoded array type signature
- */
- public static String createArraySignature(
- String typeSignature,
- int arrayCount) {
- if (arrayCount == 0)
- return typeSignature;
- StringBuffer sb = new StringBuffer(typeSignature.length() + arrayCount);
- for (int i = 0; i < arrayCount; ++i) {
- sb.append(C_ARRAY);
- }
- sb.append(typeSignature);
- return sb.toString();
+ return sb.toString();
+}
+/**
+ * Creates a new type signature with the given amount of array nesting added
+ * to the given type signature.
+ *
+ * @param typeSignature the type signature
+ * @param arrayCount the desired number of levels of array nesting
+ * @return the encoded array type signature
+ */
+public static String createArraySignature(String typeSignature, int arrayCount) {
+ if (arrayCount == 0) return typeSignature;
+ StringBuffer sb = new StringBuffer(typeSignature.length() + arrayCount);
+ for (int i = 0; i < arrayCount; ++i) {
+ sb.append(C_ARRAY);
}
-
- /**
- * Creates a method signature from the given parameter and return type
- * signatures.
- *
- * @param parameterTypes the list of parameter type signatures
- * @param returnType the return type signature
- * @return the encoded method signature
- */
- public static String createMethodSignature(
- String[] parameterTypes,
- String returnType) {
- StringBuffer sb = new StringBuffer();
- sb.append(C_PARAM_START);
- for (int i = 0; i < parameterTypes.length; ++i) {
- sb.append(parameterTypes[i]);
- }
- sb.append(C_PARAM_END);
- sb.append(returnType);
- return sb.toString();
+ sb.append(typeSignature);
+ return sb.toString();
+}
+/**
+ * Creates a method signature from the given parameter and return type
+ * signatures.
+ *
+ * @param parameterTypes the list of parameter type signatures
+ * @param returnType the return type signature
+ * @return the encoded method signature
+ */
+public static String createMethodSignature(String[] parameterTypes, String returnType) {
+ StringBuffer sb = new StringBuffer();
+ sb.append(C_PARAM_START);
+ for (int i = 0; i < parameterTypes.length; ++i) {
+ sb.append(parameterTypes[i]);
}
-
- /**
- * Creates a new type signature from the given type name encoded as a character
- * array. This method is equivalent to
- * <code>createTypeSignature(new String(typeName),isResolved)</code>, although
- * more efficient for callers with character arrays rather than strings.
- *
- * @param typeName the possibly qualified type name
- * @param isResolved <code>true</code> if the type name is to be considered
- * resolved (for example, a type name from a binary class file), and
- * <code>false</code> if the type name is to be considered unresolved
- * (for example, a type name found in source code)
- * @return the encoded type signature
- * @see #createTypeSignature(java.lang.String,boolean)
- */
- public static String createTypeSignature(char[] typeName, boolean isResolved) {
- int len = typeName.length;
- if (typeName[len - 1] != ']') {
- switch (len) {
- case 3 :
- if (typeName[0] == 'i' && typeName[1] == 'n' && typeName[2] == 't')
- return SIG_INT;
- break;
- case 4 :
- if (typeName[0] == 'v'
- && typeName[1] == 'o'
- && typeName[2] == 'i'
- && typeName[3] == 'd')
- return SIG_VOID;
- case 6 :
- if (typeName[0] == 'S'
- && typeName[1] == 't'
- && typeName[2] == 'r'
- && typeName[3] == 'i'
- && typeName[4] == 'n'
- && typeName[5] == 'g')
- if (!isResolved)
- return "QString;";
+ sb.append(C_PARAM_END);
+ sb.append(returnType);
+ return sb.toString();
+}
+/**
+ * Creates a new type signature from the given type name encoded as a character
+ * array. This method is equivalent to
+ * <code>createTypeSignature(new String(typeName),isResolved)</code>, although
+ * more efficient for callers with character arrays rather than strings.
+ *
+ * @param typeName the possibly qualified type name
+ * @param isResolved <code>true</code> if the type name is to be considered
+ * resolved (for example, a type name from a binary class file), and
+ * <code>false</code> if the type name is to be considered unresolved
+ * (for example, a type name found in source code)
+ * @return the encoded type signature
+ * @see #createTypeSignature(java.lang.String,boolean)
+ */
+public static String createTypeSignature(char[] typeName, boolean isResolved) {
+ int len = typeName.length;
+ if (typeName[len - 1] != ']') {
+ switch (len) {
+ case 3 :
+ if (typeName[0] == 'i' && typeName[1] == 'n' && typeName[2] == 't')
+ return SIG_INT;
+ break;
+ case 4 :
+ if (typeName[0] == 'v' && typeName[1] == 'o' && typeName[2] == 'i' && typeName[3] == 'd')
+ return SIG_VOID;
+ case 6 :
+ if (typeName[0] == 'S' && typeName[1] == 't' && typeName[2] == 'r' && typeName[3] == 'i' && typeName[4] == 'n' && typeName[5] == 'g')
+ if (!isResolved) return "QString;"/*nonNLS*/;
break;
- case 7 :
- if (typeName[0] == 'b'
- && typeName[1] == 'o'
- && typeName[2] == 'o'
- && typeName[3] == 'l'
- && typeName[4] == 'e'
- && typeName[5] == 'a'
- && typeName[6] == 'n')
- return SIG_BOOLEAN;
- }
+ case 7 :
+ if (typeName[0] == 'b' && typeName[1] == 'o' && typeName[2] == 'o' && typeName[3] == 'l' && typeName[4] == 'e' && typeName[5] == 'a' && typeName[6] == 'n')
+ return SIG_BOOLEAN;
}
- return createTypeSignature(new String(typeName), isResolved);
}
-
- /**
- * Creates a new type signature from the given type name.
- * <p>
- * For example:
- * <pre>
- * <code>
- * createTypeSignature("int", hucairz) -> "I"
- * createTypeSignature("java.lang.String", true) -> "Ljava.lang.String;"
- * createTypeSignature("String", false) -> "QString;"
- * createTypeSignature("java.lang.String", false) -> "Qjava.lang.String;"
- * createTypeSignature("int []", false) -> "[I"
- * </code>
- * </pre>
- * </p>
- *
- * @param typeName the possibly qualified type name
- * @param isResolved <code>true</code> if the type name is to be considered
- * resolved (for example, a type name from a binary class file), and
- * <code>false</code> if the type name is to be considered unresolved
- * (for example, a type name found in source code)
- * @return the encoded type signature
- */
- public static String createTypeSignature(String typeName, boolean isResolved) {
- try {
- Scanner scanner = new Scanner();
- scanner.setSourceBuffer(typeName.toCharArray());
- int token = scanner.getNextToken();
- StringBuffer sig = new StringBuffer();
- int arrayCount = 0;
- boolean primitive = true;
- switch (token) {
- case TerminalSymbols.TokenNameIdentifier :
- sig.append(scanner.getCurrentIdentifierSource());
- primitive = false;
- break;
- case TerminalSymbols.TokenNameboolean :
- sig.append(Signature.SIG_BOOLEAN);
- break;
- case TerminalSymbols.TokenNamebyte :
- sig.append(Signature.SIG_BYTE);
- break;
- case TerminalSymbols.TokenNamechar :
- sig.append(Signature.SIG_CHAR);
- break;
- case TerminalSymbols.TokenNamedouble :
- sig.append(Signature.SIG_DOUBLE);
- break;
- case TerminalSymbols.TokenNamefloat :
- sig.append(Signature.SIG_FLOAT);
- break;
- case TerminalSymbols.TokenNameint :
- sig.append(Signature.SIG_INT);
- break;
- case TerminalSymbols.TokenNamelong :
- sig.append(Signature.SIG_LONG);
- break;
- case TerminalSymbols.TokenNameshort :
- sig.append(Signature.SIG_SHORT);
- break;
- case TerminalSymbols.TokenNamevoid :
- sig.append(Signature.SIG_VOID);
- break;
- default :
- throw new IllegalArgumentException();
- }
+ return createTypeSignature(new String(typeName), isResolved);
+}
+/**
+ * Creates a new type signature from the given type name.
+ * <p>
+ * For example:
+ * <pre>
+ * <code>
+ * createTypeSignature("int", hucairz) -> "I"
+ * createTypeSignature("java.lang.String", true) -> "Ljava.lang.String;"
+ * createTypeSignature("String", false) -> "QString;"
+ * createTypeSignature("java.lang.String", false) -> "Qjava.lang.String;"
+ * createTypeSignature("int []", false) -> "[I"
+ * </code>
+ * </pre>
+ * </p>
+ *
+ * @param typeName the possibly qualified type name
+ * @param isResolved <code>true</code> if the type name is to be considered
+ * resolved (for example, a type name from a binary class file), and
+ * <code>false</code> if the type name is to be considered unresolved
+ * (for example, a type name found in source code)
+ * @return the encoded type signature
+ */
+public static String createTypeSignature(String typeName, boolean isResolved) {
+ try {
+ Scanner scanner = new Scanner();
+ scanner.setSourceBuffer(typeName.toCharArray());
+ int token = scanner.getNextToken();
+ StringBuffer sig = new StringBuffer();
+ int arrayCount = 0;
+ boolean primitive = true;
+ switch (token) {
+ case TerminalSymbols.TokenNameIdentifier :
+ sig.append(scanner.getCurrentIdentifierSource());
+ primitive = false;
+ break;
+ case TerminalSymbols.TokenNameboolean :
+ sig.append(Signature.SIG_BOOLEAN);
+ break;
+ case TerminalSymbols.TokenNamebyte :
+ sig.append(Signature.SIG_BYTE);
+ break;
+ case TerminalSymbols.TokenNamechar :
+ sig.append(Signature.SIG_CHAR);
+ break;
+ case TerminalSymbols.TokenNamedouble :
+ sig.append(Signature.SIG_DOUBLE);
+ break;
+ case TerminalSymbols.TokenNamefloat :
+ sig.append(Signature.SIG_FLOAT);
+ break;
+ case TerminalSymbols.TokenNameint :
+ sig.append(Signature.SIG_INT);
+ break;
+ case TerminalSymbols.TokenNamelong :
+ sig.append(Signature.SIG_LONG);
+ break;
+ case TerminalSymbols.TokenNameshort :
+ sig.append(Signature.SIG_SHORT);
+ break;
+ case TerminalSymbols.TokenNamevoid :
+ sig.append(Signature.SIG_VOID);
+ break;
+ default :
+ throw new IllegalArgumentException();
+ }
+ token = scanner.getNextToken();
+ while (!primitive && token == TerminalSymbols.TokenNameDOT) {
+ sig.append(scanner.getCurrentIdentifierSource());
token = scanner.getNextToken();
- while (!primitive && token == TerminalSymbols.TokenNameDOT) {
+ if (token == TerminalSymbols.TokenNameIdentifier) {
sig.append(scanner.getCurrentIdentifierSource());
token = scanner.getNextToken();
- if (token == TerminalSymbols.TokenNameIdentifier) {
- sig.append(scanner.getCurrentIdentifierSource());
- token = scanner.getNextToken();
- } else {
- throw new IllegalArgumentException();
- }
- }
- while (token == TerminalSymbols.TokenNameLBRACKET) {
- token = scanner.getNextToken();
- if (token != TerminalSymbols.TokenNameRBRACKET)
- throw new IllegalArgumentException();
- arrayCount++;
- token = scanner.getNextToken();
- }
- if (token != TerminalSymbols.TokenNameEOF)
- throw new IllegalArgumentException();
- if (!primitive) {
- sig.insert(0, isResolved ? C_RESOLVED : C_UNRESOLVED);
- }
- if (arrayCount == 0) {
- if (primitive)
- return sig.toString();
} else {
- char[] brackets = new char[arrayCount];
- while (arrayCount-- != 0) {
- brackets[arrayCount] = C_ARRAY;
- }
- sig.insert(0, brackets);
- }
- if (!primitive) {
- sig.append(C_NAME_END);
- }
- return sig.toString();
- } catch (InvalidInputException e) {
- throw new IllegalArgumentException();
- }
- }
-
- /**
- * Returns the array count (array nesting depth) of the given type signature.
- *
- * @param typeSignature the type signature
- * @return the array nesting depth, or 0 if not an array
- * @exception IllegalArgumentException if the signature is not syntactically
- * correct
- */
- public static int getArrayCount(String typeSignature)
- throws IllegalArgumentException {
- try {
- int count = 0;
- while (typeSignature.charAt(count) == C_ARRAY) {
- ++count;
- }
- return count;
- } catch (StringIndexOutOfBoundsException e) {
- throw new IllegalArgumentException();
- }
- }
-
- /**
- * Returns the type signature without any array nesting.
- * <p>
- * For example:
- * <pre>
- * <code>
- * getElementType("[[I") --> "I".
- * </code>
- * </pre>
- * </p>
- *
- * @param typeSignature the type signature
- * @return the type signature without arrays
- * @exception IllegalArgumentException if the signature is not syntactically
- * correct
- */
- public static String getElementType(String typeSignature)
- throws IllegalArgumentException {
- try {
- int count = 0;
- while (typeSignature.charAt(count) == C_ARRAY) {
- ++count;
+ throw new IllegalArgumentException();
}
- return typeSignature.substring(count);
- } catch (StringIndexOutOfBoundsException e) {
- throw new IllegalArgumentException();
}
- }
-
- /**
- * Returns the number of parameter types in the given method signature.
- *
- * @param methodSignature the method signature
- * @return the number of parameters
- * @exception IllegalArgumentException if the signature is not syntactically
- * correct
- */
- public static int getParameterCount(String methodSignature)
- throws IllegalArgumentException {
- try {
- int count = 0;
- int i = methodSignature.indexOf(C_PARAM_START) + 1;
- if (i == 0)
+ while (token == TerminalSymbols.TokenNameLBRACKET) {
+ token = scanner.getNextToken();
+ if (token != TerminalSymbols.TokenNameRBRACKET)
throw new IllegalArgumentException();
- int start = i;
- for (;;) {
- char c = methodSignature.charAt(i++);
- switch (c) {
- case C_ARRAY :
- break;
- case C_BOOLEAN :
- case C_BYTE :
- case C_CHAR :
- case C_DOUBLE :
- case C_FLOAT :
- case C_INT :
- case C_LONG :
- case C_SHORT :
- case C_VOID :
- ++count;
- break;
- case C_RESOLVED :
- case C_UNRESOLVED :
- i = methodSignature.indexOf(C_SEMICOLON, i) + 1;
- if (i == 0)
- throw new IllegalArgumentException();
- ++count;
- break;
- case C_PARAM_END :
- return count;
- default :
- throw new IllegalArgumentException();
- }
- }
- } catch (StringIndexOutOfBoundsException e) {
- throw new IllegalArgumentException();
+ arrayCount++;
+ token = scanner.getNextToken();
}
- }
-
- /**
- * Extracts the parameter type signatures from the given method signature.
- *
- * @param methodSignature the method signature
- * @return the list of parameter type signatures
- * @exception IllegalArgumentException if the signature is syntactically
- * incorrect
- */
- public static String[] getParameterTypes(String methodSignature)
- throws IllegalArgumentException {
- try {
- int count = getParameterCount(methodSignature);
- String[] result = new String[count];
- if (count == 0)
- return result;
- int i = methodSignature.indexOf(C_PARAM_START) + 1;
- count = 0;
- int start = i;
- for (;;) {
- char c = methodSignature.charAt(i++);
- switch (c) {
- case C_ARRAY :
- // array depth is i - start;
- break;
- case C_BOOLEAN :
- case C_BYTE :
- case C_CHAR :
- case C_DOUBLE :
- case C_FLOAT :
- case C_INT :
- case C_LONG :
- case C_SHORT :
- case C_VOID :
- // common case of base types
- if (i - start == 1) {
- switch (c) {
- case C_BOOLEAN :
- result[count++] = SIG_BOOLEAN;
- break;
- case C_BYTE :
- result[count++] = SIG_BYTE;
- break;
- case C_CHAR :
- result[count++] = SIG_CHAR;
- break;
- case C_DOUBLE :
- result[count++] = SIG_DOUBLE;
- break;
- case C_FLOAT :
- result[count++] = SIG_FLOAT;
- break;
- case C_INT :
- result[count++] = SIG_INT;
- break;
- case C_LONG :
- result[count++] = SIG_LONG;
- break;
- case C_SHORT :
- result[count++] = SIG_SHORT;
- break;
- case C_VOID :
- result[count++] = SIG_VOID;
- break;
- }
- } else {
- result[count++] = methodSignature.substring(start, i);
- }
- start = i;
- break;
- case C_RESOLVED :
- case C_UNRESOLVED :
- i = methodSignature.indexOf(C_SEMICOLON, i) + 1;
- if (i == 0)
- throw new IllegalArgumentException();
- result[count++] = methodSignature.substring(start, i);
- start = i;
- break;
- case C_PARAM_END :
- return result;
- default :
- throw new IllegalArgumentException();
- }
- }
- } catch (StringIndexOutOfBoundsException e) {
+ if (token != TerminalSymbols.TokenNameEOF)
throw new IllegalArgumentException();
+ if (!primitive) {
+ sig.insert(0, isResolved ? C_RESOLVED : C_UNRESOLVED);
}
- }
-
- /**
- * Returns a string containing all but the last segment of the given
- * dot-separated qualified name. Returns the empty string if it is not qualified.
- * <p>
- * For example:
- * <pre>
- * <code>
- * getQualifier("java.lang.Object") -> "java.lang"
- * getQualifier("Outer.Inner") -> "Outer"
- * </code>
- * </pre>
- * </p>
- *
- * @param name the name
- * @return the qualifier prefix, or the empty string if the name contains no
- * dots
- */
- public static String getQualifier(String name) {
- int lastDot = name.lastIndexOf(C_DOT);
- if (lastDot == -1) {
- return "";
+ if (arrayCount == 0) {
+ if (primitive)
+ return sig.toString();
+ } else {
+ char[] brackets = new char[arrayCount];
+ while (arrayCount-- != 0) {
+ brackets[arrayCount] = C_ARRAY;
+ }
+ sig.insert(0, brackets);
}
- return name.substring(0, lastDot);
- }
-
- /**
- * Extracts the return type from the given method signature.
- *
- * @param methodSignature the method signature
- * @return the type signature of the return type
- * @exception IllegalArgumentException if the signature is syntactically
- * incorrect
- */
- public static String getReturnType(String methodSignature)
- throws IllegalArgumentException {
- int i = methodSignature.lastIndexOf(C_PARAM_END);
- if (i == -1) {
- throw new IllegalArgumentException();
+ if (!primitive) {
+ sig.append(C_NAME_END);
}
- return methodSignature.substring(i + 1);
+ return sig.toString();
+ } catch (InvalidInputException e) {
+ throw new IllegalArgumentException();
}
-
- /**
- * Returns the last segment of the given dot-separated qualified name.
- * Returns the given name if it is not qualified.
- * <p>
- * For example:
- * <pre>
- * <code>
- * getSimpleName("java.lang.Object") -> "Object"
- * </code>
- * </pre>
- * </p>
- *
- * @param name the name
- * @return the last segment of the qualified name
- */
- public static String getSimpleName(String name) {
- int lastDot = name.lastIndexOf(C_DOT);
- if (lastDot == -1) {
- return name;
+}
+/**
+ * Returns the array count (array nesting depth) of the given type signature.
+ *
+ * @param typeSignature the type signature
+ * @return the array nesting depth, or 0 if not an array
+ * @exception IllegalArgumentException if the signature is not syntactically
+ * correct
+ */
+public static int getArrayCount(String typeSignature) throws IllegalArgumentException {
+ try {
+ int count = 0;
+ while (typeSignature.charAt(count) == C_ARRAY) {
+ ++count;
}
- return name.substring(lastDot + 1);
+ return count;
+ } catch (StringIndexOutOfBoundsException e) {
+ throw new IllegalArgumentException();
}
-
- /**
- * Returns all segments of the given dot-separated qualified name.
- * Returns an array with only the given name if it is not qualified.
- * Returns an empty array if the name is empty.
- * <p>
- * For example:
- * <pre>
- * <code>
- * getSimpleNames("java.lang.Object") -> {"java", "lang", "Object"}
- * getSimpleNames("Object") -> {"Object"}
- * getSimpleNames("") -> {}
- * </code>
- * </pre>
- *
- * @param name the name
- * @return the list of simple names, possibly empty
- */
- public static String[] getSimpleNames(String name) {
- if (name.length() == 0) {
- return new String[0];
- }
- int dot = name.indexOf(C_DOT);
- if (dot == -1) {
- return new String[] { name };
- }
- int n = 1;
- while ((dot = name.indexOf(C_DOT, dot + 1)) != -1) {
- ++n;
- }
- String[] result = new String[n + 1];
- int segStart = 0;
- for (int i = 0; i < n; ++i) {
- dot = name.indexOf(C_DOT, segStart);
- result[i] = name.substring(segStart, dot);
- segStart = dot + 1;
+}
+/**
+ * Returns the type signature without any array nesting.
+ * <p>
+ * For example:
+ * <pre>
+ * <code>
+ * getElementType("[[I") --> "I".
+ * </code>
+ * </pre>
+ * </p>
+ *
+ * @param typeSignature the type signature
+ * @return the type signature without arrays
+ * @exception IllegalArgumentException if the signature is not syntactically
+ * correct
+ */
+public static String getElementType(String typeSignature) throws IllegalArgumentException {
+ try {
+ int count = 0;
+ while (typeSignature.charAt(count) == C_ARRAY) {
+ ++count;
}
- result[n] = name.substring(segStart);
- return result;
+ return typeSignature.substring(count);
+ } catch (StringIndexOutOfBoundsException e) {
+ throw new IllegalArgumentException();
}
-
- /**
- * Converts the given array of qualified name segments to a qualified name.
- * <p>
- * For example:
- * <pre>
- * <code>
- * toQualifiedName(new String[] {"java", "lang", "Object"}) -> "java.lang.Object"
- * toQualifiedName(new String[] {"Object"}) -> "Object"
- * toQualifiedName(new String[0]) -> ""
- * </code>
- * </pre>
- * </p>
- *
- * @param segments the list of name segments, possibly empty
- * @return the dot-separated qualified name, or the empty string
- */
- public static String toQualifiedName(String[] segments) {
- if (segments.length == 0) {
- return "";
- }
- if (segments.length == 1) {
- return segments[0];
- }
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < segments.length; ++i) {
- if (i != 0)
- sb.append(C_DOT);
- sb.append(segments[i]);
+}
+/**
+ * Returns the number of parameter types in the given method signature.
+ *
+ * @param methodSignature the method signature
+ * @return the number of parameters
+ * @exception IllegalArgumentException if the signature is not syntactically
+ * correct
+ */
+public static int getParameterCount(String methodSignature) throws IllegalArgumentException {
+ try {
+ int count = 0;
+ int i = methodSignature.indexOf(C_PARAM_START) + 1;
+ if (i == 0)
+ throw new IllegalArgumentException();
+ int start = i;
+ for (;;) {
+ char c = methodSignature.charAt(i++);
+ switch (c) {
+ case C_ARRAY :
+ break;
+ case C_BOOLEAN :
+ case C_BYTE :
+ case C_CHAR :
+ case C_DOUBLE :
+ case C_FLOAT :
+ case C_INT :
+ case C_LONG :
+ case C_SHORT :
+ case C_VOID :
+ ++count;
+ break;
+ case C_RESOLVED :
+ case C_UNRESOLVED :
+ i = methodSignature.indexOf(C_SEMICOLON, i) + 1;
+ if (i == 0)
+ throw new IllegalArgumentException();
+ ++count;
+ break;
+ case C_PARAM_END :
+ return count;
+ default :
+ throw new IllegalArgumentException();
+ }
}
- return sb.toString();
+ } catch (StringIndexOutOfBoundsException e) {
+ throw new IllegalArgumentException();
}
-
- /**
- * Converts the given type signature to a readable string.
- * <p>
- * For example:
- * <pre>
- * <code>
- * toString("[Ljava.lang.String;") -> "java.lang.String[]"
- * toString("I") -> "int"
- * </code>
- * </pre>
- * </p>
- * <p>
- * Note: This method assumes that a type signature containing a <code>'$'</code>
- * is an inner type signature. While this is correct in most cases, someone could
- * define a non-inner type name containing a <code>'$'</code>. Handling this
- * correctly in all cases would have required resolving the signature, which
- * generally not feasible.
- * </p>
- *
- * @param signature the type signature
- * @return the string representation of the type
- * @exception IllegalArgumentException if the signature is not syntactically
- * correct
- */
- public static String toString(String signature)
- throws IllegalArgumentException {
- try {
- if (signature.charAt(0) == C_PARAM_START) {
- return toString(signature, "", null, true, true);
- }
- int arrayCount = getArrayCount(signature);
- switch (signature.charAt(arrayCount)) {
+}
+/**
+ * Extracts the parameter type signatures from the given method signature.
+ *
+ * @param methodSignature the method signature
+ * @return the list of parameter type signatures
+ * @exception IllegalArgumentException if the signature is syntactically
+ * incorrect
+ */
+public static String[] getParameterTypes(String methodSignature) throws IllegalArgumentException {
+ try {
+ int count = getParameterCount(methodSignature);
+ String[] result = new String[count];
+ if (count == 0)
+ return result;
+ int i = methodSignature.indexOf(C_PARAM_START) + 1;
+ count = 0;
+ int start = i;
+ for (;;) {
+ char c = methodSignature.charAt(i++);
+ switch (c) {
+ case C_ARRAY :
+ // array depth is i - start;
+ break;
case C_BOOLEAN :
- return arrayIfy("boolean", arrayCount);
case C_BYTE :
- return arrayIfy("byte", arrayCount);
case C_CHAR :
- return arrayIfy("char", arrayCount);
case C_DOUBLE :
- return arrayIfy("double", arrayCount);
case C_FLOAT :
- return arrayIfy("float", arrayCount);
case C_INT :
- return arrayIfy("int", arrayCount);
case C_LONG :
- return arrayIfy("long", arrayCount);
case C_SHORT :
- return arrayIfy("short", arrayCount);
case C_VOID :
- return arrayIfy("void", arrayCount);
+ // common case of base types
+ if (i - start == 1) {
+ switch (c) {
+ case C_BOOLEAN :
+ result[count++] = SIG_BOOLEAN;
+ break;
+ case C_BYTE :
+ result[count++] = SIG_BYTE;
+ break;
+ case C_CHAR :
+ result[count++] = SIG_CHAR;
+ break;
+ case C_DOUBLE :
+ result[count++] = SIG_DOUBLE;
+ break;
+ case C_FLOAT :
+ result[count++] = SIG_FLOAT;
+ break;
+ case C_INT :
+ result[count++] = SIG_INT;
+ break;
+ case C_LONG :
+ result[count++] = SIG_LONG;
+ break;
+ case C_SHORT :
+ result[count++] = SIG_SHORT;
+ break;
+ case C_VOID :
+ result[count++] = SIG_VOID;
+ break;
+ }
+ } else {
+ result[count++] = methodSignature.substring(start, i);
+ }
+ start = i;
+ break;
case C_RESOLVED :
case C_UNRESOLVED :
- int semi = signature.indexOf(C_SEMICOLON, arrayCount + 1);
- if (semi == -1)
+ i = methodSignature.indexOf(C_SEMICOLON, i) + 1;
+ if (i == 0)
throw new IllegalArgumentException();
-
- /**
- * Converts '$' separated type signatures into '.' separated type signature.
- * NOTE: This assumes that the type signature is an inner type signature.
- * This is true in most cases, but someone can define a non-inner type
- * name containing a '$'. However to tell the difference, we would have
- * to resolve the signature, which cannot be done at this point.
- */
- String qualifiedTypeName =
- signature.substring(arrayCount + 1, semi).replace(C_DOLLAR, C_DOT);
-
- return arrayIfy(qualifiedTypeName, arrayCount);
+ result[count++] = methodSignature.substring(start, i);
+ start = i;
+ break;
+ case C_PARAM_END:
+ return result;
default :
throw new IllegalArgumentException();
}
- } catch (StringIndexOutOfBoundsException e) {
- throw new IllegalArgumentException();
}
+ } catch (StringIndexOutOfBoundsException e) {
+ throw new IllegalArgumentException();
}
-
- /**
- * Converts the given method signature to a readable string.
- * <p>
- * For example:
- * <pre>
- * <code>
- * toString("([Ljava.lang.String;)V", "main", new String[] {"args"}, false, true) -> "void main(String[] args)"
- * </code>
- * </pre>
- * </p>
- *
- * @param methodSignature the method signature to convert
- * @param methodName the name of the method to insert in the result, or
- * <code>null</code> if no method name is to be included
- * @param parameterNames the parameter names to insert in the result, or
- * <code>null</code> if no parameter names are to be included; if supplied,
- * the number of parameter names must match that of the method signature
- * @param fullyQualifyTypeNames <code>true</code> if type names should be fully
- * qualified, and <code>false</code> to use only simple names
- * @param includeReturnType <code>true</code> if the return type is to be
- * included
- * @return the string representation of the method signature
- */
- public static String toString(
- String methodSignature,
- String methodName,
- String[] parameterNames,
- boolean fullyQualifyTypeNames,
- boolean includeReturnType) {
- StringBuffer sb = new StringBuffer();
- String[] paramTypes = getParameterTypes(methodSignature);
- if (includeReturnType) {
- String returnType = getReturnType(methodSignature);
- if (returnType.length() != 0) {
- sb.append(toString(returnType));
- sb.append(' ');
- }
+}
+/**
+ * Returns a string containing all but the last segment of the given
+ * dot-separated qualified name. Returns the empty string if it is not qualified.
+ * <p>
+ * For example:
+ * <pre>
+ * <code>
+ * getQualifier("java.lang.Object") -> "java.lang"
+ * getQualifier("Outer.Inner") -> "Outer"
+ * </code>
+ * </pre>
+ * </p>
+ *
+ * @param name the name
+ * @return the qualifier prefix, or the empty string if the name contains no
+ * dots
+ */
+public static String getQualifier(String name) {
+ int lastDot = name.lastIndexOf(C_DOT);
+ if (lastDot == -1) {
+ return ""/*nonNLS*/;
+ }
+ return name.substring(0, lastDot);
+}
+/**
+ * Extracts the return type from the given method signature.
+ *
+ * @param methodSignature the method signature
+ * @return the type signature of the return type
+ * @exception IllegalArgumentException if the signature is syntactically
+ * incorrect
+ */
+public static String getReturnType(String methodSignature) throws IllegalArgumentException {
+ int i = methodSignature.lastIndexOf(C_PARAM_END);
+ if (i == -1) {
+ throw new IllegalArgumentException();
+ }
+ return methodSignature.substring(i + 1);
+}
+/**
+ * Returns the last segment of the given dot-separated qualified name.
+ * Returns the given name if it is not qualified.
+ * <p>
+ * For example:
+ * <pre>
+ * <code>
+ * getSimpleName("java.lang.Object") -> "Object"
+ * </code>
+ * </pre>
+ * </p>
+ *
+ * @param name the name
+ * @return the last segment of the qualified name
+ */
+public static String getSimpleName(String name) {
+ int lastDot = name.lastIndexOf(C_DOT);
+ if (lastDot == -1) {
+ return name;
+ }
+ return name.substring(lastDot + 1);
+}
+/**
+ * Returns all segments of the given dot-separated qualified name.
+ * Returns an array with only the given name if it is not qualified.
+ * Returns an empty array if the name is empty.
+ * <p>
+ * For example:
+ * <pre>
+ * <code>
+ * getSimpleNames("java.lang.Object") -> {"java", "lang", "Object"}
+ * getSimpleNames("Object") -> {"Object"}
+ * getSimpleNames("") -> {}
+ * </code>
+ * </pre>
+ *
+ * @param name the name
+ * @return the list of simple names, possibly empty
+ */
+public static String[] getSimpleNames(String name) {
+ if (name.length() == 0) {
+ return new String[0];
+ }
+ int dot = name.indexOf(C_DOT);
+ if (dot == -1) {
+ return new String[] {name};
+ }
+ int n = 1;
+ while ((dot = name.indexOf(C_DOT, dot + 1)) != -1) {
+ ++n;
+ }
+ String[] result = new String[n + 1];
+ int segStart = 0;
+ for (int i = 0; i < n; ++i) {
+ dot = name.indexOf(C_DOT, segStart);
+ result[i] = name.substring(segStart, dot);
+ segStart = dot + 1;
+ }
+ result[n] = name.substring(segStart);
+ return result;
+}
+/**
+ * Converts the given array of qualified name segments to a qualified name.
+ * <p>
+ * For example:
+ * <pre>
+ * <code>
+ * toQualifiedName(new String[] {"java", "lang", "Object"}) -> "java.lang.Object"
+ * toQualifiedName(new String[] {"Object"}) -> "Object"
+ * toQualifiedName(new String[0]) -> ""
+ * </code>
+ * </pre>
+ * </p>
+ *
+ * @param segments the list of name segments, possibly empty
+ * @return the dot-separated qualified name, or the empty string
+ */
+public static String toQualifiedName(String[] segments) {
+ if (segments.length == 0) {
+ return ""/*nonNLS*/;
+ }
+ if (segments.length == 1) {
+ return segments[0];
+ }
+ StringBuffer sb = new StringBuffer();
+ for (int i = 0; i < segments.length; ++i) {
+ if (i != 0)
+ sb.append(C_DOT);
+ sb.append(segments[i]);
+ }
+ return sb.toString();
+}
+/**
+ * Converts the given type signature to a readable string.
+ * <p>
+ * For example:
+ * <pre>
+ * <code>
+ * toString("[Ljava.lang.String;") -> "java.lang.String[]"
+ * toString("I") -> "int"
+ * </code>
+ * </pre>
+ * </p>
+ * <p>
+ * Note: This method assumes that a type signature containing a <code>'$'</code>
+ * is an inner type signature. While this is correct in most cases, someone could
+ * define a non-inner type name containing a <code>'$'</code>. Handling this
+ * correctly in all cases would have required resolving the signature, which
+ * generally not feasible.
+ * </p>
+ *
+ * @param signature the type signature
+ * @return the string representation of the type
+ * @exception IllegalArgumentException if the signature is not syntactically
+ * correct
+ */
+public static String toString(String signature) throws IllegalArgumentException {
+ try {
+ if (signature.charAt(0) == C_PARAM_START) {
+ return toString(signature, ""/*nonNLS*/, null, true, true);
}
- if (methodName != null)
- sb.append(methodName);
- sb.append(C_PARAM_START);
- for (int i = 0; i < paramTypes.length; ++i) {
- if (i != 0)
- sb.append(", ");
- String readableParamType = toString(paramTypes[i]);
- if (!fullyQualifyTypeNames) {
- int lastDot = readableParamType.lastIndexOf(C_DOT);
- if (lastDot != -1) {
- readableParamType = readableParamType.substring(lastDot + 1);
- }
- }
- sb.append(readableParamType);
- if (parameterNames != null) {
- sb.append(' ');
- sb.append(parameterNames[i]);
+ int arrayCount = getArrayCount(signature);
+ switch (signature.charAt(arrayCount)) {
+ case C_BOOLEAN :
+ return arrayIfy("boolean"/*nonNLS*/, arrayCount);
+ case C_BYTE :
+ return arrayIfy("byte"/*nonNLS*/, arrayCount);
+ case C_CHAR :
+ return arrayIfy("char"/*nonNLS*/, arrayCount);
+ case C_DOUBLE :
+ return arrayIfy("double"/*nonNLS*/, arrayCount);
+ case C_FLOAT :
+ return arrayIfy("float"/*nonNLS*/, arrayCount);
+ case C_INT :
+ return arrayIfy("int"/*nonNLS*/, arrayCount);
+ case C_LONG :
+ return arrayIfy("long"/*nonNLS*/, arrayCount);
+ case C_SHORT :
+ return arrayIfy("short"/*nonNLS*/, arrayCount);
+ case C_VOID :
+ return arrayIfy("void"/*nonNLS*/, arrayCount);
+ case C_RESOLVED :
+ case C_UNRESOLVED :
+ int semi = signature.indexOf(C_SEMICOLON, arrayCount + 1);
+ if (semi == -1)
+ throw new IllegalArgumentException();
+
+ /**
+ * Converts '$' separated type signatures into '.' separated type signature.
+ * NOTE: This assumes that the type signature is an inner type signature.
+ * This is true in most cases, but someone can define a non-inner type
+ * name containing a '$'. However to tell the difference, we would have
+ * to resolve the signature, which cannot be done at this point.
+ */
+ String qualifiedTypeName = signature.substring(arrayCount+1, semi).replace(C_DOLLAR, C_DOT);
+
+ return arrayIfy(qualifiedTypeName, arrayCount);
+ default :
+ throw new IllegalArgumentException();
+ }
+ } catch (StringIndexOutOfBoundsException e) {
+ throw new IllegalArgumentException();
+ }
+}
+/**
+ * Converts the given method signature to a readable string.
+ * <p>
+ * For example:
+ * <pre>
+ * <code>
+ * toString("([Ljava.lang.String;)V", "main", new String[] {"args"}, false, true) -> "void main(String[] args)"
+ * </code>
+ * </pre>
+ * </p>
+ *
+ * @param methodSignature the method signature to convert
+ * @param methodName the name of the method to insert in the result, or
+ * <code>null</code> if no method name is to be included
+ * @param parameterNames the parameter names to insert in the result, or
+ * <code>null</code> if no parameter names are to be included; if supplied,
+ * the number of parameter names must match that of the method signature
+ * @param fullyQualifyTypeNames <code>true</code> if type names should be fully
+ * qualified, and <code>false</code> to use only simple names
+ * @param includeReturnType <code>true</code> if the return type is to be
+ * included
+ * @return the string representation of the method signature
+ */
+public static String toString(String methodSignature, String methodName, String[] parameterNames, boolean fullyQualifyTypeNames, boolean includeReturnType) {
+ StringBuffer sb = new StringBuffer();
+ String[] paramTypes = getParameterTypes(methodSignature);
+ if (includeReturnType) {
+ String returnType = getReturnType(methodSignature);
+ if (returnType.length() != 0) {
+ sb.append(toString(returnType));
+ sb.append(' ');
+ }
+ }
+ if (methodName != null)
+ sb.append(methodName);
+ sb.append(C_PARAM_START);
+ for (int i = 0; i < paramTypes.length; ++i) {
+ if (i != 0)
+ sb.append(", "/*nonNLS*/);
+ String readableParamType = toString(paramTypes[i]);
+ if (!fullyQualifyTypeNames) {
+ int lastDot = readableParamType.lastIndexOf(C_DOT);
+ if (lastDot != -1) {
+ readableParamType = readableParamType.substring(lastDot + 1);
}
}
- sb.append(C_PARAM_END);
- return sb.toString();
+ sb.append(readableParamType);
+ if (parameterNames != null) {
+ sb.append(' ');
+ sb.append(parameterNames[i]);
+ }
}
-
+ sb.append(C_PARAM_END);
+ return sb.toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/eval/ICodeSnippetRequestor.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/eval/ICodeSnippetRequestor.java
index 8fb9c58aa1..0ccc88bae8 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/eval/ICodeSnippetRequestor.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/eval/ICodeSnippetRequestor.java
@@ -19,7 +19,7 @@ import org.eclipse.jdt.internal.eval.EvaluationConstants;
* @see IEvaluationContext#evaluateCodeSnippet
*/
public interface ICodeSnippetRequestor {
-
+
/*
* RETRIEVING THE VALUE OF THE CODE SNIPPET AFTER EVALUATION
*/
@@ -28,15 +28,13 @@ public interface ICodeSnippetRequestor {
* The prefix of fields that represent the local variables in a snippet
* class.
*/
- public static final String LOCAL_VAR_PREFIX =
- new String(EvaluationConstants.LOCAL_VAR_PREFIX);
+ public static final String LOCAL_VAR_PREFIX = new String(EvaluationConstants.LOCAL_VAR_PREFIX);
/**
* The name of the field that represent 'this' in a snippet class
* instance.
*/
- public static final String DELEGATE_THIS =
- new String(EvaluationConstants.DELEGATE_THIS);
+ public static final String DELEGATE_THIS = new String(EvaluationConstants.DELEGATE_THIS);
/**
* The name of the instance method in the snippet class that runs the code
@@ -48,21 +46,19 @@ public interface ICodeSnippetRequestor {
* The name of the field (of type <code>java.lang.Object</code>) on the code
* snippet instance that contains the returned value.
*/
- public static final String RESULT_VALUE_FIELD =
- EvaluationConstants.RESULT_VALUE_FIELD;
+ public static final String RESULT_VALUE_FIELD = EvaluationConstants.RESULT_VALUE_FIELD;
/*
* The field of type java.lang.Class on the code snippet instance that contains the type of the returned value.
* The name of the field (of type <code>java.lang.Class</code>) on the code
* snippet instance that contains the runtime type of the returned value.
*/
- public static final String RESULT_TYPE_FIELD =
- EvaluationConstants.RESULT_TYPE_FIELD;
+ public static final String RESULT_TYPE_FIELD = EvaluationConstants.RESULT_TYPE_FIELD;
/*
* REPORTING A PROBLEM OF COMPILATION IN THE CODE SNIPPET
*/
-
+
/**
* Indicates a compilation problem related to a global variable.
* <p>
@@ -102,79 +98,73 @@ public interface ICodeSnippetRequestor {
*
* @see #acceptProblem
*/
- public static final int INTERNAL = 5;
- /**
- * Sends the given class files to the target and loads them. If the given
- * class name is not <code>null</code>, run the code snippet with this class
- * name. Returns whether the code snippet could be deployed. Note it must
- * return <code>true</code> even if running the code snippet threw an exception.
- * <p>
- * The details of sending and loading the class files are left up to
- * implementations.
- * </p>
- * <p>
- * To run a code snippet, an implementation should create a new instance of
- * the given code snippet class and call (directly or using another means) its
- * <code>RUN_METHOD</code>.
- * </p>
- * <p>
- * Also before the call, the implementation should copy the values of the local
- * variables (if any) into the corresponding fields of the code snippet instance.
- * A field name is formed of <code>LOCAL_VAR_PREFIX</code>
- * prepended the name of the local variable. For example, the field name for
- * local variable <code>"myLocal"</code> is <code>"val$myLocal"</code> (assuming the
- * value of <code>LOCAL_VAR_PREFIX</code> is "val$"). In the
- * same way, the implementation should copy the value of the 'this' object into the
- * field called <code>DELEGATE_THIS</code>.
- * </p>
- * <p>
- * After calling the <code>RUN_METHOD</code>, the values of the local
- * variables may have been modified. The implementation must copy the
- * values of the fields back into the local variables.
- * </p>
- * <p>
- * Finally, the overall value returned by the code snippet can be retrieved
- * from the special field <code>RESULT_VALUE_FIELD</code>
- * on the code snippet instance.
- * The <code>Class</code> that is the runtime type of the returned value can be
- * retrieved from the special field <code>RESULT_TYPE_FIELD</code>.
- * </p>
- *
- * @param classFileBytes the list of class file bytes
- * @param classFileCompoundNames the corresponding list of class file type
- * compound names (example of a compound name: {"java", "lang", "Object"})
- * @param codeSnippetClassName name of the actual class to instantiate and run,
- * or <code>null</code> if none
- * @return <code>true</code> if the code snippet was successfully deployed
- */
- public boolean acceptClassFiles(
- byte[][] classFileBytes,
- String[][] classFileCompoundNames,
- String codeSnippetClassName);
- /**
- * Notifies of an evaluation problem.
- * Problems can arise for source of the following kinds:
- * <p>
- * <ul>
- * <li>global variable (<code>VARIABLE</code>) - fragment source is name of
- * variable</li>
- * <li>code snippet (<code>CODE_SNIPPET</code>) - fragment source is code
- * snippet</li>
- * <li>import declaration (<code>IMPORT</code>) - fragment source is
- * import</li>
- * <li>package declaration (<code>PACKAGE</code>) - fragment source is
- * package declaration</li>
- * <li>other (<code>INTERNAL</code>) - no fragment source is involved, internal error occurred.</li>
- * </ul>
- * </p>
- * @param problemMarker the problem marker (cannot be null)
- * @param fragmentSource the fragment source
- * @param fragmentKind the kind of source fragment; one of:
- * <code>VARIABLE</code>, <code>CODE_SNIPPET</code>, <code>IMPORT</code>,
- * <code>PACKAGE</code>, or <code>INTERNAL</code>
- */
- public void acceptProblem(
- IMarker problemMarker,
- String fragmentSource,
- int fragmentKind);
+ public static final int INTERNAL = 5;
+/**
+ * Sends the given class files to the target and loads them. If the given
+ * class name is not <code>null</code>, run the code snippet with this class
+ * name. Returns whether the code snippet could be deployed. Note it must
+ * return <code>true</code> even if running the code snippet threw an exception.
+ * <p>
+ * The details of sending and loading the class files are left up to
+ * implementations.
+ * </p>
+ * <p>
+ * To run a code snippet, an implementation should create a new instance of
+ * the given code snippet class and call (directly or using another means) its
+ * <code>RUN_METHOD</code>.
+ * </p>
+ * <p>
+ * Also before the call, the implementation should copy the values of the local
+ * variables (if any) into the corresponding fields of the code snippet instance.
+ * A field name is formed of <code>LOCAL_VAR_PREFIX</code>
+ * prepended the name of the local variable. For example, the field name for
+ * local variable <code>"myLocal"</code> is <code>"val$myLocal"</code> (assuming the
+ * value of <code>LOCAL_VAR_PREFIX</code> is "val$"). In the
+ * same way, the implementation should copy the value of the 'this' object into the
+ * field called <code>DELEGATE_THIS</code>.
+ * </p>
+ * <p>
+ * After calling the <code>RUN_METHOD</code>, the values of the local
+ * variables may have been modified. The implementation must copy the
+ * values of the fields back into the local variables.
+ * </p>
+ * <p>
+ * Finally, the overall value returned by the code snippet can be retrieved
+ * from the special field <code>RESULT_VALUE_FIELD</code>
+ * on the code snippet instance.
+ * The <code>Class</code> that is the runtime type of the returned value can be
+ * retrieved from the special field <code>RESULT_TYPE_FIELD</code>.
+ * </p>
+ *
+ * @param classFileBytes the list of class file bytes
+ * @param classFileCompoundNames the corresponding list of class file type
+ * compound names (example of a compound name: {"java", "lang", "Object"})
+ * @param codeSnippetClassName name of the actual class to instantiate and run,
+ * or <code>null</code> if none
+ * @return <code>true</code> if the code snippet was successfully deployed
+ */
+public boolean acceptClassFiles(byte[][] classFileBytes, String[][] classFileCompoundNames, String codeSnippetClassName);
+/**
+ * Notifies of an evaluation problem.
+ * Problems can arise for source of the following kinds:
+ * <p>
+ * <ul>
+ * <li>global variable (<code>VARIABLE</code>) - fragment source is name of
+ * variable</li>
+ * <li>code snippet (<code>CODE_SNIPPET</code>) - fragment source is code
+ * snippet</li>
+ * <li>import declaration (<code>IMPORT</code>) - fragment source is
+ * import</li>
+ * <li>package declaration (<code>PACKAGE</code>) - fragment source is
+ * package declaration</li>
+ * <li>other (<code>INTERNAL</code>) - no fragment source is involved, internal error occurred.</li>
+ * </ul>
+ * </p>
+ * @param problemMarker the problem marker (cannot be null)
+ * @param fragmentSource the fragment source
+ * @param fragmentKind the kind of source fragment; one of:
+ * <code>VARIABLE</code>, <code>CODE_SNIPPET</code>, <code>IMPORT</code>,
+ * <code>PACKAGE</code>, or <code>INTERNAL</code>
+ */
+public void acceptProblem(IMarker problemMarker, String fragmentSource, int fragmentKind);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/eval/IEvaluationContext.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/eval/IEvaluationContext.java
index 7ec02189ed..6c8c0634b5 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/eval/IEvaluationContext.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/eval/IEvaluationContext.java
@@ -78,225 +78,207 @@ import org.eclipse.jdt.core.*;
* @see IJavaProject#newEvaluationContext
*/
public interface IEvaluationContext {
- /**
- * Returns the global variables declared in this evaluation context.
- * The variables are maintained in the order they are created in.
- *
- * @return the list of global variables
- */
- public IGlobalVariable[] allVariables();
- /**
- * Performs a code completion at the given position in the given code snippet,
- * reporting results to the given completion requestor.
- * <p>
- * Note that code completion does not involve evaluation.
- * <p>
- *
- * @param codeSnippet the code snippet to complete in
- * @param position the character position in the code snippet to complete at,
- * or -1 indicating the beginning of the snippet
- * @param requestor the code completion requestor capable of accepting all
- * possible types of completions
- * @exception JavaModelException if code completion could not be performed. Reasons include:
- * <ul>
- * <li>The position specified is less than -1 or is greater than the snippet's
- * length (INDEX_OUT_OF_BOUNDS)</li>
- * </ul>
- */
- public void codeComplete(
- String codeSnippet,
- int position,
- ICodeCompletionRequestor requestor)
- throws JavaModelException;
- /**
- * Resolves and returns a collection of Java elements corresponding to the source
- * code at the given positions in the given code snippet.
- * <p>
- * Note that code select does not involve evaluation, and problems are never
- * reported.
- * <p>
- *
- * @param codeSnippet the code snippet to resolve in
- * @param offset the position in the code snippet of the first character
- * of the code to resolve
- * @param length the length of the selected code to resolve
- * @return the (possibly empty) list of selection Java elements
- * @exception JavaModelException if code resolve could not be performed.
- * Reasons include:
- * <ul>
- * <li>The position specified is less than -1 or is greater than the snippet's
- * length (INDEX_OUT_OF_BOUNDS)</li>
- * </ul>
- */
- public IJavaElement[] codeSelect(String codeSnippet, int offset, int length)
- throws JavaModelException;
- /**
- * Deletes the given variable from this evaluation context. Does nothing if
- * the given variable has already been deleted.
- *
- * @param variable the global variable
- */
- public void deleteVariable(IGlobalVariable variable);
- /**
- * Evaluates the given code snippet in the context of a suspended thread.
- * The code snippet is compiled along with this context's package declaration,
- * imports, and global variables. The given requestor's
- * <code>acceptProblem</code> method is called for each compilation problem that
- * is detected. Then the resulting class files are handed to the given
- * requestor's <code>acceptClassFiles</code> method to deploy and run.
- * <p>
- * The requestor is expected to:
- * <ol>
- * <li>send the class files to the target VM,
- * <li>load them (starting with the code snippet class),
- * <li>create a new instance of the code snippet class,
- * <li>run the method <code>run()</code> of the code snippet,
- * <li>retrieve the values of the local variables,
- * <li>retrieve the returned value of the code snippet
- * </ol>
- * </p>
- * <p>
- * This method is long-running; progress and cancelation are provided
- * by the given progress monitor.
- * </p>
- *
- * @param codeSnippet the code snippet
- * @param localVariableTypeNames the dot-separated fully qualified names of the types of the local variables.
- * @param localVariableNames the names of the local variables as they are declared in the user's code.
- * @param localVariableModifiers the modifiers of the local variables (default modifier or final modifier).
- * @param declaringType the type in which the code snippet is evaluated.
- * @param isStatic whether the code snippet is evaluated in a static member of the declaring type.
- * @param isConstructorCall whether the code snippet is evaluated in a constructor of the declaring type.
- * @param requestor the code snippet requestor
- * @param progressMonitor a progress monitor
- * @exception JavaModelException if a runtime problem occurred or if this
- * context's project has no build state
- */
- public void evaluateCodeSnippet(
- String codeSnippet,
- String[] localVariableTypeNames,
- String[] localVariableNames,
- int[] localVariableModifiers,
- IType declaringType,
- boolean isStatic,
- boolean isConstructorCall,
- ICodeSnippetRequestor requestor,
- IProgressMonitor progressMonitor)
- throws JavaModelException;
- /**
- * Evaluates the given code snippet. The code snippet is
- * compiled along with this context's package declaration, imports, and
- * global variables. The given requestor's <code>acceptProblem</code> method
- * is called for each compilation problem that is detected. Then the resulting
- * class files are handed to the given requestor's <code>acceptClassFiles</code>
- * method to deploy and run. The requestor is also responsible for getting the
- * result back.
- * <p>
- * This method is long-running; progress and cancelation are provided
- * by the given progress monitor.
- * </p>
- *
- * @param codeSnippet the code snippet
- * @param requestor the code snipper requestor
- * @param progressMonitor a progress monitor
- * @exception JavaModelException if a runtime problem occurred or if this
- * context's project has no build state
- */
- public void evaluateCodeSnippet(
- String codeSnippet,
- ICodeSnippetRequestor requestor,
- IProgressMonitor progressMonitor)
- throws JavaModelException;
- /**
- * Evaluates the given global variable. During this operation,
- * this context's package declaration, imports, and <it>all</it> its declared
- * variables are verified. The given requestor's <code>acceptProblem</code>
- * method will be called for each problem that is detected.
- * <p>
- * This method is long-running; progress and cancelation are provided
- * by the given progress monitor.
- * </p>
- *
- * @param variable the global variable
- * @param requestor the code snipper requestor
- * @param progressMonitor a progress monitor
- * @exception JavaModelException if a runtime problem occurred or if this
- * context's project has no build state
- */
- public void evaluateVariable(
- IGlobalVariable variable,
- ICodeSnippetRequestor requestor,
- IProgressMonitor progressMonitor)
- throws JavaModelException;
- /**
- * Returns the import declarations for this evaluation context. Returns and empty
- * list if there are no imports (the default if the imports have never been set).
- * The syntax for the import corresponds to a fully qualified type name, or to
- * an on-demand package name as defined by ImportDeclaration (JLS2 7.5). For
- * example, <code>"java.util.Hashtable"</code> or <code>"java.util.*"</code>.
- *
- * @return the list of import names
- */
- public String[] getImports();
- /**
- * Returns the name of the package in which code snippets are to be compiled and
- * run. Returns an empty string for the default package (the default if the
- * package name has never been set). For example, <code>"com.example.myapp"</code>.
- *
- * @return the dot-separated package name, or the empty string indicating the
- * default package
- */
- public String getPackageName();
- /**
- * Returns the Java project this evaluation context was created for.
- *
- * @return the Java project
- */
- public IJavaProject getProject();
- /**
- * Creates a new global variable with the given name, type, and initializer.
- * <p>
- * The <code>typeName</code> and <code>initializer</code> are interpreted in
- * the context of this context's package and import declarations.
- * </p>
- * <p>
- * The syntax for a type name corresponds to Type in Field Declaration (JLS2 8.3).
- * </p>
- *
- * @param typeName the type name
- * @param name the name of the global variable
- * @param initializer the initializer expression, or <code>null</code> if the
- * variable is not initialized
- */
- public IGlobalVariable newVariable(
- String typeName,
- String name,
- String initializer);
- /**
- * Sets the import declarations for this evaluation context. An empty
- * list indicates there are no imports. The syntax for the import corresponds to a
- * fully qualified type name, or to an on-demand package name as defined by
- * ImportDeclaration (JLS2 7.5). For example, <code>"java.util.Hashtable"</code>
- * or <code>"java.util.*"</code>.
- *
- * @param imports the list of import names
- */
- public void setImports(String[] imports);
- /**
- * Sets the dot-separated name of the package in which code snippets are
- * to be compiled and run. For example, <code>"com.example.myapp"</code>.
- *
- * @param packageName the dot-separated package name, or the empty string
- * indicating the default package
- */
- public void setPackageName(String packageName);
- /**
- * Validates this evaluation context's import declarations. The given requestor's
- * <code>acceptProblem</code> method is called for each problem that is detected.
- *
- * @param requestor the code snipper requestor
- * @exception JavaModelException if this context's project has no build state
- */
- public void validateImports(ICodeSnippetRequestor requestor)
- throws JavaModelException;
+/**
+ * Returns the global variables declared in this evaluation context.
+ * The variables are maintained in the order they are created in.
+ *
+ * @return the list of global variables
+ */
+public IGlobalVariable[] allVariables();
+/**
+ * Performs a code completion at the given position in the given code snippet,
+ * reporting results to the given completion requestor.
+ * <p>
+ * Note that code completion does not involve evaluation.
+ * <p>
+ *
+ * @param codeSnippet the code snippet to complete in
+ * @param position the character position in the code snippet to complete at,
+ * or -1 indicating the beginning of the snippet
+ * @param requestor the code completion requestor capable of accepting all
+ * possible types of completions
+ * @exception JavaModelException if code completion could not be performed. Reasons include:
+ * <ul>
+ * <li>The position specified is less than -1 or is greater than the snippet's
+ * length (INDEX_OUT_OF_BOUNDS)</li>
+ * </ul>
+ */
+public void codeComplete(String codeSnippet, int position, ICodeCompletionRequestor requestor) throws JavaModelException;
+/**
+ * Resolves and returns a collection of Java elements corresponding to the source
+ * code at the given positions in the given code snippet.
+ * <p>
+ * Note that code select does not involve evaluation, and problems are never
+ * reported.
+ * <p>
+ *
+ * @param codeSnippet the code snippet to resolve in
+ * @param offset the position in the code snippet of the first character
+ * of the code to resolve
+ * @param length the length of the selected code to resolve
+ * @return the (possibly empty) list of selection Java elements
+ * @exception JavaModelException if code resolve could not be performed.
+ * Reasons include:
+ * <ul>
+ * <li>The position specified is less than -1 or is greater than the snippet's
+ * length (INDEX_OUT_OF_BOUNDS)</li>
+ * </ul>
+ */
+public IJavaElement[] codeSelect(String codeSnippet, int offset, int length) throws JavaModelException;
+/**
+ * Deletes the given variable from this evaluation context. Does nothing if
+ * the given variable has already been deleted.
+ *
+ * @param variable the global variable
+ */
+public void deleteVariable(IGlobalVariable variable);
+/**
+ * Evaluates the given code snippet in the context of a suspended thread.
+ * The code snippet is compiled along with this context's package declaration,
+ * imports, and global variables. The given requestor's
+ * <code>acceptProblem</code> method is called for each compilation problem that
+ * is detected. Then the resulting class files are handed to the given
+ * requestor's <code>acceptClassFiles</code> method to deploy and run.
+ * <p>
+ * The requestor is expected to:
+ * <ol>
+ * <li>send the class files to the target VM,
+ * <li>load them (starting with the code snippet class),
+ * <li>create a new instance of the code snippet class,
+ * <li>run the method <code>run()</code> of the code snippet,
+ * <li>retrieve the values of the local variables,
+ * <li>retrieve the returned value of the code snippet
+ * </ol>
+ * </p>
+ * <p>
+ * This method is long-running; progress and cancelation are provided
+ * by the given progress monitor.
+ * </p>
+ *
+ * @param codeSnippet the code snippet
+ * @param localVariableTypeNames the dot-separated fully qualified names of the types of the local variables.
+ * @param localVariableNames the names of the local variables as they are declared in the user's code.
+ * @param localVariableModifiers the modifiers of the local variables (default modifier or final modifier).
+ * @param declaringType the type in which the code snippet is evaluated.
+ * @param isStatic whether the code snippet is evaluated in a static member of the declaring type.
+ * @param isConstructorCall whether the code snippet is evaluated in a constructor of the declaring type.
+ * @param requestor the code snippet requestor
+ * @param progressMonitor a progress monitor
+ * @exception JavaModelException if a runtime problem occurred or if this
+ * context's project has no build state
+ */
+public void evaluateCodeSnippet(
+ String codeSnippet,
+ String[] localVariableTypeNames,
+ String[] localVariableNames,
+ int[] localVariableModifiers,
+ IType declaringType,
+ boolean isStatic,
+ boolean isConstructorCall,
+ ICodeSnippetRequestor requestor,
+ IProgressMonitor progressMonitor) throws JavaModelException;
+/**
+ * Evaluates the given code snippet. The code snippet is
+ * compiled along with this context's package declaration, imports, and
+ * global variables. The given requestor's <code>acceptProblem</code> method
+ * is called for each compilation problem that is detected. Then the resulting
+ * class files are handed to the given requestor's <code>acceptClassFiles</code>
+ * method to deploy and run. The requestor is also responsible for getting the
+ * result back.
+ * <p>
+ * This method is long-running; progress and cancelation are provided
+ * by the given progress monitor.
+ * </p>
+ *
+ * @param codeSnippet the code snippet
+ * @param requestor the code snipper requestor
+ * @param progressMonitor a progress monitor
+ * @exception JavaModelException if a runtime problem occurred or if this
+ * context's project has no build state
+ */
+public void evaluateCodeSnippet(String codeSnippet, ICodeSnippetRequestor requestor, IProgressMonitor progressMonitor) throws JavaModelException;
+/**
+ * Evaluates the given global variable. During this operation,
+ * this context's package declaration, imports, and <it>all</it> its declared
+ * variables are verified. The given requestor's <code>acceptProblem</code>
+ * method will be called for each problem that is detected.
+ * <p>
+ * This method is long-running; progress and cancelation are provided
+ * by the given progress monitor.
+ * </p>
+ *
+ * @param variable the global variable
+ * @param requestor the code snipper requestor
+ * @param progressMonitor a progress monitor
+ * @exception JavaModelException if a runtime problem occurred or if this
+ * context's project has no build state
+ */
+public void evaluateVariable(IGlobalVariable variable, ICodeSnippetRequestor requestor, IProgressMonitor progressMonitor) throws JavaModelException;
+/**
+ * Returns the import declarations for this evaluation context. Returns and empty
+ * list if there are no imports (the default if the imports have never been set).
+ * The syntax for the import corresponds to a fully qualified type name, or to
+ * an on-demand package name as defined by ImportDeclaration (JLS2 7.5). For
+ * example, <code>"java.util.Hashtable"</code> or <code>"java.util.*"</code>.
+ *
+ * @return the list of import names
+ */
+public String[] getImports();
+/**
+ * Returns the name of the package in which code snippets are to be compiled and
+ * run. Returns an empty string for the default package (the default if the
+ * package name has never been set). For example, <code>"com.example.myapp"</code>.
+ *
+ * @return the dot-separated package name, or the empty string indicating the
+ * default package
+ */
+public String getPackageName();
+/**
+ * Returns the Java project this evaluation context was created for.
+ *
+ * @return the Java project
+ */
+public IJavaProject getProject();
+/**
+ * Creates a new global variable with the given name, type, and initializer.
+ * <p>
+ * The <code>typeName</code> and <code>initializer</code> are interpreted in
+ * the context of this context's package and import declarations.
+ * </p>
+* <p>
+ * The syntax for a type name corresponds to Type in Field Declaration (JLS2 8.3).
+ * </p>
+ *
+ * @param typeName the type name
+ * @param name the name of the global variable
+ * @param initializer the initializer expression, or <code>null</code> if the
+ * variable is not initialized
+ */
+public IGlobalVariable newVariable(String typeName, String name, String initializer);
+/**
+ * Sets the import declarations for this evaluation context. An empty
+ * list indicates there are no imports. The syntax for the import corresponds to a
+ * fully qualified type name, or to an on-demand package name as defined by
+ * ImportDeclaration (JLS2 7.5). For example, <code>"java.util.Hashtable"</code>
+ * or <code>"java.util.*"</code>.
+ *
+ * @param imports the list of import names
+ */
+public void setImports(String[] imports);
+/**
+ * Sets the dot-separated name of the package in which code snippets are
+ * to be compiled and run. For example, <code>"com.example.myapp"</code>.
+ *
+ * @param packageName the dot-separated package name, or the empty string
+ * indicating the default package
+ */
+public void setPackageName(String packageName);
+/**
+ * Validates this evaluation context's import declarations. The given requestor's
+ * <code>acceptProblem</code> method is called for each problem that is detected.
+ *
+ * @param requestor the code snipper requestor
+ * @exception JavaModelException if this context's project has no build state
+ */
+public void validateImports(ICodeSnippetRequestor requestor) throws JavaModelException;
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/eval/IGlobalVariable.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/eval/IGlobalVariable.java
index 069f535875..fa2ea0cfc5 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/eval/IGlobalVariable.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/eval/IGlobalVariable.java
@@ -1,28 +1,28 @@
package org.eclipse.jdt.core.eval;
public interface IGlobalVariable {
- /**
- * Returns the initializer of this global variable.
- * The syntax for an initializer corresponds to VariableInitializer (JLS2 8.3).
- *
- * @return the initializer expression, or <code>null</code> if this global does
- * not have an initializer
- */
- public String getInitializer();
- /**
- * Returns the name of this global variable.
- *
- * @return the name of the global variable
- */
- public String getName();
- /**
- * Returns the fully qualified name of the type of this global
- * variable, or its simple representation if it is a primitive type
- * (<code>int</code>, <code>boolean</code>, etc.).
- * <p>
- * The syntax for a type name corresponds to Type in Field Declaration (JLS2 8.3).
- * </p>
- * @return the type name
- */
- public String getTypeName();
+/**
+ * Returns the initializer of this global variable.
+ * The syntax for an initializer corresponds to VariableInitializer (JLS2 8.3).
+ *
+ * @return the initializer expression, or <code>null</code> if this global does
+ * not have an initializer
+ */
+public String getInitializer();
+/**
+ * Returns the name of this global variable.
+ *
+ * @return the name of the global variable
+ */
+public String getName();
+/**
+ * Returns the fully qualified name of the type of this global
+ * variable, or its simple representation if it is a primitive type
+ * (<code>int</code>, <code>boolean</code>, etc.).
+ * <p>
+ * The syntax for a type name corresponds to Type in Field Declaration (JLS2 8.3).
+ * </p>
+ * @return the type name
+ */
+public String getTypeName();
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/eval/package.html b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/eval/package.html
new file mode 100644
index 0000000000..9768330479
--- /dev/null
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/eval/package.html
@@ -0,0 +1,17 @@
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <meta name="Author" content="IBM">
+ <meta name="GENERATOR" content="Mozilla/4.73 [en] (Windows NT 5.0; U) [Netscape]">
+ <title>Package-level Javadoc</title>
+</head>
+<body>
+Provides support for the evaluation of code snippets
+in a scrapbook or inside the debugger.
+<h2>
+Package Specification</h2>
+This packages provides support for the evaluation of code snippets in a
+scrapbook or inside the debugger.
+</body>
+</html>
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/DOMException.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/DOMException.java
index 0be5c73514..9a382d1ac3 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/DOMException.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/DOMException.java
@@ -1,19 +1,16 @@
package org.eclipse.jdt.core.jdom;
public class DOMException extends RuntimeException {
- /**
- * Creates a new exception with no detail message.
- */
- public DOMException() {
- }
-
- /**
- * Creates a new exception with the given detail message.
- *
- * @param message the deatil message
- */
- public DOMException(String message) {
- super(message);
- }
-
+/**
+ * Creates a new exception with no detail message.
+ */
+public DOMException() {}
+/**
+ * Creates a new exception with the given detail message.
+ *
+ * @param message the deatil message
+ */
+public DOMException(String message) {
+ super(message);
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/DOMFactory.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/DOMFactory.java
index bf9e68ae5a..a556c4856c 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/DOMFactory.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/DOMFactory.java
@@ -15,155 +15,122 @@ import org.eclipse.jdt.internal.core.JavaModelManager;
* </p>
*/
public class DOMFactory implements IDOMFactory {
- /**
- * Creates a new DOM factory.
- */
- public DOMFactory() {
- }
-
- /* (non-Javadoc)
- * Method declared on IDOMFactory.
- */
- public IDOMCompilationUnit createCompilationUnit() {
- return (new DOMBuilder()).createCompilationUnit();
- }
-
- /* (non-Javadoc)
- * Method declared on IDOMFactory.
- */
- public IDOMCompilationUnit createCompilationUnit(
- char[] sourceCode,
- String name) {
- if (sourceCode == null) {
- return null;
- }
- return (new SimpleDOMBuilder()).createCompilationUnit(
- sourceCode,
- name.toCharArray());
- }
-
- /* (non-Javadoc)
- * Method declared on IDOMFactory.
- */
- public IDOMCompilationUnit createCompilationUnit(
- String sourceCode,
- String name) {
- if (sourceCode == null) {
- return null;
- }
- return (new SimpleDOMBuilder()).createCompilationUnit(
- sourceCode.toCharArray(),
- name.toCharArray());
- }
-
- /* (non-Javadoc)
- * Method declared on IDOMFactory.
- */
- public IDOMField createField() {
- return createField("Object aField;" + JavaModelManager.LINE_SEPARATOR);
- }
-
- /* (non-Javadoc)
- * Method declared on IDOMFactory.
- */
- public IDOMField createField(String sourceCode) {
- if (sourceCode == null) {
- return null;
- }
- return (new DOMBuilder()).createField(sourceCode.toCharArray());
- }
-
- /* (non-Javadoc)
- * Method declared on IDOMFactory.
- */
- public IDOMImport createImport() {
- return (new DOMBuilder()).createImport();
- }
-
- /* (non-Javadoc)
- * Method declared on IDOMFactory.
- */
- public IDOMImport createImport(String sourceCode) {
- if (sourceCode == null) {
- return null;
- }
- return (new DOMBuilder()).createImport(sourceCode.toCharArray());
- }
-
- /* (non-Javadoc)
- * Method declared on IDOMFactory.
- */
- public IDOMInitializer createInitializer() {
- return createInitializer("static {}" + JavaModelManager.LINE_SEPARATOR);
- }
-
- /* (non-Javadoc)
- * Method declared on IDOMFactory.
- */
- public IDOMInitializer createInitializer(String sourceCode) {
- if (sourceCode == null) {
- return null;
- }
- return (new DOMBuilder()).createInitializer(sourceCode.toCharArray());
- }
-
- /* (non-Javadoc)
- * Method declared on IDOMFactory.
- */
- public IDOMMethod createMethod() {
- return createMethod(
- "public void newMethod() {"
- + JavaModelManager.LINE_SEPARATOR
- + "}"
- + JavaModelManager.LINE_SEPARATOR);
- }
-
- /* (non-Javadoc)
- * Method declared on IDOMFactory.
- */
- public IDOMMethod createMethod(String sourceCode) {
- if (sourceCode == null) {
- return null;
- }
- return (new DOMBuilder()).createMethod(sourceCode.toCharArray());
- }
-
- /* (non-Javadoc)
- * Method declared on IDOMFactory.
- */
- public IDOMPackage createPackage() {
- return (new DOMBuilder()).createPackage();
- }
-
- /* (non-Javadoc)
- * Method declared on IDOMFactory.
- */
- public IDOMPackage createPackage(String sourceCode) {
- if (sourceCode == null) {
- return null;
- }
- return (new DOMBuilder()).createPackage(sourceCode.toCharArray());
- }
-
- /* (non-Javadoc)
- * Method declared on IDOMFactory.
- */
- public IDOMType createType() {
- return createType(
- "public class AClass {"
- + JavaModelManager.LINE_SEPARATOR
- + "}"
- + JavaModelManager.LINE_SEPARATOR);
- }
-
- /* (non-Javadoc)
- * Method declared on IDOMFactory.
- */
- public IDOMType createType(String sourceCode) {
- if (sourceCode == null) {
- return null;
- }
- return (new DOMBuilder()).createType(sourceCode.toCharArray());
- }
-
+/**
+ * Creates a new DOM factory.
+ */
+public DOMFactory() {}
+/* (non-Javadoc)
+ * Method declared on IDOMFactory.
+ */
+public IDOMCompilationUnit createCompilationUnit() {
+ return (new DOMBuilder()).createCompilationUnit();
+}
+/* (non-Javadoc)
+ * Method declared on IDOMFactory.
+ */
+public IDOMCompilationUnit createCompilationUnit(char[] sourceCode, String name) {
+ if(sourceCode == null) {
+ return null;
+ }
+ return (new SimpleDOMBuilder()).createCompilationUnit(sourceCode, name.toCharArray());
+}
+/* (non-Javadoc)
+ * Method declared on IDOMFactory.
+ */
+public IDOMCompilationUnit createCompilationUnit(String sourceCode, String name) {
+ if(sourceCode == null) {
+ return null;
+ }
+ return (new SimpleDOMBuilder()).createCompilationUnit(sourceCode.toCharArray(), name.toCharArray());
+}
+/* (non-Javadoc)
+ * Method declared on IDOMFactory.
+ */
+public IDOMField createField() {
+ return createField("Object aField;"+ JavaModelManager.LINE_SEPARATOR);
+}
+/* (non-Javadoc)
+ * Method declared on IDOMFactory.
+ */
+public IDOMField createField(String sourceCode) {
+ if(sourceCode == null) {
+ return null;
+ }
+ return (new DOMBuilder()).createField(sourceCode.toCharArray());
+}
+/* (non-Javadoc)
+ * Method declared on IDOMFactory.
+ */
+public IDOMImport createImport() {
+ return (new DOMBuilder()).createImport();
+}
+/* (non-Javadoc)
+ * Method declared on IDOMFactory.
+ */
+public IDOMImport createImport(String sourceCode) {
+ if(sourceCode == null) {
+ return null;
+ }
+ return (new DOMBuilder()).createImport(sourceCode.toCharArray());
+}
+/* (non-Javadoc)
+ * Method declared on IDOMFactory.
+ */
+public IDOMInitializer createInitializer() {
+ return createInitializer("static {}"+ JavaModelManager.LINE_SEPARATOR);
+}
+/* (non-Javadoc)
+ * Method declared on IDOMFactory.
+ */
+public IDOMInitializer createInitializer(String sourceCode) {
+ if(sourceCode == null) {
+ return null;
+ }
+ return (new DOMBuilder()).createInitializer(sourceCode.toCharArray());
+}
+/* (non-Javadoc)
+ * Method declared on IDOMFactory.
+ */
+public IDOMMethod createMethod() {
+ return createMethod("public void newMethod() {"+ JavaModelManager.LINE_SEPARATOR+"}"+ JavaModelManager.LINE_SEPARATOR);
+}
+/* (non-Javadoc)
+ * Method declared on IDOMFactory.
+ */
+public IDOMMethod createMethod(String sourceCode) {
+ if(sourceCode == null) {
+ return null;
+ }
+ return (new DOMBuilder()).createMethod(sourceCode.toCharArray());
+}
+/* (non-Javadoc)
+ * Method declared on IDOMFactory.
+ */
+public IDOMPackage createPackage() {
+ return (new DOMBuilder()).createPackage();
+}
+/* (non-Javadoc)
+ * Method declared on IDOMFactory.
+ */
+public IDOMPackage createPackage(String sourceCode) {
+ if(sourceCode == null) {
+ return null;
+ }
+ return (new DOMBuilder()).createPackage(sourceCode.toCharArray());
+}
+/* (non-Javadoc)
+ * Method declared on IDOMFactory.
+ */
+public IDOMType createType() {
+ return createType("public class AClass {"+ JavaModelManager.LINE_SEPARATOR +"}"+ JavaModelManager.LINE_SEPARATOR);
+}
+/* (non-Javadoc)
+ * Method declared on IDOMFactory.
+ */
+public IDOMType createType(String sourceCode) {
+ if(sourceCode == null) {
+ return null;
+ }
+ return (new DOMBuilder()).createType(sourceCode.toCharArray());
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMCompilationUnit.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMCompilationUnit.java
index 6f3fffbeb5..e9702c11df 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMCompilationUnit.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMCompilationUnit.java
@@ -1,45 +1,45 @@
package org.eclipse.jdt.core.jdom;
public interface IDOMCompilationUnit extends IDOMNode {
- /**
- * Returns the header comment for this compilation unit. The header comment
- * appears before the first declaration in a compilation unit.
- * The syntax for a comment corresponds to Comments (JLS2 3.7), <b>including</b>
- * comment delimiters.
- *
- * @return the header comment for this compilation unit, or <code>null</code> if
- * no header comment is present
- */
- public String getHeader();
- /**
- * The <code>IDOMCompilationNode</code> refinement of this <code>IDOMNode</code>
- * method returns the name of this compilation unit.
- *
- * <p>The name of a compilation unit is the name of the first top-level public type
- * defined in the compilation unit, suffixed with ".java". For example, if the first
- * top-level public type defined in this compilation unit has the name "Hanoi",
- * then name of this compilation unit is "Hanoi.java".</p>
- *
- * <p>In the absence of a public top-level type, the name of the first top-level
- * type is used. In the absence of any type, the name of the compilation unit
- * is <code>null</code>.</p>
- *
- * @return the name of this compilation unit, or <code>null</code> if none
- */
- public String getName();
- /**
- * Sets the header comment for this compilation unit. The header comment
- * appears before the first declaration in a compilation unit.
- * The syntax for a comment corresponds to Comments (JLS2 3.7), <b>including</b>
- * comment delimiters.
- *
- * @param comment the header comment for this compilation unit, or <code>null</code> if
- * indicating no header comment
- */
- public void setHeader(String comment);
- /**
- * The <code>IDOMCompilationNode</code> refinement of this <code>IDOMNode</code>
- * method has no effect (the name is computed from the types declared within it).
- */
- public void setName(String name);
+/**
+ * Returns the header comment for this compilation unit. The header comment
+ * appears before the first declaration in a compilation unit.
+ * The syntax for a comment corresponds to Comments (JLS2 3.7), <b>including</b>
+ * comment delimiters.
+ *
+ * @return the header comment for this compilation unit, or <code>null</code> if
+ * no header comment is present
+ */
+public String getHeader();
+/**
+ * The <code>IDOMCompilationNode</code> refinement of this <code>IDOMNode</code>
+ * method returns the name of this compilation unit.
+ *
+ * <p>The name of a compilation unit is the name of the first top-level public type
+ * defined in the compilation unit, suffixed with ".java". For example, if the first
+ * top-level public type defined in this compilation unit has the name "Hanoi",
+ * then name of this compilation unit is "Hanoi.java".</p>
+ *
+ * <p>In the absence of a public top-level type, the name of the first top-level
+ * type is used. In the absence of any type, the name of the compilation unit
+ * is <code>null</code>.</p>
+ *
+ * @return the name of this compilation unit, or <code>null</code> if none
+ */
+public String getName();
+/**
+ * Sets the header comment for this compilation unit. The header comment
+ * appears before the first declaration in a compilation unit.
+ * The syntax for a comment corresponds to Comments (JLS2 3.7), <b>including</b>
+ * comment delimiters.
+ *
+ * @param comment the header comment for this compilation unit, or <code>null</code> if
+ * indicating no header comment
+ */
+public void setHeader(String comment);
+/**
+ * The <code>IDOMCompilationNode</code> refinement of this <code>IDOMNode</code>
+ * method has no effect (the name is computed from the types declared within it).
+ */
+public void setName(String name);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMFactory.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMFactory.java
index 69e26dc8cf..878df04d95 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMFactory.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMFactory.java
@@ -1,137 +1,133 @@
package org.eclipse.jdt.core.jdom;
public interface IDOMFactory {
- /**
- * Creates and return an empty JDOM. The initial content is an empty string.
- *
- * @return the new compilation unit
- */
- public IDOMCompilationUnit createCompilationUnit();
- /**
- * Creates a JDOM on the given source code. The syntax for the given source
- * code corresponds to CompilationUnit (JLS2 7.3).
- *
- * @param sourceCode the source code character array, or <code>null</code>
- * @param name the name of the compilation unit
- * @return the new compilation unit, or <code>null</code> if unable to recognize
- * the source code, or if the source code is <code>null</code>
- */
- public IDOMCompilationUnit createCompilationUnit(
- char[] sourceCode,
- String name);
- /**
- * Creates a JDOM on the given source code. The syntax for the given source
- * code corresponds to CompilationUnit (JLS2 7.3).
- *
- * @param sourceCode the source code string, or <code>null</code>
- * @param name the name of the compilation unit
- * @return the new compilation unit, or <code>null</code> if unable to recognize
- * the source code, or if the source code is <code>null</code>
- */
- public IDOMCompilationUnit createCompilationUnit(
- String sourceCode,
- String name);
- /**
- * Creates a default field document fragment. Initially the field will have
- * default protection, type <code>"Object"</code>, name <code>"aField"</code>,
- * no comment, and no initializer.
- *
- * @return the new field
- */
- public IDOMField createField();
- /**
- * Creates a field document fragment on the given source code. The given source
- * string corresponds to FieldDeclaration (JLS2 8.3) and ConstantDeclaration
- * (JLS2 9.3) restricted to a single VariableDeclarator clause.
- *
- * @param sourceCode the source code
- * @return the new field, or <code>null</code> if unable to recognize
- * the source code, if the source code is <code>null</code>, or when the source
- * contains more than one VariableDeclarator clause
- */
- public IDOMField createField(String sourceCode);
- /**
- * Creates an empty import document fragment. Initially the import will have
- * name <code>"java.lang.*"</code>.
- *
- * @return the new import
- */
- public IDOMImport createImport();
- /**
- * Creates an import document fragment on the given source code. The syntax for
- * the given source string corresponds to ImportDeclaration (JLS2 7.5).
- *
- * @param sourceCode the source code
- * @return the new import, or <code>null</code> if unable to recognize
- * the source code, or if the source code is <code>null</code>
- */
- public IDOMImport createImport(String sourceCode);
- /**
- * Creates an empty initializer document fragment. Initially the initializer
- * will be static and have no body or comment.
- *
- * @return the new initializer
- */
- public IDOMInitializer createInitializer();
- /**
- * Creates an initializer document fragment from the given source code. The
- * syntax for the given source string corresponds to InstanceInitializer
- * (JLS2 8.6) and StaticDeclaration (JLS2 8.7).
- *
- * @param sourceCode the source code
- * @return the new initializer, or <code>null</code> if unable to recognize
- * the source code, or if the source code is <code>null</code>
- */
- public IDOMInitializer createInitializer(String sourceCode);
- /**
- * Creates a default method document fragment. Initially the method
- * will have public visibility, return type <code>"void"</code>, be named
- * <code>"newMethod"</code>, have no parameters, no comment, and an empty body.
- *
- * @return the new method
- */
- public IDOMMethod createMethod();
- /**
- * Creates a method document fragment on the given source code. The syntax for
- * the given source string corresponds to MethodDeclaration (JLS2 8.4),
- * ConstructorDeclaration (JLS2 8.8), and AbstractMethodDeclaration (JLS2 9.4).
- *
- * @param sourceCode the source code
- * @return the new method, or <code>null</code> if unable to recognize
- * the source code, or if the source code is <code>null</code>
- */
- public IDOMMethod createMethod(String sourceCode);
- /**
- * Creates an empty package document fragment. Initially the package
- * declaration will have no name.
- *
- * @return the new package
- */
- public IDOMPackage createPackage();
- /**
- * Creates a package document fragment on the given source code. The syntax for
- * the given source string corresponds to PackageDeclaration (JLS2 7.4).
- *
- * @param sourceCode the source code
- * @return the new package, or <code>null</code> if unable to recognize
- * the source code, or if the source code is <code>null</code>
- */
- public IDOMPackage createPackage(String sourceCode);
- /**
- * Creates a default type document fragment. Initially the type will be
- * a public class named <code>"AClass"</code>, with no members or comment.
- *
- * @return the new type
- */
- public IDOMType createType();
- /**
- * Creates a type document fragment on the given source code. The syntax for the
- * given source string corresponds to ClassDeclaration (JLS2 8.1) and
- * InterfaceDeclaration (JLS2 9.1).
- *
- * @param sourceCode the source code
- * @return the new type, or <code>null</code> if unable to recognize
- * the source code, or if the source code is <code>null</code>
- */
- public IDOMType createType(String sourceCode);
+/**
+ * Creates and return an empty JDOM. The initial content is an empty string.
+ *
+ * @return the new compilation unit
+ */
+public IDOMCompilationUnit createCompilationUnit();
+/**
+ * Creates a JDOM on the given source code. The syntax for the given source
+ * code corresponds to CompilationUnit (JLS2 7.3).
+ *
+ * @param sourceCode the source code character array, or <code>null</code>
+ * @param name the name of the compilation unit
+ * @return the new compilation unit, or <code>null</code> if unable to recognize
+ * the source code, or if the source code is <code>null</code>
+ */
+public IDOMCompilationUnit createCompilationUnit(char[] sourceCode, String name);
+/**
+ * Creates a JDOM on the given source code. The syntax for the given source
+ * code corresponds to CompilationUnit (JLS2 7.3).
+ *
+ * @param sourceCode the source code string, or <code>null</code>
+ * @param name the name of the compilation unit
+ * @return the new compilation unit, or <code>null</code> if unable to recognize
+ * the source code, or if the source code is <code>null</code>
+ */
+public IDOMCompilationUnit createCompilationUnit(String sourceCode, String name);
+/**
+ * Creates a default field document fragment. Initially the field will have
+ * default protection, type <code>"Object"</code>, name <code>"aField"</code>,
+ * no comment, and no initializer.
+ *
+ * @return the new field
+ */
+public IDOMField createField();
+/**
+ * Creates a field document fragment on the given source code. The given source
+ * string corresponds to FieldDeclaration (JLS2 8.3) and ConstantDeclaration
+ * (JLS2 9.3) restricted to a single VariableDeclarator clause.
+ *
+ * @param sourceCode the source code
+ * @return the new field, or <code>null</code> if unable to recognize
+ * the source code, if the source code is <code>null</code>, or when the source
+ * contains more than one VariableDeclarator clause
+ */
+public IDOMField createField(String sourceCode);
+/**
+ * Creates an empty import document fragment. Initially the import will have
+ * name <code>"java.lang.*"</code>.
+ *
+ * @return the new import
+ */
+public IDOMImport createImport();
+/**
+ * Creates an import document fragment on the given source code. The syntax for
+ * the given source string corresponds to ImportDeclaration (JLS2 7.5).
+ *
+ * @param sourceCode the source code
+ * @return the new import, or <code>null</code> if unable to recognize
+ * the source code, or if the source code is <code>null</code>
+ */
+public IDOMImport createImport(String sourceCode);
+/**
+ * Creates an empty initializer document fragment. Initially the initializer
+ * will be static and have no body or comment.
+ *
+ * @return the new initializer
+ */
+public IDOMInitializer createInitializer();
+/**
+ * Creates an initializer document fragment from the given source code. The
+ * syntax for the given source string corresponds to InstanceInitializer
+ * (JLS2 8.6) and StaticDeclaration (JLS2 8.7).
+ *
+ * @param sourceCode the source code
+ * @return the new initializer, or <code>null</code> if unable to recognize
+ * the source code, or if the source code is <code>null</code>
+ */
+public IDOMInitializer createInitializer(String sourceCode);
+/**
+ * Creates a default method document fragment. Initially the method
+ * will have public visibility, return type <code>"void"</code>, be named
+ * <code>"newMethod"</code>, have no parameters, no comment, and an empty body.
+ *
+ * @return the new method
+ */
+public IDOMMethod createMethod();
+/**
+ * Creates a method document fragment on the given source code. The syntax for
+ * the given source string corresponds to MethodDeclaration (JLS2 8.4),
+ * ConstructorDeclaration (JLS2 8.8), and AbstractMethodDeclaration (JLS2 9.4).
+ *
+ * @param sourceCode the source code
+ * @return the new method, or <code>null</code> if unable to recognize
+ * the source code, or if the source code is <code>null</code>
+ */
+public IDOMMethod createMethod(String sourceCode);
+/**
+ * Creates an empty package document fragment. Initially the package
+ * declaration will have no name.
+ *
+ * @return the new package
+ */
+public IDOMPackage createPackage();
+/**
+ * Creates a package document fragment on the given source code. The syntax for
+ * the given source string corresponds to PackageDeclaration (JLS2 7.4).
+ *
+ * @param sourceCode the source code
+ * @return the new package, or <code>null</code> if unable to recognize
+ * the source code, or if the source code is <code>null</code>
+ */
+public IDOMPackage createPackage(String sourceCode);
+/**
+ * Creates a default type document fragment. Initially the type will be
+ * a public class named <code>"AClass"</code>, with no members or comment.
+ *
+ * @return the new type
+ */
+public IDOMType createType();
+/**
+ * Creates a type document fragment on the given source code. The syntax for the
+ * given source string corresponds to ClassDeclaration (JLS2 8.1) and
+ * InterfaceDeclaration (JLS2 9.1).
+ *
+ * @param sourceCode the source code
+ * @return the new type, or <code>null</code> if unable to recognize
+ * the source code, or if the source code is <code>null</code>
+ */
+public IDOMType createType(String sourceCode);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMField.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMField.java
index 28cf0e4006..c623cfcb99 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMField.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMField.java
@@ -1,57 +1,57 @@
package org.eclipse.jdt.core.jdom;
public interface IDOMField extends IDOMMember {
- /**
- * Returns the initializer expression for this field.
- * The syntax for an initializer corresponds to VariableInitializer (JLS2 8.3).
- * <p>
- * Note: The expression does not include a "<code>=</code>".
- * </p>
- *
- * @return the initializer expression, or <code>null</code> if this field does
- * not have an initializer
- */
- public String getInitializer();
- /**
- * The <code>IDOMField</code> refinement of this <code>IDOMNode</code>
- * method returns the name of this field. The syntax for the name of a field
- * corresponds to VariableDeclaratorId (JLS2 8.3).
- */
- public String getName();
- /**
- * Returns the type name of this field. The syntax for a type name of a field
- * corresponds to Type in Field Declaration (JLS2 8.3).
- *
- * @return the type name
- */
- public String getType();
- /**
- * Sets the initializer expression for this field.
- * The syntax for an initializer corresponds to VariableInitializer (JLS2 8.3).
- * <p>
- * Note: The expression does not include a "<code>=</code>".
- * </p>
- *
- * @param initializer the initializer expression, or <code>null</code> indicating
- * the field does not have an initializer
- */
- public void setInitializer(String initializer);
- /**
- * The <code>IDOMField</code> refinement of this <code>IDOMNode</code>
- * method sets the name of this field. The syntax for the name of a field
- * corresponds to VariableDeclaratorId (JLS2 8.3).
- *
- * @exception IllegalArgumentException if <code>null</code> is specified
- */
- public void setName(String name) throws IllegalArgumentException;
- /**
- * Sets the type name of this field. The syntax for a type name of a field
- * corresponds to Type in Field Declaration (JLS2 8.3). Type names must be
- * specified as they should appear in source code. For example:
- * <code>"String"</code>, <code>"int[]"</code>, or <code>"java.io.File"</code>.
- *
- * @param typeName the type name
- * @exception IllegalArgumentException if <code>null</code> is specified
- */
- public void setType(String typeName) throws IllegalArgumentException;
+/**
+ * Returns the initializer expression for this field.
+ * The syntax for an initializer corresponds to VariableInitializer (JLS2 8.3).
+ * <p>
+ * Note: The expression does not include a "<code>=</code>".
+ * </p>
+ *
+ * @return the initializer expression, or <code>null</code> if this field does
+ * not have an initializer
+ */
+public String getInitializer();
+/**
+ * The <code>IDOMField</code> refinement of this <code>IDOMNode</code>
+ * method returns the name of this field. The syntax for the name of a field
+ * corresponds to VariableDeclaratorId (JLS2 8.3).
+ */
+public String getName();
+/**
+ * Returns the type name of this field. The syntax for a type name of a field
+ * corresponds to Type in Field Declaration (JLS2 8.3).
+ *
+ * @return the type name
+ */
+public String getType();
+/**
+ * Sets the initializer expression for this field.
+ * The syntax for an initializer corresponds to VariableInitializer (JLS2 8.3).
+ * <p>
+ * Note: The expression does not include a "<code>=</code>".
+ * </p>
+ *
+ * @param initializer the initializer expression, or <code>null</code> indicating
+ * the field does not have an initializer
+ */
+public void setInitializer(String initializer);
+/**
+ * The <code>IDOMField</code> refinement of this <code>IDOMNode</code>
+ * method sets the name of this field. The syntax for the name of a field
+ * corresponds to VariableDeclaratorId (JLS2 8.3).
+ *
+ * @exception IllegalArgumentException if <code>null</code> is specified
+ */
+public void setName(String name) throws IllegalArgumentException;
+/**
+ * Sets the type name of this field. The syntax for a type name of a field
+ * corresponds to Type in Field Declaration (JLS2 8.3). Type names must be
+ * specified as they should appear in source code. For example:
+ * <code>"String"</code>, <code>"int[]"</code>, or <code>"java.io.File"</code>.
+ *
+ * @param typeName the type name
+ * @exception IllegalArgumentException if <code>null</code> is specified
+ */
+public void setType(String typeName) throws IllegalArgumentException;
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMImport.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMImport.java
index 23dbb6c23a..fc56e6a327 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMImport.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMImport.java
@@ -1,26 +1,26 @@
package org.eclipse.jdt.core.jdom;
public interface IDOMImport extends IDOMNode {
- /**
- * The <code>IDOMImport</code> refinement of this <code>IDOMNode</code>
- * method returns the name of this import. The syntax for an import name
- * corresponds to a fully qualified type name, or to an on-demand package name
- * as defined by ImportDeclaration (JLS2 7.5).
- */
- public String getName();
- /**
- * Returns whether this import declaration ends with <code>".*"</code>.
- *
- * @return <code>true</code> if this in an on-demand import
- */
- public boolean isOnDemand();
- /**
- * The <code>IDOMImport</code> refinement of this <code>IDOMNode</code>
- * method sets the name of this import. The syntax for an import name
- * corresponds to a fully qualified type name, or to an on-demand package name
- * as defined by ImportDeclaration (JLS2 7.5).
- *
- * @exception IllegalArgumentException if <code>null</code> is specified
- */
- public void setName(String name);
+/**
+ * The <code>IDOMImport</code> refinement of this <code>IDOMNode</code>
+ * method returns the name of this import. The syntax for an import name
+ * corresponds to a fully qualified type name, or to an on-demand package name
+ * as defined by ImportDeclaration (JLS2 7.5).
+ */
+public String getName();
+/**
+ * Returns whether this import declaration ends with <code>".*"</code>.
+ *
+ * @return <code>true</code> if this in an on-demand import
+ */
+public boolean isOnDemand();
+/**
+ * The <code>IDOMImport</code> refinement of this <code>IDOMNode</code>
+ * method sets the name of this import. The syntax for an import name
+ * corresponds to a fully qualified type name, or to an on-demand package name
+ * as defined by ImportDeclaration (JLS2 7.5).
+ *
+ * @exception IllegalArgumentException if <code>null</code> is specified
+ */
+public void setName(String name);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMInitializer.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMInitializer.java
index df25caf7c1..a8f82f403c 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMInitializer.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMInitializer.java
@@ -1,31 +1,31 @@
package org.eclipse.jdt.core.jdom;
public interface IDOMInitializer extends IDOMMember {
- /**
- * Returns the body of this initializer. The syntax for a body corresponds to
- * InstanceInitializer (JLS2 8.6) and StaticDeclaration (JLS2 8.7).
- *
- * @return an initializer body, including braces, or <code>null</code> if
- * no body is present
- */
- public String getBody();
- /**
- * The <code>IDOMInitializer</code> refinement of this <code>IDOMNode</code>
- * method returns <code>null</code>. An initializer does not have a name.
- */
- public String getName();
- /**
- * Sets the body of this initializer. The syntax for a body corresponds to
- * InstanceInitializer (JLS2 8.6) and StaticDeclaration (JLS2 8.7). No formatting
- * or syntax checking is performed on the body. Braces <b>must</b> be included.
- *
- * @param body an initializer body, including braces, or <code>null</code>
- * indicating no body
- */
- public void setBody(String body);
- /**
- * The <code>IDOMInitializer</code> refinement of this <code>IDOMNode</code>
- * method does nothing.
- */
- public void setName(String name);
+/**
+ * Returns the body of this initializer. The syntax for a body corresponds to
+ * InstanceInitializer (JLS2 8.6) and StaticDeclaration (JLS2 8.7).
+ *
+ * @return an initializer body, including braces, or <code>null</code> if
+ * no body is present
+ */
+public String getBody();
+/**
+ * The <code>IDOMInitializer</code> refinement of this <code>IDOMNode</code>
+ * method returns <code>null</code>. An initializer does not have a name.
+ */
+public String getName();
+/**
+ * Sets the body of this initializer. The syntax for a body corresponds to
+ * InstanceInitializer (JLS2 8.6) and StaticDeclaration (JLS2 8.7). No formatting
+ * or syntax checking is performed on the body. Braces <b>must</b> be included.
+ *
+ * @param body an initializer body, including braces, or <code>null</code>
+ * indicating no body
+ */
+public void setBody(String body);
+/**
+ * The <code>IDOMInitializer</code> refinement of this <code>IDOMNode</code>
+ * method does nothing.
+ */
+public void setName(String name);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMMember.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMMember.java
index 53a12182e9..6cb9542ce2 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMMember.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMMember.java
@@ -1,39 +1,39 @@
package org.eclipse.jdt.core.jdom;
public interface IDOMMember extends IDOMNode {
- /**
- * Returns the comment associated with this member (including comment delimiters).
- *
- * @return the comment, or <code>null</code> if this member has no associated
- * comment
- */
- public String getComment();
- /**
- * Returns the flags for this member. The flags can be examined using the
- * <code>Flags</code> class.
- *
- * @return the flags
- * @see org.eclipse.jdt.core.Flags
- */
- public int getFlags();
- /**
- * Sets the comment associated with this member. The comment will appear
- * before the member in the source. The comment must be properly formatted, including
- * delimiters. A <code>null</code> comment indicates no comment. This member's
- * deprecated flag is automatically set to reflect the deprecated tag in the
- * comment.
- *
- * @param comment the comment, including comment delimiters, or
- * <code>null</code> indicating this member should have no associated comment
- * @see #setFlags
- */
- public void setComment(String comment);
- /**
- * Sets the flags for this member. The flags can be examined using the
- * <code>Flags</code> class. The deprecated flag passed in is ignored.
- *
- * @param flags the flags
- * @see org.eclipse.jdt.core.Flags
- */
- public void setFlags(int flags);
+/**
+ * Returns the comment associated with this member (including comment delimiters).
+ *
+ * @return the comment, or <code>null</code> if this member has no associated
+ * comment
+ */
+public String getComment();
+/**
+ * Returns the flags for this member. The flags can be examined using the
+ * <code>Flags</code> class.
+ *
+ * @return the flags
+ * @see org.eclipse.jdt.core.Flags
+ */
+public int getFlags();
+/**
+ * Sets the comment associated with this member. The comment will appear
+ * before the member in the source. The comment must be properly formatted, including
+ * delimiters. A <code>null</code> comment indicates no comment. This member's
+ * deprecated flag is automatically set to reflect the deprecated tag in the
+ * comment.
+ *
+ * @param comment the comment, including comment delimiters, or
+ * <code>null</code> indicating this member should have no associated comment
+ * @see #setFlags
+ */
+public void setComment(String comment);
+/**
+ * Sets the flags for this member. The flags can be examined using the
+ * <code>Flags</code> class. The deprecated flag passed in is ignored.
+ *
+ * @param flags the flags
+ * @see org.eclipse.jdt.core.Flags
+ */
+public void setFlags(int flags);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMMethod.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMMethod.java
index 3a98b3525e..a0b53d39c5 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMMethod.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMMethod.java
@@ -1,164 +1,162 @@
package org.eclipse.jdt.core.jdom;
public interface IDOMMethod extends IDOMMember {
- /**
- * Adds the given exception to the end of the list of exceptions this method
- * is declared to throw.
- * The syntax for an exception type name is defined by Method Throws (JLS2 8.4.4).
- * Type names must be specified as they would appear in source code. For
- * example: <code>"IOException"</code> or <code>"java.io.IOException"</code>.
- * This is a convenience method for <code>setExceptions</code>.
- *
- * @param exceptionType the exception type
- * @exception IllegalArgumentException if <code>null</code> is specified
- * @see #setExceptions
- */
- public void addException(String exceptionType) throws IllegalArgumentException;
- /**
- * Adds the given parameter to the end of the parameter list.
- * This is a convenience method for <code>setParameters</code>.
- * The syntax for parameter names is defined by Formal Parameters (JLS2 8.4.1).
- * The syntax for type names is defined by Formal Parameters (JLS2 8.4.1).
- * Type names must be specified as they would appear in source code. For
- * example: <code>"File"</code>, <code>"java.io.File"</code>, or
- * <code>"int[]"</code>.
- *
- * @param type the type name
- * @param name the parameter name
- * @exception IllegalArgumentException if <code>null</code> is specified for
- * either the type or the name
- * @see #setParameters
- */
- public void addParameter(String type, String name)
- throws IllegalArgumentException;
- /**
- * Returns the body of this method. The method body includes all code following
- * the method declaration, including the enclosing braces.
- *
- * @return the body, or <code>null</code> if the method has no body (for
- * example, for an abstract or native method)
- */
- public String getBody();
- /**
- * Returns the names of the exception types this method throws
- * in the order in which they are declared in the source, or an empty array
- * if this method declares no exception types.
- * The syntax for an exception type name is defined by Method Throws (JLS2 8.4.4).
- * Type names appear as they would in source code. For example:
- * <code>"IOException"</code> or <code>"java.io.IOException"</code>.
- *
- * @return the list of exception types
- */
- public String[] getExceptions();
- /**
- * The <code>IDOMMethod</code> refinement of this <code>IDOMNode</code>
- * method returns the name of this method. Returns <code>null</code> for
- * constructors. The syntax for a method name is defined by Identifer
- * of MethodDeclarator (JLS2 8.4).
- */
- public String getName();
- /**
- * Returns the names of parameters in this method in the order they are declared,
- * or <code>null</code> if no parameters are declared.
- * The syntax for parameter names is defined by Formal Parameters (JLS2 8.4.1).
- *
- * @return the list of parameter names, or <code>null</code> if no parameters
- * are declared
- */
- public String[] getParameterNames();
- /**
- * Returns the type names for the parameters of this method in the order they are declared,
- * or <code>null</code> if no parameters are declared.
- * The syntax for type names is defined by Formal Parameters (JLS2 8.4.1).
- * Type names must be specified as they would appear in source code. For
- * example: <code>"File"</code>, <code>"java.io.File"</code>, or
- * <code>"int[]"</code>.
- *
- * @return the list of parameter types, or <code>null</code> if no parameters
- * are declared
- */
- public String[] getParameterTypes();
- /**
- * Returns the return type name, or <code>"void"</code>.
- * Returns <code>"void"</code> for constructors.
- * The syntax for return type name corresponds to ReturnType in
- * MethodDeclaration (JLS2 8.4). Names are returned as they appear in the source
- * code; for example: <code>"File"</code>, <code>"java.io.File"</code>,
- * <code>"int[]"</code>, or <code>"void"</code>.
- *
- * @return the return type
- */
- public String getReturnType();
- /**
- * Returns whether this method is a constructor.
- *
- * @return <code>true</code> for constructors, and <code>false</code> for methods
- */
- public boolean isConstructor();
- /**
- * Sets the body of this method. The method body includes all code following
- * the method declaration, including the enclosing braces. No formatting or
- * syntax checking is performed on the body.
- *
- * @return the body, or <code>null</code> indicating the method has no body (for
- * example, for an abstract or native method)
- */
- public void setBody(String body);
- /**
- * Sets whether this method represents a constructor.
- *
- * @param b <code>true</code> for constructors, and <code>false</code> for methods
- */
- public void setConstructor(boolean b);
- /**
- * Sets the names of the exception types this method throws,
- * in the order in which they are declared in the source. An empty array
- * indicates this method declares no exception types.
- * The syntax for an exception type name is defined by Method Throws (JLS2 8.4.4).
- * Type names must be specified as they would appear in source code. For
- * example: <code>"IOException"</code> or <code>"java.io.IOException"</code>.
- *
- * @param exceptionTypes the list of exception types
- */
- public void setExceptions(String[] exceptionTypes);
- /**
- * The <code>IDOMMethod</code> refinement of this <code>IDOMNode</code>
- * method sets the name of this method. The syntax for a method
- * name is defined by Identifer of MethodDeclarator (JLS2 8.4).
- * <p>
- * The name of a constructor is always <code>null</code> and thus it
- * must not be set.
- * </p>
- *
- * @exception IllegalArgumentException if <code>null</code> is specified
- */
- public void setName(String name) throws IllegalArgumentException;
- /**
- * Sets the types and names of parameters in this method in the order they are
- * to be declared. If both <code>types</code> and <code>names</code> are <code>null</code>
- * this indicates that this method has no parameters.
- * The syntax for parameter names is defined by Formal Parameters (JLS2 8.4.1).
- * The syntax for type names is defined by Formal Parameters (JLS2 8.4.1).
- * Type names must be specified as they would appear in source code. For
- * example: <code>"File"</code>, <code>"java.io.File"</code>, or
- * <code>"int[]"</code>.
- *
- * @param types the list of type names
- * @param names the list of parameter name
- * @exception IllegalArgumentException if the number of types and names do not
- * match, or if either argument is <code>null</code>
- */
- public void setParameters(String[] types, String[] names)
- throws IllegalArgumentException;
- /**
- * Sets the return type name. This has no effect on constructors.
- * The syntax for return type name corresponds to ReturnType in
- * MethodDeclaration (JLS2 8.4). Type names are specified as they appear in the
- * source code; for example: <code>"File"</code>, <code>"java.io.File"</code>,
- * <code>"int[]"</code>, or <code>"void"</code>.
- *
- * @param type the return type
- * @exception IllegalArgumentException if <code>null</code> is specified
- */
- public void setReturnType(String type) throws IllegalArgumentException;
+/**
+ * Adds the given exception to the end of the list of exceptions this method
+ * is declared to throw.
+ * The syntax for an exception type name is defined by Method Throws (JLS2 8.4.4).
+ * Type names must be specified as they would appear in source code. For
+ * example: <code>"IOException"</code> or <code>"java.io.IOException"</code>.
+ * This is a convenience method for <code>setExceptions</code>.
+ *
+ * @param exceptionType the exception type
+ * @exception IllegalArgumentException if <code>null</code> is specified
+ * @see #setExceptions
+ */
+public void addException(String exceptionType) throws IllegalArgumentException;
+/**
+ * Adds the given parameter to the end of the parameter list.
+ * This is a convenience method for <code>setParameters</code>.
+ * The syntax for parameter names is defined by Formal Parameters (JLS2 8.4.1).
+ * The syntax for type names is defined by Formal Parameters (JLS2 8.4.1).
+ * Type names must be specified as they would appear in source code. For
+ * example: <code>"File"</code>, <code>"java.io.File"</code>, or
+ * <code>"int[]"</code>.
+ *
+ * @param type the type name
+ * @param name the parameter name
+ * @exception IllegalArgumentException if <code>null</code> is specified for
+ * either the type or the name
+ * @see #setParameters
+ */
+public void addParameter(String type, String name) throws IllegalArgumentException;
+/**
+ * Returns the body of this method. The method body includes all code following
+ * the method declaration, including the enclosing braces.
+ *
+ * @return the body, or <code>null</code> if the method has no body (for
+ * example, for an abstract or native method)
+ */
+public String getBody();
+/**
+ * Returns the names of the exception types this method throws
+ * in the order in which they are declared in the source, or an empty array
+ * if this method declares no exception types.
+ * The syntax for an exception type name is defined by Method Throws (JLS2 8.4.4).
+ * Type names appear as they would in source code. For example:
+ * <code>"IOException"</code> or <code>"java.io.IOException"</code>.
+ *
+ * @return the list of exception types
+ */
+public String[] getExceptions();
+/**
+ * The <code>IDOMMethod</code> refinement of this <code>IDOMNode</code>
+ * method returns the name of this method. Returns <code>null</code> for
+ * constructors. The syntax for a method name is defined by Identifer
+ * of MethodDeclarator (JLS2 8.4).
+ */
+public String getName();
+/**
+ * Returns the names of parameters in this method in the order they are declared,
+ * or <code>null</code> if no parameters are declared.
+ * The syntax for parameter names is defined by Formal Parameters (JLS2 8.4.1).
+ *
+ * @return the list of parameter names, or <code>null</code> if no parameters
+ * are declared
+ */
+public String[] getParameterNames();
+/**
+ * Returns the type names for the parameters of this method in the order they are declared,
+ * or <code>null</code> if no parameters are declared.
+ * The syntax for type names is defined by Formal Parameters (JLS2 8.4.1).
+ * Type names must be specified as they would appear in source code. For
+ * example: <code>"File"</code>, <code>"java.io.File"</code>, or
+ * <code>"int[]"</code>.
+ *
+ * @return the list of parameter types, or <code>null</code> if no parameters
+ * are declared
+ */
+public String[] getParameterTypes();
+/**
+ * Returns the return type name, or <code>"void"</code>.
+ * Returns <code>"void"</code> for constructors.
+ * The syntax for return type name corresponds to ReturnType in
+ * MethodDeclaration (JLS2 8.4). Names are returned as they appear in the source
+ * code; for example: <code>"File"</code>, <code>"java.io.File"</code>,
+ * <code>"int[]"</code>, or <code>"void"</code>.
+ *
+ * @return the return type
+ */
+public String getReturnType();
+/**
+ * Returns whether this method is a constructor.
+ *
+ * @return <code>true</code> for constructors, and <code>false</code> for methods
+ */
+public boolean isConstructor();
+/**
+ * Sets the body of this method. The method body includes all code following
+ * the method declaration, including the enclosing braces. No formatting or
+ * syntax checking is performed on the body.
+ *
+ * @return the body, or <code>null</code> indicating the method has no body (for
+ * example, for an abstract or native method)
+ */
+public void setBody(String body);
+/**
+ * Sets whether this method represents a constructor.
+ *
+ * @param b <code>true</code> for constructors, and <code>false</code> for methods
+ */
+public void setConstructor(boolean b);
+/**
+ * Sets the names of the exception types this method throws,
+ * in the order in which they are declared in the source. An empty array
+ * indicates this method declares no exception types.
+ * The syntax for an exception type name is defined by Method Throws (JLS2 8.4.4).
+ * Type names must be specified as they would appear in source code. For
+ * example: <code>"IOException"</code> or <code>"java.io.IOException"</code>.
+ *
+ * @param exceptionTypes the list of exception types
+ */
+public void setExceptions(String[] exceptionTypes);
+/**
+ * The <code>IDOMMethod</code> refinement of this <code>IDOMNode</code>
+ * method sets the name of this method. The syntax for a method
+ * name is defined by Identifer of MethodDeclarator (JLS2 8.4).
+ * <p>
+ * The name of a constructor is always <code>null</code> and thus it
+ * must not be set.
+ * </p>
+ *
+ * @exception IllegalArgumentException if <code>null</code> is specified
+ */
+public void setName(String name) throws IllegalArgumentException;
+/**
+ * Sets the types and names of parameters in this method in the order they are
+ * to be declared. If both <code>types</code> and <code>names</code> are <code>null</code>
+ * this indicates that this method has no parameters.
+ * The syntax for parameter names is defined by Formal Parameters (JLS2 8.4.1).
+ * The syntax for type names is defined by Formal Parameters (JLS2 8.4.1).
+ * Type names must be specified as they would appear in source code. For
+ * example: <code>"File"</code>, <code>"java.io.File"</code>, or
+ * <code>"int[]"</code>.
+ *
+ * @param types the list of type names
+ * @param names the list of parameter name
+ * @exception IllegalArgumentException if the number of types and names do not
+ * match, or if either argument is <code>null</code>
+ */
+public void setParameters(String[] types, String[] names) throws IllegalArgumentException;
+/**
+ * Sets the return type name. This has no effect on constructors.
+ * The syntax for return type name corresponds to ReturnType in
+ * MethodDeclaration (JLS2 8.4). Type names are specified as they appear in the
+ * source code; for example: <code>"File"</code>, <code>"java.io.File"</code>,
+ * <code>"int[]"</code>, or <code>"void"</code>.
+ *
+ * @param type the return type
+ * @exception IllegalArgumentException if <code>null</code> is specified
+ */
+public void setReturnType(String type) throws IllegalArgumentException;
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMNode.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMNode.java
index ae6d79fda2..e0d2a7f711 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMNode.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMNode.java
@@ -48,226 +48,223 @@ import java.util.Enumeration;
* This interface is not intended to be implemented by clients.
* </p>
*/
-public interface IDOMNode extends Cloneable {
+public interface IDOMNode extends Cloneable {
/**
* Node type constant indicating a compilation unit.
* Nodes of this type maybe by safely cast to <code>IDOMCompilationUnit</code>.
* @see #getNodeType
*/
- public static int COMPILATION_UNIT = 1;
-
+ public static int COMPILATION_UNIT= 1;
+
/**
* Node type constant indicating a package declaration.
* Nodes of this type maybe by safely cast to <code>IDOMPackage</code>.
* @see #getNodeType
*/
- public static int PACKAGE = 2;
-
+ public static int PACKAGE= 2;
+
/**
* Node type constant indicating an import declaration.
* Nodes of this type maybe by safely cast to <code>IDOMImport</code>.
* @see #getNodeType
*/
- public static int IMPORT = 3;
-
+ public static int IMPORT= 3;
+
/**
* Node type constant indicating a type declaration.
* Nodes of this type maybe by safely cast to <code>IDOMType</code>.
* @see #getNodeType
*/
- public static int TYPE = 4;
-
+ public static int TYPE= 4;
+
/**
* Node type constant indicating a field declaration.
* Nodes of this type maybe by safely cast to <code>IDOMField</code>.
* @see #getNodeType
*/
- public static int FIELD = 5;
-
+ public static int FIELD= 5;
+
/**
* Node type constant indicating a method (or constructor) declaration.
* Nodes of this type maybe by safely cast to <code>IDOMMethod</code>.
* @see #getNodeType
*/
- public static int METHOD = 6;
-
+ public static int METHOD= 6;
+
/**
* Node type constant indicating an initializer declaration.
* Nodes of this type maybe by safely cast to <code>IDOMInitializer</code>.
* @see #getNodeType
*/
- public static int INITIALIZER = 7;
-
- /**
- * Adds the given un-parented node (document fragment) as the last child of this node.
- *
- * @param child the new child node
- * @exception DOMException if any of the following conditions hold:<ul>
- * <li>this node is not allowed to have children,</li>
- * <li>the child is not of an allowable type</li>
- * <li>the child already has a parent</li>
- * <li>the child is an ancestor of this node</li>
- * </ul>
- * @exception IllegalArgumentException if the child is <code>null</code>
- *
- * @see #insertSibling
- * @see #remove
- */
- public void addChild(IDOMNode child)
- throws DOMException, IllegalArgumentException;
- /**
- * Returns whether this node is allowed to have children.
- *
- * @return <code>true</code> if this node can have children
- */
- public boolean canHaveChildren();
- /**
- * Returns a stand-alone copy of the document fragment represented by this node that
- * is in no way dependent on the document this node is part of.
- *
- * @return a copy of type <code>IDOMNode</code>
- * @see #addChild
- * @see #insertSibling
- * @see #remove
- */
- public Object clone();
- /**
- * Returns the current contents of this document fragment as a character array.
- * <p>
- * Note: To obtain complete source for the".java" file, ask a compilation unit
- * node for its contents.
- * </p>
- *
- * @return the contents, or <code>null</code> if this node has no contents
- */
- public char[] getCharacters();
- /**
- * Returns the first named child of this node with the given name.
- *
- * @param name the name
- * @return the child node, or <code>null</code> if no such child exists
- */
- public IDOMNode getChild(String name);
- /**
- * Returns an enumeration of children of this node. Returns an empty enumeration
- * if this node has no children (including nodes that cannot have children).
- * Children appear in the order in which they are declared in the source code.
- *
- * @return an enumeration of the children
- */
- public Enumeration getChildren();
- /**
- * Returns the current contents of this document fragment.
- * <p>
- * Note: To obtain complete source for the".java" file, ask a compilation unit
- * node for its contents.
- * </p>
- *
- * @return the contents, or <code>null</code> if this node has no contents
- */
- public String getContents();
- /**
- * Returns the first child of this node.
- * Children appear in the order in which they exist in the source code.
- *
- * @return the first child, or <code>null</code> if this node has no children
- * @see #getChildren
- */
- public IDOMNode getFirstChild();
- /**
- * Returns a handle for the Java element associated with this
- * document fragment, based on the parent Java element.
- *
- * @param parent the parent Java element
- * @exception IllegalArgumentException if the parent element is not
- * of a valid parent type for this node
- */
- public IJavaElement getJavaElement(IJavaElement parent)
- throws IllegalArgumentException;
- /**
- * Returns the name of this node.
- * More details are provided in each of the subtypes.
- *
- * @return the name, or <code>null</code> if it has no name
- */
- public String getName();
- /**
- * Returns the sibling node immediately following this node.
- *
- * @return the next node, or <code>null</code> if there is no following node
- */
- public IDOMNode getNextNode();
- /**
- * Returns the type of this node.
- *
- * @return one of the node type constants defined in <code>IDOMNode</code>
- */
- public int getNodeType();
- /**
- * Returns the parent of this node.
- *
- * @return the parent node, or <code>null</code> if this node does not have a
- * parent
- */
- public IDOMNode getParent();
- /**
- * Returns the sibling node immediately preceding this node.
- *
- * @return the previous node, or <code>null</code> if there is no preceding node
- */
- public IDOMNode getPreviousNode();
- /**
- * Inserts the given un-parented node as a sibling of this node, immediately before
- * this node.
- *
- * @param sibling the new sibling node
- * @exception DOMException if any of the following conditions hold:<ul>
- * <li>this node is a document fragment root</li>
- * <li>the sibling is not of the correct type</li>
- * <li>the sibling already has a parent</li>
- * <li>this sibling is an ancestor of this node</li>
- * </ul>
- * @exception IllegalArgumentException if the sibling is <code>null</code>
- *
- * @see #addChild
- * @see #clone
- * @see #remove
- */
- public void insertSibling(IDOMNode sibling)
- throws DOMException, IllegalArgumentException;
- /**
- * Returns whether the given node is an allowable child for this node.
- *
- * @param node the potential child node
- * @return <code>true</code> if the given node is an allowable child
- */
- public boolean isAllowableChild(IDOMNode node);
- /**
- * Returns whether this node's signature is equivalent to the given
- * node's signature. In other words, if the nodes were siblings,
- * would the declarations collide because they represent the same declaration.
- *
- * @param node the other node
- * @return <code>true</code> if the nodes have equivalent signatures
- */
- public boolean isSignatureEqual(IDOMNode node);
- /**
- * Separates this node from its parent and siblings, maintaing any ties that this node
- * has to the underlying document fragment. A document fragment that is removed
- * from its host document may still be dependent on that host document until it is
- * inserted into a different document. Removing a root node has no effect.
- *
- * @see #addChild
- * @see #clone
- * @see #insertSibling
- */
- public void remove();
- /**
- * Sets the name of this node. Name format depends on node type.
- * More details are provided in each of the subtypes.
- *
- * @param name the name, or <code>null</code> to clear the name
- */
- public void setName(String name);
+ public static int INITIALIZER= 7;
+
+/**
+ * Adds the given un-parented node (document fragment) as the last child of this node.
+ *
+ * @param child the new child node
+ * @exception DOMException if any of the following conditions hold:<ul>
+ * <li>this node is not allowed to have children,</li>
+ * <li>the child is not of an allowable type</li>
+ * <li>the child already has a parent</li>
+ * <li>the child is an ancestor of this node</li>
+ * </ul>
+ * @exception IllegalArgumentException if the child is <code>null</code>
+ *
+ * @see #insertSibling
+ * @see #remove
+ */
+public void addChild(IDOMNode child) throws DOMException, IllegalArgumentException;
+/**
+ * Returns whether this node is allowed to have children.
+ *
+ * @return <code>true</code> if this node can have children
+ */
+public boolean canHaveChildren();
+/**
+ * Returns a stand-alone copy of the document fragment represented by this node that
+ * is in no way dependent on the document this node is part of.
+ *
+ * @return a copy of type <code>IDOMNode</code>
+ * @see #addChild
+ * @see #insertSibling
+ * @see #remove
+ */
+public Object clone();
+/**
+ * Returns the current contents of this document fragment as a character array.
+ * <p>
+ * Note: To obtain complete source for the".java" file, ask a compilation unit
+ * node for its contents.
+ * </p>
+ *
+ * @return the contents, or <code>null</code> if this node has no contents
+ */
+public char[] getCharacters();
+/**
+ * Returns the first named child of this node with the given name.
+ *
+ * @param name the name
+ * @return the child node, or <code>null</code> if no such child exists
+ */
+public IDOMNode getChild(String name);
+/**
+ * Returns an enumeration of children of this node. Returns an empty enumeration
+ * if this node has no children (including nodes that cannot have children).
+ * Children appear in the order in which they are declared in the source code.
+ *
+ * @return an enumeration of the children
+ */
+public Enumeration getChildren();
+/**
+ * Returns the current contents of this document fragment.
+ * <p>
+ * Note: To obtain complete source for the".java" file, ask a compilation unit
+ * node for its contents.
+ * </p>
+ *
+ * @return the contents, or <code>null</code> if this node has no contents
+ */
+public String getContents();
+/**
+ * Returns the first child of this node.
+ * Children appear in the order in which they exist in the source code.
+ *
+ * @return the first child, or <code>null</code> if this node has no children
+ * @see #getChildren
+ */
+public IDOMNode getFirstChild();
+/**
+ * Returns a handle for the Java element associated with this
+ * document fragment, based on the parent Java element.
+ *
+ * @param parent the parent Java element
+ * @exception IllegalArgumentException if the parent element is not
+ * of a valid parent type for this node
+ */
+public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException;
+/**
+ * Returns the name of this node.
+ * More details are provided in each of the subtypes.
+ *
+ * @return the name, or <code>null</code> if it has no name
+ */
+public String getName();
+/**
+ * Returns the sibling node immediately following this node.
+ *
+ * @return the next node, or <code>null</code> if there is no following node
+ */
+public IDOMNode getNextNode();
+/**
+ * Returns the type of this node.
+ *
+ * @return one of the node type constants defined in <code>IDOMNode</code>
+ */
+public int getNodeType();
+/**
+ * Returns the parent of this node.
+ *
+ * @return the parent node, or <code>null</code> if this node does not have a
+ * parent
+ */
+public IDOMNode getParent();
+/**
+ * Returns the sibling node immediately preceding this node.
+ *
+ * @return the previous node, or <code>null</code> if there is no preceding node
+ */
+public IDOMNode getPreviousNode();
+/**
+ * Inserts the given un-parented node as a sibling of this node, immediately before
+ * this node.
+ *
+ * @param sibling the new sibling node
+ * @exception DOMException if any of the following conditions hold:<ul>
+ * <li>this node is a document fragment root</li>
+ * <li>the sibling is not of the correct type</li>
+ * <li>the sibling already has a parent</li>
+ * <li>this sibling is an ancestor of this node</li>
+ * </ul>
+ * @exception IllegalArgumentException if the sibling is <code>null</code>
+ *
+ * @see #addChild
+ * @see #clone
+ * @see #remove
+ */
+public void insertSibling(IDOMNode sibling) throws DOMException, IllegalArgumentException;
+/**
+ * Returns whether the given node is an allowable child for this node.
+ *
+ * @param node the potential child node
+ * @return <code>true</code> if the given node is an allowable child
+ */
+public boolean isAllowableChild(IDOMNode node);
+/**
+ * Returns whether this node's signature is equivalent to the given
+ * node's signature. In other words, if the nodes were siblings,
+ * would the declarations collide because they represent the same declaration.
+ *
+ * @param node the other node
+ * @return <code>true</code> if the nodes have equivalent signatures
+ */
+public boolean isSignatureEqual(IDOMNode node);
+/**
+ * Separates this node from its parent and siblings, maintaing any ties that this node
+ * has to the underlying document fragment. A document fragment that is removed
+ * from its host document may still be dependent on that host document until it is
+ * inserted into a different document. Removing a root node has no effect.
+ *
+ * @see #addChild
+ * @see #clone
+ * @see #insertSibling
+ */
+public void remove();
+/**
+ * Sets the name of this node. Name format depends on node type.
+ * More details are provided in each of the subtypes.
+ *
+ * @param name the name, or <code>null</code> to clear the name
+ */
+public void setName(String name);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMPackage.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMPackage.java
index 2771fdef74..5231e29735 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMPackage.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMPackage.java
@@ -1,19 +1,19 @@
package org.eclipse.jdt.core.jdom;
public interface IDOMPackage extends IDOMNode {
- /**
- * The <code>IDOMPackage</code> refinement of this <code>IDOMNode</code>
- * method returns the name of this package declaration, or <code>null</code>
- * if it has none. The syntax for a package name corresponds to PackageName
- * as defined by PackageDeclaration (JLS2 7.4).
- */
- public String getName();
- /**
- * The <code>IDOMPackage</code> refinement of this <code>IDOMNode</code>
- * method sets the name of this package declaration. The syntax for a package
- * name corresponds to PackageName as defined by PackageDeclaration (JLS2 7.4).
- * A <code>null</code> name indicates an empty package declaration; that is,
- * <code>getContents</code> returns the empty string.
- */
- public void setName(String name);
+/**
+ * The <code>IDOMPackage</code> refinement of this <code>IDOMNode</code>
+ * method returns the name of this package declaration, or <code>null</code>
+ * if it has none. The syntax for a package name corresponds to PackageName
+ * as defined by PackageDeclaration (JLS2 7.4).
+ */
+public String getName();
+/**
+ * The <code>IDOMPackage</code> refinement of this <code>IDOMNode</code>
+ * method sets the name of this package declaration. The syntax for a package
+ * name corresponds to PackageName as defined by PackageDeclaration (JLS2 7.4).
+ * A <code>null</code> name indicates an empty package declaration; that is,
+ * <code>getContents</code> returns the empty string.
+ */
+public void setName(String name);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMType.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMType.java
index a760db7d41..d5c1c2be6b 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMType.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/IDOMType.java
@@ -1,105 +1,104 @@
package org.eclipse.jdt.core.jdom;
public interface IDOMType extends IDOMMember {
- /**
- * Adds the given interface name to the names of interfaces that this type implements or extends
- * (the name will be added after the existing interface names). This is a convenience method.
- *
- * For classes, this represents the interfaces that this class implements.
- * For interfaces, this represents the interfaces that this interface extends.
- * The name may or may not be fully qualified.
- *
- * @param interfaceName the syntax for an interface name is defined by
- * Interfaces in ClassDeclaration (JLS2 8.1). Type names must be specified as they would
- * appear in source code. For example: "Cloneable", "java.io.Serializable".
- *
- * @exception IllegalArgumentException if <code>null</code> is specified
- */
- public void addSuperInterface(String interfaceName)
- throws IllegalArgumentException;
- /**
- * The <code>IDOMType</code> refinement of this <code>IDOMNode</code>
- * method returns the name of this type. The name of a class is defined by
- * ClassDeclaration (JLS2 8.1); the name of an interface is defined by
- * InterfaceDeclaration (JLS2 9.1).
- */
- public String getName();
- /**
- * Returns the name of this type's superclass. The syntax for a superclass name
- * is specified by Super in ClassDeclaration (JLS2 8.1). Type names must be
- * specified as they would appear in source code. For example:
- * <code>"Object"</code>, or <code>"java.io.File"</code>.
- *
- * @return the superclass name, or <code>null</code> if this type represents
- * an interface or if no superclass has been assigned to this class
- */
- public String getSuperclass();
- /**
- * Returns the names of interfaces that this type implements or extends,
- * in the order in which they are listed in the source, or an empty array
- * if no superinterfaces are present. The syntax for interface names is
- * defined by Interfaces in ClassDeclaration (JLS2 8.1). Type names appear
- * as they would in source code. For example: <code>"Cloneable"</code>,
- * or <code>"java.io.Serializable"</code>.
- * <p>
- * For classes, this method returns the interfaces that this class implements.
- * For interfaces, this method returns the interfaces that this interface extends.
- * </p>
- *
- * @return the list of interface names
- */
- public String[] getSuperInterfaces();
- /**
- * Returns whether this type is a class.
- *
- * @return <code>true</code> for classes, and <code>false</code> for interfaces
- */
- public boolean isClass();
- /**
- * Sets whether this type is a class or an interface. If this type is
- * a class, and is changed to an interface, this type's superclass
- * becomes <code>null</code>. When a class becomes an interface or an
- * interface becomes a class, superinterfaces remain (as part of an
- * <code>implements</code> clause for classes, or an <code>extends</code>
- * clause for interfaces).
- *
- * @param b <code>true</code> for classes, and <code>false</code> for interfaces
- */
- public void setClass(boolean b);
- /**
- * The <code>IDOMType</code> refinement of this <code>IDOMNode</code>
- * method sets the name of this type. The name of a class is defined by
- * ClassDeclaration (JLS2 8.1); the name of an interface is defined by
- * InterfaceDeclaration (JLS2 9.1).
- *
- * @exception IllegalArgumentException if <code>null</code> is specified
- */
- public void setName(String name) throws IllegalArgumentException;
- /**
- * Sets the name of this type's superclass. Has nbo effect if this type
- * represents an interface. A <code>null</code> name indicates that no
- * superclass name (extends clause) should appear in the source code.
- * The syntax for a superclass name is specified by Super in ClassDeclaration
- * (JLS2 8.1). Type names must be specified as they would appear in source code.
- * For example: <code>"Object"</code>, or <code>"java.io.File"</code>.
- *
- * @param superclassName the superclass name, or <code>null</code> if this type
- * should have to no explicitly specified superclass
- */
- public void setSuperclass(String superclassName);
- /**
- * Sets the names of interfaces that this type implements or extends,
- * in the order in which they are to be listed in the source. An empty array
- * parameter indicates that no superinterfaces are present. The syntax for
- * interface names is defined by Interfaces in ClassDeclaration (JLS2 8.1).
- * Type names appear as they would in source code. For example:
- * <code>"Cloneable"</code>, or <code>"java.io.Serializable"</code>.
- * <p>
- * For classes, this method sets the interfaces that this class implements.
- * For interfaces, this method sets the interfaces that this interface extends.
- * </p>
- *
- * @param interfaceNames the list of interface names
- */
- public void setSuperInterfaces(String[] interfaceNames);
+/**
+ * Adds the given interface name to the names of interfaces that this type implements or extends
+ * (the name will be added after the existing interface names). This is a convenience method.
+ *
+ * For classes, this represents the interfaces that this class implements.
+ * For interfaces, this represents the interfaces that this interface extends.
+ * The name may or may not be fully qualified.
+ *
+ * @param interfaceName the syntax for an interface name is defined by
+ * Interfaces in ClassDeclaration (JLS2 8.1). Type names must be specified as they would
+ * appear in source code. For example: "Cloneable", "java.io.Serializable".
+ *
+ * @exception IllegalArgumentException if <code>null</code> is specified
+ */
+public void addSuperInterface(String interfaceName) throws IllegalArgumentException;
+/**
+ * The <code>IDOMType</code> refinement of this <code>IDOMNode</code>
+ * method returns the name of this type. The name of a class is defined by
+ * ClassDeclaration (JLS2 8.1); the name of an interface is defined by
+ * InterfaceDeclaration (JLS2 9.1).
+ */
+public String getName();
+/**
+ * Returns the name of this type's superclass. The syntax for a superclass name
+ * is specified by Super in ClassDeclaration (JLS2 8.1). Type names must be
+ * specified as they would appear in source code. For example:
+ * <code>"Object"</code>, or <code>"java.io.File"</code>.
+ *
+ * @return the superclass name, or <code>null</code> if this type represents
+ * an interface or if no superclass has been assigned to this class
+ */
+public String getSuperclass();
+/**
+ * Returns the names of interfaces that this type implements or extends,
+ * in the order in which they are listed in the source, or an empty array
+ * if no superinterfaces are present. The syntax for interface names is
+ * defined by Interfaces in ClassDeclaration (JLS2 8.1). Type names appear
+ * as they would in source code. For example: <code>"Cloneable"</code>,
+ * or <code>"java.io.Serializable"</code>.
+ * <p>
+ * For classes, this method returns the interfaces that this class implements.
+ * For interfaces, this method returns the interfaces that this interface extends.
+ * </p>
+ *
+ * @return the list of interface names
+ */
+public String[] getSuperInterfaces();
+/**
+ * Returns whether this type is a class.
+ *
+ * @return <code>true</code> for classes, and <code>false</code> for interfaces
+ */
+public boolean isClass();
+/**
+ * Sets whether this type is a class or an interface. If this type is
+ * a class, and is changed to an interface, this type's superclass
+ * becomes <code>null</code>. When a class becomes an interface or an
+ * interface becomes a class, superinterfaces remain (as part of an
+ * <code>implements</code> clause for classes, or an <code>extends</code>
+ * clause for interfaces).
+ *
+ * @param b <code>true</code> for classes, and <code>false</code> for interfaces
+ */
+public void setClass(boolean b);
+/**
+ * The <code>IDOMType</code> refinement of this <code>IDOMNode</code>
+ * method sets the name of this type. The name of a class is defined by
+ * ClassDeclaration (JLS2 8.1); the name of an interface is defined by
+ * InterfaceDeclaration (JLS2 9.1).
+ *
+ * @exception IllegalArgumentException if <code>null</code> is specified
+ */
+public void setName(String name) throws IllegalArgumentException;
+/**
+ * Sets the name of this type's superclass. Has nbo effect if this type
+ * represents an interface. A <code>null</code> name indicates that no
+ * superclass name (extends clause) should appear in the source code.
+ * The syntax for a superclass name is specified by Super in ClassDeclaration
+ * (JLS2 8.1). Type names must be specified as they would appear in source code.
+ * For example: <code>"Object"</code>, or <code>"java.io.File"</code>.
+ *
+ * @param superclassName the superclass name, or <code>null</code> if this type
+ * should have to no explicitly specified superclass
+ */
+public void setSuperclass(String superclassName);
+/**
+ * Sets the names of interfaces that this type implements or extends,
+ * in the order in which they are to be listed in the source. An empty array
+ * parameter indicates that no superinterfaces are present. The syntax for
+ * interface names is defined by Interfaces in ClassDeclaration (JLS2 8.1).
+ * Type names appear as they would in source code. For example:
+ * <code>"Cloneable"</code>, or <code>"java.io.Serializable"</code>.
+ * <p>
+ * For classes, this method sets the interfaces that this class implements.
+ * For interfaces, this method sets the interfaces that this interface extends.
+ * </p>
+ *
+ * @param interfaceNames the list of interface names
+ */
+public void setSuperInterfaces(String[] interfaceNames);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/package.html b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/package.html
new file mode 100644
index 0000000000..8227a410e4
--- /dev/null
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/jdom/package.html
@@ -0,0 +1,17 @@
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <meta name="Author" content="IBM">
+ <meta name="GENERATOR" content="Mozilla/4.75 [en] (Windows NT 5.0; U) [Netscape]">
+ <title>Package-level Javadoc</title>
+</head>
+<body>
+Provides a support for java document manipulation
+throught the JDOM model.
+<h2>
+Package Specification</h2>
+This package provides a support for java document manipulation throught
+the JDOM model.
+</body>
+</html>
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/core/package.html b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/package.html
new file mode 100644
index 0000000000..f3a3cf52ce
--- /dev/null
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/core/package.html
@@ -0,0 +1,19 @@
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <meta name="Author" content="IBM">
+ <meta name="GENERATOR" content="Mozilla/4.73 [en] (Windows NT 5.0; U) [Netscape]">
+ <title>Package-level Javadoc</title>
+</head>
+<body>
+The Java model is the set of classes that model the
+objects associated with creating, editing, and building a Java program.
+<h2>
+Package Specification</h2>
+
+<p><br>This package contains the Java model classes, which implement Java
+specific behavior for resources and further decompose java resources into
+model elements.
+</body>
+</html>
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Assert.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Assert.java
index e11344898d..707494cf7b 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Assert.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Assert.java
@@ -6,88 +6,82 @@ package org.eclipse.jdt.internal.core;
import org.eclipse.jdt.core.*;
public final class Assert {
- /* This class is not intended to be instantiated. */
- private Assert() {
- }
-
- /** Asserts that an argument is legal. If the given boolean is
- * not <code>true</code>, an <code>IllegalArgumentException</code>
- * is thrown.
- *
- * @param expression the outcode of the check
- * @return <code>true</code> if the check passes (does not return
- * if the check fails)
- * @exception IllegalArgumentException if the legality test failed
- */
- public static boolean isLegal(boolean expression) {
- return isLegal(expression, "");
- }
-
- /** Asserts that an argument is legal. If the given boolean is
- * not <code>true</code>, an <code>IllegalArgumentException</code>
- * is thrown.
- * The given message is included in that exception, to aid debugging.
- *
- * @param expression the outcode of the check
- * @param message the message to include in the exception
- * @return <code>true</code> if the check passes (does not return
- * if the check fails)
- * @exception IllegalArgumentException if the legality test failed
- */
- public static boolean isLegal(boolean expression, String message) {
- if (!expression)
- throw new IllegalArgumentException(message);
- return expression;
- }
-
- /** Asserts that the given object is not <code>null</code>. If this
- * is not the case, some kind of unchecked exception is thrown.
- *
- * @param object the value to test
- * @exception IllegalArgumentException if the object is <code>null</code>
- */
- public static void isNotNull(Object object) {
- isNotNull(object, "");
- }
-
- /** Asserts that the given object is not <code>null</code>. If this
- * is not the case, some kind of unchecked exception is thrown.
- * The given message is included in that exception, to aid debugging.
- *
- * @param object the value to test
- * @param message the message to include in the exception
- * @exception IllegalArgumentException if the object is <code>null</code>
- */
- public static void isNotNull(Object object, String message) {
- if (object == null)
- throw new AssertionFailedException("null argument;" + message);
- }
-
- /** Asserts that the given boolean is <code>true</code>. If this
- * is not the case, some kind of unchecked exception is thrown.
- *
- * @param expression the outcode of the check
- * @return <code>true</code> if the check passes (does not return
- * if the check fails)
- */
- public static boolean isTrue(boolean expression) {
- return isTrue(expression, "");
- }
-
- /** Asserts that the given boolean is <code>true</code>. If this
- * is not the case, some kind of unchecked exception is thrown.
- * The given message is included in that exception, to aid debugging.
- *
- * @param expression the outcode of the check
- * @param message the message to include in the exception
- * @return <code>true</code> if the check passes (does not return
- * if the check fails)
- */
- public static boolean isTrue(boolean expression, String message) {
- if (!expression)
- throw new AssertionFailedException("assertion failed; " + message);
- return expression;
- }
+/* This class is not intended to be instantiated. */
+private Assert() {
+}
+/** Asserts that an argument is legal. If the given boolean is
+ * not <code>true</code>, an <code>IllegalArgumentException</code>
+ * is thrown.
+ *
+ * @param expression the outcode of the check
+ * @return <code>true</code> if the check passes (does not return
+ * if the check fails)
+ * @exception IllegalArgumentException if the legality test failed
+ */
+public static boolean isLegal(boolean expression) {
+ return isLegal(expression, ""/*nonNLS*/);
+}
+/** Asserts that an argument is legal. If the given boolean is
+ * not <code>true</code>, an <code>IllegalArgumentException</code>
+ * is thrown.
+ * The given message is included in that exception, to aid debugging.
+ *
+ * @param expression the outcode of the check
+ * @param message the message to include in the exception
+ * @return <code>true</code> if the check passes (does not return
+ * if the check fails)
+ * @exception IllegalArgumentException if the legality test failed
+ */
+public static boolean isLegal(boolean expression, String message) {
+ if (!expression)
+ throw new IllegalArgumentException(message);
+ return expression;
+}
+/** Asserts that the given object is not <code>null</code>. If this
+ * is not the case, some kind of unchecked exception is thrown.
+ *
+ * @param object the value to test
+ * @exception IllegalArgumentException if the object is <code>null</code>
+ */
+public static void isNotNull(Object object) {
+ isNotNull(object, ""/*nonNLS*/);
+}
+/** Asserts that the given object is not <code>null</code>. If this
+ * is not the case, some kind of unchecked exception is thrown.
+ * The given message is included in that exception, to aid debugging.
+ *
+ * @param object the value to test
+ * @param message the message to include in the exception
+ * @exception IllegalArgumentException if the object is <code>null</code>
+ */
+public static void isNotNull(Object object, String message) {
+ if (object == null)
+ throw new AssertionFailedException(Util.bind("assert.nullArgument"/*nonNLS*/,message));
+}
+/** Asserts that the given boolean is <code>true</code>. If this
+ * is not the case, some kind of unchecked exception is thrown.
+ *
+ * @param expression the outcode of the check
+ * @return <code>true</code> if the check passes (does not return
+ * if the check fails)
+ */
+public static boolean isTrue(boolean expression) {
+ return isTrue(expression, ""/*nonNLS*/);
+}
+/** Asserts that the given boolean is <code>true</code>. If this
+ * is not the case, some kind of unchecked exception is thrown.
+ * The given message is included in that exception, to aid debugging.
+ *
+ * @param expression the outcode of the check
+ * @param message the message to include in the exception
+ * @return <code>true</code> if the check passes (does not return
+ * if the check fails)
+ */
+public static boolean isTrue(boolean expression, String message) {
+ if (!expression)
+ throw new AssertionFailedException(Util.bind("assert.failed"/*nonNLS*/, message));
+ return expression;
+}
public static class AssertionFailedException extends RuntimeException {
public AssertionFailedException() {
@@ -96,5 +90,4 @@ public final class Assert {
super(detail);
}
}
-
-}
+} \ No newline at end of file
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BasicCompilationUnit.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BasicCompilationUnit.java
index 531fb5fa4a..7f9ec6723d 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BasicCompilationUnit.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BasicCompilationUnit.java
@@ -12,74 +12,69 @@ import java.io.*;
* for use in the <code>SourceMapper</code>./
* @see ICompilationUnit
*/
-
+
public class BasicCompilationUnit implements ICompilationUnit {
protected char[] contents;
protected char[] fileName;
protected char[] mainTypeName;
- public BasicCompilationUnit(char[] contents, String fileName) {
- this.contents = contents;
- this.fileName = fileName.toCharArray();
-
- int start = fileName.lastIndexOf("/") + 1;
- if (start == 0 || start < fileName.lastIndexOf("\\"))
- start = fileName.lastIndexOf("\\") + 1;
+public BasicCompilationUnit(char[] contents, String fileName) {
+ this.contents = contents;
+ this.fileName = fileName.toCharArray();
- int end = fileName.lastIndexOf(".");
- if (end == -1)
- end = fileName.length();
+ int start = fileName.lastIndexOf("/"/*nonNLS*/) + 1;
+ if (start == 0 || start < fileName.lastIndexOf("\\"/*nonNLS*/))
+ start = fileName.lastIndexOf("\\"/*nonNLS*/) + 1;
- this.mainTypeName = fileName.substring(start, end).toCharArray();
- }
+ int end = fileName.lastIndexOf("."/*nonNLS*/);
+ if (end == -1)
+ end = fileName.length();
- public char[] getContents() {
- if (contents != null)
- return contents; // answer the cached source
+ this.mainTypeName = fileName.substring(start, end).toCharArray();
+}
+public char[] getContents() {
+ if (contents != null)
+ return contents; // answer the cached source
- // otherwise retrieve it
- BufferedReader reader = null;
- try {
- File file = new File(new String(fileName));
- reader = new BufferedReader(new FileReader(file));
- int length;
- char[] contents = new char[length = (int) file.length()];
- int len = 0;
- int readSize = 0;
- while ((readSize != -1) && (len != length)) {
- // See PR 1FMS89U
- // We record first the read size. In this case len is the actual read size.
- len += readSize;
- readSize = reader.read(contents, len, length - len);
- }
- reader.close();
+ // otherwise retrieve it
+ BufferedReader reader = null;
+ try {
+ File file = new File(new String(fileName));
+ reader = new BufferedReader(new FileReader(file));
+ int length;
+ char[] contents = new char[length = (int) file.length()];
+ int len = 0;
+ int readSize = 0;
+ while ((readSize != -1) && (len != length)) {
// See PR 1FMS89U
- // Now we need to resize in case the default encoding used more than one byte for each
- // character
- if (len != length)
- System.arraycopy(contents, 0, (contents = new char[len]), 0, len);
- return contents;
- } catch (FileNotFoundException e) {
- } catch (IOException e) {
- if (reader != null) {
- try {
- reader.close();
- } catch (IOException ioe) {
- }
+ // We record first the read size. In this case len is the actual read size.
+ len += readSize;
+ readSize = reader.read(contents, len, length - len);
+ }
+ reader.close();
+ // See PR 1FMS89U
+ // Now we need to resize in case the default encoding used more than one byte for each
+ // character
+ if (len != length)
+ System.arraycopy(contents, 0, (contents = new char[len]), 0, len);
+ return contents;
+ } catch (FileNotFoundException e) {
+ } catch (IOException e) {
+ if (reader != null) {
+ try {
+ reader.close();
+ } catch(IOException ioe) {
}
- };
- return new char[0];
- }
-
- public char[] getFileName() {
- return fileName;
- }
-
- public char[] getMainTypeName() {
- return mainTypeName;
- }
-
- public String toString() {
- return "CompilationUnit: " + new String(fileName);
- }
-
+ }
+ };
+ return new char[0];
+}
+public char[] getFileName() {
+ return fileName;
+}
+public char[] getMainTypeName() {
+ return mainTypeName;
+}
+public String toString(){
+ return "CompilationUnit: "/*nonNLS*/+new String(fileName);
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryField.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryField.java
index 567c08dace..dec53666d2 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryField.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryField.java
@@ -13,45 +13,39 @@ import org.eclipse.jdt.core.*;
* @see IField
*/
-/* package */
-class BinaryField extends BinaryMember implements IField {
-
- /**
- * Constructs a handle to the field with the given name in the specified type.
- */
- protected BinaryField(IType parent, String name) {
- super(FIELD, parent, name);
- }
-
- /**
- * @see IField
- */
- public Object getConstant() throws JavaModelException {
- IBinaryField info = (IBinaryField) getRawInfo();
- return convertConstant(info.getConstant());
- }
-
- /**
- * @see IMember
- */
- public int getFlags() throws JavaModelException {
- IBinaryField info = (IBinaryField) getRawInfo();
- return info.getModifiers();
- }
-
- /**
- * @see JavaElement#getHandleMemento()
- */
- protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_FIELD;
- }
-
- /**
- * @see IField
- */
- public String getTypeSignature() throws JavaModelException {
- IBinaryField info = (IBinaryField) getRawInfo();
- return new String(ClassFile.translatedName(info.getTypeName()));
- }
+/* package */ class BinaryField extends BinaryMember implements IField {
+/**
+ * Constructs a handle to the field with the given name in the specified type.
+ */
+protected BinaryField(IType parent, String name) {
+ super(FIELD, parent, name);
+}
+/**
+ * @see IField
+ */
+public Object getConstant() throws JavaModelException {
+ IBinaryField info = (IBinaryField) getRawInfo();
+ return convertConstant(info.getConstant());
+}
+/**
+ * @see IMember
+ */
+public int getFlags() throws JavaModelException {
+ IBinaryField info = (IBinaryField) getRawInfo();
+ return info.getModifiers();
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+protected char getHandleMementoDelimiter() {
+ return JavaElement.JEM_FIELD;
+}
+/**
+ * @see IField
+ */
+public String getTypeSignature() throws JavaModelException {
+ IBinaryField info = (IBinaryField) getRawInfo();
+ return new String(ClassFile.translatedName(info.getTypeName()));
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryMember.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryMember.java
index 944507d67e..c53d208971 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryMember.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryMember.java
@@ -13,116 +13,86 @@ import org.eclipse.jdt.core.*;
* Common functionality for Binary member handles.
*/
public class BinaryMember extends Member {
- /**
- * Constructs a binary member.
- */
- protected BinaryMember(int type, IJavaElement parent, String name) {
- super(type, parent, name);
- }
-
- /**
- * @see ISourceManipulation
- */
- public void copy(
- IJavaElement container,
- IJavaElement sibling,
- String rename,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
- }
-
- /**
- * @see ISourceReference
- */
- public ISourceRange getNameRange() {
- SourceMapper mapper = getSourceMapper();
- if (mapper != null) {
- return mapper.getNameRange(this);
- } else {
- return SourceMapper.fgUnknownRange;
- }
- }
-
- /**
- * @see ISourceReference
- */
- public ISourceRange getSourceRange() throws JavaModelException {
- SourceMapper mapper = getSourceMapper();
- if (mapper != null) {
- return mapper.getSourceRange(this);
- } else {
- return SourceMapper.fgUnknownRange;
- }
- }
-
- /**
- * @see IMember
- */
- public boolean isBinary() {
- return true;
- }
-
- /**
- * @see IJavaElement
- */
- public boolean isStructureKnown() throws JavaModelException {
- return ((IJavaElement) getOpenableParent()).isStructureKnown();
+/**
+ * Constructs a binary member.
+ */
+protected BinaryMember(int type, IJavaElement parent, String name) {
+ super(type, parent, name);
+}
+/**
+ * @see ISourceManipulation
+ */
+public void copy(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
+}
+/**
+ * @see ISourceReference
+ */
+public ISourceRange getNameRange() {
+ SourceMapper mapper= getSourceMapper();
+ if (mapper != null) {
+ return mapper.getNameRange(this);
+ } else {
+ return SourceMapper.fgUnknownRange;
}
-
- /**
- * @see ISourceManipulation
- */
- public void move(
- IJavaElement container,
- IJavaElement sibling,
- String rename,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
+}
+/**
+ * @see ISourceReference
+ */
+public ISourceRange getSourceRange() throws JavaModelException {
+ SourceMapper mapper= getSourceMapper();
+ if (mapper != null) {
+ return mapper.getSourceRange(this);
+ } else {
+ return SourceMapper.fgUnknownRange;
}
-
- /**
- * Opens this element and all parents that are not already open.
- *
- * @exception NotPresentException this element is not present or accessable
- */
- protected void openHierarchy() throws JavaModelException {
- Openable openableParent = (Openable) getOpenableParent();
- if (openableParent != null) {
- JavaElementInfo openableParentInfo =
- (JavaElementInfo) fgJavaModelManager.getInfo((IJavaElement) openableParent);
- if (openableParentInfo == null) {
- openableParent.openWhenClosed(null);
- openableParentInfo =
- (JavaElementInfo) fgJavaModelManager.getInfo((IJavaElement) openableParent);
- }
- ClassFileInfo cfi = (ClassFileInfo) openableParentInfo;
- cfi.getBinaryChildren(); // forces the initialization
+}
+/**
+ * @see IMember
+ */
+public boolean isBinary() {
+ return true;
+}
+/**
+ * @see IJavaElement
+ */
+public boolean isStructureKnown() throws JavaModelException {
+ return ((IJavaElement)getOpenableParent()).isStructureKnown();
+}
+/**
+ * @see ISourceManipulation
+ */
+public void move(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
+}
+/**
+ * Opens this element and all parents that are not already open.
+ *
+ * @exception NotPresentException this element is not present or accessable
+ */
+protected void openHierarchy() throws JavaModelException {
+ Openable openableParent = (Openable)getOpenableParent();
+ if (openableParent != null) {
+ JavaElementInfo openableParentInfo = (JavaElementInfo) fgJavaModelManager.getInfo((IJavaElement) openableParent);
+ if (openableParentInfo == null) {
+ openableParent.openWhenClosed(null);
+ openableParentInfo = (JavaElementInfo) fgJavaModelManager.getInfo((IJavaElement) openableParent);
}
+ ClassFileInfo cfi = (ClassFileInfo) openableParentInfo;
+ cfi.getBinaryChildren(); // forces the initialization
}
-
- /**
- * @see ISourceManipulation
- */
- public void rename(String name, boolean force, IProgressMonitor monitor)
- throws JavaModelException {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
- }
-
- /**
- * Sets the contents of this element.
- * Throws an exception as this element is read only.
- */
- public void setContents(String contents, IProgressMonitor monitor)
- throws JavaModelException {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
- }
-
+}
+/**
+ * @see ISourceManipulation
+ */
+public void rename(String name, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
+}
+/**
+ * Sets the contents of this element.
+ * Throws an exception as this element is read only.
+ */
+public void setContents(String contents, IProgressMonitor monitor) throws JavaModelException {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryMethod.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryMethod.java
index 7b634e949a..0616e24f54 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryMethod.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryMethod.java
@@ -13,8 +13,7 @@ import org.eclipse.jdt.core.*;
* @see IMethod
*/
-/* package */
-class BinaryMethod extends BinaryMember implements IMethod {
+/* package */ class BinaryMethod extends BinaryMember implements IMethod {
/**
* The parameter type signatures of the method - stored locally
@@ -30,159 +29,140 @@ class BinaryMethod extends BinaryMember implements IMethod {
/**
* An empty list of Strings
*/
- protected static final String[] fgEmptyList = new String[] {
- };
-
+ protected static final String[] fgEmptyList= new String[] {};
protected String[] fExceptionTypes;
protected String fReturnType;
- protected BinaryMethod(IType parent, String name, String[] parameterTypes) {
- super(METHOD, parent, name);
- Assert.isTrue(name.indexOf('.') == -1);
- if (parameterTypes == null) {
- fParameterTypes = fgEmptyList;
- } else {
- fParameterTypes = parameterTypes;
- }
- }
-
- public boolean equals(Object o) {
- return super.equals(o)
- && Util.equalArraysOrNull(fParameterTypes, ((BinaryMethod) o).fParameterTypes);
- }
-
- /**
- * @see IMethod
- */
- public String[] getExceptionTypes() throws JavaModelException {
- if (fExceptionTypes == null) {
- IBinaryMethod info = (IBinaryMethod) getRawInfo();
- char[][] eTypeNames = info.getExceptionTypeNames();
- if (eTypeNames == null || eTypeNames.length == 0) {
- fExceptionTypes = fgEmptyList;
- } else {
- eTypeNames = ClassFile.translatedNames(eTypeNames);
- fExceptionTypes = new String[eTypeNames.length];
- for (int j = 0, length = eTypeNames.length; j < length; j++) {
- // 1G01HRY: ITPJCORE:WINNT - method.getExceptionType not in correct format
- int nameLength = eTypeNames[j].length;
- char[] convertedName = new char[nameLength + 2];
- System.arraycopy(eTypeNames[j], 0, convertedName, 1, nameLength);
- convertedName[0] = 'L';
- convertedName[nameLength + 1] = ';';
- fExceptionTypes[j] = new String(convertedName);
- }
- }
- }
- return fExceptionTypes;
+protected BinaryMethod(IType parent, String name, String[] parameterTypes) {
+ super(METHOD, parent, name);
+ Assert.isTrue(name.indexOf('.') == -1);
+ if (parameterTypes == null) {
+ fParameterTypes= fgEmptyList;
+ } else {
+ fParameterTypes= parameterTypes;
}
-
- /**
- * @see IMember
- */
- public int getFlags() throws JavaModelException {
+}
+public boolean equals(Object o) {
+ return super.equals(o) && Util.equalArraysOrNull(fParameterTypes, ((BinaryMethod)o).fParameterTypes);
+}
+/**
+ * @see IMethod
+ */
+public String[] getExceptionTypes() throws JavaModelException {
+ if (fExceptionTypes == null) {
IBinaryMethod info = (IBinaryMethod) getRawInfo();
- return info.getModifiers();
- }
-
- /**
- * @see JavaElement#getHandleMemento()
- */
- public String getHandleMemento() {
- StringBuffer buff =
- new StringBuffer(((JavaElement) getParent()).getHandleMemento());
- buff.append(getHandleMementoDelimiter());
- buff.append(getElementName());
- for (int i = 0; i < fParameterTypes.length; i++) {
- buff.append(getHandleMementoDelimiter());
- buff.append(fParameterTypes[i]);
- }
- return buff.toString();
- }
-
- /**
- * @see JavaElement#getHandleMemento()
- */
- protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_METHOD;
- }
-
- /**
- * @see IMethod
- */
- public int getNumberOfParameters() {
- return fParameterTypes == null ? 0 : fParameterTypes.length;
- }
-
- /**
- * @see IMethod
- */
- public String[] getParameterNames() throws JavaModelException {
- if (fParameterNames == null) {
- IBinaryMethod info = (IBinaryMethod) getRawInfo();
- int paramCount =
- Signature.getParameterCount(new String(info.getMethodDescriptor()));
- fParameterNames = new String[paramCount];
- for (int i = 0; i < paramCount; i++) {
- fParameterNames[i] = "arg" + i;
+ char[][] eTypeNames = info.getExceptionTypeNames();
+ if (eTypeNames == null || eTypeNames.length == 0) {
+ fExceptionTypes = fgEmptyList;
+ } else {
+ eTypeNames = ClassFile.translatedNames(eTypeNames);
+ fExceptionTypes = new String[eTypeNames.length];
+ for (int j = 0, length = eTypeNames.length; j < length; j++) {
+ // 1G01HRY: ITPJCORE:WINNT - method.getExceptionType not in correct format
+ int nameLength = eTypeNames[j].length;
+ char[] convertedName = new char[nameLength + 2];
+ System.arraycopy(eTypeNames[j], 0, convertedName, 1, nameLength);
+ convertedName[0] = 'L';
+ convertedName[nameLength + 1] = ';';
+ fExceptionTypes[j] = new String(convertedName);
}
}
- return fParameterNames;
}
-
- /**
- * @see IMethod
- */
- public String[] getParameterTypes() {
- return fParameterTypes;
+ return fExceptionTypes;
+}
+/**
+ * @see IMember
+ */
+public int getFlags() throws JavaModelException {
+ IBinaryMethod info = (IBinaryMethod) getRawInfo();
+ return info.getModifiers();
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+public String getHandleMemento() {
+ StringBuffer buff = new StringBuffer(((JavaElement) getParent()).getHandleMemento());
+ buff.append(getHandleMementoDelimiter());
+ buff.append(getElementName());
+ for (int i = 0; i < fParameterTypes.length; i++) {
+ buff.append(getHandleMementoDelimiter());
+ buff.append(fParameterTypes[i]);
}
-
- /**
- * @see IMethod
- */
- public String getReturnType() throws JavaModelException {
+ return buff.toString();
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+protected char getHandleMementoDelimiter() {
+ return JavaElement.JEM_METHOD;
+}
+/**
+ * @see IMethod
+ */
+public int getNumberOfParameters() {
+ return fParameterTypes == null ? 0 : fParameterTypes.length;
+}
+/**
+ * @see IMethod
+ */
+public String[] getParameterNames() throws JavaModelException {
+ if (fParameterNames == null) {
IBinaryMethod info = (IBinaryMethod) getRawInfo();
- if (fReturnType == null) {
- String returnType =
- Signature.getReturnType(new String(info.getMethodDescriptor()));
- fReturnType = new String(ClassFile.translatedName(returnType.toCharArray()));
+ int paramCount = Signature.getParameterCount(new String(info.getMethodDescriptor()));
+ fParameterNames = new String[paramCount];
+ for (int i = 0; i < paramCount; i++) {
+ fParameterNames[i] = "arg"/*nonNLS*/ + i;
}
- return fReturnType;
- }
-
- /**
- * @see IMethod
- */
- public String getSignature() throws JavaModelException {
- IBinaryMethod info = (IBinaryMethod) getRawInfo();
- return new String(info.getMethodDescriptor());
}
-
- /**
- * @see IMethod
- */
- public boolean isConstructor() throws JavaModelException {
- IBinaryMethod info = (IBinaryMethod) getRawInfo();
- return info.isConstructor();
+ return fParameterNames;
+}
+/**
+ * @see IMethod
+ */
+public String[] getParameterTypes() {
+ return fParameterTypes;
+}
+/**
+ * @see IMethod
+ */
+public String getReturnType() throws JavaModelException {
+ IBinaryMethod info = (IBinaryMethod) getRawInfo();
+ if (fReturnType == null) {
+ String returnType= Signature.getReturnType(new String(info.getMethodDescriptor()));
+ fReturnType= new String(ClassFile.translatedName(returnType.toCharArray()));
}
-
- /**
- */
- public String readableName() {
-
- StringBuffer buffer = new StringBuffer(super.readableName());
- buffer.append("(");
- String[] parameterTypes = this.getParameterTypes();
- int length;
- if (parameterTypes != null && (length = parameterTypes.length) > 0) {
- for (int i = 0; i < length; i++) {
- buffer.append(Signature.toString(parameterTypes[i]));
- if (i < length - 1) {
- buffer.append(", ");
- }
+ return fReturnType;
+}
+/**
+ * @see IMethod
+ */
+public String getSignature() throws JavaModelException {
+ IBinaryMethod info = (IBinaryMethod) getRawInfo();
+ return new String(info.getMethodDescriptor());
+}
+/**
+ * @see IMethod
+ */
+public boolean isConstructor() throws JavaModelException {
+ IBinaryMethod info = (IBinaryMethod) getRawInfo();
+ return info.isConstructor();
+}
+/**
+ */
+public String readableName() {
+
+ StringBuffer buffer = new StringBuffer(super.readableName());
+ buffer.append("("/*nonNLS*/);
+ String[] parameterTypes = this.getParameterTypes();
+ int length;
+ if (parameterTypes != null && (length = parameterTypes.length) > 0) {
+ for (int i = 0; i < length; i++) {
+ buffer.append(Signature.toString(parameterTypes[i]));
+ if (i < length - 1) {
+ buffer.append(", "/*nonNLS*/);
}
}
- buffer.append(")");
- return buffer.toString();
}
-
+ buffer.append(")"/*nonNLS*/);
+ return buffer.toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryType.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryType.java
index 83aced1377..49dbcaf257 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryType.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BinaryType.java
@@ -26,388 +26,316 @@ public class BinaryType extends BinaryMember implements IType {
private static final IType[] NO_TYPES = new IType[0];
private static final IInitializer[] NO_INITIALIZERS = new IInitializer[0];
private static final String[] NO_STRINGS = new String[0];
- protected BinaryType(IJavaElement parent, String name) {
- super(TYPE, parent, name);
- Assert.isTrue(name.indexOf('.') == -1);
- }
-
- /**
- * @see IOpenable
- */
- public void close() throws JavaModelException {
- Object info = fgJavaModelManager.peekAtInfo(this);
- if (info != null) {
- ClassFileInfo cfi = getClassFileInfo();
- if (cfi.hasReadBinaryChildren()) {
- try {
- IJavaElement[] children = getChildren();
- for (int i = 0, size = children.length; i < size; ++i) {
- JavaElement child = (JavaElement) children[i];
- child.close();
- }
- } catch (JavaModelException e) {
+protected BinaryType(IJavaElement parent, String name) {
+ super(TYPE, parent, name);
+ Assert.isTrue(name.indexOf('.') == -1);
+}
+/**
+ * @see IOpenable
+ */
+public void close() throws JavaModelException {
+ Object info = fgJavaModelManager.peekAtInfo(this);
+ if (info != null) {
+ ClassFileInfo cfi = getClassFileInfo();
+ if (cfi.hasReadBinaryChildren()) {
+ try {
+ IJavaElement[] children = getChildren();
+ for (int i = 0, size = children.length; i < size; ++i) {
+ JavaElement child = (JavaElement) children[i];
+ child.close();
}
+ } catch (JavaModelException e) {
}
- closing(info);
- fgJavaModelManager.removeInfo(this);
- }
- }
-
- /**
- * Remove my cached children from the Java Model
- */
- protected void closing(Object info) throws JavaModelException {
- ClassFileInfo cfi = getClassFileInfo();
- cfi.removeBinaryChildren();
- }
-
- /**
- * @see IType
- */
- public IField createField(
- String contents,
- IJavaElement sibling,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
- }
-
- /**
- * @see IType
- */
- public IInitializer createInitializer(
- String contents,
- IJavaElement sibling,
- IProgressMonitor monitor)
- throws JavaModelException {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
- }
-
- /**
- * @see IType
- */
- public IMethod createMethod(
- String contents,
- IJavaElement sibling,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
- }
-
- /**
- * @see IType
- */
- public IType createType(
- String contents,
- IJavaElement sibling,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
- }
-
- /**
- * @see IParent
- */
- public IJavaElement[] getChildren() throws JavaModelException {
- // ensure present
- // fix for 1FWWVYT
- if (!exists()) {
- throw newNotPresentException();
}
- // get children
- ClassFileInfo cfi = getClassFileInfo();
- return cfi.getBinaryChildren();
- }
-
- protected ClassFileInfo getClassFileInfo() throws JavaModelException {
- ClassFile cf = (ClassFile) fParent;
- return (ClassFileInfo) cf.getElementInfo();
+ closing(info);
+ fgJavaModelManager.removeInfo(this);
}
-
- /**
- * @see IMember
- */
- public IType getDeclaringType() {
- try {
- char[] enclosingTypeName = ((IBinaryType) getRawInfo()).getEnclosingTypeName();
- if (enclosingTypeName == null) {
- return null;
- }
- enclosingTypeName = ClassFile.unqualifiedName(enclosingTypeName);
- return getPackageFragment()
- .getClassFile(new String(enclosingTypeName) + ".class")
- .getType();
- } catch (JavaModelException npe) {
+}
+/**
+ * Remove my cached children from the Java Model
+ */
+protected void closing(Object info) throws JavaModelException {
+ ClassFileInfo cfi = getClassFileInfo();
+ cfi.removeBinaryChildren();
+}
+/**
+ * @see IType
+ */
+public IField createField(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
+}
+/**
+ * @see IType
+ */
+public IInitializer createInitializer(String contents, IJavaElement sibling, IProgressMonitor monitor) throws JavaModelException {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
+}
+/**
+ * @see IType
+ */
+public IMethod createMethod(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
+}
+/**
+ * @see IType
+ */
+public IType createType(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
+}
+/**
+ * @see IParent
+ */
+public IJavaElement[] getChildren() throws JavaModelException {
+ // ensure present
+ // fix for 1FWWVYT
+ if (!exists()) {
+ throw newNotPresentException();
+ }
+ // get children
+ ClassFileInfo cfi = getClassFileInfo();
+ return cfi.getBinaryChildren();
+}
+protected ClassFileInfo getClassFileInfo() throws JavaModelException {
+ ClassFile cf = (ClassFile) fParent;
+ return (ClassFileInfo) cf.getElementInfo();
+}
+/**
+ * @see IMember
+ */
+public IType getDeclaringType() {
+ try {
+ char[] enclosingTypeName = ((IBinaryType) getRawInfo()).getEnclosingTypeName();
+ if (enclosingTypeName == null) {
return null;
}
- }
-
- /**
- * @see IType#getField
- */
- public IField getField(String name) {
- return new BinaryField(this, name);
- }
-
- /**
- * @see IType
- */
- public IField[] getFields() throws JavaModelException {
- Vector v = getChildrenOfType(FIELD);
- int size;
- if ((size = v.size()) == 0) {
- return NO_FIELDS;
- } else {
- IField[] array = new IField[size];
- v.copyInto(array);
- return array;
- }
- }
-
- /**
- * @see IMember
- */
- public int getFlags() throws JavaModelException {
- IBinaryType info = (IBinaryType) getRawInfo();
- return info.getModifiers();
- }
-
- /**
- * @see IType
- */
- public String getFullyQualifiedName() {
- String packageName = getPackageFragment().getElementName();
- if (packageName.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) {
- return getTypeQualifiedName();
- }
- return packageName + '.' + getTypeQualifiedName();
- }
-
- /**
- * @see IType
- */
- public IInitializer getInitializer(int occurrenceCount) {
- return new Initializer(this, occurrenceCount);
- }
-
- /**
- * @see IType
- */
- public IInitializer[] getInitializers() {
- return NO_INITIALIZERS;
- }
-
- /**
- * @see IType#getMethod
- */
- public IMethod getMethod(String name, String[] parameterTypeSignatures) {
- return new BinaryMethod(this, name, parameterTypeSignatures);
- }
-
- /**
- * @see IType
- */
- public IMethod[] getMethods() throws JavaModelException {
- Vector v = getChildrenOfType(METHOD);
- int size;
- if ((size = v.size()) == 0) {
- return NO_METHODS;
- } else {
- IMethod[] array = new IMethod[size];
- v.copyInto(array);
- return array;
- }
- }
-
- /**
- * @see IType
- */
- public IPackageFragment getPackageFragment() {
- IJavaElement parent = fParent;
- while (parent != null) {
- if (parent.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
- return (IPackageFragment) parent;
- } else {
- parent = parent.getParent();
- }
- }
- Assert.isTrue(false); // should not happen
+ enclosingTypeName = ClassFile.unqualifiedName(enclosingTypeName);
+ return getPackageFragment().getClassFile(new String(enclosingTypeName) + ".class"/*nonNLS*/).getType();
+ } catch (JavaModelException npe) {
return null;
}
-
- /**
- * @see IType#getSuperclassName
- */
- public String getSuperclassName() throws JavaModelException {
- IBinaryType info = (IBinaryType) getRawInfo();
- char[] superclassName = info.getSuperclassName();
- if (superclassName == null) {
- return null;
- }
- return new String(ClassFile.translatedName(superclassName));
+}
+/**
+ * @see IType#getField
+ */
+public IField getField(String name) {
+ return new BinaryField(this, name);
+}
+/**
+ * @see IType
+ */
+public IField[] getFields() throws JavaModelException {
+ Vector v= getChildrenOfType(FIELD);
+ int size;
+ if ((size = v.size()) == 0) {
+ return NO_FIELDS;
+ } else {
+ IField[] array= new IField[size];
+ v.copyInto(array);
+ return array;
}
-
- /**
- * @see IType#getSuperInterfaceNames
- */
- public String[] getSuperInterfaceNames() throws JavaModelException {
- IBinaryType info = (IBinaryType) getRawInfo();
- char[][] names = info.getInterfaceNames();
- int length;
- if (names == null || (length = names.length) == 0) {
- return NO_STRINGS;
- }
- names = ClassFile.translatedNames(names);
- String[] strings = new String[length];
- for (int i = 0; i < length; i++) {
- strings[i] = new String(names[i]);
- }
- return strings;
+}
+/**
+ * @see IMember
+ */
+public int getFlags() throws JavaModelException {
+ IBinaryType info = (IBinaryType) getRawInfo();
+ return info.getModifiers();
+}
+/**
+ * @see IType
+ */
+public String getFullyQualifiedName() {
+ String packageName = getPackageFragment().getElementName();
+ if (packageName.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) {
+ return getTypeQualifiedName();
}
-
- /**
- * @see IType#getType
- */
- public IType getType(String name) {
- IClassFile classFile =
- getPackageFragment().getClassFile(
- getTypeQualifiedName() + "$" + name + ".class");
- return new BinaryType(classFile, name);
+ return packageName + '.' + getTypeQualifiedName();
+}
+/**
+ * @see IType
+ */
+public IInitializer getInitializer(int occurrenceCount) {
+ return new Initializer(this, occurrenceCount);
+}
+/**
+ * @see IType
+ */
+public IInitializer[] getInitializers() {
+ return NO_INITIALIZERS;
+}
+/**
+ * @see IType#getMethod
+ */
+public IMethod getMethod(String name, String[] parameterTypeSignatures) {
+ return new BinaryMethod(this, name, parameterTypeSignatures);
+}
+/**
+ * @see IType
+ */
+public IMethod[] getMethods() throws JavaModelException {
+ Vector v= getChildrenOfType(METHOD);
+ int size;
+ if ((size = v.size()) == 0) {
+ return NO_METHODS;
+ } else {
+ IMethod[] array= new IMethod[size];
+ v.copyInto(array);
+ return array;
}
-
- /**
- * @see IType#getTypeQualifiedName
- */
- public String getTypeQualifiedName() {
- if (fParent.getElementType() == IJavaElement.CLASS_FILE) {
- String name = fParent.getElementName();
- return name.substring(0, name.lastIndexOf('.'));
- }
- if (fParent.getElementType() == IJavaElement.TYPE) {
- return ((IType) fParent).getTypeQualifiedName() + '$' + fName;
+}
+/**
+ * @see IType
+ */
+public IPackageFragment getPackageFragment() {
+ IJavaElement parent = fParent;
+ while (parent != null) {
+ if (parent.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
+ return (IPackageFragment) parent;
}
- Assert.isTrue(false); // should not be reachable
- return null;
- }
-
- /**
- * @see IType
- */
- public IType[] getTypes() throws JavaModelException {
- Vector v = getChildrenOfType(TYPE);
- int size;
- if ((size = v.size()) == 0) {
- return NO_TYPES;
- } else {
- IType[] array = new IType[size];
- v.copyInto(array);
- return array;
+ else {
+ parent = parent.getParent();
}
}
-
- /**
- * @see IParent
- */
- public boolean hasChildren() throws JavaModelException {
- return getChildren().length > 0;
- }
-
- /**
- * @see IType
- */
- public boolean isClass() throws JavaModelException {
- return !isInterface();
- }
-
- /**
- * @see IType#isInterface
- */
- public boolean isInterface() throws JavaModelException {
- IBinaryType info = (IBinaryType) getRawInfo();
- return info.isInterface();
+ Assert.isTrue(false); // should not happen
+ return null;
+}
+/**
+ * @see IType#getSuperclassName
+ */
+public String getSuperclassName() throws JavaModelException {
+ IBinaryType info = (IBinaryType) getRawInfo();
+ char[] superclassName = info.getSuperclassName();
+ if (superclassName == null) {
+ return null;
}
-
- /**
- * @see IType
- */
- public ITypeHierarchy newSupertypeHierarchy(IProgressMonitor monitor)
- throws JavaModelException {
- CreateTypeHierarchyOperation op =
- new CreateTypeHierarchyOperation(
- this,
- SearchEngine.createWorkspaceScope(),
- false);
- runOperation(op, monitor);
- return op.getResult();
+ return new String(ClassFile.translatedName(superclassName));
+}
+/**
+ * @see IType#getSuperInterfaceNames
+ */
+public String[] getSuperInterfaceNames() throws JavaModelException {
+ IBinaryType info = (IBinaryType) getRawInfo();
+ char[][] names= info.getInterfaceNames();
+ int length;
+ if (names == null || (length = names.length) == 0) {
+ return NO_STRINGS;
+ }
+ names= ClassFile.translatedNames(names);
+ String[] strings= new String[length];
+ for (int i= 0; i < length; i++) {
+ strings[i]= new String(names[i]);
+ }
+ return strings;
+}
+/**
+ * @see IType#getType
+ */
+public IType getType(String name) {
+ IClassFile classFile= getPackageFragment().getClassFile(getTypeQualifiedName() + "$"/*nonNLS*/ + name + ".class"/*nonNLS*/);
+ return new BinaryType(classFile, name);
+}
+/**
+ * @see IType#getTypeQualifiedName
+ */
+public String getTypeQualifiedName() {
+ if (fParent.getElementType() == IJavaElement.CLASS_FILE) {
+ String name= fParent.getElementName();
+ return name.substring(0,name.lastIndexOf('.'));
}
-
- /**
- * @see IType
- */
- public ITypeHierarchy newTypeHierarchy(IProgressMonitor monitor)
- throws JavaModelException {
- CreateTypeHierarchyOperation op =
- new CreateTypeHierarchyOperation(
- this,
- SearchEngine.createWorkspaceScope(),
- true);
- runOperation(op, monitor);
- return op.getResult();
+ if (fParent.getElementType() == IJavaElement.TYPE) {
+ return ((IType) fParent).getTypeQualifiedName() + '$' + fName;
}
-
- /**
- * @see IType
- */
- public ITypeHierarchy newTypeHierarchy(
- IJavaProject project,
- IProgressMonitor monitor)
- throws JavaModelException {
- if (project == null) {
- throw new IllegalArgumentException("project argument cannot be null");
- }
- CreateTypeHierarchyOperation op =
- new CreateTypeHierarchyOperation(
- this,
- SearchEngine.createJavaSearchScope(new IResource[] { project.getProject()}),
- true);
- runOperation(op, monitor);
- return op.getResult();
+ Assert.isTrue(false); // should not be reachable
+ return null;
+}
+/**
+ * @see IType
+ */
+public IType[] getTypes() throws JavaModelException {
+ Vector v= getChildrenOfType(TYPE);
+ int size;
+ if ((size = v.size()) == 0) {
+ return NO_TYPES;
+ } else {
+ IType[] array= new IType[size];
+ v.copyInto(array);
+ return array;
}
-
- /**
- * Removes all cached info from the Java Model, including all children,
- * but does not close this element.
- */
- protected void removeInfo() {
- Object info = fgJavaModelManager.peekAtInfo(this);
- if (info != null) {
- try {
- IJavaElement[] children = getChildren();
- for (int i = 0, size = children.length; i < size; ++i) {
- JavaElement child = (JavaElement) children[i];
- child.removeInfo();
- }
- } catch (JavaModelException e) {
- }
- fgJavaModelManager.removeInfo(this);
- try {
- ClassFileInfo cfi = getClassFileInfo();
- cfi.removeBinaryChildren();
- } catch (JavaModelException npe) {
+}
+/**
+ * @see IParent
+ */
+public boolean hasChildren() throws JavaModelException {
+ return getChildren().length > 0;
+}
+/**
+ * @see IType
+ */
+public boolean isClass() throws JavaModelException {
+ return !isInterface();
+}
+/**
+ * @see IType#isInterface
+ */
+public boolean isInterface() throws JavaModelException {
+ IBinaryType info = (IBinaryType) getRawInfo();
+ return info.isInterface();
+}
+/**
+ * @see IType
+ */
+public ITypeHierarchy newSupertypeHierarchy(IProgressMonitor monitor) throws JavaModelException {
+ CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, SearchEngine.createWorkspaceScope(), false);
+ runOperation(op, monitor);
+ return op.getResult();
+}
+/**
+ * @see IType
+ */
+public ITypeHierarchy newTypeHierarchy(IProgressMonitor monitor) throws JavaModelException {
+ CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, SearchEngine.createWorkspaceScope(), true);
+ runOperation(op, monitor);
+ return op.getResult();
+}
+/**
+ * @see IType
+ */
+public ITypeHierarchy newTypeHierarchy(IJavaProject project, IProgressMonitor monitor) throws JavaModelException {
+ if (project == null) {
+ throw new IllegalArgumentException(Util.bind("hierarchy.nullProject"/*nonNLS*/));
+ }
+ CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(
+ this,
+ SearchEngine.createJavaSearchScope(new IResource[]{ project.getProject() }),
+ true);
+ runOperation(op, monitor);
+ return op.getResult();
+}
+/**
+ * Removes all cached info from the Java Model, including all children,
+ * but does not close this element.
+ */
+protected void removeInfo() {
+ Object info = fgJavaModelManager.peekAtInfo(this);
+ if (info != null) {
+ try {
+ IJavaElement[] children = getChildren();
+ for (int i = 0, size = children.length; i < size; ++i) {
+ JavaElement child = (JavaElement) children[i];
+ child.removeInfo();
}
+ } catch (JavaModelException e) {
+ }
+ fgJavaModelManager.removeInfo(this);
+ try {
+ ClassFileInfo cfi = getClassFileInfo();
+ cfi.removeBinaryChildren();
+ } catch (JavaModelException npe) {
}
}
-
- public String[][] resolveType(String typeName) throws JavaModelException {
- // not implemented for binary types
- return null;
- }
-
+}
+public String[][] resolveType(String typeName) throws JavaModelException {
+ // not implemented for binary types
+ return null;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Buffer.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Buffer.java
index 1632edaec1..150909f0e4 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Buffer.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Buffer.java
@@ -24,697 +24,618 @@ public class Buffer implements IBuffer {
protected char[] fContents;
protected Vector fChangeListeners;
protected IOpenable fOwner;
- protected int fGapStart = -1;
- protected int fGapEnd = -1;
+ protected int fGapStart= -1;
+ protected int fGapEnd= -1;
- protected int fHighWatermark = 300;
- protected int fLowWatermark = 50;
- protected Object fLock = new Object();
+ protected int fHighWatermark= 300;
+ protected int fLowWatermark= 50;
+ protected Object fLock= new Object();
String lineSeparator;
-
- protected static final int F_HAS_UNSAVED_CHANGES = 1;
- protected static final int F_IS_READ_ONLY = 2;
- protected static final int F_IS_CLOSED = 4;
- /**
- * Creates a new buffer without an underlying resource.
- */
- protected Buffer(
- BufferManager manager,
- char[] contents,
- IOpenable owner,
- boolean readOnly) {
- fManager = manager;
- fFile = null;
- fContents = contents;
- fOwner = owner;
- fFlags |= F_HAS_UNSAVED_CHANGES;
- setReadOnly(readOnly);
- }
-
- /**
- * Creates a new buffer on an underlying resource.
- */
- protected Buffer(
- BufferManager manager,
- IFile file,
- char[] contents,
- IOpenable owner,
- boolean readOnly) {
- fManager = manager;
- fFile = file;
- fContents = contents;
- fOwner = owner;
- setReadOnly(readOnly);
+
+ protected static final int F_HAS_UNSAVED_CHANGES= 1;
+ protected static final int F_IS_READ_ONLY= 2;
+ protected static final int F_IS_CLOSED= 4;
+/**
+ * Creates a new buffer without an underlying resource.
+ */
+protected Buffer(BufferManager manager, char[] contents, IOpenable owner, boolean readOnly) {
+ fManager = manager;
+ fFile = null;
+ fContents = contents;
+ fOwner = owner;
+ fFlags |= F_HAS_UNSAVED_CHANGES;
+ setReadOnly(readOnly);
+}
+/**
+ * Creates a new buffer on an underlying resource.
+ */
+protected Buffer(BufferManager manager, IFile file, char[] contents, IOpenable owner, boolean readOnly) {
+ fManager = manager;
+ fFile = file;
+ fContents = contents;
+ fOwner = owner;
+ setReadOnly(readOnly);
+}
+/**
+ * @see IBuffer
+ */
+public void addBufferChangedListener(IBufferChangedListener listener) {
+ if (fChangeListeners == null) {
+ fChangeListeners = new Vector(5);
}
-
- /**
- * @see IBuffer
- */
- public void addBufferChangedListener(IBufferChangedListener listener) {
- if (fChangeListeners == null) {
- fChangeListeners = new Vector(5);
- }
- if (!fChangeListeners.contains(listener)) {
- fChangeListeners.addElement(listener);
- }
+ if (!fChangeListeners.contains(listener)) {
+ fChangeListeners.addElement(listener);
}
-
- /**
- * The <code>sizeHint</code> represents the range that will be filled afterwards.
- * If the gap is already at the right position, it must only be
- * resized if it will be no longer between low and high watermark.
- */
- protected void adjustGap(int position, int sizeHint) {
- if (position == fGapStart) {
- int size = (fGapEnd - fGapStart) - sizeHint;
- if (fLowWatermark <= size && size <= fHighWatermark)
- return;
- }
- moveAndResizeGap(position, sizeHint);
- }
-
- /**
- * Append the <code>text</code> to the actual content, the gap is moved
- * to the end of the <code>text</code>.
- */
- public void append(char[] text) {
- this.append(text, false);
+}
+/**
+ * The <code>sizeHint</code> represents the range that will be filled afterwards.
+ * If the gap is already at the right position, it must only be
+ * resized if it will be no longer between low and high watermark.
+ */
+protected void adjustGap(int position, int sizeHint) {
+ if (position == fGapStart) {
+ int size = (fGapEnd - fGapStart) - sizeHint;
+ if (fLowWatermark <= size && size <= fHighWatermark)
+ return;
}
-
- /**
- * Append the <code>text</code> to the actual content, the gap is moved
- * to the end of the <code>text</code>.
- */
- public void append(char[] text, boolean convert) {
- if (!isReadOnly()) {
- if (text == null || text.length == 0) {
- return;
- }
- if (convert)
- text = this.normalizeCRs(text);
- int length = getLength();
- adjustGap(length, text.length);
- System.arraycopy(text, 0, fContents, length, text.length);
- fGapStart += text.length;
- fFlags |= F_HAS_UNSAVED_CHANGES;
- notifyChanged(new BufferChangedEvent(this, length, 0, new String(text)));
+ moveAndResizeGap(position, sizeHint);
+}
+/**
+ * Append the <code>text</code> to the actual content, the gap is moved
+ * to the end of the <code>text</code>.
+ */
+public void append(char[] text) {
+ this.append(text, false);
+}
+/**
+ * Append the <code>text</code> to the actual content, the gap is moved
+ * to the end of the <code>text</code>.
+ */
+public void append(char[] text, boolean convert) {
+ if (!isReadOnly()) {
+ if (text == null || text.length == 0) {
+ return;
}
+ if (convert) text = this.normalizeCRs(text);
+ int length = getLength();
+ adjustGap(length, text.length);
+ System.arraycopy(text, 0, fContents, length, text.length);
+ fGapStart += text.length;
+ fFlags |= F_HAS_UNSAVED_CHANGES;
+ notifyChanged(new BufferChangedEvent(this, length, 0, new String(text)));
}
-
- /**
- * Append the <code>text</code> to the actual content, the gap is moved
- * to the end of the <code>text</code>.
- */
- public void append(String text) {
- this.append(text, false);
- }
-
- /**
- * Append the <code>text</code> to the actual content, the gap is moved
- * to the end of the <code>text</code>.
- */
- public void append(String text, boolean convert) {
- if (text == null) {
+}
+/**
+ * Append the <code>text</code> to the actual content, the gap is moved
+ * to the end of the <code>text</code>.
+ */
+public void append(String text) {
+ this.append(text, false);
+}
+/**
+ * Append the <code>text</code> to the actual content, the gap is moved
+ * to the end of the <code>text</code>.
+ */
+public void append(String text, boolean convert) {
+ if (text == null) {
+ return;
+ }
+ if (!isReadOnly()) {
+ if (convert) text = this.normalizeCRs(text);
+ int textLength = text.length();
+ if (textLength == 0) {
return;
}
- if (!isReadOnly()) {
- if (convert)
- text = this.normalizeCRs(text);
- int textLength = text.length();
- if (textLength == 0) {
- return;
- }
- int length = getLength();
- adjustGap(length, textLength);
- System.arraycopy(text.toCharArray(), 0, fContents, length, textLength);
- fGapStart += textLength;
- fFlags |= F_HAS_UNSAVED_CHANGES;
- notifyChanged(new BufferChangedEvent(this, length, 0, text));
- }
+ int length = getLength();
+ adjustGap(length, textLength);
+ System.arraycopy(text.toCharArray(), 0, fContents, length, textLength);
+ fGapStart += textLength;
+ fFlags |= F_HAS_UNSAVED_CHANGES;
+ notifyChanged(new BufferChangedEvent(this, length, 0, text));
}
-
- /**
- * @see IBuffer
- */
- public void close() throws IllegalArgumentException {
- BufferChangedEvent event = null;
- synchronized (fLock) {
- if (isClosed())
- return;
- event = new BufferChangedEvent(this, 0, 0, null);
- fContents = null;
- fFlags |= F_IS_CLOSED;
- fManager.removeBuffer(this);
- }
- notifyChanged(event); // notify outside of synchronized block
- fChangeListeners = null;
+}
+/**
+ * @see IBuffer
+ */
+public void close() throws IllegalArgumentException {
+ BufferChangedEvent event = null;
+ synchronized (fLock) {
+ if (isClosed())
+ return;
+ event = new BufferChangedEvent(this, 0, 0, null);
+ fContents = null;
+ fFlags |= F_IS_CLOSED;
+ fManager.removeBuffer(this);
}
-
- /**
- * Finds the first line separator used by the given text.
- *
- * @return </code>"\n"</code> or </code>"\r"</code> or </code>"\r\n"</code>,
- * or <code>null</code> if none found
- */
- private String findLineSeparator(char[] text) {
- // find the first line separator
- int length = text.length;
- if (length > 0) {
- char nextChar = text[0];
- for (int i = 0; i < length; i++) {
- char currentChar = nextChar;
- nextChar = i < length - 1 ? text[i + 1] : ' ';
- switch (currentChar) {
- case '\n' :
- return "\n";
- case '\r' :
- return nextChar == '\n' ? "\r\n" : "\r";
- }
+ notifyChanged(event); // notify outside of synchronized block
+ fChangeListeners = null;
+}
+/**
+ * Finds the first line separator used by the given text.
+ *
+ * @return </code>"\n"</code> or </code>"\r"</code> or </code>"\r\n"</code>,
+ * or <code>null</code> if none found
+ */
+private String findLineSeparator(char[] text) {
+ // find the first line separator
+ int length = text.length;
+ if (length > 0) {
+ char nextChar = text[0];
+ for (int i = 0; i < length; i++) {
+ char currentChar = nextChar;
+ nextChar = i < length-1 ? text[i+1] : ' ';
+ switch (currentChar) {
+ case '\n': return "\n"/*nonNLS*/;
+ case '\r': return nextChar == '\n' ? "\r\n"/*nonNLS*/ : "\r"/*nonNLS*/;
}
}
- // not found
- return null;
}
-
- /**
- * @see IBuffer
- */
- public char getChar(int position) {
- synchronized (fLock) {
- if (position < fGapStart) {
- return fContents[position];
- }
- int gapLength = fGapEnd - fGapStart;
- return fContents[position + gapLength];
+ // not found
+ return null;
+}
+/**
+ * @see IBuffer
+ */
+public char getChar(int position) {
+ synchronized (fLock) {
+ if (position < fGapStart) {
+ return fContents[position];
}
+ int gapLength = fGapEnd - fGapStart;
+ return fContents[position + gapLength];
}
-
- /**
- * @see IBuffer
- */
- public char[] getCharacters() {
- if (fContents == null)
- return new char[0];
- synchronized (fLock) {
- if (fGapStart < 0) {
- return fContents;
- }
- int length = fContents.length;
- char[] contents = new char[length - fGapEnd + fGapStart];
- System.arraycopy(fContents, 0, contents, 0, fGapStart);
- System.arraycopy(fContents, fGapEnd, contents, fGapStart, length - fGapEnd);
- return contents;
+}
+/**
+ * @see IBuffer
+ */
+public char[] getCharacters() {
+ if (fContents == null)
+ return new char[0];
+ synchronized (fLock) {
+ if (fGapStart < 0) {
+ return fContents;
}
+ int length = fContents.length;
+ char[] contents = new char[length - fGapEnd + fGapStart];
+ System.arraycopy(fContents, 0, contents, 0, fGapStart);
+ System.arraycopy(fContents, fGapEnd, contents, fGapStart, length - fGapEnd);
+ return contents;
}
-
- /**
- * @see IBuffer
- */
- public String getContents() {
- if (fContents == null)
- return "";
- synchronized (fLock) {
- if (fGapStart < 0) {
- return new String(fContents);
- }
- int length = fContents.length;
- StringBuffer buffer = new StringBuffer(length - fGapEnd + fGapStart);
- buffer.append(fContents, 0, fGapStart);
- buffer.append(fContents, fGapEnd, length - fGapEnd);
- return buffer.toString();
+}
+/**
+ * @see IBuffer
+ */
+public String getContents() {
+ if (fContents == null)
+ return ""/*nonNLS*/;
+ synchronized (fLock) {
+ if (fGapStart < 0) {
+ return new String(fContents);
}
+ int length = fContents.length;
+ StringBuffer buffer = new StringBuffer(length - fGapEnd + fGapStart);
+ buffer.append(fContents, 0, fGapStart);
+ buffer.append(fContents, fGapEnd, length - fGapEnd);
+ return buffer.toString();
}
-
- /**
- * @see IBuffer
- */
- public int getLength() {
- synchronized (fLock) {
- int length = fGapEnd - fGapStart;
- return (fContents.length - length);
- }
+}
+/**
+ * @see IBuffer
+ */
+public int getLength() {
+ synchronized (fLock) {
+ int length = fGapEnd - fGapStart;
+ return (fContents.length - length);
}
-
- /**
- * Returns the line separator used by this buffer.
- * Uses the given text if none found.
- *
- * @return </code>"\n"</code> or </code>"\r"</code> or </code>"\r\n"</code>
- */
- private String getLineSeparator(char[] text) {
+}
+/**
+ * Returns the line separator used by this buffer.
+ * Uses the given text if none found.
+ *
+ * @return </code>"\n"</code> or </code>"\r"</code> or </code>"\r\n"</code>
+ */
+private String getLineSeparator(char[] text) {
+ if (this.lineSeparator == null) {
+ // search in this buffer's contents first
+ this.lineSeparator = this.findLineSeparator(this.getCharacters());
if (this.lineSeparator == null) {
- // search in this buffer's contents first
- this.lineSeparator = this.findLineSeparator(this.getCharacters());
+ // search in the given text
+ this.lineSeparator = this.findLineSeparator(text);
if (this.lineSeparator == null) {
- // search in the given text
- this.lineSeparator = this.findLineSeparator(text);
- if (this.lineSeparator == null) {
- // default to system line separator
- return JavaModelManager.LINE_SEPARATOR;
- }
+ // default to system line separator
+ return JavaModelManager.LINE_SEPARATOR;
}
}
- return this.lineSeparator;
- }
-
- /**
- * @see IBuffer
- */
- public IOpenable getOwner() {
- return fOwner;
}
-
- /**
- * @see IBuffer
- */
- public String getText(int offset, int length) {
- if (fContents == null)
- return "";
- synchronized (fLock) {
- if (offset + length < fGapStart)
- return new String(fContents, offset, length);
- if (fGapStart < offset) {
- int gapLength = fGapEnd - fGapStart;
- return new String(fContents, offset + gapLength, length);
- }
- StringBuffer buf = new StringBuffer();
- buf.append(fContents, offset, fGapStart - offset);
- buf.append(fContents, fGapEnd, offset + length - fGapStart);
- return buf.toString();
+ return this.lineSeparator;
+}
+/**
+ * @see IBuffer
+ */
+public IOpenable getOwner() {
+ return fOwner;
+}
+/**
+ * @see IBuffer
+ */
+public String getText(int offset, int length) {
+ if (fContents == null)
+ return ""/*nonNLS*/;
+ synchronized (fLock) {
+ if (offset + length < fGapStart)
+ return new String(fContents, offset, length);
+ if (fGapStart < offset) {
+ int gapLength = fGapEnd - fGapStart;
+ return new String(fContents, offset + gapLength, length);
}
+ StringBuffer buf = new StringBuffer();
+ buf.append(fContents, offset, fGapStart - offset);
+ buf.append(fContents, fGapEnd, offset + length - fGapStart);
+ return buf.toString();
}
-
- /**
- * @see IBuffer
- */
- public IResource getUnderlyingResource() {
- return fFile;
- }
-
- /**
- * @see IBuffer
- */
- public boolean hasUnsavedChanges() {
- return (fFlags & F_HAS_UNSAVED_CHANGES) != 0;
- }
-
- /**
- * @see IBuffer
- */
- public boolean isClosed() {
- return (fFlags & F_IS_CLOSED) != 0;
- }
-
- /**
- * @see IBuffer
- */
- public boolean isReadOnly() {
- return (fFlags & F_IS_READ_ONLY) != 0;
- }
-
- /**
- * Moves the gap to location and adjust its size to the
- * anticipated change size. The size represents the expected
- * range of the gap that will be filled after the gap has been moved.
- * Thus the gap is resized to actual size + the specified size and
- * moved to the given position.
- */
- protected void moveAndResizeGap(int position, int size) {
- char[] content = null;
- int oldSize = fGapEnd - fGapStart;
- int newSize = fHighWatermark + size;
- if (newSize < 0) {
- if (oldSize > 0) {
- content = new char[fContents.length - oldSize];
- System.arraycopy(fContents, 0, content, 0, fGapStart);
- System.arraycopy(
- fContents,
- fGapEnd,
- content,
- fGapStart,
- content.length - fGapStart);
- fContents = content;
- }
- fGapStart = fGapEnd = position;
- return;
+}
+/**
+ * @see IBuffer
+ */
+public IResource getUnderlyingResource() {
+ return fFile;
+}
+/**
+ * @see IBuffer
+ */
+public boolean hasUnsavedChanges() {
+ return (fFlags & F_HAS_UNSAVED_CHANGES) != 0;
+}
+/**
+ * @see IBuffer
+ */
+public boolean isClosed() {
+ return (fFlags & F_IS_CLOSED) != 0;
+}
+/**
+ * @see IBuffer
+ */
+public boolean isReadOnly() {
+ return (fFlags & F_IS_READ_ONLY) != 0;
+}
+/**
+ * Moves the gap to location and adjust its size to the
+ * anticipated change size. The size represents the expected
+ * range of the gap that will be filled after the gap has been moved.
+ * Thus the gap is resized to actual size + the specified size and
+ * moved to the given position.
+ */
+protected void moveAndResizeGap(int position, int size) {
+ char[] content = null;
+ int oldSize = fGapEnd - fGapStart;
+ int newSize = fHighWatermark + size;
+ if (newSize < 0) {
+ if (oldSize > 0) {
+ content = new char[fContents.length - oldSize];
+ System.arraycopy(fContents, 0, content, 0, fGapStart);
+ System.arraycopy(fContents, fGapEnd, content, fGapStart, content.length - fGapStart);
+ fContents = content;
}
- content = new char[fContents.length + (newSize - oldSize)];
- int newGapStart = position;
- int newGapEnd = newGapStart + newSize;
- if (oldSize == 0) {
+ fGapStart = fGapEnd = position;
+ return;
+ }
+ content = new char[fContents.length + (newSize - oldSize)];
+ int newGapStart = position;
+ int newGapEnd = newGapStart + newSize;
+ if (oldSize == 0) {
+ System.arraycopy(fContents, 0, content, 0, newGapStart);
+ System.arraycopy(fContents, newGapStart, content, newGapEnd, content.length - newGapEnd);
+ } else
+ if (newGapStart < fGapStart) {
+ int delta = fGapStart - newGapStart;
System.arraycopy(fContents, 0, content, 0, newGapStart);
- System.arraycopy(
- fContents,
- newGapStart,
- content,
- newGapEnd,
- content.length - newGapEnd);
- } else
- if (newGapStart < fGapStart) {
- int delta = fGapStart - newGapStart;
- System.arraycopy(fContents, 0, content, 0, newGapStart);
- System.arraycopy(fContents, newGapStart, content, newGapEnd, delta);
- System.arraycopy(
- fContents,
- fGapEnd,
- content,
- newGapEnd + delta,
- fContents.length - fGapEnd);
- } else {
- int delta = newGapStart - fGapStart;
- System.arraycopy(fContents, 0, content, 0, fGapStart);
- System.arraycopy(fContents, fGapEnd, content, fGapStart, delta);
- System.arraycopy(
- fContents,
- fGapEnd + delta,
- content,
- newGapEnd,
- content.length - newGapEnd);
- }
- fContents = content;
- fGapStart = newGapStart;
- fGapEnd = newGapEnd;
- }
-
- /**
- * Normalizes the cariage returns in the given text.
- * They are all changed to use this buffer's line sepatator.
- */
- private char[] normalizeCRs(char[] text) {
- CharArrayBuffer buffer = new CharArrayBuffer();
- int lineStart = 0;
- int length = text.length;
- if (length == 0)
- return text;
- String lineSeparator = this.getLineSeparator(text);
- char nextChar = text[0];
- for (int i = 0; i < length; i++) {
- char currentChar = nextChar;
- nextChar = i < length - 1 ? text[i + 1] : ' ';
- switch (currentChar) {
- case '\n' :
- int lineLength = i - lineStart;
- char[] line = new char[lineLength];
- System.arraycopy(text, lineStart, line, 0, lineLength);
- buffer.append(line);
- buffer.append(lineSeparator);
- lineStart = i + 1;
- break;
- case '\r' :
- lineLength = i - lineStart;
- line = new char[lineLength];
- System.arraycopy(text, lineStart, line, 0, lineLength);
- buffer.append(line);
- buffer.append(lineSeparator);
- if (nextChar == '\n') {
- nextChar = ' ';
- i++;
- }
- lineStart = i + 1;
- break;
- }
- }
- char[] lastLine;
- if (lineStart > 0) {
- int lastLineLength = length - lineStart;
- if (lastLineLength > 0) {
- lastLine = new char[lastLineLength];
- System.arraycopy(text, lineStart, lastLine, 0, lastLineLength);
- buffer.append(lastLine);
- }
- return buffer.getContents();
+ System.arraycopy(fContents, newGapStart, content, newGapEnd, delta);
+ System.arraycopy(fContents, fGapEnd, content, newGapEnd + delta, fContents.length - fGapEnd);
} else {
- return text;
+ int delta = newGapStart - fGapStart;
+ System.arraycopy(fContents, 0, content, 0, fGapStart);
+ System.arraycopy(fContents, fGapEnd, content, fGapStart, delta);
+ System.arraycopy(fContents, fGapEnd + delta, content, newGapEnd, content.length - newGapEnd);
}
- }
-
- /**
- * Normalizes the cariage returns in the given text.
- * They are all changed to use this buffer's line sepatator.
- */
- private String normalizeCRs(String text) {
- return new String(this.normalizeCRs(text.toCharArray()));
- }
-
- /**
- * Notify the listeners that this buffer has changed.
- * To avoid deadlock, this should not be called in a synchronized block.
- */
- protected void notifyChanged(BufferChangedEvent event) {
- if (fChangeListeners != null) {
- for (int i = 0, size = fChangeListeners.size(); i < size; ++i) {
- IBufferChangedListener listener =
- (IBufferChangedListener) fChangeListeners.elementAt(i);
- listener.bufferChanged(event);
- }
+ fContents = content;
+ fGapStart = newGapStart;
+ fGapEnd = newGapEnd;
+}
+/**
+ * Normalizes the cariage returns in the given text.
+ * They are all changed to use this buffer's line sepatator.
+ */
+private char[] normalizeCRs(char[] text) {
+ CharArrayBuffer buffer = new CharArrayBuffer();
+ int lineStart = 0;
+ int length = text.length;
+ if (length == 0) return text;
+ String lineSeparator = this.getLineSeparator(text);
+ char nextChar = text[0];
+ for (int i = 0; i < length; i++) {
+ char currentChar = nextChar;
+ nextChar = i < length-1 ? text[i+1] : ' ';
+ switch (currentChar) {
+ case '\n':
+ int lineLength = i-lineStart;
+ char[] line = new char[lineLength];
+ System.arraycopy(text, lineStart, line, 0, lineLength);
+ buffer.append(line);
+ buffer.append(lineSeparator);
+ lineStart = i+1;
+ break;
+ case '\r':
+ lineLength = i-lineStart;
+ line = new char[lineLength];
+ System.arraycopy(text, lineStart, line, 0, lineLength);
+ buffer.append(line);
+ buffer.append(lineSeparator);
+ if (nextChar == '\n') {
+ nextChar = ' ';
+ i++;
+ }
+ lineStart = i+1;
+ break;
}
}
-
- /**
- * @see IBuffer
- */
- public void removeBufferChangedListener(IBufferChangedListener listener) {
- if (fChangeListeners != null) {
- fChangeListeners.removeElement(listener);
- if (fChangeListeners.size() == 0) {
- fChangeListeners = null;
- }
+ char[] lastLine;
+ if (lineStart > 0) {
+ int lastLineLength = length-lineStart;
+ if (lastLineLength > 0) {
+ lastLine = new char[lastLineLength];
+ System.arraycopy(text, lineStart, lastLine, 0, lastLineLength);
+ buffer.append(lastLine);
}
+ return buffer.getContents();
+ } else {
+ return text;
}
-
- /**
- * Replaces <code>length</code> characters starting from <code>position</code> with <code>text<code>.
- * After that operation, the gap is placed at the end of the
- * inserted <code>text</code>.
- */
- public void replace(int position, int length, char[] text) {
- this.replace(position, length, text, false);
- }
-
- /**
- * Replaces <code>length</code> characters starting from <code>position</code> with <code>text<code>.
- * After that operation, the gap is placed at the end of the
- * inserted <code>text</code>.
- */
- public void replace(int position, int length, char[] text, boolean convert) {
- if (!isReadOnly()) {
- if (text == null) {
- text = new char[0];
- } else {
- if (convert)
- text = this.normalizeCRs(text);
- }
- synchronized (fLock) {
- // move gap
- adjustGap(position + length, text.length - length);
-
- // overwrite
- int min = Math.min(text.length, length);
- for (int i = position, j = 0; i < position + min; i++, j++)
- fContents[i] = text[j];
- if (length > text.length) {
- // enlarge the gap
- fGapStart -= (length - text.length);
- } else
- if (text.length > length) {
- // shrink gap
- fGapStart += (text.length - length);
- for (int i = length; i < text.length; i++)
- fContents[position + i] = text[i];
- }
- }
- fFlags |= F_HAS_UNSAVED_CHANGES;
- String string = null;
- if (text.length > 0) {
- string = new String(text);
- }
- notifyChanged(new BufferChangedEvent(this, position, length, string));
+}
+/**
+ * Normalizes the cariage returns in the given text.
+ * They are all changed to use this buffer's line sepatator.
+ */
+private String normalizeCRs(String text) {
+ return new String(this.normalizeCRs(text.toCharArray()));
+}
+/**
+ * Notify the listeners that this buffer has changed.
+ * To avoid deadlock, this should not be called in a synchronized block.
+ */
+protected void notifyChanged(BufferChangedEvent event) {
+ if (fChangeListeners != null) {
+ for (int i = 0, size = fChangeListeners.size(); i < size; ++i) {
+ IBufferChangedListener listener = (IBufferChangedListener) fChangeListeners.elementAt(i);
+ listener.bufferChanged(event);
}
}
-
- /**
- * Replaces <code>length</code> characters starting from <code>position</code> with <code>text<code>.
- * After that operation, the gap is placed at the end of the
- * inserted <code>text</code>.
- */
- public void replace(int position, int length, String text) {
- this.replace(position, length, text, false);
+}
+/**
+ * @see IBuffer
+ */
+public void removeBufferChangedListener(IBufferChangedListener listener) {
+ if (fChangeListeners != null) {
+ fChangeListeners.removeElement(listener);
+ if (fChangeListeners.size() == 0) {
+ fChangeListeners = null;
+ }
}
-
- /**
- * Replaces <code>length</code> characters starting from <code>position</code> with <code>text<code>.
- * After that operation, the gap is placed at the end of the
- * inserted <code>text</code>.
- */
- public void replace(int position, int length, String text, boolean convert) {
- if (!isReadOnly()) {
- int textLength = 0;
- if (text != null) {
- if (convert)
- text = this.normalizeCRs(text);
- textLength = text.length();
- }
-
- synchronized (fLock) {
- // move gap
- adjustGap(position + length, textLength - length);
-
- // overwrite
- int min = Math.min(textLength, length);
- for (int i = position, j = 0; i < position + min; i++, j++)
- fContents[i] = text.charAt(j);
- if (length > textLength) {
- // enlarge the gap
- fGapStart -= (length - textLength);
- } else
- if (textLength > length) {
- // shrink gap
- fGapStart += (textLength - length);
- for (int i = length; i < textLength; i++)
- fContents[position + i] = text.charAt(i);
- }
- }
- fFlags |= F_HAS_UNSAVED_CHANGES;
-
- notifyChanged(new BufferChangedEvent(this, position, length, text));
+}
+/**
+ * Replaces <code>length</code> characters starting from <code>position</code> with <code>text<code>.
+ * After that operation, the gap is placed at the end of the
+ * inserted <code>text</code>.
+ */
+public void replace(int position, int length, char[] text) {
+ this.replace(position, length, text, false);
+}
+/**
+ * Replaces <code>length</code> characters starting from <code>position</code> with <code>text<code>.
+ * After that operation, the gap is placed at the end of the
+ * inserted <code>text</code>.
+ */
+public void replace(int position, int length, char[] text, boolean convert) {
+ if (!isReadOnly()) {
+ if (text == null) {
+ text = new char[0];
+ } else {
+ if (convert) text = this.normalizeCRs(text);
+ }
+ synchronized (fLock) {
+ // move gap
+ adjustGap(position + length, text.length - length);
+
+ // overwrite
+ int min = Math.min(text.length, length);
+ for (int i = position, j = 0; i < position + min; i++, j++)
+ fContents[i] = text[j];
+ if (length > text.length) {
+ // enlarge the gap
+ fGapStart -= (length - text.length);
+ } else
+ if (text.length > length) {
+ // shrink gap
+ fGapStart += (text.length - length);
+ for (int i = length; i < text.length; i++)
+ fContents[position + i] = text[i];
+ }
+ }
+ fFlags |= F_HAS_UNSAVED_CHANGES;
+ String string = null;
+ if (text.length > 0) {
+ string = new String(text);
}
+ notifyChanged(new BufferChangedEvent(this, position, length, string));
}
-
- /**
- * @see IBuffer
- */
- public void save(IProgressMonitor progress, boolean force)
- throws JavaModelException {
-
- // determine if saving is required
- if (isReadOnly() || fFile == null) {
- return;
+}
+/**
+ * Replaces <code>length</code> characters starting from <code>position</code> with <code>text<code>.
+ * After that operation, the gap is placed at the end of the
+ * inserted <code>text</code>.
+ */
+public void replace(int position, int length, String text) {
+ this.replace(position, length, text, false);
+}
+/**
+ * Replaces <code>length</code> characters starting from <code>position</code> with <code>text<code>.
+ * After that operation, the gap is placed at the end of the
+ * inserted <code>text</code>.
+ */
+public void replace(int position, int length, String text, boolean convert) {
+ if (!isReadOnly()) {
+ int textLength = 0;
+ if (text != null) {
+ if (convert) text = this.normalizeCRs(text);
+ textLength = text.length();
}
+
synchronized (fLock) {
- if (!hasUnsavedChanges())
- return;
- byte[] bytes = getContents().getBytes();
- ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
-
- // use a platform operation to update the resource contents
- try {
- fFile.setContents(stream, force, true, null); // record history
- } catch (CoreException e) {
- throw new JavaModelException(e);
- }
-
- // the resource no longer has unsaved changes
- fFlags &= ~(F_HAS_UNSAVED_CHANGES);
+ // move gap
+ adjustGap(position + length, textLength - length);
+
+ // overwrite
+ int min = Math.min(textLength, length);
+ for (int i = position, j = 0; i < position + min; i++, j++)
+ fContents[i] = text.charAt(j);
+ if (length > textLength) {
+ // enlarge the gap
+ fGapStart -= (length - textLength);
+ } else
+ if (textLength > length) {
+ // shrink gap
+ fGapStart += (textLength - length);
+ for (int i = length; i < textLength; i++)
+ fContents[position + i] = text.charAt(i);
+ }
}
+ fFlags |= F_HAS_UNSAVED_CHANGES;
+
+ notifyChanged(new BufferChangedEvent(this, position, length, text));
}
+}
+/**
+ * @see IBuffer
+ */
+public void save(IProgressMonitor progress, boolean force) throws JavaModelException {
- /**
- * @see IBuffer
- */
- public void setContents(char[] contents) {
- this.setContents(contents, false);
+ // determine if saving is required
+ if (isReadOnly() || fFile == null) {
+ return;
}
-
- /**
- * @see IBuffer
- */
- public void setContents(char[] contents, boolean convert) {
- if (!isReadOnly()) {
- String string = null;
- if (contents != null) {
- if (convert)
- contents = this.normalizeCRs(contents);
- string = new String(contents);
- }
- BufferChangedEvent event =
- new BufferChangedEvent(this, 0, this.getLength(), string);
- synchronized (fLock) {
- fContents = contents;
- fFlags |= F_HAS_UNSAVED_CHANGES;
- fGapStart = -1;
- fGapEnd = -1;
- }
- notifyChanged(event);
+ synchronized (fLock) {
+ if (!hasUnsavedChanges())
+ return;
+ byte[] bytes = getContents().getBytes();
+ ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
+
+ // use a platform operation to update the resource contents
+ try {
+ fFile.setContents(stream, force, true, null); // record history
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
- }
- /**
- * @see IBuffer
- */
- public void setContents(String contents) {
- this.setContents(contents, false);
+ // the resource no longer has unsaved changes
+ fFlags &= ~ (F_HAS_UNSAVED_CHANGES);
}
-
- /**
- * @see IBuffer
- */
- public void setContents(String contents, boolean convert) {
- if (!isReadOnly()) {
- char[] charContents = null;
- if (contents != null) {
- charContents = contents.toCharArray();
- if (convert) {
- charContents = this.normalizeCRs(charContents);
- contents = new String(charContents);
- }
- }
- BufferChangedEvent event =
- new BufferChangedEvent(this, 0, this.getLength(), contents);
- synchronized (fLock) {
- fContents = charContents;
- fFlags |= F_HAS_UNSAVED_CHANGES;
- fGapStart = -1;
- fGapEnd = -1;
- }
- notifyChanged(event);
+}
+/**
+ * @see IBuffer
+ */
+public void setContents(char[] contents) {
+ this.setContents(contents, false);
+}
+/**
+ * @see IBuffer
+ */
+public void setContents(char[] contents, boolean convert) {
+ if (!isReadOnly()) {
+ String string = null;
+ if (contents != null) {
+ if (convert) contents = this.normalizeCRs(contents);
+ string = new String(contents);
}
- }
-
- /**
- * Sets this <code>Buffer</code> to be read only.
- */
- protected void setReadOnly(boolean readOnly) {
- if (readOnly) {
- fFlags |= F_IS_READ_ONLY;
- } else {
- fFlags &= ~(F_IS_READ_ONLY);
+ BufferChangedEvent event = new BufferChangedEvent(this, 0, this.getLength(), string);
+ synchronized (fLock) {
+ fContents = contents;
+ fFlags |= F_HAS_UNSAVED_CHANGES;
+ fGapStart = -1;
+ fGapEnd = -1;
}
+ notifyChanged(event);
}
-
- /**
- * Adjusts low and high water mark to the specified values.
- */
- public void setWaterMarks(int low, int high) {
- fLowWatermark = low;
- fHighWatermark = high;
- }
-
- public String toString() {
- char[] contents = this.getCharacters();
- int length = contents.length;
- StringBuffer buffer = new StringBuffer(length);
- buffer.append("Buffer:\n");
- for (int i = 0; i < length; i++) {
- char car = contents[i];
- switch (car) {
- case '\n' :
- buffer.append("\\n\n");
- break;
- case '\r' :
- if (i < length - 1 && contents[i + 1] == '\n') {
- buffer.append("\\r\\n\n");
- i++;
- } else {
- buffer.append("\\r\n");
- }
- break;
- default :
- buffer.append(car);
- break;
+}
+/**
+ * @see IBuffer
+ */
+public void setContents(String contents) {
+ this.setContents(contents, false);
+}
+/**
+ * @see IBuffer
+ */
+public void setContents(String contents, boolean convert) {
+ if (!isReadOnly()) {
+ char[] charContents = null;
+ if (contents != null) {
+ charContents = contents.toCharArray();
+ if (convert) {
+ charContents = this.normalizeCRs(charContents);
+ contents = new String(charContents);
}
}
- return buffer.toString();
+ BufferChangedEvent event = new BufferChangedEvent(this, 0, this.getLength(), contents);
+ synchronized (fLock) {
+ fContents = charContents;
+ fFlags |= F_HAS_UNSAVED_CHANGES;
+ fGapStart = -1;
+ fGapEnd = -1;
+ }
+ notifyChanged(event);
}
-
+}
+/**
+ * Sets this <code>Buffer</code> to be read only.
+ */
+protected void setReadOnly(boolean readOnly) {
+ if (readOnly) {
+ fFlags |= F_IS_READ_ONLY;
+ } else {
+ fFlags &= ~(F_IS_READ_ONLY);
+ }
+}
+/**
+ * Adjusts low and high water mark to the specified values.
+ */
+public void setWaterMarks(int low, int high) {
+ fLowWatermark = low;
+ fHighWatermark = high;
+}
+public String toString() {
+ char[] contents = this.getCharacters();
+ int length = contents.length;
+ StringBuffer buffer = new StringBuffer(length);
+ buffer.append("Buffer:\n"/*nonNLS*/);
+ for (int i = 0; i < length; i++) {
+ char car = contents[i];
+ switch (car) {
+ case '\n':
+ buffer.append("\\n\n"/*nonNLS*/);
+ break;
+ case '\r':
+ if (i < length-1 && contents[i+1] == '\n') {
+ buffer.append("\\r\\n\n"/*nonNLS*/);
+ i++;
+ } else {
+ buffer.append("\\r\n"/*nonNLS*/);
+ }
+ break;
+ default:
+ buffer.append(car);
+ break;
+ }
+ }
+ return buffer.toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BufferCache.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BufferCache.java
index a47fe4a2fb..1ca3e3bfc4 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BufferCache.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BufferCache.java
@@ -12,44 +12,40 @@ import org.eclipse.jdt.internal.core.util.LRUCache;
* An LRU cache of <code>IBuffers</code>.
*/
public class BufferCache extends OverflowingLRUCache {
- /**
- * Constructs a new buffer cache of the given size.
- */
- public BufferCache(int size) {
- super(size);
- }
-
- /**
- * Constructs a new buffer cache of the given size.
- */
- public BufferCache(int size, int overflow) {
- super(size, overflow);
- }
-
- /**
- * Returns true if the buffer is successfully closed and
- * removed from the cache, otherwise false.
- *
- * <p>NOTE: this triggers an external removal of this buffer
- * by closing the buffer.
- */
- protected boolean close(LRUCacheEntry entry) {
- IBuffer buffer = (IBuffer) entry._fValue;
- synchronized (buffer) {
- if (buffer.hasUnsavedChanges()) {
- return false;
- } else {
- buffer.close();
- return true;
- }
+/**
+ * Constructs a new buffer cache of the given size.
+ */
+public BufferCache(int size) {
+ super(size);
+}
+/**
+ * Constructs a new buffer cache of the given size.
+ */
+public BufferCache(int size, int overflow) {
+ super(size, overflow);
+}
+/**
+ * Returns true if the buffer is successfully closed and
+ * removed from the cache, otherwise false.
+ *
+ * <p>NOTE: this triggers an external removal of this buffer
+ * by closing the buffer.
+ */
+protected boolean close(LRUCacheEntry entry) {
+ IBuffer buffer= (IBuffer) entry._fValue;
+ synchronized (buffer) {
+ if (buffer.hasUnsavedChanges()) {
+ return false;
+ } else {
+ buffer.close();
+ return true;
}
}
-
+}
/**
* Returns a new instance of the reciever.
*/
protected LRUCache newInstance(int size, int overflow) {
return new BufferCache(size, overflow);
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BufferManager.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BufferManager.java
index 7659f4d04f..bd5086f2fc 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BufferManager.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/BufferManager.java
@@ -26,196 +26,170 @@ public class BufferManager implements IBufferManager {
*/
protected OverflowingLRUCache fOpenBuffers = new BufferCache(20);
protected static BufferManager fgDefaultBufferManager;
- /**
- * Creates a new buffer manager.
- */
- public BufferManager() {
- }
-
- /**
- * Adds a buffer to the table of open buffers.
- */
- protected void addBuffer(IBuffer buffer) {
- fOpenBuffers.put(buffer.getOwner(), buffer);
- }
-
- /**
- * Returns the given bytes as a char array.
- */
- public static char[] bytesToChar(byte[] bytes) throws JavaModelException {
-
- return getInputStreamAsCharArray(new ByteArrayInputStream(bytes));
+/**
+ * Creates a new buffer manager.
+ */
+public BufferManager() {
+}
+/**
+ * Adds a buffer to the table of open buffers.
+ */
+protected void addBuffer(IBuffer buffer) {
+ fOpenBuffers.put(buffer.getOwner(), buffer);
+}
+/**
+ * Returns the given bytes as a char array.
+ */
+public static char[] bytesToChar(byte[] bytes) throws JavaModelException {
- }
+ return getInputStreamAsCharArray(new ByteArrayInputStream(bytes));
- /**
- * @see IBufferManager
- */
- public IBuffer getBuffer(IOpenable owner) {
- return (IBuffer) fOpenBuffers.get(owner);
+}
+/**
+ * @see IBufferManager
+ */
+public IBuffer getBuffer(IOpenable owner) {
+ return (IBuffer)fOpenBuffers.get(owner);
+}
+/**
+ * Returns the default buffer manager.
+ * TBD: There shouldn't be a global buffer manager.
+ * It should be a registered manager with the workspace.
+ */
+public synchronized static IBufferManager getDefaultBufferManager() {
+ if (fgDefaultBufferManager == null) {
+ fgDefaultBufferManager = new BufferManager();
}
-
- /**
- * Returns the default buffer manager.
- * TBD: There shouldn't be a global buffer manager.
- * It should be a registered manager with the workspace.
- */
- public synchronized static IBufferManager getDefaultBufferManager() {
- if (fgDefaultBufferManager == null) {
- fgDefaultBufferManager = new BufferManager();
+ return fgDefaultBufferManager;
+}
+/**
+ * Returns the given input stream's contents as a character array.
+ */
+protected static char[] getInputStreamAsCharArray(InputStream stream) throws JavaModelException {
+ InputStreamReader reader= null;
+ reader= new InputStreamReader(stream);
+ char[] contents = new char[0];
+ char[] grow;
+ try {
+ int available= stream.available();
+ int charsRead= 0;
+ int pos = 0;
+ while (available > 0) {
+ grow = new char[contents.length + available];
+ System.arraycopy(contents, 0, grow, 0, contents.length);
+ contents = grow;
+ charsRead= reader.read(contents, pos, available);
+ available= stream.available();
+ }
+ if (charsRead < available && charsRead > 0) {
+ grow = new char[contents.length - (available - charsRead)];
+ System.arraycopy(contents, 0, grow, 0, grow.length);
+ contents= grow;
}
- return fgDefaultBufferManager;
- }
-
- /**
- * Returns the given input stream's contents as a character array.
- */
- protected static char[] getInputStreamAsCharArray(InputStream stream)
- throws JavaModelException {
- InputStreamReader reader = null;
- reader = new InputStreamReader(stream);
- char[] contents = new char[0];
- char[] grow;
+ } catch (IOException e) {
+ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
+ } finally {
try {
- int available = stream.available();
- int charsRead = 0;
- int pos = 0;
- while (available > 0) {
- grow = new char[contents.length + available];
- System.arraycopy(contents, 0, grow, 0, contents.length);
- contents = grow;
- charsRead = reader.read(contents, pos, available);
- available = stream.available();
- }
- if (charsRead < available && charsRead > 0) {
- grow = new char[contents.length - (available - charsRead)];
- System.arraycopy(contents, 0, grow, 0, grow.length);
- contents = grow;
- }
- } catch (IOException e) {
- throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
- } finally {
- try {
- reader.close();
- } catch (IOException ioe) {
- throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION);
- }
+ reader.close();
+ } catch (IOException ioe) {
+ throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION);
}
- return contents;
}
-
- /**
- * The <code>Enumeration</code> answered is thread safe.
- *
- * @see OverflowLRUCache
- * @see IBufferManager
- */
- public Enumeration getOpenBuffers() {
- synchronized (fOpenBuffers) {
- fOpenBuffers.shrink();
- return fOpenBuffers.elements();
- }
+ return contents;
+}
+/**
+ * The <code>Enumeration</code> answered is thread safe.
+ *
+ * @see OverflowLRUCache
+ * @see IBufferManager
+ */
+public Enumeration getOpenBuffers() {
+ synchronized (fOpenBuffers) {
+ fOpenBuffers.shrink();
+ return fOpenBuffers.elements();
}
-
- /**
- * Returns the given file's contents as a byte array.
- */
- public static byte[] getResourceContentsAsBytes(IFile file)
- throws JavaModelException {
- InputStream stream = null;
- try {
- stream = file.getContents(true);
- } catch (CoreException e) {
- throw new JavaModelException(e);
- }
- byte[] contents = new byte[0];
- byte[] grow;
- try {
- int available = stream.available();
- int pos = 0;
- while (available > 0) {
- grow = new byte[contents.length + available];
- System.arraycopy(contents, 0, grow, 0, contents.length);
- contents = grow;
- stream.read(contents, pos, available);
- available = stream.available();
- }
- } catch (IOException e) {
- throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
- } finally {
- try {
- stream.close();
- } catch (IOException ioe) {
- throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION);
- }
- }
- return contents;
+}
+/**
+ * Returns the given file's contents as a byte array.
+ */
+public static byte[] getResourceContentsAsBytes(IFile file) throws JavaModelException {
+ InputStream stream= null;
+ try {
+ stream = file.getContents(true);
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
-
- /**
- * Returns the given file's contents as a character array.
- */
- public static char[] getResourceContentsAsCharArray(IFile file)
- throws JavaModelException {
- InputStream stream = null;
- try {
- stream = file.getContents(true);
- } catch (CoreException e) {
- throw new JavaModelException(e);
+ byte[] contents = new byte[0];
+ byte[] grow;
+ try {
+ int available = stream.available();
+ int pos = 0;
+ while (available > 0) {
+ grow = new byte[contents.length + available];
+ System.arraycopy(contents, 0, grow, 0, contents.length);
+ contents = grow;
+ stream.read(contents, pos, available);
+ available = stream.available();
}
- return getInputStreamAsCharArray(stream);
- }
-
- /**
- * @see IBufferManager
- */
- public IBuffer openBuffer(
- char[] contents,
- IProgressMonitor progress,
- IOpenable owner,
- boolean readOnly)
- throws IllegalArgumentException {
- if (contents == null || owner == null) {
- throw new IllegalArgumentException();
+ } catch (IOException e) {
+ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
+ } finally {
+ try {
+ stream.close();
+ } catch (IOException ioe) {
+ throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION);
}
- Buffer buffer = new Buffer(this, contents, owner, readOnly);
- addBuffer(buffer);
- return buffer;
}
-
- /**
- * @see IBufferManager
- */
- public IBuffer openBuffer(
- IFile file,
- IProgressMonitor progress,
- IOpenable owner,
- boolean readOnly)
- throws JavaModelException {
- if (file == null || owner == null) {
- throw new IllegalArgumentException();
- }
- char[] contents = getResourceContentsAsCharArray(file);
- Buffer buffer = new Buffer(this, file, contents, owner, readOnly);
- addBuffer(buffer);
- return buffer;
+ return contents;
+}
+/**
+ * Returns the given file's contents as a character array.
+ */
+public static char[] getResourceContentsAsCharArray(IFile file) throws JavaModelException {
+ InputStream stream= null;
+ try {
+ stream = file.getContents(true);
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
-
- /**
- * Removes a buffer from the table of open buffers.
- */
- protected void removeBuffer(IBuffer buffer) {
- fOpenBuffers.remove(buffer.getOwner());
+ return getInputStreamAsCharArray(stream);
+}
+/**
+ * @see IBufferManager
+ */
+public IBuffer openBuffer(char[] contents, IProgressMonitor progress, IOpenable owner, boolean readOnly) throws IllegalArgumentException {
+ if (contents == null || owner == null) {
+ throw new IllegalArgumentException();
}
-
- /**
- * Returns the given String as a byte array. This is centralized here in case
- * we need to do special conversion.
- */
- public static byte[] stringToBytes(String s) {
-
- return s.getBytes();
-
+ Buffer buffer = new Buffer(this, contents, owner, readOnly);
+ addBuffer(buffer);
+ return buffer;
+}
+/**
+ * @see IBufferManager
+ */
+public IBuffer openBuffer(IFile file, IProgressMonitor progress, IOpenable owner, boolean readOnly) throws JavaModelException {
+ if (file == null || owner == null) {
+ throw new IllegalArgumentException();
}
+ char[] contents = getResourceContentsAsCharArray(file);
+ Buffer buffer = new Buffer(this, file, contents, owner, readOnly);
+ addBuffer(buffer);
+ return buffer;
+}
+/**
+ * Removes a buffer from the table of open buffers.
+ */
+protected void removeBuffer(IBuffer buffer) {
+ fOpenBuffers.remove(buffer.getOwner());
+}
+/**
+ * Returns the given String as a byte array. This is centralized here in case
+ * we need to do special conversion.
+ */
+public static byte[] stringToBytes(String s) {
+ return s.getBytes();
+
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ClassFile.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ClassFile.java
index 3a7ca5702f..a956b0d46b 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ClassFile.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ClassFile.java
@@ -25,461 +25,417 @@ import java.lang.reflect.Modifier;
public class ClassFile extends Openable implements IClassFile {
protected BinaryType fBinaryType = null;
- /*
- * Creates a handle to a class file.
- *
- * @exception IllegalArgumentExcpetion if the name does not end with ".class"
- */
- protected ClassFile(IPackageFragment parent, String name) {
- super(CLASS_FILE, parent, name);
- if (!name.toUpperCase().endsWith(".CLASS")) {
- throw new IllegalArgumentException("class file name must end with .class");
- }
+/*
+ * Creates a handle to a class file.
+ *
+ * @exception IllegalArgumentExcpetion if the name does not end with ".class"
+ */
+protected ClassFile(IPackageFragment parent, String name) {
+ super(CLASS_FILE, parent, name);
+ if (!Util.isClassFileName(name)) {
+ throw new IllegalArgumentException(Util.bind("element.invalidClassFileName"/*nonNLS*/));
}
-
- /**
- * @see ICodeAssist
- */
- public void codeComplete(int offset, ICodeCompletionRequestor requestor)
- throws JavaModelException {
- String source = getSource();
- if (source != null) {
- BasicCompilationUnit cu =
- new BasicCompilationUnit(getSource().toCharArray(), getElementName() + ".java");
- codeComplete(cu, cu, offset, requestor);
- }
+}
+/**
+ * @see ICodeAssist
+ */
+public void codeComplete(int offset, ICodeCompletionRequestor requestor) throws JavaModelException {
+ String source = getSource();
+ if (source != null) {
+ BasicCompilationUnit cu = new BasicCompilationUnit(getSource().toCharArray(), getElementName() + ".java"/*nonNLS*/);
+ codeComplete(cu, cu, offset, requestor);
}
-
- /**
- * @see ICodeResolve
- */
- public IJavaElement[] codeSelect(int offset, int length)
- throws JavaModelException {
- IBuffer buffer = getBuffer();
- if (buffer != null) {
- char[] contents = null;
- contents = buffer.getCharacters();
- String name = getElementName();
- name = name.substring(0, name.length() - 6); // remove ".class"
- name = name + ".java";
- BasicCompilationUnit cu = new BasicCompilationUnit(contents, name);
- return super.codeSelect(cu, offset, length);
- } else {
- //has no associated souce
- return new IJavaElement[] {
- };
- }
+}
+/**
+ * @see ICodeResolve
+ */
+public IJavaElement[] codeSelect(int offset, int length) throws JavaModelException {
+ IBuffer buffer = getBuffer();
+ if (buffer != null) {
+ char[] contents = null;
+ contents = buffer.getCharacters();
+ String name = getElementName();
+ name = name.substring(0, name.length() - 6); // remove ".class"
+ name = name + ".java"/*nonNLS*/;
+ BasicCompilationUnit cu = new BasicCompilationUnit(contents, name);
+ return super.codeSelect(cu, offset, length);
+ } else {
+ //has no associated souce
+ return new IJavaElement[] {};
}
-
- /**
- * Returns a new element info for this element.
- */
- protected OpenableElementInfo createElementInfo() {
- return new ClassFileInfo(this);
+}
+/**
+ * Returns a new element info for this element.
+ */
+protected OpenableElementInfo createElementInfo() {
+ return new ClassFileInfo(this);
+}
+/**
+ * Finds the deepest <code>IJavaElement</code> in the hierarchy of
+ * <code>elt</elt>'s children (including <code>elt</code> itself)
+ * which has a source range that encloses <code>position</code>
+ * according to <code>mapper</code>.
+ */
+protected IJavaElement findElement(IJavaElement elt, int position, SourceMapper mapper) {
+ SourceRange range = mapper.getSourceRange(elt);
+ if (range == null || position < range.getOffset() || range.getOffset() + range.getLength() - 1 < position) {
+ return null;
}
-
- /**
- * Finds the deepest <code>IJavaElement</code> in the hierarchy of
- * <code>elt</elt>'s children (including <code>elt</code> itself)
- * which has a source range that encloses <code>position</code>
- * according to <code>mapper</code>.
- */
- protected IJavaElement findElement(
- IJavaElement elt,
- int position,
- SourceMapper mapper) {
- SourceRange range = mapper.getSourceRange(elt);
- if (range == null
- || position < range.getOffset()
- || range.getOffset() + range.getLength() - 1 < position) {
- return null;
- }
- if (elt instanceof IParent) {
- try {
- IJavaElement[] children = ((IParent) elt).getChildren();
- for (int i = 0; i < children.length; i++) {
- IJavaElement match = findElement(children[i], position, mapper);
- if (match != null) {
- return match;
- }
+ if (elt instanceof IParent) {
+ try {
+ IJavaElement[] children = ((IParent) elt).getChildren();
+ for (int i = 0; i < children.length; i++) {
+ IJavaElement match = findElement(children[i], position, mapper);
+ if (match != null) {
+ return match;
}
- } catch (JavaModelException npe) {
}
+ } catch (JavaModelException npe) {
}
- return elt;
}
-
- /**
- * Creates the children elements for this class file adding the resulting
- * new handles and info objects to the newElements table. Returns true
- * if successful, or false if an error is encountered parsing the class file.
- *
- * @see Openable
- * @see Signature
- */
- protected boolean generateInfos(
- OpenableElementInfo info,
- IProgressMonitor pm,
- Hashtable newElements,
- IResource underlyingResource)
- throws JavaModelException {
- IBinaryType typeInfo = getBinaryTypeInfo((IFile) underlyingResource);
- if (typeInfo == null) {
- // The structure of a class file is unknown if a class file format errors occurred
- //during the creation of the diet class file representative of this ClassFile.
- info.setChildren(new IJavaElement[] {
- });
- return false;
- }
-
- // Make the type
- IType type = new BinaryType(this, new String(simpleName(typeInfo.getName())));
- info.addChild(type);
- newElements.put(type, typeInfo);
- return true;
+ return elt;
+}
+/**
+ * Creates the children elements for this class file adding the resulting
+ * new handles and info objects to the newElements table. Returns true
+ * if successful, or false if an error is encountered parsing the class file.
+ *
+ * @see Openable
+ * @see Signature
+ */
+protected boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Hashtable newElements, IResource underlyingResource) throws JavaModelException {
+ IBinaryType typeInfo = getBinaryTypeInfo((IFile) underlyingResource);
+ if (typeInfo == null) {
+ // The structure of a class file is unknown if a class file format errors occurred
+ //during the creation of the diet class file representative of this ClassFile.
+ info.setChildren(new IJavaElement[] {});
+ return false;
}
- /**
- * Returns the <code>ClassFileReader</code>specific for this IClassFile, based
- * on its underlying resource, or <code>null</code> if unable to create
- * the diet class file.
- * There are two cases to consider:<ul>
- * <li>a class file corresponding to an IFile resource</li>
- * <li>a class file corresponding to a zip entry in a JAR</li>
- * </ul>
- *
- * @exception JavaModelException when the IFile resource or JAR is not available
- * or when this class file is not present in the JAR
- */
- private IBinaryType getBinaryTypeInfo(IFile file) throws JavaModelException {
- JavaElement le = (JavaElement) getParent();
- if (le instanceof JarPackageFragment) {
+ // Make the type
+ IType type = new BinaryType(this, new String(simpleName(typeInfo.getName())));
+ info.addChild(type);
+ newElements.put(type, typeInfo);
+ return true;
+}
+/**
+ * Returns the <code>ClassFileReader</code>specific for this IClassFile, based
+ * on its underlying resource, or <code>null</code> if unable to create
+ * the diet class file.
+ * There are two cases to consider:<ul>
+ * <li>a class file corresponding to an IFile resource</li>
+ * <li>a class file corresponding to a zip entry in a JAR</li>
+ * </ul>
+ *
+ * @exception JavaModelException when the IFile resource or JAR is not available
+ * or when this class file is not present in the JAR
+ */
+private IBinaryType getBinaryTypeInfo(IFile file) throws JavaModelException {
+ JavaElement le = (JavaElement) getParent();
+ if (le instanceof JarPackageFragment) {
+ try {
+ JarPackageFragmentRoot root = (JarPackageFragmentRoot) le.getParent();
+ IBinaryType info = null;
+ ZipFile zip = null;
try {
- JarPackageFragmentRoot root = (JarPackageFragmentRoot) le.getParent();
- IBinaryType info = null;
- ZipFile zip = null;
- try {
- zip = root.getJar();
- String entryName = getParent().getElementName();
- entryName = entryName.replace('.', '/');
- if (entryName.equals("")) {
- entryName += getElementName();
- } else {
- entryName += '/' + getElementName();
- }
- info = ClassFileReader.read(zip, entryName);
- } finally {
- if (zip != null) {
- try {
- zip.close();
- } catch (IOException e) {
- // ignore
- }
- }
+ zip = root.getJar();
+ String entryName = getParent().getElementName();
+ entryName = entryName.replace('.', '/');
+ if (entryName.equals(""/*nonNLS*/)) {
+ entryName += getElementName();
+ } else {
+ entryName += '/' + getElementName();
}
- if (info == null) {
- throw newNotPresentException();
+ info = ClassFileReader.read(zip, entryName);
+ } finally {
+ if (zip != null) {
+ try {
+ zip.close();
+ } catch (IOException e) {
+ // ignore
+ }
}
- return info;
- } catch (ClassFormatException cfe) {
- //the structure remains unknown
- return null;
- } catch (IOException ioe) {
- throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION);
- } catch (CoreException e) {
- throw new JavaModelException(e);
}
- } else {
- byte[] contents = null;
- contents = BufferManager.getResourceContentsAsBytes(file);
- try {
- return new ClassFileReader(contents, getElementName().toCharArray());
- } catch (ClassFormatException cfe) {
- //the structure remains unknown
- return null;
+ if (info == null) {
+ throw newNotPresentException();
}
- }
- }
-
- /**
- * Note: a buffer with no unsaved changes can be closed by the Java Model
- * since it has a finite number of buffers allowed open at one time. If this
- * is the first time a request is being made for the buffer, an attempt is
- * made to create and fill this element's buffer. If the buffer has been
- * closed since it was first opened, the buffer is re-created.
- *
- * @see IOpenable
- */
- public IBuffer getBuffer() throws JavaModelException {
- IBuffer buffer = getBufferManager().getBuffer(this);
- if (buffer == null) {
- // try to (re)open a buffer
- return openBuffer(null);
- }
- return buffer;
- }
-
- /**
- * @see IMember
- */
- public IClassFile getClassFile() {
- return this;
- }
-
- /**
- * A class file has a corresponding resource unless it is contained
- * in a jar.
- *
- * @see IJavaElement
- */
- public IResource getCorrespondingResource() throws JavaModelException {
- IPackageFragmentRoot root = (IPackageFragmentRoot) getParent().getParent();
- if (root.isArchive()) {
+ return info;
+ } catch (ClassFormatException cfe) {
+ //the structure remains unknown
return null;
- } else {
- return getUnderlyingResource();
+ } catch (IOException ioe) {
+ throw new JavaModelException(ioe, IJavaModelStatusConstants.IO_EXCEPTION);
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
- }
-
- /**
- * @see IClassFile
- */
- public IJavaElement getElementAt(int position) throws JavaModelException {
- IJavaElement parent = getParent();
- while (parent.getElementType() != IJavaElement.PACKAGE_FRAGMENT_ROOT) {
- parent = parent.getParent();
- }
- PackageFragmentRoot root = (PackageFragmentRoot) parent;
- SourceMapper mapper = root.getSourceMapper();
- if (mapper == null) {
+ } else {
+ byte[] contents = null;
+ contents = BufferManager.getResourceContentsAsBytes(file);
+ try {
+ return new ClassFileReader(contents, getElementName().toCharArray());
+ } catch (ClassFormatException cfe) {
+ //the structure remains unknown
return null;
- } else {
- IType type = getType();
- return findElement(type, position, mapper);
}
}
-
- /**
- * @see JavaElement#getHandleMemento()
- */
- protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_CLASSFILE;
- }
-
- /**
- * @see ISourceReference
- */
- public String getSource() throws JavaModelException {
- IBuffer buffer = getBuffer();
- if (buffer == null) {
- return null;
- }
- return buffer.getContents();
+}
+/**
+ * Note: a buffer with no unsaved changes can be closed by the Java Model
+ * since it has a finite number of buffers allowed open at one time. If this
+ * is the first time a request is being made for the buffer, an attempt is
+ * made to create and fill this element's buffer. If the buffer has been
+ * closed since it was first opened, the buffer is re-created.
+ *
+ * @see IOpenable
+ */
+public IBuffer getBuffer() throws JavaModelException {
+ IBuffer buffer = getBufferManager().getBuffer(this);
+ if (buffer == null) {
+ // try to (re)open a buffer
+ return openBuffer(null);
}
-
- /**
- * @see ISourceReference
- */
- public ISourceRange getSourceRange() throws JavaModelException {
- return new SourceRange(0, getBuffer().getContents().toString().length());
+ return buffer;
+}
+/**
+ * @see IMember
+ */
+public IClassFile getClassFile() {
+ return this;
+}
+/**
+ * A class file has a corresponding resource unless it is contained
+ * in a jar.
+ *
+ * @see IJavaElement
+ */
+public IResource getCorrespondingResource() throws JavaModelException {
+ IPackageFragmentRoot root= (IPackageFragmentRoot)getParent().getParent();
+ if (root.isArchive()) {
+ return null;
+ } else {
+ return getUnderlyingResource();
}
-
- /**
- * @see IClassFile
- */
- public IType getType() throws JavaModelException {
- if (fBinaryType == null) {
- // Remove the ".class" from the name of the ClassFile - always works
- // since constructor fails if name does not end with ".class"
- String name = fName.substring(0, fName.lastIndexOf('.'));
- name = name.substring(name.lastIndexOf('.') + 1);
- int index = name.lastIndexOf('$');
- if (index > -1) {
- name = name.substring(index + 1);
- }
- fBinaryType = new BinaryType(this, name);
- }
- return fBinaryType;
+}
+/**
+ * @see IClassFile
+ */
+public IJavaElement getElementAt(int position) throws JavaModelException {
+ IJavaElement parent = getParent();
+ while (parent.getElementType() != IJavaElement.PACKAGE_FRAGMENT_ROOT) {
+ parent = parent.getParent();
}
-
- /**
- *
- */
- public WorkingCopy getWorkingCopy() {
- String name = getElementName();
- name = name.substring(0, name.length() - 6); // remove ".class"
- name = name + ".java";
- return new WorkingCopy((IPackageFragment) getParent(), name);
+ PackageFragmentRoot root = (PackageFragmentRoot) parent;
+ SourceMapper mapper = root.getSourceMapper();
+ if (mapper == null) {
+ return null;
+ } else {
+ IType type = getType();
+ return findElement(type, position, mapper);
}
-
- /**
- * @see Openable
- */
- protected boolean hasBuffer() {
- return true;
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+protected char getHandleMementoDelimiter() {
+ return JavaElement.JEM_CLASSFILE;
+}
+/**
+ * @see ISourceReference
+ */
+public String getSource() throws JavaModelException {
+ IBuffer buffer = getBuffer();
+ if (buffer == null) {
+ return null;
}
-
- /**
- * If I am not open, return true to avoid parsing.
- *
- * @see IParent
- */
- public boolean hasChildren() throws JavaModelException {
- if (isOpen()) {
- return getChildren().length > 0;
- } else {
- return true;
+ return buffer.getContents();
+}
+/**
+ * @see ISourceReference
+ */
+public ISourceRange getSourceRange() throws JavaModelException {
+ return new SourceRange(0, getBuffer().getContents().toString().length());
+}
+/**
+ * @see IClassFile
+ */
+public IType getType() throws JavaModelException {
+ if (fBinaryType == null) {
+ // Remove the ".class" from the name of the ClassFile - always works
+ // since constructor fails if name does not end with ".class"
+ String name = fName.substring(0, fName.lastIndexOf('.'));
+ name = name.substring(name.lastIndexOf('.') + 1);
+ int index = name.lastIndexOf('$');
+ if (index > -1) {
+ name = name.substring(index + 1);
}
+ fBinaryType = new BinaryType(this, name);
}
-
- /**
- * @see IClassFile
- */
- public boolean isClass() throws JavaModelException {
- return getType().isClass();
- }
-
- /**
- * @see IClassFile
- */
- public boolean isInterface() throws JavaModelException {
- return getType().isInterface();
- }
-
- /**
- * Returns true - class files are always read only.
- */
- public boolean isReadOnly() {
+ return fBinaryType;
+}
+/**
+ *
+ */
+public WorkingCopy getWorkingCopy() {
+ String name = getElementName();
+ name = name.substring(0, name.length() - 6); // remove ".class"
+ name = name + ".java"/*nonNLS*/;
+ return new WorkingCopy((IPackageFragment) getParent(), name);
+}
+/**
+ * @see Openable
+ */
+protected boolean hasBuffer() {
+ return true;
+}
+/**
+ * If I am not open, return true to avoid parsing.
+ *
+ * @see IParent
+ */
+public boolean hasChildren() throws JavaModelException {
+ if (isOpen()) {
+ return getChildren().length > 0;
+ } else {
return true;
}
-
- /**
- * Opens and returns buffer on the source code associated with this class file.
- * Maps the source code to the children elements of this class file.
- * If no source code is associated with this class file,
- * <code>null</code> is returned.
- *
- * @see Openable
- */
- protected IBuffer openBuffer(IProgressMonitor pm) throws JavaModelException {
- SourceMapper mapper = getSourceMapper();
- if (mapper != null) {
- char[] contents = mapper.findSource(getType());
- if (contents != null) {
- IBufferManager bufManager = getBufferManager();
- IBuffer buf = bufManager.openBuffer(contents, pm, this, isReadOnly());
- // do the source mapping
- mapper.mapSource(getType(), contents);
- return buf;
- }
- } else {
- // Attempts to find the corresponding java file
- String qualifiedName = getType().getFullyQualifiedName();
- INameLookup lookup = ((JavaProject) getJavaProject()).getNameLookup();
- ICompilationUnit cu = lookup.findCompilationUnit(qualifiedName);
- if (cu != null) {
- return cu.getBuffer();
- }
+}
+/**
+ * @see IClassFile
+ */
+public boolean isClass() throws JavaModelException {
+ return getType().isClass();
+}
+/**
+ * @see IClassFile
+ */
+public boolean isInterface() throws JavaModelException {
+ return getType().isInterface();
+}
+/**
+ * Returns true - class files are always read only.
+ */
+public boolean isReadOnly() {
+ return true;
+}
+/**
+ * Opens and returns buffer on the source code associated with this class file.
+ * Maps the source code to the children elements of this class file.
+ * If no source code is associated with this class file,
+ * <code>null</code> is returned.
+ *
+ * @see Openable
+ */
+protected IBuffer openBuffer(IProgressMonitor pm) throws JavaModelException {
+ SourceMapper mapper = getSourceMapper();
+ if (mapper != null) {
+ char[] contents = mapper.findSource(getType());
+ if (contents != null) {
+ IBufferManager bufManager = getBufferManager();
+ IBuffer buf = bufManager.openBuffer(contents, pm, this, isReadOnly());
+ // do the source mapping
+ mapper.mapSource(getType(), contents);
+ return buf;
}
- return null;
- }
-
- /**
- * Returns the Java Model format of the simple class name for the
- * given className which is provided in diet class file format,
- * or <code>null</code> if the given className is <code>null</code>.
- * (This removes package name and enclosing type names).
- *
- * <p><code>ClassFileReader</code> format is similar to "java/lang/Object",
- * and corresponding Java Model simple name format is "Object".
- */
-
- /* package */
- static char[] simpleName(char[] className) {
- if (className == null)
- return null;
- className = unqualifiedName(className);
- int count = 0;
- for (int i = className.length - 1; i > -1; i--) {
- if (className[i] == '$') {
- char[] name = new char[count];
- System.arraycopy(className, i + 1, name, 0, count);
- return name;
- }
- count++;
+ } else {
+ // Attempts to find the corresponding java file
+ String qualifiedName = getType().getFullyQualifiedName();
+ INameLookup lookup = ((JavaProject) getJavaProject()).getNameLookup();
+ ICompilationUnit cu = lookup.findCompilationUnit(qualifiedName);
+ if (cu != null) {
+ return cu.getBuffer();
}
- return className;
}
+ return null;
+}
+/**
+ * Returns the Java Model format of the simple class name for the
+ * given className which is provided in diet class file format,
+ * or <code>null</code> if the given className is <code>null</code>.
+ * (This removes package name and enclosing type names).
+ *
+ * <p><code>ClassFileReader</code> format is similar to "java/lang/Object",
+ * and corresponding Java Model simple name format is "Object".
+ */
- /**
- * Returns the Java Model representation of the given name
- * which is provided in diet class file format, or <code>null</code>
- * if the given name is <code>null</code>.
- *
- * <p><code>ClassFileReader</code> format is similar to "java/lang/Object",
- * and corresponding Java Model format is "java.lang.Object".
- */
-
- public static char[] translatedName(char[] name) {
- if (name == null)
- return null;
- int nameLength = name.length;
- char[] newName = new char[nameLength];
- for (int i = 0; i < nameLength; i++) {
- if (name[i] == '/') {
- newName[i] = '.';
- } else {
- newName[i] = name[i];
- }
+/* package */ static char[] simpleName(char[] className) {
+ if (className == null)
+ return null;
+ className = unqualifiedName(className);
+ int count = 0;
+ for (int i = className.length - 1; i > -1; i--) {
+ if (className[i] == '$') {
+ char[] name = new char[count];
+ System.arraycopy(className, i + 1, name, 0, count);
+ return name;
}
- return newName;
+ count++;
}
+ return className;
+}
+/**
+ * Returns the Java Model representation of the given name
+ * which is provided in diet class file format, or <code>null</code>
+ * if the given name is <code>null</code>.
+ *
+ * <p><code>ClassFileReader</code> format is similar to "java/lang/Object",
+ * and corresponding Java Model format is "java.lang.Object".
+ */
- /**
- * Returns the Java Model representation of the given names
- * which are provided in diet class file format, or <code>null</code>
- * if the given names are <code>null</code>.
- *
- * <p><code>ClassFileReader</code> format is similar to "java/lang/Object",
- * and corresponding Java Model format is "java.lang.Object".
- */
-
- /* package */
- static char[][] translatedNames(char[][] names) {
- if (names == null)
- return null;
- int length = names.length;
- char[][] newNames = new char[length][];
- for (int i = 0; i < length; i++) {
- newNames[i] = translatedName(names[i]);
+public static char[] translatedName(char[] name) {
+ if (name == null)
+ return null;
+ int nameLength = name.length;
+ char[] newName= new char[nameLength];
+ for (int i= 0; i < nameLength; i++) {
+ if (name[i] == '/') {
+ newName[i]= '.';
+ } else {
+ newName[i]= name[i];
}
- return newNames;
}
+ return newName;
+}
+/**
+ * Returns the Java Model representation of the given names
+ * which are provided in diet class file format, or <code>null</code>
+ * if the given names are <code>null</code>.
+ *
+ * <p><code>ClassFileReader</code> format is similar to "java/lang/Object",
+ * and corresponding Java Model format is "java.lang.Object".
+ */
- /**
- * Returns the Java Model format of the unqualified class name for the
- * given className which is provided in diet class file format,
- * or <code>null</code> if the given className is <code>null</code>.
- * (This removes the package name, but not enclosing type names).
- *
- * <p><code>ClassFileReader</code> format is similar to "java/lang/Object",
- * and corresponding Java Model simple name format is "Object".
- */
+/* package */ static char[][] translatedNames(char[][] names) {
+ if (names == null)
+ return null;
+ int length = names.length;
+ char[][] newNames = new char[length][];
+ for(int i = 0; i < length; i++) {
+ newNames[i] = translatedName(names[i]);
+ }
+ return newNames;
+}
+/**
+ * Returns the Java Model format of the unqualified class name for the
+ * given className which is provided in diet class file format,
+ * or <code>null</code> if the given className is <code>null</code>.
+ * (This removes the package name, but not enclosing type names).
+ *
+ * <p><code>ClassFileReader</code> format is similar to "java/lang/Object",
+ * and corresponding Java Model simple name format is "Object".
+ */
- /* package */
- static char[] unqualifiedName(char[] className) {
- if (className == null)
- return null;
- int count = 0;
- for (int i = className.length - 1; i > -1; i--) {
- if (className[i] == '/') {
- char[] name = new char[count];
- System.arraycopy(className, i + 1, name, 0, count);
- return name;
- }
- count++;
+/* package */ static char[] unqualifiedName(char[] className) {
+ if (className == null)
+ return null;
+ int count = 0;
+ for (int i = className.length - 1; i > -1; i--) {
+ if (className[i] == '/') {
+ char[] name = new char[count];
+ System.arraycopy(className, i + 1, name, 0, count);
+ return name;
}
- return className;
+ count++;
}
-
+ return className;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ClassFileInfo.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ClassFileInfo.java
index b2f0473997..2db5ba76dd 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ClassFileInfo.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ClassFileInfo.java
@@ -20,9 +20,8 @@ import java.util.Enumeration;
/**
* Element info for <code>ClassFile</code> handles.
*/
-
-/* package */
-class ClassFileInfo extends OpenableElementInfo {
+
+/* package */ class ClassFileInfo extends OpenableElementInfo {
/**
* The children of the <code>BinaryType</code> corresponding to our
* <code>ClassFile</code>. These are kept here because we don't have
@@ -37,164 +36,136 @@ class ClassFileInfo extends OpenableElementInfo {
* Back-pointer to the IClassFile to allow lazy initialization.
*/
protected IClassFile fClassFile = null;
- /**
- * Creates a new <code>ClassFileInfo</code> for <code>classFile</code>.
- */
- ClassFileInfo(IClassFile classFile) {
- fClassFile = classFile;
+/**
+ * Creates a new <code>ClassFileInfo</code> for <code>classFile</code>.
+ */
+ClassFileInfo(IClassFile classFile) {
+ fClassFile = classFile;
+}
+/**
+ * Creates the handles and infos for the fields of the given binary type.
+ * Adds new handles to the given vector.
+ */
+private void generateFieldInfos(IType type, IBinaryType typeInfo, Hashtable newElements, Vector children) {
+ // Make the fields
+ IBinaryField[] fields = typeInfo.getFields();
+ if (fields == null) {
+ return;
}
-
- /**
- * Creates the handles and infos for the fields of the given binary type.
- * Adds new handles to the given vector.
- */
- private void generateFieldInfos(
- IType type,
- IBinaryType typeInfo,
- Hashtable newElements,
- Vector children) {
- // Make the fields
- IBinaryField[] fields = typeInfo.getFields();
- if (fields == null) {
- return;
- }
- for (int i = 0, fieldCount = fields.length; i < fieldCount; i++) {
- IBinaryField fieldInfo = fields[i];
- IField field = new BinaryField(type, new String(fieldInfo.getName()));
- newElements.put(field, fieldInfo);
- children.addElement(field);
- }
+ for (int i = 0, fieldCount = fields.length; i < fieldCount; i++) {
+ IBinaryField fieldInfo = fields[i];
+ IField field = new BinaryField(type, new String(fieldInfo.getName()));
+ newElements.put(field, fieldInfo);
+ children.addElement(field);
}
-
- /**
- * Creates the handles and infos for the inner types of the given binary type.
- * Adds new handles to the given vector.
- */
- private void generateInnerClassInfos(
- IType type,
- IBinaryType typeInfo,
- Hashtable newElements,
- Vector children) {
- // Add inner types
- // If the current type is an inner type, innerClasses returns
- // an extra entry for the current type. This entry must be removed.
- // Can also return an entry for the enclosing type of an inner type.
- IBinaryNestedType[] innerTypes = typeInfo.getMemberTypes();
- if (innerTypes != null) {
- for (int i = 0, typeCount = innerTypes.length; i < typeCount; i++) {
- IBinaryNestedType binaryType = innerTypes[i];
- String innerQualifiedName = new String(binaryType.getName());
- IClassFile classFile =
- ((IPackageFragment) fClassFile.getParent()).getClassFile(
- new String(ClassFile.unqualifiedName(binaryType.getName())) + ".class");
- IType innerType =
- new BinaryType(
- classFile,
- new String(ClassFile.simpleName(binaryType.getName())));
- children.addElement(innerType);
- }
+}
+/**
+ * Creates the handles and infos for the inner types of the given binary type.
+ * Adds new handles to the given vector.
+ */
+private void generateInnerClassInfos(IType type, IBinaryType typeInfo, Hashtable newElements, Vector children) {
+ // Add inner types
+ // If the current type is an inner type, innerClasses returns
+ // an extra entry for the current type. This entry must be removed.
+ // Can also return an entry for the enclosing type of an inner type.
+ IBinaryNestedType[] innerTypes = typeInfo.getMemberTypes();
+ if (innerTypes != null) {
+ for (int i = 0, typeCount = innerTypes.length; i < typeCount; i++) {
+ IBinaryNestedType binaryType = innerTypes[i];
+ String innerQualifiedName = new String(binaryType.getName());
+ IClassFile classFile= ((IPackageFragment)fClassFile.getParent()).getClassFile(new String(ClassFile.unqualifiedName(binaryType.getName())) + ".class"/*nonNLS*/);
+ IType innerType = new BinaryType(classFile, new String(ClassFile.simpleName(binaryType.getName())));
+ children.addElement(innerType);
}
}
-
- /**
- * Creates the handles and infos for the methods of the given binary type.
- * Adds new handles to the given vector.
- */
- private void generateMethodInfos(
- IType type,
- IBinaryType typeInfo,
- Hashtable newElements,
- Vector children) {
- IBinaryMethod[] methods = typeInfo.getMethods();
- if (methods == null) {
- return;
+}
+/**
+ * Creates the handles and infos for the methods of the given binary type.
+ * Adds new handles to the given vector.
+ */
+private void generateMethodInfos(IType type, IBinaryType typeInfo, Hashtable newElements, Vector children) {
+ IBinaryMethod[] methods = typeInfo.getMethods();
+ if (methods == null) {
+ return;
+ }
+ for (int i = 0, methodCount = methods.length; i < methodCount; i++) {
+ IBinaryMethod methodInfo = methods[i];
+ String[] pNames= Signature.getParameterTypes(new String(methodInfo.getMethodDescriptor()));
+ char[][] paramNames= new char[pNames.length][];
+ for (int j= 0; j < pNames.length; j++) {
+ paramNames[j]= pNames[j].toCharArray();
}
- for (int i = 0, methodCount = methods.length; i < methodCount; i++) {
- IBinaryMethod methodInfo = methods[i];
- String[] pNames =
- Signature.getParameterTypes(new String(methodInfo.getMethodDescriptor()));
- char[][] paramNames = new char[pNames.length][];
- for (int j = 0; j < pNames.length; j++) {
- paramNames[j] = pNames[j].toCharArray();
- }
- char[][] parameterTypes = ClassFile.translatedNames(paramNames);
- String selector = new String(methodInfo.getSelector());
- if (methodInfo.isConstructor()) {
- selector = type.getElementName();
- }
- for (int j = 0; j < pNames.length; j++) {
- pNames[j] = new String(parameterTypes[j]);
- }
- IMethod method = new BinaryMethod(type, selector, pNames);
- children.addElement(method);
- newElements.put(method, methodInfo);
+ char[][] parameterTypes = ClassFile.translatedNames(paramNames);
+ String selector = new String(methodInfo.getSelector());
+ if (methodInfo.isConstructor()) {
+ selector = type.getElementName();
}
- }
-
- /**
- * Returns the list of children (<code>BinaryMember</code>s) of the
- * <code>BinaryType</code> of our <code>ClassFile</code>.
- */
- IJavaElement[] getBinaryChildren() throws JavaModelException {
- if (fBinaryChildren == null) {
- readBinaryChildren();
+ for (int j= 0; j < pNames.length; j++) {
+ pNames[j]= new String(parameterTypes[j]);
}
- return fBinaryChildren;
+ IMethod method = new BinaryMethod(type, selector, pNames);
+ children.addElement(method);
+ newElements.put(method, methodInfo);
}
-
- /**
- * Returns true iff the <code>readBinaryChildren</code> has already
- * been called.
- */
- boolean hasReadBinaryChildren() {
- return fBinaryChildren != null;
+}
+/**
+ * Returns the list of children (<code>BinaryMember</code>s) of the
+ * <code>BinaryType</code> of our <code>ClassFile</code>.
+ */
+IJavaElement[] getBinaryChildren() throws JavaModelException {
+ if (fBinaryChildren == null) {
+ readBinaryChildren();
}
-
- /**
- * Creates the handles for <code>BinaryMember</code>s defined in this
- * <code>ClassFile</code> and adds them to the
- * <code>JavaModelManager</code>'s cache.
- */
- private void readBinaryChildren() {
- Vector children = new Vector();
- Hashtable newElements = new Hashtable();
- BinaryType type = null;
- IBinaryType typeInfo = null;
- JavaModelManager manager =
- (JavaModelManager) JavaModelManager.getJavaModelManager();
- try {
- type = (BinaryType) fClassFile.getType();
- typeInfo = (IBinaryType) manager.getInfo(type);
- } catch (JavaModelException npe) {
- return;
- }
- if (typeInfo != null) { //may not be a valid class file
- generateFieldInfos(type, typeInfo, newElements, children);
- generateMethodInfos(type, typeInfo, newElements, children);
- generateInnerClassInfos(type, typeInfo, newElements, children);
- }
- for (Enumeration e = newElements.keys(); e.hasMoreElements();) {
- IJavaElement key = (IJavaElement) e.nextElement();
- Object value = newElements.get(key);
- manager.putInfo(key, value);
- }
- fBinaryChildren = new IJavaElement[children.size()];
- children.copyInto(fBinaryChildren);
+ return fBinaryChildren;
+}
+/**
+ * Returns true iff the <code>readBinaryChildren</code> has already
+ * been called.
+ */
+boolean hasReadBinaryChildren() {
+ return fBinaryChildren != null;
+}
+/**
+ * Creates the handles for <code>BinaryMember</code>s defined in this
+ * <code>ClassFile</code> and adds them to the
+ * <code>JavaModelManager</code>'s cache.
+ */
+private void readBinaryChildren() {
+ Vector children = new Vector();
+ Hashtable newElements = new Hashtable();
+ BinaryType type = null;
+ IBinaryType typeInfo = null;
+ JavaModelManager manager = (JavaModelManager) JavaModelManager.getJavaModelManager();
+ try {
+ type = (BinaryType) fClassFile.getType();
+ typeInfo = (IBinaryType) manager.getInfo(type);
+ } catch (JavaModelException npe) {
+ return;
}
-
- /**
- * Removes the binary children handles and remove their infos from
- * the <code>JavaModelManager</code>'s cache.
- */
- void removeBinaryChildren() {
- if (fBinaryChildren != null) {
- JavaModelManager manager =
- (JavaModelManager) JavaModelManager.getJavaModelManager();
- for (int i = 0; i < fBinaryChildren.length; i++) {
- manager.removeInfo(fBinaryChildren[i]);
- }
- fBinaryChildren = fgEmptyChildren;
+ if (typeInfo != null) { //may not be a valid class file
+ generateFieldInfos(type, typeInfo, newElements, children);
+ generateMethodInfos(type, typeInfo, newElements, children);
+ generateInnerClassInfos(type, typeInfo, newElements, children);
+ }
+ for (Enumeration e = newElements.keys(); e.hasMoreElements();) {
+ IJavaElement key = (IJavaElement) e.nextElement();
+ Object value = newElements.get(key);
+ manager.putInfo(key, value);
+ }
+ fBinaryChildren = new IJavaElement[children.size()];
+ children.copyInto(fBinaryChildren);
+}
+/**
+ * Removes the binary children handles and remove their infos from
+ * the <code>JavaModelManager</code>'s cache.
+ */
+void removeBinaryChildren() {
+ if (fBinaryChildren != null) {
+ JavaModelManager manager = (JavaModelManager) JavaModelManager.getJavaModelManager();
+ for (int i = 0; i <fBinaryChildren.length; i++) {
+ manager.removeInfo(fBinaryChildren[i]);
}
+ fBinaryChildren = fgEmptyChildren;
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ClasspathEntry.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ClasspathEntry.java
index 7da08eaea4..8ec95adbbd 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ClasspathEntry.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ClasspathEntry.java
@@ -21,7 +21,7 @@ public class ClasspathEntry implements IClasspathEntry {
* CPE_PROJECT, CPE_LIBRARY or CPE_SOURCE.
*/
protected int entryKind;
-
+
/**
* Describes the kind of package fragment roots found on
* this classpath entry - either K_BINARY or K_SOURCE or
@@ -72,162 +72,139 @@ public class ClasspathEntry implements IClasspathEntry {
/**
* A constant indicating an output location.
*/
- protected static final int K_OUTPUT = 10;
- /**
- * Creates a class path entry of the specified kind with the given path.
- */
- public ClasspathEntry(
- int contentKind,
- int entryKind,
- IPath path,
- IPath sourceAttachmentPath,
- IPath sourceAttachmentRootPath) {
- this.contentKind = contentKind;
- this.entryKind = entryKind;
- this.path = path;
- this.sourceAttachmentPath = sourceAttachmentPath;
- this.sourceAttachmentRootPath = sourceAttachmentRootPath;
- }
-
- /**
- * Returns true if the given object is a classpath entry
- * with equivalent attributes.
- */
- public boolean equals(Object object) {
- if (this == object)
- return true;
- if (object instanceof IClasspathEntry) {
- IClasspathEntry otherEntry = (IClasspathEntry) object;
-
- if (this.contentKind != otherEntry.getContentKind())
- return false;
-
- if (this.entryKind != otherEntry.getEntryKind())
- return false;
-
- if (!this.path.equals(otherEntry.getPath()))
- return false;
+ protected static final int K_OUTPUT= 10;
+/**
+ * Creates a class path entry of the specified kind with the given path.
+ */
+public ClasspathEntry(int contentKind, int entryKind, IPath path, IPath sourceAttachmentPath, IPath sourceAttachmentRootPath) {
+ this.contentKind = contentKind;
+ this.entryKind = entryKind;
+ this.path = path;
+ this.sourceAttachmentPath = sourceAttachmentPath;
+ this.sourceAttachmentRootPath = sourceAttachmentRootPath;
+}
+/**
+ * Returns true if the given object is a classpath entry
+ * with equivalent attributes.
+ */
+public boolean equals(Object object) {
+ if (this == object) return true;
+ if (object instanceof IClasspathEntry) {
+ IClasspathEntry otherEntry = (IClasspathEntry) object;
- IPath otherPath = otherEntry.getSourceAttachmentPath();
- if (this.sourceAttachmentPath == null) {
- if (otherPath != null)
- return false;
- } else {
- if (!this.sourceAttachmentPath.equals(otherPath))
- return false;
- }
+ if (this.contentKind != otherEntry.getContentKind()) return false;
- otherPath = otherEntry.getSourceAttachmentRootPath();
- if (this.sourceAttachmentRootPath == null) {
- if (otherPath != null)
- return false;
- } else {
- if (!this.sourceAttachmentRootPath.equals(otherPath))
- return false;
- }
+ if (this.entryKind != otherEntry.getEntryKind()) return false;
+
+ if (!this.path.equals(otherEntry.getPath())) return false;
- return true;
+ IPath otherPath = otherEntry.getSourceAttachmentPath();
+ if (this.sourceAttachmentPath == null) {
+ if (otherPath != null) return false;
} else {
- return false;
+ if (!this.sourceAttachmentPath.equals(otherPath)) return false;
+ }
+
+ otherPath = otherEntry.getSourceAttachmentRootPath();
+ if (this.sourceAttachmentRootPath == null) {
+ if (otherPath != null) return false;
+ } else {
+ if (!this.sourceAttachmentRootPath.equals(otherPath)) return false;
}
- }
-
- /**
- * @see IClasspathEntry
- */
- public int getContentKind() {
- return this.contentKind;
- }
-
- /**
- * @see IClasspathEntry
- */
- public int getEntryKind() {
- return this.entryKind;
- }
-
- /**
- * @see IClasspathEntry
- */
- public IPath getPath() {
- return this.path;
- }
-
- /**
- * @see IClasspathEntry
- * @deprecated
- */
- public IClasspathEntry getResolvedEntry() {
- return JavaCore.getResolvedClasspathEntry(this);
+ return true;
+ } else {
+ return false;
}
+}
+/**
+ * @see IClasspathEntry
+ */
+public int getContentKind() {
+ return this.contentKind;
+}
+/**
+ * @see IClasspathEntry
+ */
+public int getEntryKind() {
+ return this.entryKind;
+}
+/**
+ * @see IClasspathEntry
+ */
+public IPath getPath() {
+ return this.path;
+}
+/**
+ * @see IClasspathEntry
+ * @deprecated
+ */
+public IClasspathEntry getResolvedEntry() {
- /**
- * @see IClasspathEntry
- */
- public IPath getSourceAttachmentPath() {
- return this.sourceAttachmentPath;
+ return JavaCore.getResolvedClasspathEntry(this);
+}
+/**
+ * @see IClasspathEntry
+ */
+public IPath getSourceAttachmentPath() {
+ return this.sourceAttachmentPath;
+}
+/**
+ * @see IClasspathEntry
+ */
+public IPath getSourceAttachmentRootPath() {
+ return this.sourceAttachmentRootPath;
+}
+/**
+ * Returns the hash code for this classpath entry
+ */
+public int hashCode() {
+ return this.path.hashCode();
+}
+/**
+ * Returns a printable representation of this classpath entry.
+ */
+public String toString() {
+ StringBuffer buffer= new StringBuffer();
+ buffer.append(getPath().toString());
+ buffer.append('[');
+ switch (getEntryKind()) {
+ case IClasspathEntry.CPE_LIBRARY:
+ buffer.append("CPE_LIBRARY"/*nonNLS*/);
+ break;
+ case IClasspathEntry.CPE_PROJECT:
+ buffer.append("CPE_PROJECT"/*nonNLS*/);
+ break;
+ case IClasspathEntry.CPE_SOURCE:
+ buffer.append("CPE_SOURCE"/*nonNLS*/);
+ break;
+ case IClasspathEntry.CPE_VARIABLE:
+ buffer.append("CPE_VARIABLE"/*nonNLS*/);
+ break;
}
-
- /**
- * @see IClasspathEntry
- */
- public IPath getSourceAttachmentRootPath() {
- return this.sourceAttachmentRootPath;
+ buffer.append("]["/*nonNLS*/);
+ switch (getContentKind()) {
+ case IPackageFragmentRoot.K_BINARY:
+ buffer.append("K_BINARY"/*nonNLS*/);
+ break;
+ case IPackageFragmentRoot.K_SOURCE:
+ buffer.append("K_SOURCE"/*nonNLS*/);
+ break;
+ case ClasspathEntry.K_OUTPUT:
+ buffer.append("K_OUTPUT"/*nonNLS*/);
+ break;
}
-
- /**
- * Returns the hash code for this classpath entry
- */
- public int hashCode() {
- return this.path.hashCode();
+ buffer.append(']');
+ if (getSourceAttachmentPath() != null){
+ buffer.append("[sourcePath:"/*nonNLS*/);
+ buffer.append(getSourceAttachmentPath());
+ buffer.append(']');
}
-
- /**
- * Returns a printable representation of this classpath entry.
- */
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append(getPath().toString());
- buffer.append('[');
- switch (getEntryKind()) {
- case IClasspathEntry.CPE_LIBRARY :
- buffer.append("CPE_LIBRARY");
- break;
- case IClasspathEntry.CPE_PROJECT :
- buffer.append("CPE_PROJECT");
- break;
- case IClasspathEntry.CPE_SOURCE :
- buffer.append("CPE_SOURCE");
- break;
- case IClasspathEntry.CPE_VARIABLE :
- buffer.append("CPE_VARIABLE");
- break;
- }
- buffer.append("][");
- switch (getContentKind()) {
- case IPackageFragmentRoot.K_BINARY :
- buffer.append("K_BINARY");
- break;
- case IPackageFragmentRoot.K_SOURCE :
- buffer.append("K_SOURCE");
- break;
- case ClasspathEntry.K_OUTPUT :
- buffer.append("K_OUTPUT");
- break;
- }
+ if (getSourceAttachmentRootPath() != null){
+ buffer.append("[rootPath:"/*nonNLS*/);
+ buffer.append(getSourceAttachmentRootPath());
buffer.append(']');
- if (getSourceAttachmentPath() != null) {
- buffer.append("[sourcePath:");
- buffer.append(getSourceAttachmentPath());
- buffer.append(']');
- }
- if (getSourceAttachmentRootPath() != null) {
- buffer.append("[rootPath:");
- buffer.append(getSourceAttachmentRootPath());
- buffer.append(']');
- }
- return buffer.toString();
}
-
+ return buffer.toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
index 335c5ce992..28d5127d25 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CommitWorkingCopyOperation.java
@@ -41,116 +41,110 @@ import org.eclipse.jdt.core.IPackageFragment;
* containing the compilation unit).
*/
public class CommitWorkingCopyOperation extends JavaModelOperation {
- /**
- * Constructs an operation to commit the contents of a working copy
- * to its original compilation unit.
- */
- public CommitWorkingCopyOperation(ICompilationUnit element, boolean force) {
- super(new IJavaElement[] { element }, force);
- }
-
- /**
- * Checks that the package declaration in the compilation unit matches the actual
- * package fragment the CU is defined in.
- *
- * @exception JavaModelException with an <code>INVALID_PACKAGE</code> JavaModelStatus if the
- * package declaration is invalid.
- * @see IJavaModelStatusConstants.INVALID_PACKAGE
- */
- private void checkPackageDeclaration(ICompilationUnit cu)
- throws JavaModelException {
- IPackageFragment frag = (IPackageFragment) cu.getParent();
- IPackageDeclaration[] decls = cu.getPackageDeclarations();
- String pkgName = frag.getElementName();
- if (pkgName.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) {
- if (decls != null && decls.length > 0) {
- throw new JavaModelException(
- new JavaModelStatus(
- IJavaModelStatusConstants.INVALID_PACKAGE,
- cu,
- decls[0].getElementName()));
- }
- } else {
- if (decls == null
- || decls.length != 1
- || !pkgName.equals(decls[0].getElementName())) {
- throw new JavaModelException(
- new JavaModelStatus(
- IJavaModelStatusConstants.INVALID_PACKAGE,
- cu,
- (decls == null || decls.length == 0)
- ? IPackageFragment.DEFAULT_PACKAGE_NAME
- : decls[0].getElementName()));
- }
+/**
+ * Constructs an operation to commit the contents of a working copy
+ * to its original compilation unit.
+ */
+public CommitWorkingCopyOperation(ICompilationUnit element, boolean force) {
+ super(new IJavaElement[] {element}, force);
+}
+/**
+ * Checks that the package declaration in the compilation unit matches the actual
+ * package fragment the CU is defined in.
+ *
+ * @exception JavaModelException with an <code>INVALID_PACKAGE</code> JavaModelStatus if the
+ * package declaration is invalid.
+ * @see IJavaModelStatusConstants.INVALID_PACKAGE
+ */
+private void checkPackageDeclaration(ICompilationUnit cu)
+ throws JavaModelException {
+ IPackageFragment frag = (IPackageFragment) cu.getParent();
+ IPackageDeclaration[] decls = cu.getPackageDeclarations();
+ String pkgName = frag.getElementName();
+ if (pkgName.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) {
+ if (decls != null && decls.length > 0) {
+ throw new JavaModelException(
+ new JavaModelStatus(
+ IJavaModelStatusConstants.INVALID_PACKAGE,
+ cu,
+ decls[0].getElementName()));
+ }
+ } else {
+ if (decls == null
+ || decls.length != 1
+ || !pkgName.equals(decls[0].getElementName())) {
+ throw new JavaModelException(
+ new JavaModelStatus(
+ IJavaModelStatusConstants.INVALID_PACKAGE,
+ cu,
+ (decls == null || decls.length == 0) ? IPackageFragment.DEFAULT_PACKAGE_NAME : decls[0].getElementName()));
}
}
+}
+/**
+ * @exception JavaModelException if setting the source
+ * of the original compilation unit fails
+ */
+protected void executeOperation() throws JavaModelException {
+ beginTask(Util.bind("workingCopy.commit"/*nonNLS*/), 2);
+ ICompilationUnit copy = getCompilationUnit();
+ ICompilationUnit original = (ICompilationUnit) copy.getOriginalElement();
- /**
- * @exception JavaModelException if setting the source
- * of the original compilation unit fails
- */
- protected void executeOperation() throws JavaModelException {
- beginTask("Committing working copy...", 2);
- ICompilationUnit copy = getCompilationUnit();
- ICompilationUnit original = (ICompilationUnit) copy.getOriginalElement();
-
- // creates the delta builder (this remembers the content of the cu)
- JavaElementDeltaBuilder deltaBuilder = new JavaElementDeltaBuilder(original);
-
- // save the cu
- original.getBuffer().setContents(copy.getBuffer().getCharacters());
- original.save(fMonitor, fForce);
+
+ // creates the delta builder (this remembers the content of the cu)
+ JavaElementDeltaBuilder deltaBuilder = new JavaElementDeltaBuilder(original);
- // make sure working copy is in sync
- copy.restore();
- worked(1);
+ // save the cu
+ original.getBuffer().setContents(copy.getBuffer().getCharacters());
+ original.save(fMonitor, fForce);
- // build the deltas
- deltaBuilder.buildDeltas();
+ // make sure working copy is in sync
+ copy.restore();
+ worked(1);
- // add the deltas to the list of deltas created during this operation
- if (deltaBuilder.delta != null) {
- addDelta(deltaBuilder.delta);
- }
- worked(1);
+ // build the deltas
+ deltaBuilder.buildDeltas();
- done();
- // checkPackageDeclaration(original);
+ // add the deltas to the list of deltas created during this operation
+ if (deltaBuilder.delta != null) {
+ addDelta(deltaBuilder.delta);
}
-
- /**
- * Returns the compilation unit this operation is working on.
- */
- protected ICompilationUnit getCompilationUnit() {
- return (ICompilationUnit) getElementToProcess();
+ worked(1);
+
+ done();
+// checkPackageDeclaration(original);
+}
+/**
+ * Returns the compilation unit this operation is working on.
+ */
+protected ICompilationUnit getCompilationUnit() {
+ return (ICompilationUnit)getElementToProcess();
+}
+/**
+ * Possible failures: <ul>
+ * <li>INVALID_ELEMENT_TYPES - the compilation unit supplied to this
+ * operation is not a working copy
+ * <li>ELEMENT_NOT_PRESENT - the compilation unit the working copy is
+ * based on no longer exists.
+ * <li>UPDATE_CONFLICT - the original compilation unit has changed since
+ * the working copy was created and the operation specifies no force
+ * </ul>
+ */
+public IJavaModelStatus verify() {
+ ICompilationUnit cu = getCompilationUnit();
+ if (!cu.isWorkingCopy()) {
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, cu);
}
-
- /**
- * Possible failures: <ul>
- * <li>INVALID_ELEMENT_TYPES - the compilation unit supplied to this
- * operation is not a working copy
- * <li>ELEMENT_NOT_PRESENT - the compilation unit the working copy is
- * based on no longer exists.
- * <li>UPDATE_CONFLICT - the original compilation unit has changed since
- * the working copy was created and the operation specifies no force
- * </ul>
- */
- public IJavaModelStatus verify() {
- ICompilationUnit cu = getCompilationUnit();
- if (!cu.isWorkingCopy()) {
- return new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, cu);
- }
- ICompilationUnit original = (ICompilationUnit) cu.getOriginalElement();
- IResource resource = null;
- try {
- resource = original.getUnderlyingResource();
- } catch (JavaModelException e) {
- return e.getJavaModelStatus();
- }
- if (!cu.isBasedOn(resource) && !fForce) {
- return new JavaModelStatus(IJavaModelStatusConstants.UPDATE_CONFLICT);
- }
- return JavaModelStatus.VERIFIED_OK;
+ ICompilationUnit original= (ICompilationUnit)cu.getOriginalElement();
+ IResource resource= null;
+ try {
+ resource = original.getUnderlyingResource();
+ } catch (JavaModelException e) {
+ return e.getJavaModelStatus();
}
-
+ if (!cu.isBasedOn(resource) && !fForce) {
+ return new JavaModelStatus(IJavaModelStatusConstants.UPDATE_CONFLICT);
+ }
+ return JavaModelStatus.VERIFIED_OK;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnit.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnit.java
index 412db8b1ea..4965de0c0a 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnit.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnit.java
@@ -16,672 +16,559 @@ import org.eclipse.jdt.internal.core.lookup.*;
import java.util.*;
+import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
+
/**
* @see ICompilationUnit
*/
-public class CompilationUnit
- extends Openable
- implements ICompilationUnit, org.eclipse.jdt.internal.compiler.env.ICompilationUnit {
-
- /**
- * Constructs a handle to a compilation unit with the given name in the
- * specified package.
- *
- * @exception IllegalArgumentException if the name of the compilation unit
- * does not end with ".java"
- */
- protected CompilationUnit(IPackageFragment parent, String name) {
- super(COMPILATION_UNIT, parent, name);
- if (!name.toUpperCase().endsWith(".JAVA")) {
- throw new IllegalArgumentException("compilation unit name must end with .java");
- }
- }
-
- /**
- * Accepts the given visitor onto the parsed tree of this compilation unit, after
- * having runned the name resolution.
- * The visitor's corresponding <code>visit</code> method is called with the
- * corresponding parse tree. If the visitor returns <code>true</code>, this method
- * visits this parse node's members.
- *
- * @param visitor the visitor
- * @exception JavaModelException if this method fails. Reasons include:
- * <ul>
- * <li> This element does not exist.</li>
- * <li> The visitor failed with this exception.</li>
- * </ul>
- */
- public void accept(IAbstractSyntaxTreeVisitor visitor)
- throws JavaModelException {
- CompilationUnitVisitor.visit(this, visitor);
- }
-
- /**
- * @see ICodeAssist
- */
- public void codeComplete(int offset, ICodeCompletionRequestor requestor)
- throws JavaModelException {
- codeComplete(
- this,
- isWorkingCopy()
- ? (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) getOriginalElement()
- : this,
- offset,
- requestor);
- }
-
- /**
- * @see ICodeResolve
- */
- public IJavaElement[] codeSelect(int offset, int length)
- throws JavaModelException {
- return super.codeSelect(this, offset, length);
- }
+public class CompilationUnit extends Openable implements ICompilationUnit, org.eclipse.jdt.internal.compiler.env.ICompilationUnit {
- /**
- * @see IWorkingCopy
- */
- public void commit(boolean force, IProgressMonitor monitor)
- throws JavaModelException {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this));
- }
-
- /**
- * @see ISourceManipulation
- */
- public void copy(
- IJavaElement container,
- IJavaElement sibling,
- String rename,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- if (container == null) {
- throw new IllegalArgumentException("container cannot be null");
- }
- IJavaElement[] elements = new IJavaElement[] { this };
- IJavaElement[] containers = new IJavaElement[] { container };
- String[] renamings = null;
- if (rename != null) {
- renamings = new String[] { rename };
- }
- getJavaModel().copy(elements, containers, null, renamings, force, monitor);
+/**
+ * Constructs a handle to a compilation unit with the given name in the
+ * specified package.
+ *
+ * @exception IllegalArgumentException if the name of the compilation unit
+ * does not end with ".java"
+ */
+protected CompilationUnit(IPackageFragment parent, String name) {
+ super(COMPILATION_UNIT, parent, name);
+ if (!Util.isJavaFileName(name)) {
+ throw new IllegalArgumentException(Util.bind("element.invalidUnitName"/*nonNLS*/));
}
-
- /**
- * Returns a new element info for this element.
- */
- protected OpenableElementInfo createElementInfo() {
- return new CompilationUnitElementInfo();
+}
+/**
+ * Accepts the given visitor onto the parsed tree of this compilation unit, after
+ * having runned the name resolution.
+ * The visitor's corresponding <code>visit</code> method is called with the
+ * corresponding parse tree. If the visitor returns <code>true</code>, this method
+ * visits this parse node's members.
+ *
+ * @param visitor the visitor
+ * @exception JavaModelException if this method fails. Reasons include:
+ * <ul>
+ * <li> This element does not exist.</li>
+ * <li> The visitor failed with this exception.</li>
+ * </ul>
+ */
+public void accept(IAbstractSyntaxTreeVisitor visitor) throws JavaModelException {
+ CompilationUnitVisitor.visit(this, visitor);
+}
+/**
+ * @see ICodeAssist
+ */
+public void codeComplete(int offset, ICodeCompletionRequestor requestor) throws JavaModelException {
+ codeComplete(this, isWorkingCopy() ? (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) getOriginalElement() : this, offset, requestor);
+}
+/**
+ * @see ICodeResolve
+ */
+public IJavaElement[] codeSelect(int offset, int length) throws JavaModelException {
+ return super.codeSelect(this, offset, length);
+}
+/**
+ * @see IWorkingCopy
+ */
+public void commit(boolean force, IProgressMonitor monitor) throws JavaModelException {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this));
+}
+/**
+ * @see ISourceManipulation
+ */
+public void copy(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ if (container == null) {
+ throw new IllegalArgumentException(Util.bind("operation.nullContainer"/*nonNLS*/));
}
-
- /**
- * @see ICompilationUnit
- */
- public IImportDeclaration createImport(
- String name,
- IJavaElement sibling,
- IProgressMonitor monitor)
- throws JavaModelException {
- CreateImportOperation op = new CreateImportOperation(name, this);
- if (sibling != null) {
- op.createBefore(sibling);
- }
- runOperation(op, monitor);
- return getImport(name);
+ IJavaElement[] elements = new IJavaElement[] {this};
+ IJavaElement[] containers = new IJavaElement[] {container};
+ String[] renamings = null;
+ if (rename != null) {
+ renamings = new String[] {rename};
}
-
- /**
- * @see ICompilationUnit
- */
- public IPackageDeclaration createPackageDeclaration(
- String name,
- IProgressMonitor monitor)
- throws JavaModelException {
-
- CreatePackageDeclarationOperation op =
- new CreatePackageDeclarationOperation(name, this);
- runOperation(op, monitor);
- return getPackageDeclaration(name);
+ getJavaModel().copy(elements, containers, null, renamings, force, monitor);
+}
+/**
+ * Returns a new element info for this element.
+ */
+protected OpenableElementInfo createElementInfo() {
+ return new CompilationUnitElementInfo();
+}
+/**
+ * @see ICompilationUnit
+ */
+public IImportDeclaration createImport(String name, IJavaElement sibling, IProgressMonitor monitor) throws JavaModelException {
+ CreateImportOperation op = new CreateImportOperation(name, this);
+ if (sibling != null) {
+ op.createBefore(sibling);
}
-
- /**
- * @see ICompilationUnit
- */
- public IType createType(
- String content,
- IJavaElement sibling,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- if (!exists()) {
- //autogenerate this compilation unit
- IPackageFragment pkg = (IPackageFragment) getParent();
- String source = "";
- if (pkg.getElementName().length() > 0) {
- //not the default package...add the package declaration
- source =
- "package " + pkg.getElementName() + ";" + JavaModelManager.LINE_SEPARATOR;
- }
- CreateCompilationUnitOperation op =
- new CreateCompilationUnitOperation(pkg, fName, source, force);
- runOperation(op, monitor);
- }
- CreateTypeOperation op = new CreateTypeOperation(this, content, force);
- if (sibling != null) {
- op.createBefore(sibling);
+ runOperation(op, monitor);
+ return getImport(name);
+}
+/**
+ * @see ICompilationUnit
+ */
+public IPackageDeclaration createPackageDeclaration(String name, IProgressMonitor monitor) throws JavaModelException {
+
+ CreatePackageDeclarationOperation op= new CreatePackageDeclarationOperation(name, this);
+ runOperation(op, monitor);
+ return getPackageDeclaration(name);
+}
+/**
+ * @see ICompilationUnit
+ */
+public IType createType(String content, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ if (!exists()) {
+ //autogenerate this compilation unit
+ IPackageFragment pkg = (IPackageFragment) getParent();
+ String source = ""/*nonNLS*/;
+ if (pkg.getElementName().length() > 0) {
+ //not the default package...add the package declaration
+ source = "package "/*nonNLS*/ + pkg.getElementName() + ";"/*nonNLS*/ + JavaModelManager.LINE_SEPARATOR;
}
+ CreateCompilationUnitOperation op = new CreateCompilationUnitOperation(pkg, fName, source, force);
runOperation(op, monitor);
- return (IType) op.getResultElements()[0];
}
-
- /**
- * @see ISourceManipulation
- */
- public void delete(boolean force, IProgressMonitor monitor)
- throws JavaModelException {
- IJavaElement[] elements = new IJavaElement[] { this };
- getJavaModel().delete(elements, force, monitor);
- }
-
- /**
- * This is not a working copy, do nothing.
- *
- * @see IWorkingCopy
- */
- public void destroy() {
- }
-
- /**
- * Returns true if this handle represents the same Java element
- * as the given handle.
- *
- * <p>Compilation units must also check working copy state;
- *
- * @see Object#equals
- */
- public boolean equals(Object o) {
- return super.equals(o) && !((ICompilationUnit) o).isWorkingCopy();
+ CreateTypeOperation op = new CreateTypeOperation(this, content, force);
+ if (sibling != null) {
+ op.createBefore(sibling);
}
-
- /**
- * @see JavaElement#equalsDOMNode
- */
- protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
- String name = getElementName();
- if (node.getNodeType() == IDOMNode.COMPILATION_UNIT && name != null) {
- String nodeName = node.getName();
- if (nodeName == null)
- return false;
- if (name.equals(nodeName)) {
- return true;
- } else {
- // iterate through all the types inside the receiver and see if one of them can fit
- IType[] types = getTypes();
- String typeNodeName = nodeName.substring(0, nodeName.indexOf(".java"));
- for (int i = 0, max = types.length; i < max; i++) {
- if (types[i].getElementName().equals(typeNodeName)) {
- return true;
- }
+ runOperation(op, monitor);
+ return (IType) op.getResultElements()[0];
+}
+/**
+ * @see ISourceManipulation
+ */
+public void delete(boolean force, IProgressMonitor monitor) throws JavaModelException {
+ IJavaElement[] elements= new IJavaElement[] {this};
+ getJavaModel().delete(elements, force, monitor);
+}
+/**
+ * This is not a working copy, do nothing.
+ *
+ * @see IWorkingCopy
+ */
+public void destroy() {
+}
+/**
+ * Returns true if this handle represents the same Java element
+ * as the given handle.
+ *
+ * <p>Compilation units must also check working copy state;
+ *
+ * @see Object#equals
+ */
+public boolean equals(Object o) {
+ return super.equals(o) && !((ICompilationUnit)o).isWorkingCopy();
+}
+/**
+ * @see JavaElement#equalsDOMNode
+ */
+protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
+ String name = getElementName();
+ if (node.getNodeType() == IDOMNode.COMPILATION_UNIT && name != null ) {
+ String nodeName = node.getName();
+ if (nodeName == null) return false;
+ if (name.equals(nodeName)) {
+ return true;
+ } else {
+ // iterate through all the types inside the receiver and see if one of them can fit
+ IType[] types = getTypes();
+ String typeNodeName = nodeName.substring(0, nodeName.indexOf(".java"/*nonNLS*/));
+ for (int i = 0, max = types.length; i < max; i++) {
+ if (types[i].getElementName().equals(typeNodeName)) {
+ return true;
}
}
}
- return false;
}
-
- /**
- * @see Openable
- */
- protected boolean generateInfos(
- OpenableElementInfo info,
- IProgressMonitor pm,
- Hashtable newElements,
- IResource underlyingResource)
- throws JavaModelException {
-
- if (getParent() instanceof JarPackageFragment) {
- // ignore .java files in jar
- throw newNotPresentException();
- } else {
- // put the info now, because getting the contents requires it
- fgJavaModelManager.putInfo(this, info);
- CompilationUnitElementInfo unitInfo = (CompilationUnitElementInfo) info;
-
- // generate structure
- CompilationUnitStructureRequestor requestor =
- new CompilationUnitStructureRequestor(this, unitInfo, newElements);
- IProblemFactory factory = new ProblemFactory();
- SourceElementParser parser = new SourceElementParser(requestor, factory);
- parser.parseCompilationUnit(this, !isWorkingCopy());
- if (isWorkingCopy()) {
- // remember problems
- Vector problems = requestor.fProblems;
- if (problems != null) {
- problems.copyInto(
- ((WorkingCopyElementInfo) unitInfo).problems = new IProblem[problems.size()]);
- }
-
- CompilationUnit original = (CompilationUnit) getOriginalElement();
- unitInfo.fTimestamp =
- ((IFile) original.getUnderlyingResource()).getModificationStamp();
- if (unitInfo.fTimestamp == IResource.NULL_STAMP) {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.INVALID_RESOURCE));
- }
+ return false;
+}
+/**
+ * @see Openable
+ */
+protected boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Hashtable newElements, IResource underlyingResource) throws JavaModelException {
+
+ if (getParent() instanceof JarPackageFragment) {
+ // ignore .java files in jar
+ throw newNotPresentException();
+ } else {
+ // put the info now, because getting the contents requires it
+ fgJavaModelManager.putInfo(this, info);
+ CompilationUnitElementInfo unitInfo = (CompilationUnitElementInfo) info;
+
+ // generate structure
+ CompilationUnitStructureRequestor requestor = new CompilationUnitStructureRequestor(this, unitInfo, newElements);
+ IProblemFactory factory = new DefaultProblemFactory();
+ SourceElementParser parser = new SourceElementParser(requestor, factory);
+ parser.parseCompilationUnit(this, !isWorkingCopy());
+ if (isWorkingCopy()) {
+ // remember problems
+ Vector problems = requestor.fProblems;
+ if (problems != null) {
+ problems.copyInto(((WorkingCopyElementInfo)unitInfo).problems = new IProblem[problems.size()]);
+ }
+
+ CompilationUnit original = (CompilationUnit) getOriginalElement();
+ unitInfo.fTimestamp = ((IFile) original.getUnderlyingResource()).getModificationStamp();
+ if(unitInfo.fTimestamp == IResource.NULL_STAMP){
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_RESOURCE));
}
- return unitInfo.isStructureKnown();
}
+ return unitInfo.isStructureKnown();
}
-
- /**
- * @see ICompilationUnit
- */
- public IType[] getAllTypes() throws JavaModelException {
- IJavaElement[] types = getTypes();
- int i;
- Vector allTypes = new Vector(types.length);
- Vector typesToTraverse = new Vector(types.length);
+}
+/**
+ * @see ICompilationUnit
+ */
+public IType[] getAllTypes() throws JavaModelException {
+ IJavaElement[] types = getTypes();
+ int i;
+ Vector allTypes = new Vector(types.length);
+ Vector typesToTraverse = new Vector(types.length);
+ for (i = 0; i < types.length; i++) {
+ typesToTraverse.addElement(types[i]);
+ }
+ while (!typesToTraverse.isEmpty()) {
+ IType type = (IType) typesToTraverse.elementAt(0);
+ typesToTraverse.removeElement(type);
+ allTypes.addElement(type);
+ types = type.getTypes();
for (i = 0; i < types.length; i++) {
typesToTraverse.addElement(types[i]);
}
- while (!typesToTraverse.isEmpty()) {
- IType type = (IType) typesToTraverse.elementAt(0);
- typesToTraverse.removeElement(type);
- allTypes.addElement(type);
- types = type.getTypes();
- for (i = 0; i < types.length; i++) {
- typesToTraverse.addElement(types[i]);
- }
- }
- allTypes.trimToSize();
- IType[] arrayOfAllTypes = new IType[allTypes.size()];
- allTypes.copyInto(arrayOfAllTypes);
- return arrayOfAllTypes;
- }
-
- /**
- * @see IMember
- */
- public ICompilationUnit getCompilationUnit() {
- return this;
- }
-
- /**
- * @see org.eclipse.jdt.internal.compiler.env.api.ICompilationUnit
- */
- public char[] getContents() {
- try {
- return getBuffer().getCharacters();
- } catch (NullPointerException e) { // buffer could be null
- return new char[0];
- } catch (JavaModelException e) {
- return new char[0];
- }
- }
-
- /**
- * A compilation unit has a corresponding resource unless it is contained
- * in a jar.
- *
- * @see IJavaElement
- */
- public IResource getCorrespondingResource() throws JavaModelException {
- IPackageFragmentRoot root = (IPackageFragmentRoot) getParent().getParent();
- if (root.isArchive()) {
- return null;
- } else {
- return getUnderlyingResource();
- }
- }
-
- /**
- * @see ICompilationUnit
- */
- public IJavaElement getElementAt(int position) throws JavaModelException {
-
- IJavaElement e = getSourceElementAt(position);
- if (e == this) {
- return null;
- } else {
- return e;
- }
- }
-
- /**
- * @see org.eclipse.jdt.internal.compiler.env.api.ICompilationUnit
- */
- public char[] getFileName() {
- return getElementName().toCharArray();
}
-
- /**
- * @see JavaElement#getHandleMemento()
- */
- protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_COMPILATIONUNIT;
- }
-
- /**
- * @see ICompilationUnit#getImport
- */
- public IImportDeclaration getImport(String name) {
- return new ImportDeclaration(getImportContainer(), name);
- }
-
- /**
- * @see ICompilationUnit
- */
- public IImportContainer getImportContainer() {
- return new ImportContainer(this);
- }
-
- /**
- * @see ICompilationUnit
- */
- public IImportDeclaration[] getImports() throws JavaModelException {
- IImportContainer container = getImportContainer();
- if (container.exists()) {
- IJavaElement[] elements = container.getChildren();
- IImportDeclaration[] imprts = new IImportDeclaration[elements.length];
- System.arraycopy(elements, 0, imprts, 0, elements.length);
- return imprts;
- } else
- if (!exists()) {
- throw newNotPresentException();
- } else {
- return new IImportDeclaration[0];
- }
-
- }
-
- /**
- * @see org.eclipse.jdt.internal.compiler.env.api.ICompilationUnit
- */
- public char[] getMainTypeName() {
- String name = getElementName();
- //remove the .java
- name = name.substring(0, name.length() - 5);
- return name.toCharArray();
+ allTypes.trimToSize();
+ IType[] arrayOfAllTypes = new IType[allTypes.size()];
+ allTypes.copyInto(arrayOfAllTypes);
+ return arrayOfAllTypes;
+}
+/**
+ * @see IMember
+ */
+public ICompilationUnit getCompilationUnit() {
+ return this;
+}
+/**
+ * @see org.eclipse.jdt.internal.compiler.env.api.ICompilationUnit
+ */
+public char[] getContents() {
+ try {
+ return getBuffer().getCharacters();
+ } catch (NullPointerException e) { // buffer could be null
+ return new char[0];
+ } catch (JavaModelException e) {
+ return new char[0];
}
-
- /**
- * Returns <code>null</code>, this is not a working copy.
- *
- * @see IWorkingCopy
- */
- public IJavaElement getOriginal(IJavaElement workingCopyElement) {
+}
+/**
+ * A compilation unit has a corresponding resource unless it is contained
+ * in a jar.
+ *
+ * @see IJavaElement
+ */
+public IResource getCorrespondingResource() throws JavaModelException {
+ IPackageFragmentRoot root= (IPackageFragmentRoot)getParent().getParent();
+ if (root.isArchive()) {
return null;
+ } else {
+ return getUnderlyingResource();
}
+}
+/**
+ * @see ICompilationUnit
+ */
+public IJavaElement getElementAt(int position) throws JavaModelException {
- /**
- * Returns <code>null</code>, this is not a working copy.
- *
- * @see IWorkingCopy
- */
- public IJavaElement getOriginalElement() {
+ IJavaElement e= getSourceElementAt(position);
+ if (e == this) {
return null;
+ } else {
+ return e;
}
-
- /**
- * @see ICompilationUnit#getPackageDeclaration(String)
- */
- public IPackageDeclaration getPackageDeclaration(String name) {
- return new PackageDeclaration(this, name);
- }
-
- /**
- * @see ICompilationUnit
- */
- public IPackageDeclaration[] getPackageDeclarations()
- throws JavaModelException {
- Vector v = getChildrenOfType(PACKAGE_DECLARATION);
- IPackageDeclaration[] array = new IPackageDeclaration[v.size()];
- v.copyInto(array);
- return array;
- }
-
- /**
- * Returns the reference information for this compilation unit
- */
- public ReferenceInfo getReferenceInfo() throws JavaModelException {
- return ((CompilationUnitElementInfo) getElementInfo()).getReferenceInfo();
- }
-
- /**
- * @see ISourceReference
- */
- public String getSource() throws JavaModelException {
- IBuffer buffer = getBuffer();
- if (buffer == null)
- return "";
- return buffer.getContents();
- }
-
- /**
- * @see ISourceReference
- */
- public ISourceRange getSourceRange() throws JavaModelException {
- return ((CompilationUnitElementInfo) getElementInfo()).getSourceRange();
- }
-
- /**
- * @see ICompilationUnit
- */
- public IType getType(String name) {
- return new SourceType(this, name);
- }
-
- /**
- * @see ICompilationUnit
- */
- public IType[] getTypes() throws JavaModelException {
- Vector v = getChildrenOfType(TYPE);
- IType[] array = new IType[v.size()];
- v.copyInto(array);
- return array;
- }
-
- /**
- * @see IWorkingCopy
- */
- public IJavaElement getWorkingCopy() throws JavaModelException {
- WorkingCopy workingCopy =
- new WorkingCopy((IPackageFragment) getParent(), getElementName());
- // open the working copy now to ensure contents are that of the current state of this element
- workingCopy.open(null);
- return workingCopy;
- }
-
- /**
- * @see Openable
- */
- protected boolean hasBuffer() {
- return true;
- }
-
- /**
- * If I am not open, return true to avoid parsing.
- *
- * @see IParent
- */
- public boolean hasChildren() throws JavaModelException {
- if (isOpen()) {
- return getChildren().length > 0;
- } else {
- return true;
- }
- }
-
- /**
- * Returns false, this is not a working copy.
- *
- * @see IWorkingCopy
- */
- public boolean isBasedOn(IResource resource) {
- return false;
- }
-
- /**
- * @see IOpenable
- */
- public boolean isConsistent() throws JavaModelException {
- return fgJavaModelManager.getElementsOutOfSynchWithBuffers().get(this) == null;
+}
+/**
+ * @see org.eclipse.jdt.internal.compiler.env.api.ICompilationUnit
+ */
+public char[] getFileName(){
+ return getElementName().toCharArray();
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+protected char getHandleMementoDelimiter() {
+ return JavaElement.JEM_COMPILATIONUNIT;
+}
+/**
+ * @see ICompilationUnit#getImport
+ */
+public IImportDeclaration getImport(String name) {
+ return new ImportDeclaration(getImportContainer(), name);
+}
+/**
+ * @see ICompilationUnit
+ */
+public IImportContainer getImportContainer() {
+ return new ImportContainer(this);
+}
+/**
+ * @see ICompilationUnit
+ */
+public IImportDeclaration[] getImports() throws JavaModelException {
+ IImportContainer container= getImportContainer();
+ if (container.exists()) {
+ IJavaElement[] elements= container.getChildren();
+ IImportDeclaration[] imprts= new IImportDeclaration[elements.length];
+ System.arraycopy(elements, 0, imprts, 0, elements.length);
+ return imprts;
+ } else if (!exists()) {
+ throw newNotPresentException();
+ } else {
+ return new IImportDeclaration[0];
}
- /**
- * @see Openable
- */
- protected boolean isSourceElement() {
+}
+/**
+ * @see org.eclipse.jdt.internal.compiler.env.api.ICompilationUnit
+ */
+public char[] getMainTypeName(){
+ String name= getElementName();
+ //remove the .java
+ name= name.substring(0, name.length() - 5);
+ return name.toCharArray();
+}
+/**
+ * Returns <code>null</code>, this is not a working copy.
+ *
+ * @see IWorkingCopy
+ */
+public IJavaElement getOriginal(IJavaElement workingCopyElement) {
+ return null;
+}
+/**
+ * Returns <code>null</code>, this is not a working copy.
+ *
+ * @see IWorkingCopy
+ */
+public IJavaElement getOriginalElement() {
+ return null;
+}
+/**
+ * @see ICompilationUnit#getPackageDeclaration(String)
+ */
+public IPackageDeclaration getPackageDeclaration(String name) {
+ return new PackageDeclaration(this, name);
+}
+/**
+ * @see ICompilationUnit
+ */
+public IPackageDeclaration[] getPackageDeclarations() throws JavaModelException {
+ Vector v= getChildrenOfType(PACKAGE_DECLARATION);
+ IPackageDeclaration[] array= new IPackageDeclaration[v.size()];
+ v.copyInto(array);
+ return array;
+}
+/**
+ * Returns the reference information for this compilation unit
+ */
+public ReferenceInfo getReferenceInfo() throws JavaModelException {
+ return ((CompilationUnitElementInfo)getElementInfo()).getReferenceInfo();
+}
+/**
+ * @see ISourceReference
+ */
+public String getSource() throws JavaModelException {
+ IBuffer buffer = getBuffer();
+ if (buffer == null) return ""/*nonNLS*/;
+ return buffer.getContents();
+}
+/**
+ * @see ISourceReference
+ */
+public ISourceRange getSourceRange() throws JavaModelException {
+ return ((CompilationUnitElementInfo) getElementInfo()).getSourceRange();
+}
+/**
+ * @see ICompilationUnit
+ */
+public IType getType(String name) {
+ return new SourceType(this, name);
+}
+/**
+ * @see ICompilationUnit
+ */
+public IType[] getTypes() throws JavaModelException {
+ Vector v= getChildrenOfType(TYPE);
+ IType[] array= new IType[v.size()];
+ v.copyInto(array);
+ return array;
+}
+/**
+ * @see IWorkingCopy
+ */
+public IJavaElement getWorkingCopy() throws JavaModelException {
+ WorkingCopy workingCopy= new WorkingCopy((IPackageFragment)getParent(), getElementName());
+ // open the working copy now to ensure contents are that of the current state of this element
+ workingCopy.open(null);
+ return workingCopy;
+}
+/**
+ * @see Openable
+ */
+protected boolean hasBuffer() {
+ return true;
+}
+/**
+ * If I am not open, return true to avoid parsing.
+ *
+ * @see IParent
+ */
+public boolean hasChildren() throws JavaModelException {
+ if (isOpen()) {
+ return getChildren().length > 0;
+ } else {
return true;
}
-
- /**
- * @see IWorkingCopy
- */
- public boolean isWorkingCopy() {
- return false;
- }
-
- /**
- * @see IOpenable
- */
- public void makeConsistent(IProgressMonitor pm) throws JavaModelException {
- if (!isConsistent()) {
- // create a new info and make it the current info
- OpenableElementInfo info = createElementInfo();
- buildStructure(info, pm);
- }
- }
-
- /**
- * @see ISourceManipulation
- */
- public void move(
- IJavaElement container,
- IJavaElement sibling,
- String rename,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- if (container == null) {
- throw new IllegalArgumentException("container cannot be null");
- }
- IJavaElement[] elements = new IJavaElement[] { this };
- IJavaElement[] containers = new IJavaElement[] { container };
-
- String[] renamings = null;
- if (rename != null) {
- renamings = new String[] { rename };
- }
- getJavaModel().move(elements, containers, null, renamings, force, monitor);
- }
-
- /**
- * Changes the source end index of this element and all children (following
- * <code>child</code>).
- */
- public void offsetSourceEndAndChildren(int amount, IJavaElement child) {
- try {
- CompilationUnitElementInfo cuInfo =
- (CompilationUnitElementInfo) getElementInfo();
- cuInfo.setSourceLength(cuInfo.getSourceLength() + amount);
- IJavaElement[] children = getChildren();
- boolean afterChild = false;
- for (int i = 0; i < children.length; i++) {
- IJavaElement aChild = children[i];
- if (child == null || aChild.equals(child)) {
- afterChild = true;
- } else
- if (afterChild) {
- ((JavaElement) aChild).offsetSourceRange(amount);
- }
- }
- } catch (JavaModelException npe) {
- return;
- }
- }
-
- /**
- * Changes the source indexes of this element and all children elements.
- */
- public void offsetSourceRange(int amount) {
- try {
- CompilationUnitElementInfo cuInfo =
- (CompilationUnitElementInfo) getElementInfo();
- cuInfo.setSourceLength(cuInfo.getSourceLength() + amount);
- IJavaElement[] children = getChildren();
- for (int i = 0; i < children.length; i++) {
- IJavaElement aChild = children[i];
- ((JavaElement) aChild).offsetSourceRange(amount);
- }
- } catch (JavaModelException npe) {
- return;
- }
- }
-
- /**
- * @see Openable
- */
- protected IBuffer openBuffer(IProgressMonitor pm) throws JavaModelException {
- IBuffer buf =
- getBufferManager().openBuffer(
- (IFile) getUnderlyingResource(),
- pm,
- this,
- isReadOnly());
- buf.addBufferChangedListener(this);
- return buf;
- }
-
- /**
- * @see IWorkingCopy
- */
- public IMarker[] reconcile() throws JavaModelException {
- // Reconciling is not supported on non working copies
- return null;
+}
+/**
+ * Returns false, this is not a working copy.
+ *
+ * @see IWorkingCopy
+ */
+public boolean isBasedOn(IResource resource) {
+ return false;
+}
+/**
+ * @see IOpenable
+ */
+public boolean isConsistent() throws JavaModelException {
+ return fgJavaModelManager.getElementsOutOfSynchWithBuffers().get(this) == null;
+}
+/**
+ * @see Openable
+ */
+protected boolean isSourceElement() {
+ return true;
+}
+/**
+ * @see IWorkingCopy
+ */
+public boolean isWorkingCopy() {
+ return false;
+}
+/**
+ * @see IOpenable
+ */
+public void makeConsistent(IProgressMonitor pm) throws JavaModelException {
+ if (!isConsistent()) {
+ // create a new info and make it the current info
+ OpenableElementInfo info = createElementInfo();
+ buildStructure(info, pm);
}
-
- /**
- * @see ISourceManipulation
- */
- public void rename(String name, boolean force, IProgressMonitor monitor)
- throws JavaModelException {
- if (name == null) {
- throw new IllegalArgumentException("name cannot be null");
+}
+/**
+ * @see ISourceManipulation
+ */
+public void move(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ if (container == null) {
+ throw new IllegalArgumentException(Util.bind("operation.nullContainer"/*nonNLS*/));
+ }
+ IJavaElement[] elements= new IJavaElement[] {this};
+ IJavaElement[] containers= new IJavaElement[] {container};
+
+ String[] renamings= null;
+ if (rename != null) {
+ renamings= new String[] {rename};
+ }
+ getJavaModel().move(elements, containers, null, renamings, force, monitor);
+}
+/**
+ * Changes the source end index of this element and all children (following
+ * <code>child</code>).
+ */
+public void offsetSourceEndAndChildren(int amount, IJavaElement child) {
+ try {
+ CompilationUnitElementInfo cuInfo = (CompilationUnitElementInfo) getElementInfo();
+ cuInfo.setSourceLength(cuInfo.getSourceLength() + amount);
+ IJavaElement[] children = getChildren();
+ boolean afterChild = false;
+ for (int i = 0; i < children.length; i++) {
+ IJavaElement aChild = children[i];
+ if (child == null || aChild.equals(child)) {
+ afterChild = true;
+ } else
+ if (afterChild) {
+ ((JavaElement) aChild).offsetSourceRange(amount);
+ }
}
- IJavaElement[] elements = new IJavaElement[] { this };
- IJavaElement[] dests = new IJavaElement[] { this.getParent()};
- String[] renamings = new String[] { name };
- getJavaModel().rename(elements, dests, renamings, force, monitor);
+ } catch (JavaModelException npe) {
+ return;
}
-
- /**
- * Does nothing - this is not a working copy.
- *
- * @see IWorkingCopy
- */
- public void restore() throws JavaModelException {
- }
-
- /**
- * Updates the source end index for this element.
- */
- public void triggerSourceEndOffset(int amount, int nameStart, int nameEnd) {
- try {
- CompilationUnitElementInfo cuInfo = (CompilationUnitElementInfo) getRawInfo();
- cuInfo.setSourceLength(cuInfo.getSourceLength() + amount);
- } catch (JavaModelException npe) {
- return;
+}
+/**
+ * Changes the source indexes of this element and all children elements.
+ */
+public void offsetSourceRange(int amount) {
+ try {
+ CompilationUnitElementInfo cuInfo = (CompilationUnitElementInfo) getElementInfo();
+ cuInfo.setSourceLength(cuInfo.getSourceLength() + amount);
+ IJavaElement[] children = getChildren();
+ for (int i = 0; i < children.length; i++) {
+ IJavaElement aChild = children[i];
+ ((JavaElement) aChild).offsetSourceRange(amount);
}
+ } catch (JavaModelException npe) {
+ return;
}
-
- /**
- * Updates the source indexes for this element.
- */
- public void triggerSourceRangeOffset(int amount, int nameStart, int nameEnd) {
- triggerSourceEndOffset(amount, nameStart, nameEnd);
+}
+/**
+ * @see Openable
+ */
+protected IBuffer openBuffer(IProgressMonitor pm) throws JavaModelException {
+ IBuffer buf = getBufferManager().openBuffer((IFile) getUnderlyingResource(), pm, this, isReadOnly());
+ buf.addBufferChangedListener(this);
+ return buf;
+}
+/**
+ * @see IWorkingCopy
+ */
+public IMarker[] reconcile() throws JavaModelException {
+ // Reconciling is not supported on non working copies
+ return null;
+}
+/**
+ * @see ISourceManipulation
+ */
+public void rename(String name, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ if (name == null) {
+ throw new IllegalArgumentException(Util.bind("operation.nullName"/*nonNLS*/));
+ }
+ IJavaElement[] elements= new IJavaElement[] {this};
+ IJavaElement[] dests= new IJavaElement[] {this.getParent()};
+ String[] renamings= new String[] {name};
+ getJavaModel().rename(elements, dests, renamings, force, monitor);
+}
+/**
+ * Does nothing - this is not a working copy.
+ *
+ * @see IWorkingCopy
+ */
+public void restore () throws JavaModelException {
+}
+/**
+ * Updates the source end index for this element.
+ */
+public void triggerSourceEndOffset(int amount, int nameStart, int nameEnd) {
+ try {
+ CompilationUnitElementInfo cuInfo = (CompilationUnitElementInfo) getRawInfo();
+ cuInfo.setSourceLength(cuInfo.getSourceLength() + amount);
+ } catch (JavaModelException npe) {
+ return;
}
-
+}
+/**
+ * Updates the source indexes for this element.
+ */
+public void triggerSourceRangeOffset(int amount, int nameStart, int nameEnd) {
+ triggerSourceEndOffset(amount, nameStart, nameEnd);
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitElementInfo.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitElementInfo.java
index 0806d983aa..ae761f07e8 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitElementInfo.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitElementInfo.java
@@ -9,8 +9,7 @@ import org.eclipse.core.resources.*;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.internal.core.lookup.ReferenceInfo;
-/* package */
-class CompilationUnitElementInfo extends OpenableElementInfo {
+/* package */ class CompilationUnitElementInfo extends OpenableElementInfo {
/**
* The length of this compilation unit's source code <code>String</code>
@@ -26,36 +25,31 @@ class CompilationUnitElementInfo extends OpenableElementInfo {
* was opened or last updated.
*/
protected long fTimestamp;
- /**
- * Returns the reference information for this compilation unit
- */
- public ReferenceInfo getReferenceInfo() {
- return fRefInfo;
- }
-
- /**
- * Returns the length of the source string.
- */
- public int getSourceLength() {
- return fSourceLength;
- }
-
- protected ISourceRange getSourceRange() {
- return new SourceRange(0, fSourceLength);
- }
-
- /**
- * Sets the reference information for this compilation unit
- */
- public void setReferenceInfo(ReferenceInfo info) {
- fRefInfo = info;
- }
-
- /**
- * Sets the length of the source string.
- */
- public void setSourceLength(int newSourceLength) {
- fSourceLength = newSourceLength;
- }
-
+/**
+ * Returns the reference information for this compilation unit
+ */
+public ReferenceInfo getReferenceInfo() {
+ return fRefInfo;
+}
+/**
+ * Returns the length of the source string.
+ */
+public int getSourceLength() {
+ return fSourceLength;
+}
+protected ISourceRange getSourceRange() {
+ return new SourceRange(0, fSourceLength);
+}
+/**
+ * Sets the reference information for this compilation unit
+ */
+public void setReferenceInfo(ReferenceInfo info) {
+ fRefInfo = info;
+}
+/**
+ * Sets the length of the source string.
+ */
+public void setSourceLength(int newSourceLength) {
+ fSourceLength = newSourceLength;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitStructureRequestor.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitStructureRequestor.java
index b583ad616b..acecc72b22 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitStructureRequestor.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitStructureRequestor.java
@@ -17,8 +17,7 @@ import java.util.*;
/**
* A requestor for the fuzzy parser, used to compute the children of an ICompilationUnit.
*/
-public class CompilationUnitStructureRequestor
- implements ISourceElementRequestor {
+public class CompilationUnitStructureRequestor implements ISourceElementRequestor {
/**
* The handle to the compilation unit being parsed
@@ -33,7 +32,7 @@ public class CompilationUnitStructureRequestor
/**
* The import container info - null until created
*/
- protected JavaElementInfo fImportContainerInfo = null;
+ protected JavaElementInfo fImportContainerInfo= null;
/**
* Hashtable of children elements of the compilation unit.
@@ -61,7 +60,7 @@ public class CompilationUnitStructureRequestor
/**
* The name of the source file being parsed.
*/
- protected char[] fSourceFileName = null;
+ protected char[] fSourceFileName= null;
/**
* The dot-separated name of the package the compilation unit
@@ -69,7 +68,7 @@ public class CompilationUnitStructureRequestor
* compilation unit, and initialized by #acceptPackage.
* Initialized to <code>null</code> for the default package.
*/
- protected char[] fPackageName = null;
+ protected char[] fPackageName= null;
/**
* Array of bytes describing reference info found during the
@@ -78,159 +77,141 @@ public class CompilationUnitStructureRequestor
*
* @see ReferenceInfo
*/
- protected byte[] fReferenceKinds = fgEmptyByte;
+ protected byte[] fReferenceKinds= fgEmptyByte;
/**
* Array of referenced names found during the
* parse. Entires are char arrays, and the corresponding
* reference kinds are in fReferenceKinds.
*/
- protected char[][] fReferenceNames = fgEmptyCharChar;
+ protected char[][] fReferenceNames= fgEmptyCharChar;
/**
* The number of references reported thus far. Used to
* expand the arrays of reference kinds and names.
*/
- protected int fRefCount = 0;
+ protected int fRefCount= 0;
/**
* The initial size of the reference kind and name
* arrays. If the arrays fill, they are doubled in
* size
*/
- protected static int fgReferenceAllocation = 50;
+ protected static int fgReferenceAllocation= 50;
/**
* Collection of problems reported during the parse.
* If any errors appear (i.e. not warnings), the structure
* of the compilation unit is considered unknown.
- */
+ */
protected Vector fProblems;
/**
* Empty collections used for efficient initialization
*/
protected static String[] fgEmptyStringArray = new String[0];
- protected static byte[] fgEmptyByte = new byte[] {
- };
-
- protected static char[][] fgEmptyCharChar = new char[][] {
- };
+ protected static byte[] fgEmptyByte= new byte[]{};
+ protected static char[][] fgEmptyCharChar= new char[][]{};
+ protected static char[] fgEmptyChar= new char[]{};
- protected static char[] fgEmptyChar = new char[] {
- };
protected HashtableOfObject fieldRefCache;
protected HashtableOfObject messageRefCache;
protected HashtableOfObject typeRefCache;
protected HashtableOfObject unknownRefCache;
- protected CompilationUnitStructureRequestor(
- ICompilationUnit unit,
- CompilationUnitElementInfo unitInfo,
- Hashtable newElements)
- throws JavaModelException {
- fUnit = unit;
- fUnitInfo = unitInfo;
- fNewElements = newElements;
- fSourceFileName = unit.getElementName().toCharArray();
- }
-
- public void acceptConstructorReference(
- char[] typeName,
- int argCount,
- int sourcePosition) {
-
- // type name could be qualified
- if (CharOperation.indexOf('.', typeName) < 0) {
- acceptTypeReference(typeName, sourcePosition);
- } else {
- acceptTypeReference(CharOperation.splitOn('.', typeName), -1, -1);
- // source positions are not used
- // use simple name afterwards
- typeName = CharOperation.lastSegment(typeName, '.');
- }
- if (argCount < 10) {
- // common case (i.e. small arg count)
- int len = typeName.length;
- char[] name = new char[len + 4];
- name[0] = '<';
- System.arraycopy(typeName, 0, name, 1, len);
- // fix for 1FWAKJJ
- name[len + 1] = '>';
- name[len + 2] = '/';
- name[len + 3] = (char) ('0' + argCount);
- addReference(ReferenceInfo.REFTYPE_call, name);
- } else {
- String name = "<" + new String(typeName) + ">/" + argCount;
- addReference(ReferenceInfo.REFTYPE_call, name.toCharArray());
- }
- }
-
- public void acceptFieldReference(char[] fieldName, int sourcePosition) {
- addReference(ReferenceInfo.REFTYPE_var, fieldName);
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void acceptImport(
- int declarationStart,
- int declarationEnd,
- char[] name,
- boolean onDemand) {
- JavaElementInfo parentInfo = (JavaElementInfo) fInfoStack.peek();
- JavaElement parentHandle = (JavaElement) fHandleStack.peek();
- if (!(parentHandle.getElementType() == IJavaElement.COMPILATION_UNIT)) {
- Assert.isTrue(false); // Should not happen
- }
-
- ICompilationUnit parentCU = (ICompilationUnit) parentHandle;
- //create the import container and its info
- IImportContainer importContainer = parentCU.getImportContainer();
- if (fImportContainerInfo == null) {
- fImportContainerInfo = new JavaElementInfo();
- fImportContainerInfo.setIsStructureKnown(true);
- parentInfo.addChild(importContainer);
- fNewElements.put(importContainer, fImportContainerInfo);
- }
-
- // tack on the '.*' if it is onDemand
- String importName;
- if (onDemand) {
- importName = new String(name) + ".*";
- } else {
- importName = new String(name);
- }
-
- ImportDeclaration handle = new ImportDeclaration(importContainer, importName);
- resolveDuplicates(handle);
-
- SourceRefElementInfo info = new SourceRefElementInfo();
- info.setSourceRangeStart(declarationStart);
- info.setSourceRangeEnd(declarationEnd);
-
- fImportContainerInfo.addChild(handle);
- fNewElements.put(handle, info);
+protected CompilationUnitStructureRequestor(ICompilationUnit unit, CompilationUnitElementInfo unitInfo, Hashtable newElements) throws JavaModelException {
+ fUnit = unit;
+ fUnitInfo = unitInfo;
+ fNewElements = newElements;
+ fSourceFileName= unit.getElementName().toCharArray();
+}
+public void acceptConstructorReference(char[] typeName, int argCount, int sourcePosition) {
+
+ // type name could be qualified
+ if (CharOperation.indexOf('.', typeName) < 0){
+ acceptTypeReference(typeName, sourcePosition);
+ } else {
+ acceptTypeReference(CharOperation.splitOn('.', typeName), -1, -1); // source positions are not used
+ // use simple name afterwards
+ typeName = CharOperation.lastSegment(typeName, '.');
+ }
+ if (argCount < 10) {
+ // common case (i.e. small arg count)
+ int len = typeName.length;
+ char[] name = new char[len+4];
+ name[0] = '<';
+ System.arraycopy(typeName, 0, name, 1, len);
+ // fix for 1FWAKJJ
+ name[len+1] = '>';
+ name[len+2] = '/';
+ name[len+3] = (char) ('0' + argCount);
+ addReference(ReferenceInfo.REFTYPE_call, name);
+ }
+ else {
+ String name = "<"/*nonNLS*/ + new String(typeName) + ">/"/*nonNLS*/ + argCount;
+ addReference(ReferenceInfo.REFTYPE_call, name.toCharArray());
}
-
- /**
- * @see ISourceElementRequestor
- */
- public void acceptInitializer(
- int modifiers,
- int declarationSourceStart,
- int declarationSourceEnd) {
+}
+public void acceptFieldReference(char[] fieldName, int sourcePosition) {
+ addReference(ReferenceInfo.REFTYPE_var, fieldName);
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void acceptImport(int declarationStart, int declarationEnd, char[] name, boolean onDemand) {
+ JavaElementInfo parentInfo = (JavaElementInfo) fInfoStack.peek();
+ JavaElement parentHandle= (JavaElement)fHandleStack.peek();
+ if (!(parentHandle.getElementType() == IJavaElement.COMPILATION_UNIT)) {
+ Assert.isTrue(false); // Should not happen
+ }
+
+ ICompilationUnit parentCU= (ICompilationUnit)parentHandle;
+ //create the import container and its info
+ IImportContainer importContainer= parentCU.getImportContainer();
+ if (fImportContainerInfo == null) {
+ fImportContainerInfo= new JavaElementInfo();
+ fImportContainerInfo.setIsStructureKnown(true);
+ parentInfo.addChild(importContainer);
+ fNewElements.put(importContainer, fImportContainerInfo);
+ }
+
+ // tack on the '.*' if it is onDemand
+ String importName;
+ if (onDemand) {
+ importName= new String(name) + ".*"/*nonNLS*/;
+ } else {
+ importName= new String(name);
+ }
+
+ ImportDeclaration handle = new ImportDeclaration(importContainer, importName);
+ resolveDuplicates(handle);
+
+ SourceRefElementInfo info = new SourceRefElementInfo();
+ info.setSourceRangeStart(declarationStart);
+ info.setSourceRangeEnd(declarationEnd);
+
+ fImportContainerInfo.addChild(handle);
+ fNewElements.put(handle, info);
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void acceptInitializer(
+ int modifiers,
+ int declarationSourceStart,
+ int declarationSourceEnd) {
JavaElementInfo parentInfo = (JavaElementInfo) fInfoStack.peek();
- JavaElement parentHandle = (JavaElement) fHandleStack.peek();
+ JavaElement parentHandle= (JavaElement)fHandleStack.peek();
IInitializer handle = null;
-
+
if (parentHandle.getElementType() == IJavaElement.TYPE) {
handle = ((IType) parentHandle).getInitializer(1);
- } else {
+ }
+ else {
Assert.isTrue(false); // Should not happen
}
resolveDuplicates(handle);
-
+
InitializerElementInfo info = new InitializerElementInfo();
info.setSourceRangeStart(declarationSourceStart);
info.setSourceRangeEnd(declarationSourceEnd);
@@ -238,57 +219,48 @@ public class CompilationUnitStructureRequestor
parentInfo.addChild(handle);
fNewElements.put(handle, info);
+}
+/*
+ * Table of line separator position. This table is passed once at the end
+ * of the parse action, so as to allow computation of normalized ranges.
+ *
+ * A line separator might corresponds to several characters in the source,
+ *
+ */
+public void acceptLineSeparatorPositions(int[] positions) {}
+public void acceptMethodReference(char[] methodName, int argCount, int sourcePosition) {
+ if (argCount < 10) {
+ // common case (i.e. small arg count)
+ int len = methodName.length;
+ char[] name = new char[len+2];
+ System.arraycopy(methodName, 0, name, 0, len);
+ name[len] = '/';
+ name[len+1] = (char) ('0' + argCount);
+ addReference(ReferenceInfo.REFTYPE_call, name);
+ }
+ else {
+ String name = new String(methodName) + "/"/*nonNLS*/ + argCount;
+ addReference(ReferenceInfo.REFTYPE_call, name.toCharArray());
}
-
- /*
- * Table of line separator position. This table is passed once at the end
- * of the parse action, so as to allow computation of normalized ranges.
- *
- * A line separator might corresponds to several characters in the source,
- *
- */
- public void acceptLineSeparatorPositions(int[] positions) {
- }
-
- public void acceptMethodReference(
- char[] methodName,
- int argCount,
- int sourcePosition) {
- if (argCount < 10) {
- // common case (i.e. small arg count)
- int len = methodName.length;
- char[] name = new char[len + 2];
- System.arraycopy(methodName, 0, name, 0, len);
- name[len] = '/';
- name[len + 1] = (char) ('0' + argCount);
- addReference(ReferenceInfo.REFTYPE_call, name);
- } else {
- String name = new String(methodName) + "/" + argCount;
- addReference(ReferenceInfo.REFTYPE_call, name.toCharArray());
- }
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void acceptPackage(
- int declarationStart,
- int declarationEnd,
- char[] name) {
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void acceptPackage(int declarationStart, int declarationEnd, char[] name) {
JavaElementInfo parentInfo = (JavaElementInfo) fInfoStack.peek();
- JavaElement parentHandle = (JavaElement) fHandleStack.peek();
+ JavaElement parentHandle= (JavaElement)fHandleStack.peek();
IPackageDeclaration handle = null;
- fPackageName = name;
-
+ fPackageName= name;
+
if (parentHandle.getElementType() == IJavaElement.COMPILATION_UNIT) {
- handle =
- new PackageDeclaration((ICompilationUnit) parentHandle, new String(name));
- } else {
+ handle = new PackageDeclaration((ICompilationUnit) parentHandle, new String(name));
+ }
+ else {
Assert.isTrue(false); // Should not happen
}
resolveDuplicates(handle);
-
+
SourceRefElementInfo info = new SourceRefElementInfo();
info.setSourceRangeStart(declarationStart);
info.setSourceRangeEnd(declarationEnd);
@@ -296,204 +268,168 @@ public class CompilationUnitStructureRequestor
parentInfo.addChild(handle);
fNewElements.put(handle, info);
+}
+public void acceptProblem(IProblem problem) {
+ if (fProblems == null) {
+ fProblems= new Vector();
}
-
- public void acceptProblem(IProblem problem) {
- if (fProblems == null) {
- fProblems = new Vector();
- }
- fProblems.addElement(problem);
- }
-
- public void acceptTypeReference(
- char[][] typeName,
- int sourceStart,
- int sourceEnd) {
- int last = typeName.length - 1;
- for (int i = 0; i < last; ++i) {
- addReference(ReferenceInfo.REFTYPE_unknown, typeName[i]);
- }
- addReference(ReferenceInfo.REFTYPE_type, typeName[last]);
- }
-
- public void acceptTypeReference(char[] typeName, int sourcePosition) {
- addReference(ReferenceInfo.REFTYPE_type, typeName);
- }
-
- public void acceptUnknownReference(
- char[][] name,
- int sourceStart,
- int sourceEnd) {
- for (int i = 0; i < name.length; ++i) {
- addReference(ReferenceInfo.REFTYPE_unknown, name[i]);
- }
- }
-
- public void acceptUnknownReference(char[] name, int sourcePosition) {
- addReference(ReferenceInfo.REFTYPE_unknown, name);
+ fProblems.addElement(problem);
+}
+public void acceptTypeReference(char[][] typeName, int sourceStart, int sourceEnd) {
+ int last = typeName.length - 1;
+ for (int i = 0; i < last; ++i) {
+ addReference(ReferenceInfo.REFTYPE_unknown, typeName[i]);
}
-
- /**
- * Adds the given reference to the reference info for this CU.
- */
- protected void addReference(byte kind, char[] name) {
-
- HashtableOfObject refCache = null;
- switch (kind) {
- case ReferenceInfo.REFTYPE_unknown :
- if ((refCache = this.unknownRefCache) == null) {
- refCache = this.unknownRefCache = new HashtableOfObject(5);
- }
- break;
- case ReferenceInfo.REFTYPE_call :
- if ((refCache = this.messageRefCache) == null) {
- refCache = this.messageRefCache = new HashtableOfObject(5);
- }
- break;
- case ReferenceInfo.REFTYPE_type :
- if ((refCache = this.typeRefCache) == null) {
- refCache = this.typeRefCache = new HashtableOfObject(5);
- }
- break;
- case ReferenceInfo.REFTYPE_var :
- if ((refCache = this.fieldRefCache) == null) {
- refCache = this.fieldRefCache = new HashtableOfObject(5);
- }
- break;
- case ReferenceInfo.REFTYPE_import :
- case ReferenceInfo.REFTYPE_derive :
- case ReferenceInfo.REFTYPE_class :
- case ReferenceInfo.REFTYPE_constant :
- }
- if (refCache == null)
- addReference0(kind, name); // backward compatible
- if (refCache.containsKey(name))
- return;
- refCache.put(name, name);
- addReference0(kind, name);
+ addReference(ReferenceInfo.REFTYPE_type, typeName[last]);
+}
+public void acceptTypeReference(char[] typeName, int sourcePosition) {
+ addReference(ReferenceInfo.REFTYPE_type, typeName);
+}
+public void acceptUnknownReference(char[][] name, int sourceStart, int sourceEnd) {
+ for (int i = 0; i < name.length; ++i) {
+ addReference(ReferenceInfo.REFTYPE_unknown, name[i]);
}
+}
+public void acceptUnknownReference(char[] name, int sourcePosition) {
+ addReference(ReferenceInfo.REFTYPE_unknown, name);
+}
+/**
+ * Adds the given reference to the reference info for this CU.
+ */
+protected void addReference(byte kind, char[] name) {
- /**
- * Adds the given reference to the reference info for this CU.
- */
- private void addReference0(byte kind, char[] name) {
-
- int count = fRefCount++;
- if (count >= fReferenceKinds.length) {
- int size = fgReferenceAllocation;
- if (fReferenceKinds.length > 0) {
- size = fReferenceKinds.length * 2;
+ HashtableOfObject refCache = null;
+ switch(kind){
+ case ReferenceInfo.REFTYPE_unknown:
+ if ((refCache = this.unknownRefCache) == null){
+ refCache = this.unknownRefCache = new HashtableOfObject(5);
}
- byte[] kinds = new byte[size];
- System.arraycopy(fReferenceKinds, 0, kinds, 0, fReferenceKinds.length);
- fReferenceKinds = kinds;
- char[][] names = new char[size][];
- System.arraycopy(fReferenceNames, 0, names, 0, fReferenceNames.length);
- fReferenceNames = names;
- }
- fReferenceKinds[count] = kind;
- fReferenceNames[count] = name;
- }
+ break;
+ case ReferenceInfo.REFTYPE_call:
+ if ((refCache = this.messageRefCache) == null){
+ refCache = this.messageRefCache = new HashtableOfObject(5);
+ }
+ break;
+ case ReferenceInfo.REFTYPE_type:
+ if ((refCache = this.typeRefCache) == null){
+ refCache = this.typeRefCache = new HashtableOfObject(5);
+ }
+ break;
+ case ReferenceInfo.REFTYPE_var:
+ if ((refCache = this.fieldRefCache) == null){
+ refCache = this.fieldRefCache = new HashtableOfObject(5);
+ }
+ break;
+ case ReferenceInfo.REFTYPE_import:
+ case ReferenceInfo.REFTYPE_derive:
+ case ReferenceInfo.REFTYPE_class:
+ case ReferenceInfo.REFTYPE_constant:
+ }
+ if (refCache == null) addReference0(kind, name); // backward compatible
+ if (refCache.containsKey(name)) return;
+ refCache.put(name, name);
+ addReference0(kind, name);
+}
+/**
+ * Adds the given reference to the reference info for this CU.
+ */
+private void addReference0(byte kind, char[] name) {
- /**
- * Convert these type names to signatures.
- * @see Signature.
- */
- /* default */
- static String[] convertTypeNamesToSigs(char[][] typeNames) {
- if (typeNames == null)
- return fgEmptyStringArray;
- int n = typeNames.length;
- if (n == 0)
- return fgEmptyStringArray;
- String[] typeSigs = new String[n];
- for (int i = 0; i < n; ++i) {
- typeSigs[i] = Signature.createTypeSignature(typeNames[i], false);
+ int count = fRefCount++;
+ if (count >= fReferenceKinds.length) {
+ int size = fgReferenceAllocation;
+ if (fReferenceKinds.length > 0) {
+ size = fReferenceKinds.length * 2;
}
- return typeSigs;
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void enterClass(
- int declarationStart,
- int modifiers,
- char[] name,
- int nameSourceStart,
- int nameSourceEnd,
- char[] superclass,
- char[][] superinterfaces) {
-
- enterType(
- declarationStart,
- modifiers,
- name,
- nameSourceStart,
- nameSourceEnd,
- superclass,
- superinterfaces);
-
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void enterCompilationUnit() {
- fInfoStack = new Stack();
- fHandleStack = new Stack();
- fInfoStack.push(fUnitInfo);
- fHandleStack.push(fUnit);
- }
+ byte[] kinds = new byte[size];
+ System.arraycopy(fReferenceKinds, 0, kinds, 0, fReferenceKinds.length);
+ fReferenceKinds = kinds;
+ char[][] names = new char[size][];
+ System.arraycopy(fReferenceNames, 0, names, 0, fReferenceNames.length);
+ fReferenceNames = names;
+ }
+ fReferenceKinds[count] = kind;
+ fReferenceNames[count] = name;
+}
+/**
+ * Convert these type names to signatures.
+ * @see Signature.
+ */
+/* default */ static String[] convertTypeNamesToSigs(char[][] typeNames) {
+ if (typeNames == null)
+ return fgEmptyStringArray;
+ int n = typeNames.length;
+ if (n == 0)
+ return fgEmptyStringArray;
+ String[] typeSigs = new String[n];
+ for (int i = 0; i < n; ++i) {
+ typeSigs[i] = Signature.createTypeSignature(typeNames[i], false);
+ }
+ return typeSigs;
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void enterClass(
+ int declarationStart,
+ int modifiers,
+ char[] name,
+ int nameSourceStart,
+ int nameSourceEnd,
+ char[] superclass,
+ char[][] superinterfaces) {
- /**
- * @see ISourceElementRequestor
- */
- public void enterConstructor(
- int declarationStart,
- int modifiers,
- char[] name,
- int nameSourceStart,
- int nameSourceEnd,
- char[][] parameterTypes,
- char[][] parameterNames,
- char[][] exceptionTypes) {
-
- enterMethod(
- declarationStart,
- modifiers,
- null,
- name,
- nameSourceStart,
- nameSourceEnd,
- parameterTypes,
- parameterNames,
- exceptionTypes,
- true);
- }
+ enterType(declarationStart, modifiers, name, nameSourceStart, nameSourceEnd, superclass, superinterfaces);
- /**
- * @see ISourceElementRequestor
- */
- public void enterField(
- int declarationStart,
- int modifiers,
- char[] type,
- char[] name,
- int nameSourceStart,
- int nameSourceEnd) {
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void enterCompilationUnit() {
+ fInfoStack = new Stack();
+ fHandleStack= new Stack();
+ fInfoStack.push(fUnitInfo);
+ fHandleStack.push(fUnit);
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void enterConstructor(
+ int declarationStart,
+ int modifiers,
+ char[] name,
+ int nameSourceStart,
+ int nameSourceEnd,
+ char[][] parameterTypes,
+ char[][] parameterNames,
+ char[][] exceptionTypes) {
+
+ enterMethod(declarationStart, modifiers, null, name, nameSourceStart,
+ nameSourceEnd, parameterTypes, parameterNames, exceptionTypes, true);
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void enterField(
+ int declarationStart,
+ int modifiers,
+ char[] type,
+ char[] name,
+ int nameSourceStart,
+ int nameSourceEnd) {
SourceTypeElementInfo parentInfo = (SourceTypeElementInfo) fInfoStack.peek();
- JavaElement parentHandle = (JavaElement) fHandleStack.peek();
+ JavaElement parentHandle= (JavaElement)fHandleStack.peek();
IField handle = null;
-
+
if (parentHandle.getElementType() == IJavaElement.TYPE) {
handle = new SourceField((IType) parentHandle, new String(name));
- } else {
+ }
+ else {
Assert.isTrue(false); // Should not happen
}
resolveDuplicates(handle);
-
+
SourceFieldElementInfo info = new SourceFieldElementInfo();
info.setName(name);
info.setNameSourceStart(nameSourceStart);
@@ -508,96 +444,77 @@ public class CompilationUnitStructureRequestor
fInfoStack.push(info);
fHandleStack.push(handle);
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void enterInterface(
- int declarationStart,
- int modifiers,
- char[] name,
- int nameSourceStart,
- int nameSourceEnd,
- char[][] superinterfaces) {
-
- enterType(
- declarationStart,
- modifiers,
- name,
- nameSourceStart,
- nameSourceEnd,
- null,
- superinterfaces);
-
- }
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void enterInterface(
+ int declarationStart,
+ int modifiers,
+ char[] name,
+ int nameSourceStart,
+ int nameSourceEnd,
+ char[][] superinterfaces) {
- /**
- * @see ISourceElementRequestor
- */
- public void enterMethod(
- int declarationStart,
- int modifiers,
- char[] returnType,
- char[] name,
- int nameSourceStart,
- int nameSourceEnd,
- char[][] parameterTypes,
- char[][] parameterNames,
- char[][] exceptionTypes) {
-
- enterMethod(
- declarationStart,
- modifiers,
- returnType,
- name,
- nameSourceStart,
- nameSourceEnd,
- parameterTypes,
- parameterNames,
- exceptionTypes,
- false);
- }
+ enterType(declarationStart, modifiers, name, nameSourceStart, nameSourceEnd, null, superinterfaces);
- /**
- * @see ISourceElementRequestor
- */
- protected void enterMethod(
- int declarationStart,
- int modifiers,
- char[] returnType,
- char[] name,
- int nameSourceStart,
- int nameSourceEnd,
- char[][] parameterTypes,
- char[][] parameterNames,
- char[][] exceptionTypes,
- boolean isConstructor) {
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void enterMethod(
+ int declarationStart,
+ int modifiers,
+ char[] returnType,
+ char[] name,
+ int nameSourceStart,
+ int nameSourceEnd,
+ char[][] parameterTypes,
+ char[][] parameterNames,
+ char[][] exceptionTypes) {
+
+ enterMethod(declarationStart, modifiers, returnType, name, nameSourceStart,
+ nameSourceEnd, parameterTypes, parameterNames, exceptionTypes, false);
+}
+/**
+ * @see ISourceElementRequestor
+ */
+protected void enterMethod(
+ int declarationStart,
+ int modifiers,
+ char[] returnType,
+ char[] name,
+ int nameSourceStart,
+ int nameSourceEnd,
+ char[][] parameterTypes,
+ char[][] parameterNames,
+ char[][] exceptionTypes,
+ boolean isConstructor) {
SourceTypeElementInfo parentInfo = (SourceTypeElementInfo) fInfoStack.peek();
- JavaElement parentHandle = (JavaElement) fHandleStack.peek();
+ JavaElement parentHandle= (JavaElement)fHandleStack.peek();
IMethod handle = null;
// translate nulls to empty arrays
if (parameterTypes == null) {
- parameterTypes = fgEmptyCharChar;
+ parameterTypes= fgEmptyCharChar;
}
if (parameterNames == null) {
- parameterNames = fgEmptyCharChar;
+ parameterNames= fgEmptyCharChar;
}
if (exceptionTypes == null) {
- exceptionTypes = fgEmptyCharChar;
+ exceptionTypes= fgEmptyCharChar;
}
-
+
String[] parameterTypeSigs = convertTypeNamesToSigs(parameterTypes);
if (parentHandle.getElementType() == IJavaElement.TYPE) {
- handle =
- new SourceMethod((IType) parentHandle, new String(name), parameterTypeSigs);
- } else {
+ handle = new SourceMethod((IType) parentHandle, new String(name), parameterTypeSigs);
+ }
+ else {
Assert.isTrue(false); // Should not happen
}
resolveDuplicates(handle);
-
+
SourceMethodElementInfo info = new SourceMethodElementInfo();
info.setSourceRangeStart(declarationStart);
int flags = modifiers;
@@ -608,8 +525,7 @@ public class CompilationUnitStructureRequestor
info.setFlags(flags);
info.setArgumentNames(parameterNames);
info.setArgumentTypeNames(parameterTypes);
- info.setReturnType(returnType == null ? new char[] { 'v', 'o', 'i', 'd' }
- : returnType);
+ info.setReturnType(returnType == null ? new char[]{'v', 'o','i', 'd'} : returnType);
info.setExceptionTypeNames(exceptionTypes);
parentInfo.addChild(handle);
@@ -617,163 +533,151 @@ public class CompilationUnitStructureRequestor
fNewElements.put(handle, info);
fInfoStack.push(info);
fHandleStack.push(handle);
- }
-
- /**
- * Common processing for classes and interfaces.
- */
- protected void enterType(
- int declarationStart,
- int modifiers,
- char[] name,
- int nameSourceStart,
- int nameSourceEnd,
- char[] superclass,
- char[][] superinterfaces) {
-
- char[] enclosingTypeName = null;
- char[] qualifiedName = null;
-
- JavaElementInfo parentInfo = (JavaElementInfo) fInfoStack.peek();
- JavaElement parentHandle = (JavaElement) fHandleStack.peek();
- IType handle = null;
- String nameString = new String(name);
-
- if (parentHandle.getElementType() == IJavaElement.COMPILATION_UNIT) {
- handle = ((ICompilationUnit) parentHandle).getType(nameString);
- if (fPackageName == null) {
- qualifiedName = nameString.toCharArray();
- } else {
- qualifiedName = (new String(fPackageName) + "." + nameString).toCharArray();
- }
- } else
- if (parentHandle.getElementType() == IJavaElement.TYPE) {
- handle = ((IType) parentHandle).getType(nameString);
- enclosingTypeName = ((SourceTypeElementInfo) parentInfo).getName();
- qualifiedName =
- (new String(((SourceTypeElementInfo) parentInfo).getQualifiedName())
- + "."
- + nameString)
- .toCharArray();
- } else {
- Assert.isTrue(false); // Should not happen
- }
- resolveDuplicates(handle);
-
- SourceTypeElementInfo info = new SourceTypeElementInfo();
- info.setHandle(handle);
- info.setSourceRangeStart(declarationStart);
- info.setFlags(modifiers);
- info.setName(name);
- info.setNameSourceStart(nameSourceStart);
- info.setNameSourceEnd(nameSourceEnd);
- info.setSuperclassName(superclass);
- info.setSuperInterfaceNames(superinterfaces);
- info.setEnclosingTypeName(enclosingTypeName);
- info.setSourceFileName(fSourceFileName);
- info.setPackageName(fPackageName);
- info.setQualifiedName(qualifiedName);
- Enumeration e = fNewElements.keys();
- while (e.hasMoreElements()) {
- Object object = e.nextElement();
- if (object instanceof IImportDeclaration)
- info.addImport(((IImportDeclaration) object).getElementName().toCharArray());
- }
-
- parentInfo.addChild(handle);
- if (parentInfo instanceof SourceTypeElementInfo) {
- ((SourceTypeElementInfo) parentInfo).addMemberType(info);
+}
+/**
+ * Common processing for classes and interfaces.
+ */
+protected void enterType(
+ int declarationStart,
+ int modifiers,
+ char[] name,
+ int nameSourceStart,
+ int nameSourceEnd,
+ char[] superclass,
+ char[][] superinterfaces) {
+
+ char[] enclosingTypeName= null;
+ char[] qualifiedName= null;
+
+ JavaElementInfo parentInfo = (JavaElementInfo) fInfoStack.peek();
+ JavaElement parentHandle= (JavaElement)fHandleStack.peek();
+ IType handle = null;
+ String nameString= new String(name);
+
+ if (parentHandle.getElementType() == IJavaElement.COMPILATION_UNIT) {
+ handle = ((ICompilationUnit) parentHandle).getType(nameString);
+ if (fPackageName == null) {
+ qualifiedName= nameString.toCharArray();
+ } else {
+ qualifiedName= (new String(fPackageName) + "."/*nonNLS*/ + nameString).toCharArray();
}
- fNewElements.put(handle, info);
-
- fInfoStack.push(info);
- fHandleStack.push(handle);
-
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void exitClass(int declarationEnd) {
- exitMember(declarationEnd);
}
+ else if (parentHandle.getElementType() == IJavaElement.TYPE) {
+ handle = ((IType) parentHandle).getType(nameString);
+ enclosingTypeName= ((SourceTypeElementInfo)parentInfo).getName();
+ qualifiedName= (new String(((SourceTypeElementInfo)parentInfo).getQualifiedName()) + "."/*nonNLS*/ + nameString).toCharArray();
+ }
+ else {
+ Assert.isTrue(false); // Should not happen
+ }
+ resolveDuplicates(handle);
+
+ SourceTypeElementInfo info = new SourceTypeElementInfo();
+ info.setHandle(handle);
+ info.setSourceRangeStart(declarationStart);
+ info.setFlags(modifiers);
+ info.setName(name);
+ info.setNameSourceStart(nameSourceStart);
+ info.setNameSourceEnd(nameSourceEnd);
+ info.setSuperclassName(superclass);
+ info.setSuperInterfaceNames(superinterfaces);
+ info.setEnclosingTypeName(enclosingTypeName);
+ info.setSourceFileName(fSourceFileName);
+ info.setPackageName(fPackageName);
+ info.setQualifiedName(qualifiedName);
+ Enumeration e = fNewElements.keys();
+ while(e.hasMoreElements()) {
+ Object object = e.nextElement();
+ if (object instanceof IImportDeclaration)
+ info.addImport(((IImportDeclaration)object).getElementName().toCharArray());
+ }
+
+
+ parentInfo.addChild(handle);
+ if (parentInfo instanceof SourceTypeElementInfo) {
+ ((SourceTypeElementInfo)parentInfo).addMemberType(info);
+ }
+ fNewElements.put(handle, info);
+
+ fInfoStack.push(info);
+ fHandleStack.push(handle);
- /**
- * @see ISourceElementRequestor
- */
- public void exitCompilationUnit(int declarationEnd) {
- fUnitInfo.setSourceLength(declarationEnd + 1);
-
- // make the reference arrays the correct size
- if (fRefCount != fReferenceKinds.length) {
- byte[] kinds = new byte[fRefCount];
- System.arraycopy(fReferenceKinds, 0, kinds, 0, fRefCount);
- fReferenceKinds = kinds;
- char[][] names = new char[fRefCount][];
- System.arraycopy(fReferenceNames, 0, names, 0, fRefCount);
- fReferenceNames = names;
- }
- fUnitInfo.setReferenceInfo(new ReferenceInfo(fReferenceNames, fReferenceKinds));
-
- // determine if there were any parsing errors
- fUnitInfo.setIsStructureKnown(true);
- if (fProblems != null) {
- for (int i = 0; i < fProblems.size(); i++) {
- IProblem problem = (IProblem) fProblems.elementAt(i);
- if (!problem.isWarning()) {
- fUnitInfo.setIsStructureKnown(false);
- break;
- }
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void exitClass(int declarationEnd) {
+ exitMember(declarationEnd);
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void exitCompilationUnit(int declarationEnd) {
+ fUnitInfo.setSourceLength(declarationEnd + 1);
+
+ // make the reference arrays the correct size
+ if (fRefCount != fReferenceKinds.length) {
+ byte[] kinds= new byte[fRefCount];
+ System.arraycopy(fReferenceKinds, 0, kinds, 0, fRefCount);
+ fReferenceKinds= kinds;
+ char[][] names= new char[fRefCount][];
+ System.arraycopy(fReferenceNames, 0, names, 0, fRefCount);
+ fReferenceNames= names;
+ }
+ fUnitInfo.setReferenceInfo(new ReferenceInfo(fReferenceNames, fReferenceKinds));
+
+ // determine if there were any parsing errors
+ fUnitInfo.setIsStructureKnown(true);
+ if (fProblems != null) {
+ for (int i= 0; i < fProblems.size(); i++) {
+ IProblem problem= (IProblem)fProblems.elementAt(i);
+ if (!problem.isWarning()) {
+ fUnitInfo.setIsStructureKnown(false);
+ break;
}
}
}
-
- /**
- * @see ISourceElementRequestor
- */
- public void exitConstructor(int declarationEnd) {
- exitMember(declarationEnd);
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void exitField(int declarationEnd) {
- exitMember(declarationEnd);
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void exitInterface(int declarationEnd) {
- exitMember(declarationEnd);
- }
-
- /**
- * common processing for classes and interfaces
- */
- protected void exitMember(int declarationEnd) {
- SourceRefElementInfo info = (SourceRefElementInfo) fInfoStack.pop();
- info.setSourceRangeEnd(declarationEnd);
- fHandleStack.pop();
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void exitMethod(int declarationEnd) {
- exitMember(declarationEnd);
- }
-
- /**
- * Resolves duplicate handles by incrementing the occurrence count
- * of the handle being created until there is no conflict.
- */
- protected void resolveDuplicates(IJavaElement handle) {
- while (fNewElements.containsKey(handle)) {
- JavaElement h = (JavaElement) handle;
- h.setOccurrenceCount(h.getOccurrenceCount() + 1);
- }
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void exitConstructor(int declarationEnd) {
+ exitMember(declarationEnd);
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void exitField(int declarationEnd) {
+ exitMember(declarationEnd);
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void exitInterface(int declarationEnd) {
+ exitMember(declarationEnd);
+}
+/**
+ * common processing for classes and interfaces
+ */
+protected void exitMember(int declarationEnd) {
+ SourceRefElementInfo info = (SourceRefElementInfo) fInfoStack.pop();
+ info.setSourceRangeEnd(declarationEnd);
+ fHandleStack.pop();
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void exitMethod(int declarationEnd) {
+ exitMember(declarationEnd);
+}
+/**
+ * Resolves duplicate handles by incrementing the occurrence count
+ * of the handle being created until there is no conflict.
+ */
+protected void resolveDuplicates(IJavaElement handle) {
+ while (fNewElements.containsKey(handle)) {
+ JavaElement h = (JavaElement) handle;
+ h.setOccurrenceCount(h.getOccurrenceCount() + 1);
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitVisitor.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitVisitor.java
index 2c68bb7195..8a3b8ec22f 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitVisitor.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompilationUnitVisitor.java
@@ -82,7 +82,7 @@ protected static IErrorHandlingPolicy getHandlingPolicy() {
// passes the initial set of files to the batch oracle (to avoid finding more than once the same units when case insensitive match)
return new IErrorHandlingPolicy() {
public boolean stopOnFirstError() {
- return true;
+ return false;
}
public boolean proceedOnErrors() {
return false; // stop if there are some errors
@@ -100,24 +100,6 @@ protected static ConfigurableOption[] getOptions() {
CompilerOptions options = new CompilerOptions();
return options.getConfigurableOptions(Locale.getDefault());
}
-protected static IProblemFactory getProblemFactory(final IAbstractSyntaxTreeVisitor visitor) {
-
- return new DefaultProblemFactory(Locale.getDefault()){
- public IProblem createProblem(char[] originatingFileName, int problemId, String[] arguments, int severity, int startPosition, int endPosition, int lineNumber) {
-
- IProblem problem = super.createProblem(
- originatingFileName,
- problemId,
- arguments,
- severity,
- startPosition,
- endPosition,
- lineNumber);
- visitor.acceptProblem(problem);
- return problem;
- }
- };
-}
/*
* Answer the component to which will be handed back compilation results from the compiler
*/
@@ -152,4 +134,23 @@ public static void visit(ICompilationUnit unitElement, IAbstractSyntaxTreeVisito
}
}
}
+
+protected static IProblemFactory getProblemFactory(final IAbstractSyntaxTreeVisitor visitor) {
+
+ return new DefaultProblemFactory(Locale.getDefault()){
+ public IProblem createProblem(char[] originatingFileName, int problemId, String[] arguments, int severity, int startPosition, int endPosition, int lineNumber) {
+
+ IProblem problem = super.createProblem(
+ originatingFileName,
+ problemId,
+ arguments,
+ severity,
+ startPosition,
+ endPosition,
+ lineNumber);
+ visitor.acceptProblem(problem);
+ return problem;
+ }
+ };
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompletionRequestorWrapper.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompletionRequestorWrapper.java
index 11d6ee7f35..0e00231814 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompletionRequestorWrapper.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CompletionRequestorWrapper.java
@@ -4,7 +4,7 @@ package org.eclipse.jdt.internal.core;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
-
+
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.*;
import org.eclipse.jdt.internal.codeassist.ICompletionRequestor;
@@ -13,210 +13,89 @@ import org.eclipse.jdt.core.*;
public class CompletionRequestorWrapper implements ICompletionRequestor {
ICodeCompletionRequestor clientRequestor;
- public CompletionRequestorWrapper(ICodeCompletionRequestor clientRequestor) {
- this.clientRequestor = clientRequestor;
- }
-
- /**
- * See ICompletionRequestor
- */
- public void acceptClass(
- char[] packageName,
- char[] className,
- char[] completionName,
- int modifiers,
- int completionStart,
- int completionEnd) {
-
- this.clientRequestor.acceptClass(
- packageName,
- className,
- completionName,
- modifiers,
- completionStart,
- completionEnd);
- }
-
- /**
- * See ICompletionRequestor
- */
- public void acceptError(IProblem error) {
-
- if (true)
- return; // work-around PR 1GD9RLP: ITPJCORE:WIN2000 - Code assist is slow
- try {
- IMarker marker =
- ResourcesPlugin.getWorkspace().getRoot().createMarker(
- IJavaModelMarker.TRANSIENT_PROBLEM);
- marker.setAttribute(IJavaModelMarker.ID, error.getID());
- marker.setAttribute(IMarker.CHAR_START, error.getSourceStart());
- marker.setAttribute(IMarker.CHAR_END, error.getSourceEnd() + 1);
- marker.setAttribute(IMarker.LINE_NUMBER, error.getSourceLineNumber());
- //marker.setAttribute(IMarker.LOCATION, "#" + error.getSourceLineNumber());
- marker.setAttribute(IMarker.MESSAGE, error.getMessage());
- marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
-
- this.clientRequestor.acceptError(marker);
-
- } catch (CoreException e) {
- }
- }
-
- /**
- * See ICompletionRequestor
- */
- public void acceptField(
- char[] declaringTypePackageName,
- char[] declaringTypeName,
- char[] name,
- char[] typePackageName,
- char[] typeName,
- char[] completionName,
- int modifiers,
- int completionStart,
- int completionEnd) {
- this.clientRequestor.acceptField(
- declaringTypePackageName,
- declaringTypeName,
- name,
- typePackageName,
- typeName,
- completionName,
- modifiers,
- completionStart,
- completionEnd);
- }
-
- /**
- * See ICompletionRequestor
- */
- public void acceptInterface(
- char[] packageName,
- char[] interfaceName,
- char[] completionName,
- int modifiers,
- int completionStart,
- int completionEnd) {
- this.clientRequestor.acceptInterface(
- packageName,
- interfaceName,
- completionName,
- modifiers,
- completionStart,
- completionEnd);
- }
-
- /**
- * See ICompletionRequestor
- */
- public void acceptKeyword(
- char[] keywordName,
- int completionStart,
- int completionEnd) {
- this.clientRequestor.acceptKeyword(keywordName, completionStart, completionEnd);
- }
-
- /**
- * See ICompletionRequestor
- */
- public void acceptLabel(
- char[] labelName,
- int completionStart,
- int completionEnd) {
- this.clientRequestor.acceptLabel(labelName, completionStart, completionEnd);
- }
-
- /**
- * See ICompletionRequestor
- */
- public void acceptLocalVariable(
- char[] name,
- char[] typePackageName,
- char[] typeName,
- int modifiers,
- int completionStart,
- int completionEnd) {
- this.clientRequestor.acceptLocalVariable(
- name,
- typePackageName,
- typeName,
- modifiers,
- completionStart,
- completionEnd);
- }
-
- /**
- * See ICompletionRequestor
- */
- public void acceptMethod(
- char[] declaringTypePackageName,
- char[] declaringTypeName,
- char[] selector,
- char[][] parameterPackageNames,
- char[][] parameterTypeNames,
- char[] returnTypePackageName,
- char[] returnTypeName,
- char[] completionName,
- int modifiers,
- int completionStart,
- int completionEnd) {
- this.clientRequestor.acceptMethod(
- declaringTypePackageName,
- declaringTypeName,
- selector,
- parameterPackageNames,
- parameterTypeNames,
- returnTypePackageName,
- returnTypeName,
- completionName,
- modifiers,
- completionStart,
- completionEnd);
- }
-
- /**
- * See ICompletionRequestor
- */
- public void acceptModifier(
- char[] modifierName,
- int completionStart,
- int completionEnd) {
- this.clientRequestor.acceptModifier(
- modifierName,
- completionStart,
- completionEnd);
- }
+public CompletionRequestorWrapper(ICodeCompletionRequestor clientRequestor){
+ this.clientRequestor = clientRequestor;
+}
+/**
+ * See ICompletionRequestor
+ */
+public void acceptClass(char[] packageName, char[] className, char[] completionName, int modifiers, int completionStart, int completionEnd) {
- /**
- * See ICompletionRequestor
- */
- public void acceptPackage(
- char[] packageName,
- char[] completionName,
- int completionStart,
- int completionEnd) {
- this.clientRequestor.acceptPackage(
- packageName,
- completionName,
- completionStart,
- completionEnd);
+ this.clientRequestor.acceptClass(packageName, className, completionName, modifiers, completionStart, completionEnd);
+}
+/**
+ * See ICompletionRequestor
+ */
+public void acceptError(IProblem error) {
+
+ if (true) return; // work-around PR 1GD9RLP: ITPJCORE:WIN2000 - Code assist is slow
+ try {
+ IMarker marker = ResourcesPlugin.getWorkspace().getRoot().createMarker(IJavaModelMarker.TRANSIENT_PROBLEM);
+ marker.setAttribute(IJavaModelMarker.ID, error.getID());
+ marker.setAttribute(IMarker.CHAR_START, error.getSourceStart());
+ marker.setAttribute(IMarker.CHAR_END, error.getSourceEnd() + 1);
+ marker.setAttribute(IMarker.LINE_NUMBER, error.getSourceLineNumber());
+ //marker.setAttribute(IMarker.LOCATION, "#" + error.getSourceLineNumber());
+ marker.setAttribute(IMarker.MESSAGE, error.getMessage());
+ marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
+
+ this.clientRequestor.acceptError(marker);
+
+ } catch(CoreException e){
}
-
- /**
- * See ICompletionRequestor
- */
- public void acceptType(
- char[] packageName,
- char[] typeName,
- char[] completionName,
- int completionStart,
- int completionEnd) {
- this.clientRequestor.acceptType(
- packageName,
- typeName,
- completionName,
- completionStart,
- completionEnd);
+}
+/**
+ * See ICompletionRequestor
+ */
+public void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[] typePackageName, char[] typeName, char[] completionName, int modifiers, int completionStart, int completionEnd) {
+ this.clientRequestor.acceptField(declaringTypePackageName, declaringTypeName, name, typePackageName, typeName, completionName, modifiers, completionStart, completionEnd);
+}
+/**
+ * See ICompletionRequestor
+ */
+public void acceptInterface(char[] packageName, char[] interfaceName, char[] completionName, int modifiers, int completionStart, int completionEnd) {
+ this.clientRequestor.acceptInterface(packageName, interfaceName, completionName, modifiers, completionStart, completionEnd);
}
-
+/**
+ * See ICompletionRequestor
+ */
+public void acceptKeyword(char[] keywordName, int completionStart, int completionEnd) {
+ this.clientRequestor.acceptKeyword(keywordName, completionStart, completionEnd);
+}
+/**
+ * See ICompletionRequestor
+ */
+public void acceptLabel(char[] labelName, int completionStart, int completionEnd) {
+ this.clientRequestor.acceptLabel(labelName, completionStart, completionEnd);
+}
+/**
+ * See ICompletionRequestor
+ */
+public void acceptLocalVariable(char[] name, char[] typePackageName, char[] typeName, int modifiers, int completionStart, int completionEnd) {
+ this.clientRequestor.acceptLocalVariable(name, typePackageName, typeName, modifiers, completionStart, completionEnd);
+}
+/**
+ * See ICompletionRequestor
+ */
+public void acceptMethod(char[] declaringTypePackageName, char[] declaringTypeName, char[] selector, char[][] parameterPackageNames, char[][] parameterTypeNames, char[] returnTypePackageName, char[] returnTypeName, char[] completionName, int modifiers, int completionStart, int completionEnd) {
+ this.clientRequestor.acceptMethod(declaringTypePackageName, declaringTypeName, selector, parameterPackageNames, parameterTypeNames, returnTypePackageName, returnTypeName, completionName, modifiers, completionStart, completionEnd);
+}
+/**
+ * See ICompletionRequestor
+ */
+public void acceptModifier(char[] modifierName, int completionStart, int completionEnd) {
+ this.clientRequestor.acceptModifier(modifierName, completionStart, completionEnd);
+}
+/**
+ * See ICompletionRequestor
+ */
+public void acceptPackage(char[] packageName, char[] completionName, int completionStart, int completionEnd) {
+ this.clientRequestor.acceptPackage(packageName, completionName, completionStart, completionEnd);
+}
+/**
+ * See ICompletionRequestor
+ */
+public void acceptType(char[] packageName, char[] typeName, char[] completionName, int completionStart, int completionEnd) {
+ this.clientRequestor.acceptType(packageName, typeName, completionName, completionStart, completionEnd);
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CopyElementsOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CopyElementsOperation.java
index ffd41512cf..4858baf980 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CopyElementsOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CopyElementsOperation.java
@@ -45,246 +45,200 @@ import java.util.Hashtable;
*/
public class CopyElementsOperation extends MultiOperation {
+
private Hashtable fSources = new Hashtable();
- /**
- * When executed, this operation will copy the given elements to the
- * given containers. The elements and destination containers must be in
- * the correct order. If there is > 1 destination, the number of destinations
- * must be the same as the number of elements being copied/moved/renamed.
- */
- public CopyElementsOperation(
- IJavaElement[] elementsToCopy,
- IJavaElement[] destContainers,
- boolean force) {
- super(elementsToCopy, destContainers, force);
- }
-
- /**
- * When executed, this operation will copy the given elements to the
- * given container.
- */
- public CopyElementsOperation(
- IJavaElement[] elementsToCopy,
- IJavaElement destContainer,
- boolean force) {
- this(elementsToCopy, new IJavaElement[] { destContainer }, force);
- }
-
- /**
- * Returns the <code>String</code> to use as the main task name
- * for progress monitoring.
- */
- protected String getMainTaskName() {
- return "Copying elements...";
- }
-
- /**
- * Returns the nested operation to use for processing this element
- */
- protected JavaModelOperation getNestedOperation(IJavaElement element) {
- try {
- IJavaElement dest = getDestinationParent(element);
- switch (element.getElementType()) {
- case IJavaElement.PACKAGE_DECLARATION :
- return new CreatePackageDeclarationOperation(
- element.getElementName(),
- (ICompilationUnit) dest);
- case IJavaElement.IMPORT_DECLARATION :
- return new CreateImportOperation(
- element.getElementName(),
- (ICompilationUnit) dest);
- case IJavaElement.TYPE :
- if (isRenamingMainType(element, dest)) {
- return new RenameResourceElementsOperation(
- new IJavaElement[] { dest },
- new IJavaElement[] { dest.getParent()},
- new String[] { getNewNameFor(element) + ".java" },
- fForce);
- } else {
- return new CreateTypeOperation(
- dest,
- getSourceFor(element) + JavaModelManager.LINE_SEPARATOR,
- fForce);
- }
- case IJavaElement.METHOD :
- return new CreateMethodOperation(
- (IType) dest,
- getSourceFor(element) + JavaModelManager.LINE_SEPARATOR,
- fForce);
- case IJavaElement.FIELD :
- return new CreateFieldOperation(
- (IType) dest,
- getSourceFor(element) + JavaModelManager.LINE_SEPARATOR,
- fForce);
- case IJavaElement.INITIALIZER :
- return new CreateInitializerOperation(
- (IType) dest,
- getSourceFor(element) + JavaModelManager.LINE_SEPARATOR);
- default :
- return null;
- }
- } catch (JavaModelException npe) {
- return null;
+/**
+ * When executed, this operation will copy the given elements to the
+ * given containers. The elements and destination containers must be in
+ * the correct order. If there is > 1 destination, the number of destinations
+ * must be the same as the number of elements being copied/moved/renamed.
+ */
+public CopyElementsOperation(IJavaElement[] elementsToCopy, IJavaElement[] destContainers, boolean force) {
+ super(elementsToCopy, destContainers, force);
+}
+/**
+ * When executed, this operation will copy the given elements to the
+ * given container.
+ */
+public CopyElementsOperation(IJavaElement[] elementsToCopy, IJavaElement destContainer, boolean force) {
+ this(elementsToCopy, new IJavaElement[]{destContainer}, force);
+}
+/**
+ * Returns the <code>String</code> to use as the main task name
+ * for progress monitoring.
+ */
+protected String getMainTaskName() {
+ return Util.bind("operation.copyElementProgress"/*nonNLS*/);
+}
+/**
+ * Returns the nested operation to use for processing this element
+ */
+protected JavaModelOperation getNestedOperation(IJavaElement element) {
+ try {
+ IJavaElement dest = getDestinationParent(element);
+ switch (element.getElementType()) {
+ case IJavaElement.PACKAGE_DECLARATION :
+ return new CreatePackageDeclarationOperation(element.getElementName(), (ICompilationUnit) dest);
+ case IJavaElement.IMPORT_DECLARATION :
+ return new CreateImportOperation(element.getElementName(), (ICompilationUnit) dest);
+ case IJavaElement.TYPE :
+ if (isRenamingMainType(element, dest)) {
+ return new RenameResourceElementsOperation(new IJavaElement[] {dest}, new IJavaElement[] {dest.getParent()}, new String[]{getNewNameFor(element) + ".java"/*nonNLS*/}, fForce);
+ } else {
+ return new CreateTypeOperation(dest, getSourceFor(element) + JavaModelManager.LINE_SEPARATOR, fForce);
+ }
+ case IJavaElement.METHOD :
+ return new CreateMethodOperation((IType) dest, getSourceFor(element) + JavaModelManager.LINE_SEPARATOR, fForce);
+ case IJavaElement.FIELD :
+ return new CreateFieldOperation((IType) dest, getSourceFor(element) + JavaModelManager.LINE_SEPARATOR, fForce);
+ case IJavaElement.INITIALIZER :
+ return new CreateInitializerOperation((IType) dest, getSourceFor(element) + JavaModelManager.LINE_SEPARATOR);
+ default :
+ return null;
}
+ } catch (JavaModelException npe) {
+ return null;
}
-
- /**
- * Returns the cached source for this element or compute it if not already cached.
- */
- private String getSourceFor(IJavaElement element) throws JavaModelException {
- String source = (String) fSources.get(element);
- if (source == null && element instanceof IMember) {
- IMember member = (IMember) element;
- ICompilationUnit cu = member.getCompilationUnit();
- String cuSource = cu.getSource();
- IDOMCompilationUnit domCU =
- new DOMFactory().createCompilationUnit(cuSource, cu.getElementName());
- IDOMNode node = ((JavaElement) element).findNode(domCU);
- source = new String(node.getCharacters());
- fSources.put(element, source);
- }
- return source;
+}
+/**
+ * Returns the cached source for this element or compute it if not already cached.
+ */
+private String getSourceFor(IJavaElement element) throws JavaModelException {
+ String source = (String) fSources.get(element);
+ if (source == null && element instanceof IMember) {
+ IMember member = (IMember)element;
+ ICompilationUnit cu = member.getCompilationUnit();
+ String cuSource = cu.getSource();
+ IDOMCompilationUnit domCU = new DOMFactory().createCompilationUnit(cuSource, cu.getElementName());
+ IDOMNode node = ((JavaElement)element).findNode(domCU);
+ source = new String(node.getCharacters());
+ fSources.put(element, source);
}
-
- /**
- * Returns <code>true</code> if this element is the main type of its compilation unit.
- */
- protected boolean isRenamingMainType(IJavaElement element, IJavaElement dest) {
- if ((isRename() || getNewNameFor(element) != null)
- && dest.getElementType() == IJavaElement.COMPILATION_UNIT) {
- String typeName = dest.getElementName();
- typeName = typeName.substring(0, typeName.length() - 5);
- return element.getElementName().equals(typeName)
- && element.getParent().equals(dest);
- }
- return false;
+ return source;
+}
+/**
+ * Returns <code>true</code> if this element is the main type of its compilation unit.
+ */
+protected boolean isRenamingMainType(IJavaElement element, IJavaElement dest) {
+ if ((isRename() || getNewNameFor(element) != null)
+ && dest.getElementType() == IJavaElement.COMPILATION_UNIT) {
+ String typeName = dest.getElementName();
+ typeName = typeName.substring(0, typeName.length() - 5);
+ return element.getElementName().equals(typeName) && element.getParent().equals(dest);
}
-
- /**
- * Copy/move the element from the source to destination, renaming
- * the elements as specified, honoring the collision policy.
- *
- * @exception JavaModelException if the operation is unable to
- * be completed
- */
- protected void processElement(IJavaElement element) throws JavaModelException {
- JavaModelOperation op = getNestedOperation(element);
- boolean createElementInCUOperation = op instanceof CreateElementInCUOperation;
- if (op == null) {
- return;
- }
- if (createElementInCUOperation) {
- IJavaElement sibling = (IJavaElement) fInsertBeforeElements.get(element);
- if (sibling != null) {
- ((CreateElementInCUOperation) op).setRelativePosition(
- sibling,
- CreateElementInCUOperation.INSERT_BEFORE);
- } else
- if (isRename()) {
- IJavaElement anchor = resolveRenameAnchor(element);
- if (anchor != null) {
- ((CreateElementInCUOperation) op).setRelativePosition(
- anchor,
- CreateElementInCUOperation.INSERT_AFTER);
- // insert after so that the anchor is found before when deleted below
- }
+ return false;
+}
+/**
+ * Copy/move the element from the source to destination, renaming
+ * the elements as specified, honoring the collision policy.
+ *
+ * @exception JavaModelException if the operation is unable to
+ * be completed
+ */
+protected void processElement(IJavaElement element) throws JavaModelException {
+ JavaModelOperation op = getNestedOperation(element);
+ boolean createElementInCUOperation =op instanceof CreateElementInCUOperation;
+ if (op == null) {
+ return;
+ }
+ if (createElementInCUOperation) {
+ IJavaElement sibling = (IJavaElement) fInsertBeforeElements.get(element);
+ if (sibling != null) {
+ ((CreateElementInCUOperation) op).setRelativePosition(sibling, CreateElementInCUOperation.INSERT_BEFORE);
+ } else
+ if (isRename()) {
+ IJavaElement anchor = resolveRenameAnchor(element);
+ if (anchor != null) {
+ ((CreateElementInCUOperation) op).setRelativePosition(anchor, CreateElementInCUOperation.INSERT_AFTER); // insert after so that the anchor is found before when deleted below
}
- String newName = getNewNameFor(element);
- if (newName != null) {
- ((CreateElementInCUOperation) op).setAlteredName(newName);
}
+ String newName = getNewNameFor(element);
+ if (newName != null) {
+ ((CreateElementInCUOperation) op).setAlteredName(newName);
}
- executeNestedOperation(op, 1);
+ }
+ executeNestedOperation(op, 1);
- JavaElement destination = (JavaElement) getDestinationParent(element);
- destination.getCompilationUnit().close();
+ JavaElement destination = (JavaElement) getDestinationParent(element);
+ destination.getCompilationUnit().close();
- if (createElementInCUOperation
- && isMove()
- && !isRenamingMainType(element, destination)) {
- DeleteElementsOperation deleteOp =
- new DeleteElementsOperation(new IJavaElement[] { element }, fForce);
- executeNestedOperation(deleteOp, 1);
- }
+ if (createElementInCUOperation && isMove() && !isRenamingMainType(element, destination)) {
+ DeleteElementsOperation deleteOp = new DeleteElementsOperation(new IJavaElement[] { element }, fForce);
+ executeNestedOperation(deleteOp, 1);
}
-
- /**
- * Returns the anchor used for positioning in the destination for
- * the element being renamed. For renaming, if no anchor has
- * explicitly been provided, the element is anchored in the same position.
- */
- private IJavaElement resolveRenameAnchor(IJavaElement element)
- throws JavaModelException {
- IParent parent = (IParent) element.getParent();
- IJavaElement[] children = parent.getChildren();
- for (int i = 0; i < children.length; i++) {
- IJavaElement child = children[i];
- if (child.equals(element)) {
- return child;
- }
+}
+/**
+ * Returns the anchor used for positioning in the destination for
+ * the element being renamed. For renaming, if no anchor has
+ * explicitly been provided, the element is anchored in the same position.
+ */
+private IJavaElement resolveRenameAnchor(IJavaElement element) throws JavaModelException {
+ IParent parent = (IParent) element.getParent();
+ IJavaElement[] children = parent.getChildren();
+ for (int i = 0; i < children.length; i++) {
+ IJavaElement child = children[i];
+ if (child.equals(element)) {
+ return child;
}
- return null;
}
-
- /**
- * Possible failures:
- * <ul>
- * <li>NO_ELEMENTS_TO_PROCESS - no elements supplied to the operation
- * <li>INDEX_OUT_OF_BOUNDS - the number of renamings supplied to the operation
- * does not match the number of elements that were supplied.
- * </ul>
- */
- protected IJavaModelStatus verify() {
- IJavaModelStatus status = super.verify();
- if (!status.isOK()) {
- return status;
- }
- if (fRenamingsList != null
- && fRenamingsList.length != fElementsToProcess.length) {
- return new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS);
- }
- return JavaModelStatus.VERIFIED_OK;
+ return null;
+}
+/**
+ * Possible failures:
+ * <ul>
+ * <li>NO_ELEMENTS_TO_PROCESS - no elements supplied to the operation
+ * <li>INDEX_OUT_OF_BOUNDS - the number of renamings supplied to the operation
+ * does not match the number of elements that were supplied.
+ * </ul>
+ */
+protected IJavaModelStatus verify() {
+ IJavaModelStatus status = super.verify();
+ if (!status.isOK()) {
+ return status;
}
+ if (fRenamingsList != null && fRenamingsList.length != fElementsToProcess.length) {
+ return new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS);
+ }
+ return JavaModelStatus.VERIFIED_OK;
+}
+/**
+ * @see MultiOperation
+ *
+ * Possible failure codes:
+ * <ul>
+ *
+ * <li>ELEMENT_DOES_NOT_EXIST - <code>element</code> or its specified destination is
+ * is <code>null</code> or does not exist. If a <code>null</code> element is
+ * supplied, no element is provided in the status, otherwise, the non-existant element
+ * is supplied in the status.
+ * <li>INVALID_ELEMENT_TYPES - <code>element</code> is not contained within a compilation unit.
+ * This operation only operates on elements contained within compilation units.
+ * <li>READ_ONLY - <code>element</code> is read only.
+ * <li>INVALID_DESTINATION - The destination parent specified for <code>element</code>
+ * is of an incompatible type. The destination for a package declaration or import declaration must
+ * be a compilation unit; the destination for a type must be a type or compilation
+ * unit; the destinaion for any type member (other than a type) must be a type. When
+ * this error occurs, the element provided in the operation status is the <code>element</code>.
+ * <li>INVALID_NAME - the new name for <code>element</code> does not have valid syntax.
+ * In this case the element and name are provided in the status.
- /**
- * @see MultiOperation
- *
- * Possible failure codes:
- * <ul>
- *
- * <li>ELEMENT_DOES_NOT_EXIST - <code>element</code> or its specified destination is
- * is <code>null</code> or does not exist. If a <code>null</code> element is
- * supplied, no element is provided in the status, otherwise, the non-existant element
- * is supplied in the status.
- * <li>INVALID_ELEMENT_TYPES - <code>element</code> is not contained within a compilation unit.
- * This operation only operates on elements contained within compilation units.
- * <li>READ_ONLY - <code>element</code> is read only.
- * <li>INVALID_DESTINATION - The destination parent specified for <code>element</code>
- * is of an incompatible type. The destination for a package declaration or import declaration must
- * be a compilation unit; the destination for a type must be a type or compilation
- * unit; the destinaion for any type member (other than a type) must be a type. When
- * this error occurs, the element provided in the operation status is the <code>element</code>.
- * <li>INVALID_NAME - the new name for <code>element</code> does not have valid syntax.
- * In this case the element and name are provided in the status.
-
- * </ul>
- */
- protected void verify(IJavaElement element) throws JavaModelException {
- if (element == null || !element.exists())
- error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element);
+ * </ul>
+ */
+protected void verify(IJavaElement element) throws JavaModelException {
+ if (element == null || !element.exists())
+ error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element);
- if (element.getElementType() < IJavaElement.TYPE)
- error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
+ if (element.getElementType() < IJavaElement.TYPE)
+ error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
- if (element.isReadOnly())
- error(IJavaModelStatusConstants.READ_ONLY, element);
+ if (element.isReadOnly())
+ error(IJavaModelStatusConstants.READ_ONLY, element);
- IJavaElement dest = getDestinationParent(element);
- verifyDestination(element, dest);
- verifySibling(element, dest);
- if (fRenamingsList != null) {
- verifyRenaming(element);
- }
+ IJavaElement dest = getDestinationParent(element);
+ verifyDestination(element, dest);
+ verifySibling(element, dest);
+ if (fRenamingsList != null) {
+ verifyRenaming(element);
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
index 56c57b657e..3fe95cd814 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CopyResourceElementsOperation.java
@@ -48,7 +48,7 @@ public class CopyResourceElementsOperation extends MultiOperation {
* copied/moved/renamed. Keyed by elements' project(s), and
* values are the corresponding deltas.
*/
- protected Hashtable fDeltasPerProject = new Hashtable(1);
+ protected Hashtable fDeltasPerProject= new Hashtable(1);
/**
* The <code>DOMFactory</code> used to manipulate the source code of
* <code>ICompilationUnit</code>.
@@ -58,457 +58,391 @@ public class CopyResourceElementsOperation extends MultiOperation {
* The list of new resources created during this operation.
*/
protected Vector fCreatedElements;
- /**
- * When executed, this operation will copy the given resources to the
- * given containers. The resources and destination containers must be in
- * the correct order. If there is > 1 destination, the number of destinations
- * must be the same as the number of resources being copied/moved.
- */
- public CopyResourceElementsOperation(
- IJavaElement[] resourcesToCopy,
- IJavaElement[] destContainers,
- boolean force) {
- super(resourcesToCopy, destContainers, force);
- fFactory = new DOMFactory();
- }
-
- /**
- * When executed, this operation will copy the given resources to the
- * given container.
- */
- public CopyResourceElementsOperation(
- IJavaElement[] resourcesToCopy,
- IJavaElement destContainer,
- boolean force) {
- this(resourcesToCopy, new IJavaElement[] { destContainer }, force);
+/**
+ * When executed, this operation will copy the given resources to the
+ * given containers. The resources and destination containers must be in
+ * the correct order. If there is > 1 destination, the number of destinations
+ * must be the same as the number of resources being copied/moved.
+ */
+public CopyResourceElementsOperation(IJavaElement[] resourcesToCopy, IJavaElement[] destContainers, boolean force) {
+ super(resourcesToCopy, destContainers, force);
+ fFactory = new DOMFactory();
+}
+/**
+ * When executed, this operation will copy the given resources to the
+ * given container.
+ */
+public CopyResourceElementsOperation(IJavaElement[] resourcesToCopy, IJavaElement destContainer, boolean force) {
+ this(resourcesToCopy, new IJavaElement[]{destContainer}, force);
+}
+/**
+ * Returns the children of <code>source</code> which are affected by this operation.
+ * If <code>source</code> is a <code>K_SOURCE</code>, these are the <code>.java</code>
+ * files, if it is a <code>K_BINARY</code>, they are the <code>.class</code> files.
+ */
+private IResource[] collectResourcesOfInterest(IPackageFragment source) throws JavaModelException {
+ IJavaElement[] children = source.getChildren();
+ int childOfInterest = IJavaElement.COMPILATION_UNIT;
+ if (source.getKind() == IPackageFragmentRoot.K_BINARY) {
+ childOfInterest = IJavaElement.CLASS_FILE;
}
-
- /**
- * Returns the children of <code>source</code> which are affected by this operation.
- * If <code>source</code> is a <code>K_SOURCE</code>, these are the <code>.java</code>
- * files, if it is a <code>K_BINARY</code>, they are the <code>.class</code> files.
- */
- private IResource[] collectResourcesOfInterest(IPackageFragment source)
- throws JavaModelException {
- IJavaElement[] children = source.getChildren();
- int childOfInterest = IJavaElement.COMPILATION_UNIT;
- if (source.getKind() == IPackageFragmentRoot.K_BINARY) {
- childOfInterest = IJavaElement.CLASS_FILE;
- }
- Vector correctKindChildren = new Vector(children.length);
- for (int i = 0; i < children.length; i++) {
- IJavaElement child = children[i];
- if (child.getElementType() == childOfInterest) {
- correctKindChildren.addElement(child.getUnderlyingResource());
- }
- }
- // Gather non-java resources
- Object[] nonJavaResources = source.getNonJavaResources();
- int actualNonJavaResourceCount = 0;
- for (int i = 0, max = nonJavaResources.length; i < max; i++) {
- if (nonJavaResources[i] instanceof IResource)
- actualNonJavaResourceCount++;
- }
- IResource[] actualNonJavaResources = new IResource[actualNonJavaResourceCount];
- for (int i = 0, max = nonJavaResources.length, index = 0; i < max; i++) {
- if (nonJavaResources[i] instanceof IResource)
- actualNonJavaResources[index++] = (IResource) nonJavaResources[i];
- }
-
- if (actualNonJavaResourceCount != 0) {
- int correctKindChildrenSize = correctKindChildren.size();
- IResource[] result =
- new IResource[correctKindChildrenSize + actualNonJavaResourceCount];
- correctKindChildren.copyInto(result);
- System.arraycopy(
- actualNonJavaResources,
- 0,
- result,
- correctKindChildrenSize,
- actualNonJavaResourceCount);
- return result;
- } else {
- IResource[] result = new IResource[correctKindChildren.size()];
- correctKindChildren.copyInto(result);
- return result;
+ Vector correctKindChildren = new Vector(children.length);
+ for (int i = 0; i < children.length; i++) {
+ IJavaElement child = children[i];
+ if (child.getElementType() == childOfInterest) {
+ correctKindChildren.addElement(child.getUnderlyingResource());
}
}
-
- /**
- * Creates any destination package fragment(s) which do not exists yet.
- */
- private void createNeededPackageFragments(
- IPackageFragmentRoot root,
- String newFragName)
- throws JavaModelException {
- IContainer parentFolder = (IContainer) root.getUnderlyingResource();
- JavaElementDelta projectDelta = getDeltaFor(root.getJavaProject());
- String[] names = Signature.getSimpleNames(newFragName);
- StringBuffer sideEffectPackageName = new StringBuffer();
- for (int i = 0; i < names.length; i++) {
- String subFolderName = names[i];
- sideEffectPackageName.append(subFolderName);
- IResource subFolder = parentFolder.findMember(subFolderName);
- if (subFolder == null) {
- createFolder(parentFolder, subFolderName, fForce);
- parentFolder = parentFolder.getFolder(new Path(subFolderName));
- IPackageFragment sideEffectPackage =
- root.getPackageFragment(sideEffectPackageName.toString());
- if (i < names.length - 1) { // all but the last one are side effect packages
- projectDelta.added(sideEffectPackage);
- }
- fCreatedElements.addElement(sideEffectPackage);
- } else {
- parentFolder = (IContainer) subFolder;
- }
- sideEffectPackageName.append('.');
- }
+ // Gather non-java resources
+ Object[] nonJavaResources = source.getNonJavaResources();
+ int actualNonJavaResourceCount = 0;
+ for (int i = 0, max = nonJavaResources.length; i < max; i++){
+ if (nonJavaResources[i] instanceof IResource) actualNonJavaResourceCount++;
}
-
- /**
- * Returns the <code>JavaElementDelta</code> for <code>javaProject</code>,
- * creating it and putting it in <code>fDeltasPerProject</code> if
- * it does not exist yet.
- */
- private JavaElementDelta getDeltaFor(IJavaProject javaProject) {
- JavaElementDelta delta = (JavaElementDelta) fDeltasPerProject.get(javaProject);
- if (delta == null) {
- delta = new JavaElementDelta(javaProject);
- fDeltasPerProject.put(javaProject, delta);
- }
- return delta;
+ IResource[] actualNonJavaResources = new IResource[actualNonJavaResourceCount];
+ for (int i = 0, max = nonJavaResources.length, index = 0; i < max; i++){
+ if (nonJavaResources[i] instanceof IResource) actualNonJavaResources[index++] = (IResource)nonJavaResources[i];
}
-
- /**
- * @see MultiOperation
- */
- protected String getMainTaskName() {
- return "Copying resources...";
+
+ if (actualNonJavaResourceCount != 0) {
+ int correctKindChildrenSize = correctKindChildren.size();
+ IResource[] result = new IResource[correctKindChildrenSize + actualNonJavaResourceCount];
+ correctKindChildren.copyInto(result);
+ System.arraycopy(actualNonJavaResources, 0, result, correctKindChildrenSize, actualNonJavaResourceCount);
+ return result;
+ } else {
+ IResource[] result = new IResource[correctKindChildren.size()];
+ correctKindChildren.copyInto(result);
+ return result;
}
-
- /**
- * Sets the deltas to register the changes resulting from this operation
- * for this source element and its destination.
- * If the operation is a cross project operation<ul>
- * <li>On a copy, the delta should be rooted in the dest project
- * <li>On a move, two deltas are generated<ul>
- * <li>one rooted in the source project
- * <li>one rooted in the destination project</ul></ul>
- * If the operation is rooted in a single project, the delta is rooted in that project
- *
- */
- protected void prepareDeltas(
- IJavaElement sourceElement,
- IJavaElement destinationElement) {
- IJavaProject destProject = destinationElement.getJavaProject();
- if (isMove()) {
- IJavaProject sourceProject = sourceElement.getJavaProject();
- getDeltaFor(sourceProject).movedFrom(sourceElement, destinationElement);
- getDeltaFor(destProject).movedTo(destinationElement, sourceElement);
+}
+/**
+ * Creates any destination package fragment(s) which do not exists yet.
+ */
+private void createNeededPackageFragments(IPackageFragmentRoot root, String newFragName) throws JavaModelException {
+ IContainer parentFolder = (IContainer) root.getUnderlyingResource();
+ JavaElementDelta projectDelta = getDeltaFor(root.getJavaProject());
+ String[] names = Signature.getSimpleNames(newFragName);
+ StringBuffer sideEffectPackageName = new StringBuffer();
+ for (int i = 0; i < names.length; i++) {
+ String subFolderName = names[i];
+ sideEffectPackageName.append(subFolderName);
+ IResource subFolder = parentFolder.findMember(subFolderName);
+ if (subFolder == null) {
+ createFolder(parentFolder, subFolderName, fForce);
+ parentFolder = parentFolder.getFolder(new Path(subFolderName));
+ IPackageFragment sideEffectPackage = root.getPackageFragment(sideEffectPackageName.toString());
+ if (i < names.length - 1) { // all but the last one are side effect packages
+ projectDelta.added(sideEffectPackage);
+ }
+ fCreatedElements.addElement(sideEffectPackage);
} else {
- getDeltaFor(destProject).added(destinationElement);
+ parentFolder = (IContainer) subFolder;
}
+ sideEffectPackageName.append('.');
}
-
- /**
- * Copies/moves a compilation unit with the name <code>newCUName</code>
- * to the destination package.<br>
- * The package statement in the compilation unit is updated if necessary.
- * The main type of the compilation unit is renamed if necessary.
- *
- * @exception JavaModelException if the operation is unable to
- * complete
- */
- private void processCompilationUnitResource(
- ICompilationUnit source,
- IPackageFragment dest)
- throws JavaModelException {
- String newCUName = getNewNameFor(source);
- String destName = (newCUName != null) ? newCUName : source.getElementName();
- String newContent = updatedContent(source, dest, newCUName);
-
- // copy resource
- IFile sourceResource =
- (IFile) (source.isWorkingCopy() ? source.getOriginalElement() : source)
- .getCorrespondingResource();
- IContainer destFolder = (IContainer) dest.getCorrespondingResource();
- // can be an IFolder or an IProject
- IFile destFile = destFolder.getFile(new Path(destName));
- try {
- if (destFile.exists()) {
- if (fForce) {
- // we can remove it
- deleteResource(destFile, false);
- } else {
- // abort
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION));
- }
- }
- if (this.isMove()) {
- sourceResource.move(
- destFile.getFullPath(),
- fForce,
- true,
- getSubProgressMonitor(1));
+}
+/**
+ * Returns the <code>JavaElementDelta</code> for <code>javaProject</code>,
+ * creating it and putting it in <code>fDeltasPerProject</code> if
+ * it does not exist yet.
+ */
+private JavaElementDelta getDeltaFor(IJavaProject javaProject) {
+ JavaElementDelta delta = (JavaElementDelta) fDeltasPerProject.get(javaProject);
+ if (delta == null) {
+ delta = new JavaElementDelta(javaProject);
+ fDeltasPerProject.put(javaProject, delta);
+ }
+ return delta;
+}
+/**
+ * @see MultiOperation
+ */
+protected String getMainTaskName() {
+ return Util.bind("operation.copyResourceProgress"/*nonNLS*/);
+}
+/**
+ * Sets the deltas to register the changes resulting from this operation
+ * for this source element and its destination.
+ * If the operation is a cross project operation<ul>
+ * <li>On a copy, the delta should be rooted in the dest project
+ * <li>On a move, two deltas are generated<ul>
+ * <li>one rooted in the source project
+ * <li>one rooted in the destination project</ul></ul>
+ * If the operation is rooted in a single project, the delta is rooted in that project
+ *
+ */
+protected void prepareDeltas(IJavaElement sourceElement, IJavaElement destinationElement) {
+ IJavaProject destProject = destinationElement.getJavaProject();
+ if (isMove()) {
+ IJavaProject sourceProject = sourceElement.getJavaProject();
+ getDeltaFor(sourceProject).movedFrom(sourceElement, destinationElement);
+ getDeltaFor(destProject).movedTo(destinationElement, sourceElement);
+ } else {
+ getDeltaFor(destProject).added(destinationElement);
+ }
+}
+/**
+ * Copies/moves a compilation unit with the name <code>newCUName</code>
+ * to the destination package.<br>
+ * The package statement in the compilation unit is updated if necessary.
+ * The main type of the compilation unit is renamed if necessary.
+ *
+ * @exception JavaModelException if the operation is unable to
+ * complete
+ */
+private void processCompilationUnitResource(ICompilationUnit source, IPackageFragment dest) throws JavaModelException {
+ String newCUName = getNewNameFor(source);
+ String destName = (newCUName != null) ? newCUName : source.getElementName();
+ String newContent = updatedContent(source, dest, newCUName);
+
+ // copy resource
+ IFile sourceResource = (IFile)(source.isWorkingCopy() ? source.getOriginalElement() : source).getCorrespondingResource();
+ IContainer destFolder = (IContainer)dest.getCorrespondingResource(); // can be an IFolder or an IProject
+ IFile destFile = destFolder.getFile(new Path(destName));
+ try {
+ if (destFile.exists()) {
+ if (fForce) {
+ // we can remove it
+ deleteResource(destFile, false);
} else {
- sourceResource.copy(destFile.getFullPath(), fForce, getSubProgressMonitor(1));
+ // abort
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION));
}
- } catch (JavaModelException e) {
- throw e;
- } catch (CoreException e) {
- throw new JavaModelException(e);
- }
-
- // update new resource content
- try {
- destFile.setContents(
- new ByteArrayInputStream(newContent.getBytes()),
- fForce,
- true,
- getSubProgressMonitor(1));
- } catch (CoreException e) {
- throw new JavaModelException(e);
}
-
- // register the correct change deltas
- ICompilationUnit destCU = dest.getCompilationUnit(destName);
- prepareDeltas(source, destCU);
- if (newCUName != null) {
- //the main type has been renamed
- String oldName = source.getElementName();
- oldName = oldName.substring(0, oldName.length() - 5);
- String newName = newCUName;
- newName = newName.substring(0, newName.length() - 5);
- prepareDeltas(source.getType(oldName), destCU.getType(newName));
+ if (this.isMove()) {
+ sourceResource.move(destFile.getFullPath(), fForce, true, getSubProgressMonitor(1));
+ } else {
+ sourceResource.copy(destFile.getFullPath(), fForce, getSubProgressMonitor(1));
}
+ } catch (JavaModelException e) {
+ throw e;
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
- /**
- * Process all of the changed deltas generated by this operation.
- */
- protected void processDeltas() {
- Enumeration deltas = fDeltasPerProject.elements();
- while (deltas.hasMoreElements()) {
- addDelta((IJavaElementDelta) deltas.nextElement());
+ // update new resource content
+ try {
+ if (newContent != null){
+ destFile.setContents(new ByteArrayInputStream(newContent.getBytes()), fForce, true, getSubProgressMonitor(1));
}
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
- /**
- * @see MultiOperation
- * This method delegates to <code>processCompilationUnitResource</code> or
- * <code>processPackageFragmentResource</code>, depending on the type of
- * <code>element</code>.
- */
- protected void processElement(IJavaElement element) throws JavaModelException {
- IJavaElement dest = getDestinationParent(element);
- switch (element.getElementType()) {
- case IJavaElement.COMPILATION_UNIT :
- processCompilationUnitResource(
- (ICompilationUnit) element,
- (IPackageFragment) dest);
- fCreatedElements.addElement(
- ((IPackageFragment) dest).getCompilationUnit(element.getElementName()));
- break;
- case IJavaElement.PACKAGE_FRAGMENT :
- processPackageFragmentResource(
- (IPackageFragment) element,
- (IPackageFragmentRoot) dest,
- getNewNameFor(element));
- break;
- default :
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element));
- }
+ // register the correct change deltas
+ ICompilationUnit destCU = dest.getCompilationUnit(destName);
+ prepareDeltas(source, destCU);
+ if (newCUName != null) {
+ //the main type has been renamed
+ String oldName = source.getElementName();
+ oldName = oldName.substring(0, oldName.length() - 5);
+ String newName = newCUName;
+ newName = newName.substring(0, newName.length() - 5);
+ prepareDeltas(source.getType(oldName), destCU.getType(newName));
}
-
- /**
- * @see MultiOperation
- * Overridden to allow special processing of <code>JavaElementDelta</code>s
- * and <code>fResultElements</code>.
- */
- protected void processElements() throws JavaModelException {
- fCreatedElements = new Vector(fElementsToProcess.length);
- try {
- super.processElements();
- } catch (JavaModelException jme) {
- throw jme;
- } finally {
- fResultElements = new IJavaElement[fCreatedElements.size()];
- fCreatedElements.copyInto(fResultElements);
- processDeltas();
- }
+}
+/**
+ * Process all of the changed deltas generated by this operation.
+ */
+protected void processDeltas() {
+ Enumeration deltas = fDeltasPerProject.elements();
+ while (deltas.hasMoreElements()) {
+ addDelta((IJavaElementDelta) deltas.nextElement());
}
-
- /**
- * Copies/moves a package fragment with the name <code>newName</code>
- * to the destination package.<br>
- *
- * @exception JavaModelException if the operation is unable to
- * complete
- */
- private void processPackageFragmentResource(
- IPackageFragment source,
- IPackageFragmentRoot root,
- String newName)
- throws JavaModelException {
- try {
- // grab the members before applying the rename (covers nested cases: p --> p.p.p
- IResource[] members = ((IContainer) source.getUnderlyingResource()).members();
-
- String newFragName = (newName == null) ? source.getElementName() : newName;
- createNeededPackageFragments(root, newFragName);
- IPackageFragment newFrag = root.getPackageFragment(newFragName);
-
- // process the leaf resources
- IResource[] resources = collectResourcesOfInterest(source);
- if (resources.length > 0) {
- IPath destPath = newFrag.getUnderlyingResource().getFullPath();
- if (isRename()) {
- if (!destPath.equals(source.getUnderlyingResource().getFullPath())) {
- moveResources(resources, destPath);
- }
- } else
- if (isMove()) {
- // we need to delete this resource if this operation wants to override existing resources
- for (int i = 0, max = resources.length; i < max; i++) {
- IResource destinationResource =
- getWorkspace().getRoot().findMember(destPath.append(resources[i].getName()));
- if (destinationResource != null) {
- if (fForce) {
- deleteResource(destinationResource, false);
- } else {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION));
- }
- }
+}
+/**
+ * @see MultiOperation
+ * This method delegates to <code>processCompilationUnitResource</code> or
+ * <code>processPackageFragmentResource</code>, depending on the type of
+ * <code>element</code>.
+ */
+protected void processElement(IJavaElement element) throws JavaModelException {
+ IJavaElement dest = getDestinationParent(element);
+ switch (element.getElementType()) {
+ case IJavaElement.COMPILATION_UNIT :
+ processCompilationUnitResource((ICompilationUnit) element, (IPackageFragment) dest);
+ fCreatedElements.addElement(((IPackageFragment) dest).getCompilationUnit(element.getElementName()));
+ break;
+ case IJavaElement.PACKAGE_FRAGMENT :
+ processPackageFragmentResource((IPackageFragment) element, (IPackageFragmentRoot) dest, getNewNameFor(element));
+ break;
+ default :
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element));
+ }
+}
+/**
+ * @see MultiOperation
+ * Overridden to allow special processing of <code>JavaElementDelta</code>s
+ * and <code>fResultElements</code>.
+ */
+protected void processElements() throws JavaModelException {
+ fCreatedElements = new Vector(fElementsToProcess.length);
+ try {
+ super.processElements();
+ } catch (JavaModelException jme) {
+ throw jme;
+ } finally {
+ fResultElements = new IJavaElement[fCreatedElements.size()];
+ fCreatedElements.copyInto(fResultElements);
+ processDeltas();
+ }
+}
+/**
+ * Copies/moves a package fragment with the name <code>newName</code>
+ * to the destination package.<br>
+ *
+ * @exception JavaModelException if the operation is unable to
+ * complete
+ */
+private void processPackageFragmentResource(IPackageFragment source, IPackageFragmentRoot root, String newName) throws JavaModelException {
+ try {
+ // grab the members before applying the rename (covers nested cases: p --> p.p.p
+ IResource[] members = ((IContainer) source.getUnderlyingResource()).members();
+
+ String newFragName = (newName == null) ? source.getElementName() : newName;
+ createNeededPackageFragments(root, newFragName);
+ IPackageFragment newFrag = root.getPackageFragment(newFragName);
+
+ // process the leaf resources
+ IResource[] resources = collectResourcesOfInterest(source);
+ if (resources.length > 0) {
+ IPath destPath = newFrag.getUnderlyingResource().getFullPath();
+ if (isRename()) {
+ if (! destPath.equals(source.getUnderlyingResource().getFullPath())) {
+ moveResources(resources, destPath);
+ }
+ } else if (isMove()) {
+ // we need to delete this resource if this operation wants to override existing resources
+ for (int i = 0, max = resources.length; i < max; i++) {
+ IResource destinationResource = getWorkspace().getRoot().findMember(destPath.append(resources[i].getName()));
+ if (destinationResource != null) {
+ if (fForce) {
+ deleteResource(destinationResource, false);
+ } else {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION));
}
- moveResources(resources, destPath);
- } else {
- // we need to delete this resource if this operation wants to override existing resources
- for (int i = 0, max = resources.length; i < max; i++) {
- IResource destinationResource =
- getWorkspace().getRoot().findMember(destPath.append(resources[i].getName()));
- if (destinationResource != null) {
- if (fForce) {
- // we need to delete this resource if this operation wants to override existing resources
- deleteResource(destinationResource, false);
- } else {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION));
- }
- }
+ }
+ }
+ moveResources(resources, destPath);
+ } else {
+ // we need to delete this resource if this operation wants to override existing resources
+ for (int i = 0, max = resources.length; i < max; i++) {
+ IResource destinationResource = getWorkspace().getRoot().findMember(destPath.append(resources[i].getName()));
+ if (destinationResource != null) {
+ if (fForce) {
+ // we need to delete this resource if this operation wants to override existing resources
+ deleteResource(destinationResource, false);
+ } else {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION));
}
- copyResources(resources, destPath);
}
- if (!newFrag.getElementName().equals(source.getElementName())) {
- // if package has been renamed, update the compilation units
- for (int i = 0; i < resources.length; i++) {
- if (resources[i].getName().endsWith(".java")) {
- // we only consider potential compilation units
- ICompilationUnit cu = newFrag.getCompilationUnit(resources[i].getName());
- IDOMCompilationUnit domCU =
- fFactory.createCompilationUnit(cu.getSource(), cu.getElementName());
- if (domCU != null) {
- updatePackageStatement(domCU, newFragName);
- ((Buffer) cu.getBuffer()).setContents(domCU.getContents(), true);
- cu.save(null, false);
- }
+ }
+ copyResources(resources, destPath);
+ }
+ if (!newFrag.getElementName().equals(source.getElementName())) { // if package has been renamed, update the compilation units
+ for (int i = 0; i < resources.length; i++) {
+ if (resources[i].getName().endsWith(".java"/*nonNLS*/)) {
+ // we only consider potential compilation units
+ ICompilationUnit cu = newFrag.getCompilationUnit(resources[i].getName());
+ IDOMCompilationUnit domCU = fFactory.createCompilationUnit(cu.getSource(), cu.getElementName());
+ if (domCU != null) {
+ updatePackageStatement(domCU, newFragName);
+ ((Buffer)cu.getBuffer()).setContents(domCU.getContents(), true);
+ cu.save(null, false);
}
}
}
}
+ }
- // discard empty old package (if still empty after the rename)
- if (isMove()
- && ((IContainer) source.getUnderlyingResource()).members().length == 0) {
+ // discard empty old package (if still empty after the rename)
+ if (isMove()) {
+ // delete remaining files in this package (.class file in the case where Proj=src=bin)
+ IResource[] remaingFiles = ((IContainer)source.getUnderlyingResource()).members();
+ boolean isEmpty = true;
+ for (int i = 0, length = remaingFiles.length; i < length; i++) {
+ IResource file = remaingFiles[i];
+ if (file instanceof IFile) {
+ this.deleteResource(file, true);
+ } else {
+ isEmpty = false;
+ }
+ }
+ if (isEmpty) {
+ // delete recursively empty folders
deleteEmptyPackageFragment(source, false);
}
-
- //register the correct change deltas
- prepareDeltas(source, newFrag);
- } catch (DOMException dom) {
- throw new JavaModelException(dom, IJavaModelStatusConstants.DOM_EXCEPTION);
- } catch (JavaModelException e) {
- throw e;
- } catch (CoreException ce) {
- throw new JavaModelException(ce);
}
- }
- /**
- * Updates the content of <code>cu</code>, modifying the type name and/or package
- * declaration as necessary.
- *
- * @return the new source
- */
- private String updatedContent(
- ICompilationUnit cu,
- IPackageFragment dest,
- String newName)
- throws JavaModelException {
- String currPackageName = cu.getParent().getElementName();
- String destPackageName = dest.getElementName();
- if (currPackageName.equals(destPackageName) && newName == null) {
- return cu.getSource();
- } else {
- String typeName = cu.getElementName();
- typeName = typeName.substring(0, typeName.length() - 5);
- IDOMCompilationUnit cuDOM = null;
- cuDOM =
- fFactory.createCompilationUnit(cu.getBuffer().getCharacters(), typeName);
- updateTypeName(cu, cuDOM, cu.getElementName(), newName);
- updatePackageStatement(cuDOM, destPackageName);
- return cuDOM.getContents();
- }
+ //register the correct change deltas
+ prepareDeltas(source, newFrag);
+ } catch (DOMException dom) {
+ throw new JavaModelException(dom, IJavaModelStatusConstants.DOM_EXCEPTION);
+ } catch (JavaModelException e) {
+ throw e;
+ } catch (CoreException ce) {
+ throw new JavaModelException(ce);
}
-
- /**
- * Makes sure that <code>cu</code> declares to be in the <code>pkgName</code> package.
- */
- private void updatePackageStatement(IDOMCompilationUnit domCU, String pkgName)
- throws JavaModelException {
- boolean defaultPackage = pkgName.equals(IPackageFragment.DEFAULT_PACKAGE_NAME);
- boolean seenPackageNode = false;
- Enumeration enum = domCU.getChildren();
- while (enum.hasMoreElements()) {
- IDOMNode node = (IDOMNode) enum.nextElement();
- if (node.getNodeType() == IDOMNode.PACKAGE) {
- if (!defaultPackage) {
- node.setName(pkgName);
- } else {
- node.remove();
- }
- seenPackageNode = true;
- break;
+}
+/**
+ * Updates the content of <code>cu</code>, modifying the type name and/or package
+ * declaration as necessary.
+ *
+ * @return the new source
+ */
+private String updatedContent(ICompilationUnit cu, IPackageFragment dest, String newName) throws JavaModelException {
+ String currPackageName = cu.getParent().getElementName();
+ String destPackageName = dest.getElementName();
+ if (currPackageName.equals(destPackageName) && newName == null) {
+ return cu.getSource();
+ } else {
+ String typeName = cu.getElementName();
+ typeName = typeName.substring(0, typeName.length() - 5);
+ IDOMCompilationUnit cuDOM = null;
+ cuDOM = fFactory.createCompilationUnit(cu.getBuffer().getCharacters(), typeName);
+ updateTypeName(cu, cuDOM, cu.getElementName(), newName);
+ updatePackageStatement(cuDOM, destPackageName);
+ return cuDOM.getContents();
+ }
+}
+/**
+ * Makes sure that <code>cu</code> declares to be in the <code>pkgName</code> package.
+ */
+private void updatePackageStatement(IDOMCompilationUnit domCU, String pkgName) throws JavaModelException {
+ boolean defaultPackage = pkgName.equals(IPackageFragment.DEFAULT_PACKAGE_NAME);
+ boolean seenPackageNode = false;
+ Enumeration enum = domCU.getChildren();
+ while (enum.hasMoreElements()) {
+ IDOMNode node = (IDOMNode) enum.nextElement();
+ if (node.getNodeType() == IDOMNode.PACKAGE) {
+ if (! defaultPackage) {
+ node.setName(pkgName);
+ } else {
+ node.remove();
}
- }
- if (!seenPackageNode && !defaultPackage) {
- //the cu was in a default package...no package declaration
- //create the new package declaration as the first child of the cu
- IDOMPackage pkg =
- fFactory.createPackage(
- "package " + pkgName + ";" + JavaModelManager.LINE_SEPARATOR);
- domCU.getFirstChild().insertSibling(pkg);
+ seenPackageNode = true;
+ break;
}
}
-
+ if (!seenPackageNode && !defaultPackage) {
+ //the cu was in a default package...no package declaration
+ //create the new package declaration as the first child of the cu
+ IDOMPackage pkg = fFactory.createPackage("package "/*nonNLS*/ + pkgName + ";"/*nonNLS*/ + JavaModelManager.LINE_SEPARATOR);
+ domCU.getFirstChild().insertSibling(pkg);
+ }
+}
/**
* Renames the main type in <code>cu</code>.
*/
- private void updateTypeName(
- ICompilationUnit cu,
- IDOMCompilationUnit domCU,
- String oldName,
- String newName)
- throws JavaModelException {
+ private void updateTypeName(ICompilationUnit cu, IDOMCompilationUnit domCU, String oldName, String newName) throws JavaModelException {
if (newName != null) {
if (fRenamedCompilationUnits == null) {
- fRenamedCompilationUnits = new Vector(1);
+ fRenamedCompilationUnits= new Vector(1);
}
fRenamedCompilationUnits.addElement(cu);
- String oldTypeName = oldName.substring(0, oldName.length() - 5);
- String newTypeName = newName.substring(0, newName.length() - 5);
+ String oldTypeName= oldName.substring(0, oldName.length() - 5);
+ String newTypeName= newName.substring(0, newName.length() - 5);
// update main type name
IType[] types = cu.getTypes();
for (int i = 0, max = types.length; i < max; i++) {
@@ -522,60 +456,55 @@ public class CopyResourceElementsOperation extends MultiOperation {
}
}
}
-
- /**
- * Possible failures:
- * <ul>
- * <li>NO_ELEMENTS_TO_PROCESS - no elements supplied to the operation
- * <li>INDEX_OUT_OF_BOUNDS - the number of renamings supplied to the operation
- * does not match the number of elements that were supplied.
- * </ul>
- */
- protected IJavaModelStatus verify() {
- IJavaModelStatus status = super.verify();
- if (!status.isOK()) {
- return status;
- }
-
- if (fRenamingsList != null
- && fRenamingsList.length != fElementsToProcess.length) {
- return new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS);
- }
- return JavaModelStatus.VERIFIED_OK;
+/**
+ * Possible failures:
+ * <ul>
+ * <li>NO_ELEMENTS_TO_PROCESS - no elements supplied to the operation
+ * <li>INDEX_OUT_OF_BOUNDS - the number of renamings supplied to the operation
+ * does not match the number of elements that were supplied.
+ * </ul>
+ */
+protected IJavaModelStatus verify() {
+ IJavaModelStatus status = super.verify();
+ if (!status.isOK()) {
+ return status;
}
- /**
- * @see MultiOperation
- */
- protected void verify(IJavaElement element) throws JavaModelException {
- if (element == null || !element.exists())
- error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element);
-
- if (element.isReadOnly() && (isRename() || isMove()))
- error(IJavaModelStatusConstants.READ_ONLY, element);
-
- int elementType = element.getElementType();
-
- if (elementType == IJavaElement.COMPILATION_UNIT) {
- if (isMove() && ((ICompilationUnit) element).isWorkingCopy())
- error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
- } else
- if (elementType != IJavaElement.PACKAGE_FRAGMENT) {
- error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
- }
-
- JavaElement dest = (JavaElement) getDestinationParent(element);
- verifyDestination(element, dest);
- if (fRenamings != null) {
- verifyRenaming(element);
- }
-
- IContainer folder = (IContainer) dest.getUnderlyingResource();
- String name = element.getElementName();
- String rename = getNewNameFor(element);
- if (rename != null) {
- name = rename;
- }
+ if (fRenamingsList != null && fRenamingsList.length != fElementsToProcess.length) {
+ return new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS);
+ }
+ return JavaModelStatus.VERIFIED_OK;
+}
+/**
+ * @see MultiOperation
+ */
+protected void verify(IJavaElement element) throws JavaModelException {
+ if (element == null || !element.exists())
+ error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element);
+
+ if (element.isReadOnly() && (isRename() || isMove()))
+ error(IJavaModelStatusConstants.READ_ONLY, element);
+
+ int elementType = element.getElementType();
+
+ if (elementType == IJavaElement.COMPILATION_UNIT) {
+ if (isMove() && ((ICompilationUnit) element).isWorkingCopy())
+ error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
+ } else if (elementType != IJavaElement.PACKAGE_FRAGMENT) {
+ error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
+ }
+
+ JavaElement dest = (JavaElement) getDestinationParent(element);
+ verifyDestination(element, dest);
+ if (fRenamings != null) {
+ verifyRenaming(element);
}
+ IContainer folder = (IContainer) dest.getUnderlyingResource();
+ String name = element.getElementName();
+ String rename = getNewNameFor(element);
+ if (rename != null) {
+ name = rename;
+ }
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateCompilationUnitOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateCompilationUnitOperation.java
index 25e5fa19a8..2a8ce5ffbe 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateCompilationUnitOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateCompilationUnitOperation.java
@@ -38,72 +38,63 @@ public class CreateCompilationUnitOperation extends JavaModelOperation {
/**
* The source code to use when creating the element.
*/
- protected String fSource = null;
- /**
- * When executed, this operation will create a compilation unit with the given name.
- * The name should have the ".java" suffix.
- */
- public CreateCompilationUnitOperation(
- IPackageFragment parentElement,
- String name,
- String source,
- boolean force) {
- super(null, new IJavaElement[] { parentElement }, force);
- fName = name;
- fSource = source;
+ protected String fSource= null;
+/**
+ * When executed, this operation will create a compilation unit with the given name.
+ * The name should have the ".java" suffix.
+ */
+public CreateCompilationUnitOperation(IPackageFragment parentElement, String name, String source, boolean force) {
+ super(null, new IJavaElement[] {parentElement}, force);
+ fName = name;
+ fSource = source;
+}
+/**
+ * Creates a compilation unit.
+ *
+ * @exception JavaModelException if unable to create the compilation unit.
+ */
+protected void executeOperation() throws JavaModelException {
+ beginTask(Util.bind("operation.createUnitProgress"/*nonNLS*/), 2);
+ JavaElementDelta delta = newJavaElementDelta();
+ ICompilationUnit unit = getCompilationUnit();
+ IPackageFragment pkg = (IPackageFragment) getParentElement();
+ IContainer folder = (IContainer) pkg.getUnderlyingResource();
+ InputStream stream = new ByteArrayInputStream(BufferManager.stringToBytes(fSource));
+ worked(1);
+ createFile(folder, unit.getElementName(), stream, fForce);
+ worked(1);
+ fResultElements = new IJavaElement[] {getCompilationUnit()};
+ for (int i = 0; i < fResultElements.length; i++) {
+ delta.added(fResultElements[i]);
}
-
- /**
- * Creates a compilation unit.
- *
- * @exception JavaModelException if unable to create the compilation unit.
- */
- protected void executeOperation() throws JavaModelException {
- beginTask("Creating a compilation unit...", 2);
- JavaElementDelta delta = newJavaElementDelta();
- ICompilationUnit unit = getCompilationUnit();
- IPackageFragment pkg = (IPackageFragment) getParentElement();
- IContainer folder = (IContainer) pkg.getUnderlyingResource();
- InputStream stream =
- new ByteArrayInputStream(BufferManager.stringToBytes(fSource));
- worked(1);
- createFile(folder, unit.getElementName(), stream, fForce);
- worked(1);
- fResultElements = new IJavaElement[] { getCompilationUnit()};
- for (int i = 0; i < fResultElements.length; i++) {
- delta.added(fResultElements[i]);
- }
- addDelta(delta);
- done();
+ addDelta(delta);
+ done();
+}
+/**
+ * @see CreateElementInCUOperation#getCompilationUnit()
+ */
+protected ICompilationUnit getCompilationUnit() {
+ return ((IPackageFragment)getParentElement()).getCompilationUnit(fName);
+}
+/**
+ * Possible failures: <ul>
+ * <li>NO_ELEMENTS_TO_PROCESS - the package fragment supplied to the operation is
+ * <code>null</code>.
+ * <li>INVALID_NAME - the compilation unit name provided to the operation
+ * is <code>null</code> or has an invalid syntax
+ * <li>INVALID_CONTENTS - the source specified for the compiliation unit is null
+ * </ul>
+ */
+public IJavaModelStatus verify() {
+ if (getParentElement() == null) {
+ return new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
}
-
- /**
- * @see CreateElementInCUOperation#getCompilationUnit()
- */
- protected ICompilationUnit getCompilationUnit() {
- return ((IPackageFragment) getParentElement()).getCompilationUnit(fName);
+ if (!JavaConventions.validateCompilationUnitName(fName).isOK()) {
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_NAME, fName);
}
-
- /**
- * Possible failures: <ul>
- * <li>NO_ELEMENTS_TO_PROCESS - the package fragment supplied to the operation is
- * <code>null</code>.
- * <li>INVALID_NAME - the compilation unit name provided to the operation
- * is <code>null</code> or has an invalid syntax
- * <li>INVALID_CONTENTS - the source specified for the compiliation unit is null
- * </ul>
- */
- public IJavaModelStatus verify() {
- if (getParentElement() == null) {
- return new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
- }
- if (!JavaConventions.validateCompilationUnitName(fName).isOK()) {
- return new JavaModelStatus(IJavaModelStatusConstants.INVALID_NAME, fName);
- }
- if (fSource == null) {
- return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS);
- }
- return JavaModelStatus.VERIFIED_OK;
+ if (fSource == null) {
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS);
}
-
+ return JavaModelStatus.VERIFIED_OK;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateElementInCUOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateElementInCUOperation.java
index 5df9ecbde5..e6c4681111 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateElementInCUOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateElementInCUOperation.java
@@ -75,241 +75,214 @@ public abstract class CreateElementInCUOperation extends JavaModelOperation {
* or -1 if the new element is append to the end of the CU.
*/
protected int fReplacementLength = -1;
- /**
- * Constructs an operation that creates a Java Language Element with
- * the specified parent, contained within a compilation unit.
- */
- public CreateElementInCUOperation(IJavaElement parentElement) {
- super(null, new IJavaElement[] { parentElement });
- initializeDefaultPosition();
- }
-
- /**
- * Only allow cancelling if this operation is not nested.
- */
- protected void checkCanceled() {
- if (!fNested) {
- super.checkCanceled();
- }
- }
-
- /**
- * Instructs this operation to position the new element after
- * the given sibling, or to add the new element as the last child
- * of its parent if <code>null</code>.
- */
- public void createAfter(IJavaElement sibling) {
- setRelativePosition(sibling, INSERT_AFTER);
- }
-
- /**
- * Instructs this operation to position the new element before
- * the given sibling, or to add the new element as the last child
- * of its parent if <code>null</code>.
- */
- public void createBefore(IJavaElement sibling) {
- setRelativePosition(sibling, INSERT_BEFORE);
- }
-
- /**
- * Execute the operation - generate new source for the compilation unit
- * and save the results.
- *
- * @exception JavaModelException if the operation is unable to complete
- */
- protected void executeOperation() throws JavaModelException {
- beginTask(getMainTaskName(), getMainAmountOfWork());
- JavaElementDelta delta = newJavaElementDelta();
- ICompilationUnit unit = getCompilationUnit();
- generateNewCompilationUnitDOM(unit);
- if (fCreationOccurred) {
- //a change has really occurred
- Buffer buffer = (Buffer) unit.getBuffer();
- switch (fReplacementLength) {
- case -1 :
- // element is append at the end
- buffer.append(fCreatedElement.getCharacters(), true);
- break;
- case 0 :
- // element is inserted
- buffer.replace(fInsertionPosition, 0, fCreatedElement.getCharacters(), true);
- break;
- default :
- // element is replacing the previous one
- buffer.replace(
- fInsertionPosition,
- fReplacementLength,
- fCreatedElement.getCharacters(),
- true);
- }
- unit.save(null, false);
- worked(1);
- fResultElements = generateResultHandles();
- for (int i = 0; i < fResultElements.length; i++) {
- delta.added(fResultElements[i]);
- }
- addDelta(delta);
- }
- done();
+/**
+ * Constructs an operation that creates a Java Language Element with
+ * the specified parent, contained within a compilation unit.
+ */
+public CreateElementInCUOperation(IJavaElement parentElement) {
+ super(null, new IJavaElement[]{parentElement});
+ initializeDefaultPosition();
+}
+/**
+ * Only allow cancelling if this operation is not nested.
+ */
+protected void checkCanceled() {
+ if (!fNested) {
+ super.checkCanceled();
}
-
- /**
- * Returns a JDOM document fragment for the element being created.
- */
- protected abstract IDOMNode generateElementDOM() throws JavaModelException;
- /**
- * Returns the DOM with the new source to use for the given compilation unit.
- */
- protected void generateNewCompilationUnitDOM(ICompilationUnit cu)
- throws JavaModelException {
- char[] prevSource = cu.getBuffer().getCharacters();
-
- // create a JDOM for the compilation unit
- fCUDOM =
- (new DOMFactory()).createCompilationUnit(prevSource, cu.getElementName());
- IDOMNode child = generateElementDOM();
- if (child != null) {
- insertDOMNode(fCUDOM, child);
+}
+/**
+ * Instructs this operation to position the new element after
+ * the given sibling, or to add the new element as the last child
+ * of its parent if <code>null</code>.
+ */
+public void createAfter(IJavaElement sibling) {
+ setRelativePosition(sibling, INSERT_AFTER);
+}
+/**
+ * Instructs this operation to position the new element before
+ * the given sibling, or to add the new element as the last child
+ * of its parent if <code>null</code>.
+ */
+public void createBefore(IJavaElement sibling) {
+ setRelativePosition(sibling, INSERT_BEFORE);
+}
+/**
+ * Execute the operation - generate new source for the compilation unit
+ * and save the results.
+ *
+ * @exception JavaModelException if the operation is unable to complete
+ */
+protected void executeOperation() throws JavaModelException {
+ beginTask(getMainTaskName(), getMainAmountOfWork());
+ JavaElementDelta delta = newJavaElementDelta();
+ ICompilationUnit unit = getCompilationUnit();
+ generateNewCompilationUnitDOM(unit);
+ if (fCreationOccurred) {
+ //a change has really occurred
+ Buffer buffer = (Buffer)unit.getBuffer();
+ switch (fReplacementLength) {
+ case -1 :
+ // element is append at the end
+ buffer.append(fCreatedElement.getCharacters(), true);
+ break;
+ case 0 :
+ // element is inserted
+ buffer.replace(fInsertionPosition, 0, fCreatedElement.getCharacters(), true);
+ break;
+ default :
+ // element is replacing the previous one
+ buffer.replace(fInsertionPosition, fReplacementLength, fCreatedElement.getCharacters(), true);
}
+ unit.save(null, false);
worked(1);
+ fResultElements = generateResultHandles();
+ for (int i = 0; i < fResultElements.length; i++) {
+ delta.added(fResultElements[i]);
+ }
+ addDelta(delta);
}
+ done();
+}
+/**
+ * Returns a JDOM document fragment for the element being created.
+ */
+protected abstract IDOMNode generateElementDOM() throws JavaModelException;
+/**
+ * Returns the DOM with the new source to use for the given compilation unit.
+ */
+protected void generateNewCompilationUnitDOM(ICompilationUnit cu) throws JavaModelException {
+ char[] prevSource = cu.getBuffer().getCharacters();
- /**
- * Creates and returns the handle for the element this operation created.
- */
- protected abstract IJavaElement generateResultHandle();
- /**
- * Creates and returns the handles for the elements this operation created.
- */
- protected IJavaElement[] generateResultHandles() throws JavaModelException {
- return new IJavaElement[] { generateResultHandle()};
- }
-
- /**
- * Returns the compilation unit in which the new element is being created.
- */
- protected ICompilationUnit getCompilationUnit() {
- return getCompilationUnitFor(getParentElement());
- }
-
- /**
- * Returns the amount of work for the main task of this operation for
- * progress reporting.
- * @see executeOperation()
- */
- protected int getMainAmountOfWork() {
- return 2;
- }
-
- /**
- * Returns the name of the main task of this operation for
- * progress reporting.
- * @see executeOperation()
- */
- protected abstract String getMainTaskName();
- /**
- * Returns the elements created by this operation.
- */
- public IJavaElement[] getResultElements() {
- return fResultElements;
- }
-
- /**
- * Sets the default position in which to create the new type
- * member. By default, the new element is positioned as the
- * last child of the parent element in which it is created.
- * Operations that require a different default position must
- * override this method.
- */
- protected void initializeDefaultPosition() {
-
+ // create a JDOM for the compilation unit
+ fCUDOM = (new DOMFactory()).createCompilationUnit(prevSource, cu.getElementName());
+ IDOMNode child = generateElementDOM();
+ if (child != null) {
+ insertDOMNode(fCUDOM, child);
}
+ worked(1);
+}
+/**
+ * Creates and returns the handle for the element this operation created.
+ */
+protected abstract IJavaElement generateResultHandle();
+/**
+ * Creates and returns the handles for the elements this operation created.
+ */
+protected IJavaElement[] generateResultHandles() throws JavaModelException {
+ return new IJavaElement[]{generateResultHandle()};
+}
+/**
+ * Returns the compilation unit in which the new element is being created.
+ */
+protected ICompilationUnit getCompilationUnit() {
+ return getCompilationUnitFor(getParentElement());
+}
+/**
+ * Returns the amount of work for the main task of this operation for
+ * progress reporting.
+ * @see executeOperation()
+ */
+protected int getMainAmountOfWork(){
+ return 2;
+}
+/**
+ * Returns the name of the main task of this operation for
+ * progress reporting.
+ * @see executeOperation()
+ */
+protected abstract String getMainTaskName();
+/**
+ * Returns the elements created by this operation.
+ */
+public IJavaElement[] getResultElements() {
+ return fResultElements;
+}
+/**
+ * Sets the default position in which to create the new type
+ * member. By default, the new element is positioned as the
+ * last child of the parent element in which it is created.
+ * Operations that require a different default position must
+ * override this method.
+ */
+protected void initializeDefaultPosition() {
- /**
- * Inserts the given child into the given JDOM,
- * based on the position settings of this operation.
- *
- * @see createAfter(IJavaElement)
- * @see createBefore(IJavaElement);
- */
- protected void insertDOMNode(IDOMNode parent, IDOMNode child) {
- if (fInsertionPolicy != INSERT_LAST) {
- IDOMNode sibling = ((JavaElement) fAnchorElement).findNode(fCUDOM);
- if (sibling != null && fInsertionPolicy == INSERT_AFTER) {
- sibling = sibling.getNextNode();
- }
- if (sibling != null) {
- sibling.insertSibling(child);
- fCreatedElement = (DOMNode) child;
- fInsertionPosition = ((DOMNode) sibling).getStartPosition();
- fReplacementLength = 0;
- return;
- }
+}
+/**
+ * Inserts the given child into the given JDOM,
+ * based on the position settings of this operation.
+ *
+ * @see createAfter(IJavaElement)
+ * @see createBefore(IJavaElement);
+ */
+protected void insertDOMNode(IDOMNode parent, IDOMNode child) {
+ if (fInsertionPolicy != INSERT_LAST) {
+ IDOMNode sibling = ((JavaElement)fAnchorElement).findNode(fCUDOM);
+ if (sibling != null && fInsertionPolicy == INSERT_AFTER) {
+ sibling = sibling.getNextNode();
+ }
+ if (sibling != null) {
+ sibling.insertSibling(child);
+ fCreatedElement = (DOMNode)child;
+ fInsertionPosition = ((DOMNode)sibling).getStartPosition();
+ fReplacementLength = 0;
+ return;
}
- //add as the last element of the parent
- parent.addChild(child);
- fCreatedElement = (DOMNode) child;
- DOMNode lastChild = (DOMNode) fCreatedElement.getPreviousNode();
- fInsertionPosition =
- lastChild == null
- ? ((DOMNode) parent).getInsertionPosition()
- : lastChild.getEndPosition() + 1;
- fReplacementLength = parent.getParent() == null ? -1 : 0;
}
-
- /**
- * Sets the name of the <code>DOMNode</code> that will be used to
- * create this new element.
- * Used by the <code>CopyElementsOperation</code> for renaming.
- * Only used for <code>CreateTypeMemberOperation</code>
- */
- protected void setAlteredName(String newName) {
+ //add as the last element of the parent
+ parent.addChild(child);
+ fCreatedElement = (DOMNode)child;
+ DOMNode lastChild = (DOMNode)fCreatedElement.getPreviousNode();
+ fInsertionPosition = lastChild == null ? ((DOMNode)parent).getInsertionPosition() : lastChild.getEndPosition() + 1;
+ fReplacementLength = parent.getParent() == null ? -1 : 0;
+}
+/**
+ * Sets the name of the <code>DOMNode</code> that will be used to
+ * create this new element.
+ * Used by the <code>CopyElementsOperation</code> for renaming.
+ * Only used for <code>CreateTypeMemberOperation</code>
+ */
+protected void setAlteredName(String newName) {
+}
+/**
+ * Instructs this operation to position the new element relative
+ * to the given sibling, or to add the new element as the last child
+ * of its parent if <code>null</code>. The <code>position</code>
+ * must be one of the position constants.
+ */
+protected void setRelativePosition(IJavaElement sibling, int policy) throws IllegalArgumentException {
+ if (sibling == null) {
+ fAnchorElement = null;
+ fInsertionPolicy = INSERT_LAST;
+ } else {
+ fAnchorElement = sibling;
+ fInsertionPolicy = policy;
}
-
- /**
- * Instructs this operation to position the new element relative
- * to the given sibling, or to add the new element as the last child
- * of its parent if <code>null</code>. The <code>position</code>
- * must be one of the position constants.
- */
- protected void setRelativePosition(IJavaElement sibling, int policy)
- throws IllegalArgumentException {
- if (sibling == null) {
- fAnchorElement = null;
- fInsertionPolicy = INSERT_LAST;
- } else {
- fAnchorElement = sibling;
- fInsertionPolicy = policy;
- }
+}
+/**
+ * Possible failures: <ul>
+ * <li>NO_ELEMENTS_TO_PROCESS - the compilation unit supplied to the operation is
+ * <code>null</code>.
+ * <li>INVALID_NAME - no name, a name was null or not a valid
+ * import declaration name.
+ * <li>INVALID_SIBLING - the sibling provided for positioning is not valid.
+ * </ul>
+ * @see IJavaModelStatus
+ * @see JavaNamingConventions
+ */
+public IJavaModelStatus verify() {
+ if (getParentElement() == null) {
+ return new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
}
-
- /**
- * Possible failures: <ul>
- * <li>NO_ELEMENTS_TO_PROCESS - the compilation unit supplied to the operation is
- * <code>null</code>.
- * <li>INVALID_NAME - no name, a name was null or not a valid
- * import declaration name.
- * <li>INVALID_SIBLING - the sibling provided for positioning is not valid.
- * </ul>
- * @see IJavaModelStatus
- * @see JavaNamingConventions
- */
- public IJavaModelStatus verify() {
- if (getParentElement() == null) {
- return new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
+ if (fAnchorElement != null) {
+ IJavaElement domPresentParent = fAnchorElement.getParent();
+ if (domPresentParent.getElementType() == IJavaElement.IMPORT_CONTAINER) {
+ domPresentParent = domPresentParent.getParent();
}
- if (fAnchorElement != null) {
- IJavaElement domPresentParent = fAnchorElement.getParent();
- if (domPresentParent.getElementType() == IJavaElement.IMPORT_CONTAINER) {
- domPresentParent = domPresentParent.getParent();
- }
- if (!domPresentParent.equals(getParentElement())) {
- return new JavaModelStatus(
- IJavaModelStatusConstants.INVALID_SIBLING,
- fAnchorElement);
- }
+ if (!domPresentParent.equals(getParentElement())) {
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_SIBLING, fAnchorElement);
}
- return JavaModelStatus.VERIFIED_OK;
}
-
+ return JavaModelStatus.VERIFIED_OK;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateFieldOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateFieldOperation.java
index a8699361b8..79ab766ce7 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateFieldOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateFieldOperation.java
@@ -19,81 +19,72 @@ import org.eclipse.jdt.core.jdom.*;
* </ul>
*/
public class CreateFieldOperation extends CreateTypeMemberOperation {
- /**
- * When executed, this operation will create a field with the given name
- * in the given type with the specified source.
- *
- * <p>By default the new field is positioned after the last existing field
- * declaration, or as the first member in the type if there are no
- * field declarations.
- */
- public CreateFieldOperation(
- IType parentElement,
- String source,
- boolean force) {
- super(parentElement, source, force);
- }
-
- /**
- * @see CreateTypeMemberOperation#generateElementDOM
- */
- protected IDOMNode generateElementDOM() throws JavaModelException {
+/**
+ * When executed, this operation will create a field with the given name
+ * in the given type with the specified source.
+ *
+ * <p>By default the new field is positioned after the last existing field
+ * declaration, or as the first member in the type if there are no
+ * field declarations.
+ */
+public CreateFieldOperation(IType parentElement, String source, boolean force) {
+ super(parentElement, source, force);
+}
+/**
+ * @see CreateTypeMemberOperation#generateElementDOM
+ */
+protected IDOMNode generateElementDOM() throws JavaModelException {
+ if (fDOMNode == null) {
+ fDOMNode = (new DOMFactory()).createField(fSource);
if (fDOMNode == null) {
- fDOMNode = (new DOMFactory()).createField(fSource);
- if (fDOMNode == null) {
- fDOMNode = generateSyntaxIncorrectDOM();
- }
- if (fAlteredName != null && fDOMNode != null) {
- fDOMNode.setName(fAlteredName);
- }
+ fDOMNode = generateSyntaxIncorrectDOM();
+ }
+ if (fAlteredName != null && fDOMNode != null) {
+ fDOMNode.setName(fAlteredName);
}
- return fDOMNode;
- }
-
- /**
- * @see CreateElementInCUOperation#generateResultHandle
- */
- protected IJavaElement generateResultHandle() {
- return getType().getField(fDOMNode.getName());
- }
-
- /**
- * @see CreateElementInCUOperation#getMainTaskName
- */
- public String getMainTaskName() {
- return "Creating a field...";
}
-
- /**
- * By default the new field is positioned after the last existing field
- * declaration, or as the first member in the type if there are no
- * field declarations.
- */
- protected void initializeDefaultPosition() {
- IType parentElement = getType();
- try {
- IJavaElement[] elements = parentElement.getFields();
+ return fDOMNode;
+}
+/**
+ * @see CreateElementInCUOperation#generateResultHandle
+ */
+protected IJavaElement generateResultHandle() {
+ return getType().getField(fDOMNode.getName());
+}
+/**
+ * @see CreateElementInCUOperation#getMainTaskName
+ */
+public String getMainTaskName(){
+ return Util.bind("operation.createFieldProgress"/*nonNLS*/);
+}
+/**
+ * By default the new field is positioned after the last existing field
+ * declaration, or as the first member in the type if there are no
+ * field declarations.
+ */
+protected void initializeDefaultPosition() {
+ IType parentElement = getType();
+ try {
+ IJavaElement[] elements = parentElement.getFields();
+ if (elements != null && elements.length > 0) {
+ createAfter(elements[elements.length - 1]);
+ } else {
+ elements = parentElement.getChildren();
if (elements != null && elements.length > 0) {
- createAfter(elements[elements.length - 1]);
- } else {
- elements = parentElement.getChildren();
- if (elements != null && elements.length > 0) {
- createBefore(elements[0]);
- }
+ createBefore(elements[0]);
}
- } catch (JavaModelException e) {
}
+ } catch (JavaModelException e) {
}
-
- /**
- * @see CreateTypeMemberOperation#verifyNameCollision
- */
- protected IJavaModelStatus verifyNameCollision() {
- IType type = getType();
- if (type.getField(fDOMNode.getName()).exists()) {
- return new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION);
- }
- return JavaModelStatus.VERIFIED_OK;
+}
+/**
+ * @see CreateTypeMemberOperation#verifyNameCollision
+ */
+protected IJavaModelStatus verifyNameCollision() {
+ IType type= getType();
+ if (type.getField(fDOMNode.getName()).exists()) {
+ return new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION);
}
-
+ return JavaModelStatus.VERIFIED_OK;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateImportOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateImportOperation.java
index 3387473c98..f40b1fb73a 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateImportOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateImportOperation.java
@@ -38,98 +38,90 @@ public class CreateImportOperation extends CreateElementInCUOperation {
* The name of the import to be created.
*/
protected String fImportName;
- /**
- * When executed, this operation will add an import to the given compilation unit.
- */
- public CreateImportOperation(
- String importName,
- ICompilationUnit parentElement) {
- super(parentElement);
- fImportName = importName;
+/**
+ * When executed, this operation will add an import to the given compilation unit.
+ */
+public CreateImportOperation(String importName, ICompilationUnit parentElement) {
+ super(parentElement);
+ fImportName = importName;
+}
+/**
+ * @see CreateTypeMemberOperation#generateElementDOM
+ */
+protected IDOMNode generateElementDOM() throws JavaModelException {
+ if (fCUDOM.getChild(fImportName) == null) {
+ DOMFactory factory = new DOMFactory();
+ //not a duplicate
+ IDOMImport imp = factory.createImport();
+ imp.setName(fImportName);
+ return imp;
}
-
- /**
- * @see CreateTypeMemberOperation#generateElementDOM
- */
- protected IDOMNode generateElementDOM() throws JavaModelException {
- if (fCUDOM.getChild(fImportName) == null) {
- DOMFactory factory = new DOMFactory();
- //not a duplicate
- IDOMImport imp = factory.createImport();
- imp.setName(fImportName);
- return imp;
+
+ //no new import was generated
+ fCreationOccurred = false;
+ //all the work has already been done
+ return null;
+}
+/**
+ * @see CreateElementInCUOperation#generateResultHandle
+ */
+protected IJavaElement generateResultHandle() {
+ return getCompilationUnit().getImport(fImportName);
+}
+/**
+ * @see CreateElementInCUOperation#getMainTaskName
+ */
+public String getMainTaskName(){
+ return Util.bind("operation.createImportsProgress"/*nonNLS*/);
+}
+/**
+ * Sets the correct position for the new import:<ul>
+ * <li> after the last import
+ * <li> if no imports, before the first type
+ * <li> if no type, after the package statement
+ * <li> and if no package statement - first thing in the CU
+ */
+protected void initializeDefaultPosition() {
+ try {
+ ICompilationUnit cu = getCompilationUnit();
+ IImportDeclaration[] imports = cu.getImports();
+ if (imports.length > 0) {
+ createAfter(imports[imports.length - 1]);
+ return;
}
-
- //no new import was generated
- fCreationOccurred = false;
- //all the work has already been done
- return null;
- }
-
- /**
- * @see CreateElementInCUOperation#generateResultHandle
- */
- protected IJavaElement generateResultHandle() {
- return getCompilationUnit().getImport(fImportName);
- }
-
- /**
- * @see CreateElementInCUOperation#getMainTaskName
- */
- public String getMainTaskName() {
- return "Creating imports...";
- }
-
- /**
- * Sets the correct position for the new import:<ul>
- * <li> after the last import
- * <li> if no imports, before the first type
- * <li> if no type, after the package statement
- * <li> and if no package statement - first thing in the CU
- */
- protected void initializeDefaultPosition() {
- try {
- ICompilationUnit cu = getCompilationUnit();
- IImportDeclaration[] imports = cu.getImports();
- if (imports.length > 0) {
- createAfter(imports[imports.length - 1]);
- return;
- }
- IType[] types = cu.getTypes();
- if (types.length > 0) {
- createBefore(types[0]);
+ IType[] types = cu.getTypes();
+ if (types.length > 0) {
+ createBefore(types[0]);
+ return;
+ }
+ IJavaElement[] children = cu.getChildren();
+ //look for the package declaration
+ for (int i = 0; i < children.length; i++) {
+ if (children[i].getElementType() == IJavaElement.PACKAGE_DECLARATION) {
+ createAfter(children[i]);
return;
}
- IJavaElement[] children = cu.getChildren();
- //look for the package declaration
- for (int i = 0; i < children.length; i++) {
- if (children[i].getElementType() == IJavaElement.PACKAGE_DECLARATION) {
- createAfter(children[i]);
- return;
- }
- }
- } catch (JavaModelException npe) {
}
+ } catch (JavaModelException npe) {
}
-
- /**
- * Possible failures: <ul>
- * <li>NO_ELEMENTS_TO_PROCESS - the compilation unit supplied to the operation is
- * <code>null</code>.
- * <li>INVALID_NAME - not a valid import declaration name.
- * </ul>
- * @see IJavaModelStatus
- * @see JavaNamingConventions
- */
- public IJavaModelStatus verify() {
- IJavaModelStatus status = super.verify();
- if (!status.isOK()) {
- return status;
- }
- if (!JavaConventions.validateImportDeclaration(fImportName).isOK()) {
- return new JavaModelStatus(IJavaModelStatusConstants.INVALID_NAME, fImportName);
- }
- return JavaModelStatus.VERIFIED_OK;
+}
+/**
+ * Possible failures: <ul>
+ * <li>NO_ELEMENTS_TO_PROCESS - the compilation unit supplied to the operation is
+ * <code>null</code>.
+ * <li>INVALID_NAME - not a valid import declaration name.
+ * </ul>
+ * @see IJavaModelStatus
+ * @see JavaNamingConventions
+ */
+public IJavaModelStatus verify() {
+ IJavaModelStatus status = super.verify();
+ if (!status.isOK()) {
+ return status;
}
-
+ if (!JavaConventions.validateImportDeclaration(fImportName).isOK()) {
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_NAME, fImportName);
+ }
+ return JavaModelStatus.VERIFIED_OK;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateInitializerOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateInitializerOperation.java
index 4a2a03eb0a..436ee5ad48 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateInitializerOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateInitializerOperation.java
@@ -23,88 +23,82 @@ public class CreateInitializerOperation extends CreateTypeMemberOperation {
* The current number of initializers in the parent type.
* Used to retrieve the handle of the newly created initializer.
*/
- protected int fNumberOfInitializers = 1;
- /**
- * When executed, this operation will create an initializer with the given name
- * in the given type with the specified source.
- *
- * <p>By default the new initializer is positioned after the last existing initializer
- * declaration, or as the first member in the type if there are no
- * initializers.
- */
- public CreateInitializerOperation(IType parentElement, String source) {
- super(parentElement, source, false);
- }
-
- /**
- * @see CreateTypeMemberOperation#generateElementDOM
- */
- protected IDOMNode generateElementDOM() throws JavaModelException {
- IDOMInitializer domInitializer = (new DOMFactory()).createInitializer(fSource);
- if (domInitializer == null) {
- domInitializer = (IDOMInitializer) generateSyntaxIncorrectDOM();
- }
- return domInitializer;
+ protected int fNumberOfInitializers= 1;
+/**
+ * When executed, this operation will create an initializer with the given name
+ * in the given type with the specified source.
+ *
+ * <p>By default the new initializer is positioned after the last existing initializer
+ * declaration, or as the first member in the type if there are no
+ * initializers.
+ */
+public CreateInitializerOperation(IType parentElement, String source) {
+ super(parentElement, source, false);
+}
+/**
+ * @see CreateTypeMemberOperation#generateElementDOM
+ */
+protected IDOMNode generateElementDOM() throws JavaModelException {
+ IDOMInitializer domInitializer = (new DOMFactory()).createInitializer(fSource);
+ if (domInitializer == null) {
+ domInitializer = (IDOMInitializer) generateSyntaxIncorrectDOM();
}
-
- /**
- * @see CreateElementInCUOperation#generateResultHandle
- */
- protected IJavaElement generateResultHandle() {
- try {
- //update the children to be current
- getType().getCompilationUnit().close();
- if (fAnchorElement == null) {
- return getType().getInitializer(fNumberOfInitializers);
- } else {
- IJavaElement[] children = getType().getChildren();
- int count = 0;
- for (int i = 0; i < children.length; i++) {
- IJavaElement child = children[i];
- if (child.equals(fAnchorElement)) {
- if (child.getElementType() == IJavaElement.INITIALIZER
- && fInsertionPolicy == CreateElementInCUOperation.INSERT_AFTER) {
- count++;
- }
- return getType().getInitializer(count);
- } else
- if (child.getElementType() == IJavaElement.INITIALIZER) {
- count++;
- }
- }
+ return domInitializer;
+}
+/**
+ * @see CreateElementInCUOperation#generateResultHandle
+ */
+protected IJavaElement generateResultHandle() {
+ try {
+ //update the children to be current
+ getType().getCompilationUnit().close();
+ if (fAnchorElement == null) {
+ return getType().getInitializer(fNumberOfInitializers);
+ } else {
+ IJavaElement[] children = getType().getChildren();
+ int count = 0;
+ for (int i = 0; i < children.length; i++) {
+ IJavaElement child = children[i];
+ if (child.equals(fAnchorElement)) {
+ if (child .getElementType() == IJavaElement.INITIALIZER && fInsertionPolicy == CreateElementInCUOperation.INSERT_AFTER) {
+ count++;
+ }
+ return getType().getInitializer(count);
+ } else
+ if (child.getElementType() == IJavaElement.INITIALIZER) {
+ count++;
+ }
}
- } catch (JavaModelException jme) {
}
- return null;
+ } catch (JavaModelException jme) {
}
-
- /**
- * @see CreateElementInCUOperation#getMainTaskName
- */
- public String getMainTaskName() {
- return "Creating an initializer...";
- }
-
- /**
- * By default the new initializer is positioned after the last existing initializer
- * declaration, or as the first member in the type if there are no
- * initializers.
- */
- protected void initializeDefaultPosition() {
- IType parentElement = getType();
- try {
- IJavaElement[] elements = parentElement.getInitializers();
+ return null;
+}
+/**
+ * @see CreateElementInCUOperation#getMainTaskName
+ */
+public String getMainTaskName(){
+ return Util.bind("operation.createInitializerProgress"/*nonNLS*/);
+}
+/**
+ * By default the new initializer is positioned after the last existing initializer
+ * declaration, or as the first member in the type if there are no
+ * initializers.
+ */
+protected void initializeDefaultPosition() {
+ IType parentElement = getType();
+ try {
+ IJavaElement[] elements = parentElement.getInitializers();
+ if (elements != null && elements.length > 0) {
+ fNumberOfInitializers= elements.length;
+ createAfter(elements[elements.length - 1]);
+ } else {
+ elements = parentElement.getChildren();
if (elements != null && elements.length > 0) {
- fNumberOfInitializers = elements.length;
- createAfter(elements[elements.length - 1]);
- } else {
- elements = parentElement.getChildren();
- if (elements != null && elements.length > 0) {
- createBefore(elements[0]);
- }
+ createBefore(elements[0]);
}
- } catch (JavaModelException e) {
}
+ } catch (JavaModelException e) {
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateMethodOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateMethodOperation.java
index 38b1512cd6..d99a852b86 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateMethodOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateMethodOperation.java
@@ -20,92 +20,82 @@ import org.eclipse.jdt.core.jdom.*;
*/
public class CreateMethodOperation extends CreateTypeMemberOperation {
protected String[] fParameterTypes;
- /**
- * When executed, this operation will create a method
- * in the given type with the specified source.
- */
- public CreateMethodOperation(
- IType parentElement,
- String source,
- boolean force) {
- super(parentElement, source, force);
- }
-
- /**
- * Returns the type signatures of the parameter types of the
- * current <code>DOMMethod</code>
- */
- protected String[] convertDOMMethodTypesToSignatures() {
- if (fParameterTypes == null) {
- if (fDOMNode != null) {
- String[] domParameterTypes = ((IDOMMethod) fDOMNode).getParameterTypes();
- if (domParameterTypes != null) {
- fParameterTypes = new String[domParameterTypes.length];
- // convert the DOM types to signatures
- int i;
- for (i = 0; i < fParameterTypes.length; i++) {
- fParameterTypes[i] =
- Signature.createTypeSignature(domParameterTypes[i].toCharArray(), false);
- }
+/**
+ * When executed, this operation will create a method
+ * in the given type with the specified source.
+ */
+public CreateMethodOperation(IType parentElement, String source, boolean force) {
+ super(parentElement, source, force);
+}
+/**
+ * Returns the type signatures of the parameter types of the
+ * current <code>DOMMethod</code>
+ */
+protected String[] convertDOMMethodTypesToSignatures() {
+ if (fParameterTypes == null) {
+ if (fDOMNode != null) {
+ String[] domParameterTypes = ((IDOMMethod)fDOMNode).getParameterTypes();
+ if (domParameterTypes != null) {
+ fParameterTypes = new String[domParameterTypes.length];
+ // convert the DOM types to signatures
+ int i;
+ for (i = 0; i < fParameterTypes.length; i++) {
+ fParameterTypes[i] = Signature.createTypeSignature(domParameterTypes[i].toCharArray(), false);
}
}
}
- return fParameterTypes;
}
-
- /**
- * @see CreateTypeMemberOperation#generateElementDOM
- */
- protected IDOMNode generateElementDOM() throws JavaModelException {
- if (fDOMNode == null) {
- fDOMNode = (new DOMFactory()).createMethod(fSource);
- if (fDOMNode == null) { //syntactically incorrect source
- fDOMNode = generateSyntaxIncorrectDOM();
- }
- if (fAlteredName != null && fDOMNode != null) {
- fDOMNode.setName(fAlteredName);
- }
+ return fParameterTypes;
+}
+/**
+ * @see CreateTypeMemberOperation#generateElementDOM
+ */
+protected IDOMNode generateElementDOM() throws JavaModelException {
+ if (fDOMNode == null) {
+ fDOMNode = (new DOMFactory()).createMethod(fSource);
+ if (fDOMNode == null) { //syntactically incorrect source
+ fDOMNode = generateSyntaxIncorrectDOM();
}
- return fDOMNode;
- }
-
- /**
- * @see CreateElementInCUOperation#generateResultHandle
- */
- protected IJavaElement generateResultHandle() {
- String[] types = convertDOMMethodTypesToSignatures();
- String name;
- if (((IDOMMethod) fDOMNode).isConstructor()) {
- name = fDOMNode.getParent().getName();
- } else {
- name = fDOMNode.getName();
+ if (fAlteredName != null && fDOMNode != null) {
+ fDOMNode.setName(fAlteredName);
}
- return getType().getMethod(name, types);
}
-
- /**
- * @see CreateElementInCUOperation#getMainTaskName
- */
- public String getMainTaskName() {
- return "Creating a method...";
+ return fDOMNode;
+}
+/**
+ * @see CreateElementInCUOperation#generateResultHandle
+ */
+protected IJavaElement generateResultHandle() {
+ String[] types = convertDOMMethodTypesToSignatures();
+ String name;
+ if (((IDOMMethod) fDOMNode).isConstructor()) {
+ name = fDOMNode.getParent().getName();
+ } else {
+ name = fDOMNode.getName();
}
-
- /**
- * @see CreateTypeMemberOperation#verifyNameCollision
- */
- protected IJavaModelStatus verifyNameCollision() {
- if (fDOMNode != null) {
- IType type = getType();
- String name = fDOMNode.getName();
- if (name == null) { //constructor
- name = type.getElementName();
- }
- String[] types = convertDOMMethodTypesToSignatures();
- if (type.getMethod(name, types).exists()) {
- return new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION);
- }
+ return getType().getMethod(name, types);
+}
+/**
+ * @see CreateElementInCUOperation#getMainTaskName
+ */
+public String getMainTaskName(){
+ return Util.bind("operation.createMethodProgress"/*nonNLS*/);
+}
+/**
+ * @see CreateTypeMemberOperation#verifyNameCollision
+ */
+protected IJavaModelStatus verifyNameCollision() {
+ if (fDOMNode != null) {
+ IType type = getType();
+ String name = fDOMNode.getName();
+ if (name == null) { //constructor
+ name = type.getElementName();
+ }
+ String[] types = convertDOMMethodTypesToSignatures();
+ if (type.getMethod(name, types).exists()) {
+ return new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION);
}
- return JavaModelStatus.VERIFIED_OK;
}
-
+ return JavaModelStatus.VERIFIED_OK;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreatePackageDeclarationOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreatePackageDeclarationOperation.java
index 7238b8eadb..14fd9662ab 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreatePackageDeclarationOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreatePackageDeclarationOperation.java
@@ -20,109 +20,100 @@ import org.eclipse.jdt.internal.core.jdom.DOMNode;
* <li>Package name
* </ul>
*/
-public class CreatePackageDeclarationOperation
- extends CreateElementInCUOperation {
+public class CreatePackageDeclarationOperation extends CreateElementInCUOperation {
/**
* The name of the package declaration being created
*/
protected String fName = null;
- /**
- * When executed, this operation will add a package declaration to the given compilation unit.
- */
- public CreatePackageDeclarationOperation(
- String name,
- ICompilationUnit parentElement) {
- super(parentElement);
- fName = name;
- }
-
- /**
- * @see CreateTypeMemberOperation#generateElementDOM
- */
- protected IDOMNode generateElementDOM() throws JavaModelException {
- IJavaElement[] children = getCompilationUnit().getChildren();
- //look for an existing package declaration
- for (int i = 0; i < children.length; i++) {
- if (children[i].getElementType() == IJavaElement.PACKAGE_DECLARATION) {
- IPackageDeclaration pck = (IPackageDeclaration) children[i];
- IDOMPackage pack = (IDOMPackage) ((JavaElement) pck).findNode(fCUDOM);
- if (!pack.getName().equals(fName)) {
- // get the insertion position before setting the name, as this makes it a detailed node
- // thus the start position is always 0
- DOMNode node = (DOMNode) pack;
- fInsertionPosition = node.getStartPosition();
- fReplacementLength = node.getEndPosition() - fInsertionPosition + 1;
- pack.setName(fName);
- fCreatedElement = (org.eclipse.jdt.internal.core.jdom.DOMNode) pack;
- } else {
- //equivalent package declaration already exists
- fCreationOccurred = false;
- }
-
- return null;
- }
- }
- IDOMPackage pack = (new DOMFactory()).createPackage();
- pack.setName(fName);
- return pack;
- }
-
- /**
- * Creates and returns the handle for the element this operation created.
- */
- protected IJavaElement generateResultHandle() {
- return getCompilationUnit().getPackageDeclaration(fName);
- }
-
- /**
- * @see CreateElementInCUOperation#getMainTaskName
- */
- public String getMainTaskName() {
- return "Creating a package declaration...";
- }
-
- /**
- * Sets the correct position for new package declaration:<ul>
- * <li> before the first import
- * <li> if no imports, before the first type
- * <li> if no type - first thing in the CU
- * <li>
- */
- protected void initializeDefaultPosition() {
- try {
- ICompilationUnit cu = getCompilationUnit();
- IImportDeclaration[] imports = cu.getImports();
- if (imports.length > 0) {
- createBefore(imports[0]);
- return;
- }
- IType[] types = cu.getTypes();
- if (types.length > 0) {
- createBefore(types[0]);
- return;
+/**
+ * When executed, this operation will add a package declaration to the given compilation unit.
+ */
+public CreatePackageDeclarationOperation(String name, ICompilationUnit parentElement) {
+ super(parentElement);
+ fName= name;
+}
+/**
+ * @see CreateTypeMemberOperation#generateElementDOM
+ */
+protected IDOMNode generateElementDOM() throws JavaModelException {
+ IJavaElement[] children = getCompilationUnit().getChildren();
+ //look for an existing package declaration
+ for (int i = 0; i < children.length; i++) {
+ if (children[i].getElementType() == IJavaElement.PACKAGE_DECLARATION) {
+ IPackageDeclaration pck = (IPackageDeclaration) children[i];
+ IDOMPackage pack = (IDOMPackage) ((JavaElement)pck).findNode(fCUDOM);
+ if (!pack.getName().equals(fName)) {
+ // get the insertion position before setting the name, as this makes it a detailed node
+ // thus the start position is always 0
+ DOMNode node = (DOMNode)pack;
+ fInsertionPosition = node.getStartPosition();
+ fReplacementLength = node.getEndPosition() - fInsertionPosition + 1;
+ pack.setName(fName);
+ fCreatedElement = (org.eclipse.jdt.internal.core.jdom.DOMNode)pack;
+ } else {
+ //equivalent package declaration already exists
+ fCreationOccurred= false;
}
- } catch (JavaModelException npe) {
+
+ return null;
}
}
-
- /**
- * Possible failures: <ul>
- * <li>NO_ELEMENTS_TO_PROCESS - no compilation unit was supplied to the operation
- * <li>INVALID_NAME - a name supplied to the operation was not a valid
- * package declaration name.
- * </ul>
- * @see IJavaModelStatus
- * @see JavaNamingConventions
- */
- public IJavaModelStatus verify() {
- IJavaModelStatus status = super.verify();
- if (!status.isOK()) {
- return status;
+ IDOMPackage pack = (new DOMFactory()).createPackage();
+ pack.setName(fName);
+ return pack;
+}
+/**
+ * Creates and returns the handle for the element this operation created.
+ */
+protected IJavaElement generateResultHandle() {
+ return getCompilationUnit().getPackageDeclaration(fName);
+}
+/**
+ * @see CreateElementInCUOperation#getMainTaskName
+ */
+public String getMainTaskName(){
+ return Util.bind("operation.createPackageProgress"/*nonNLS*/);
+}
+/**
+ * Sets the correct position for new package declaration:<ul>
+ * <li> before the first import
+ * <li> if no imports, before the first type
+ * <li> if no type - first thing in the CU
+ * <li>
+ */
+protected void initializeDefaultPosition() {
+ try {
+ ICompilationUnit cu = getCompilationUnit();
+ IImportDeclaration[] imports = cu.getImports();
+ if (imports.length > 0) {
+ createBefore(imports[0]);
+ return;
}
- if (!JavaConventions.validatePackageName(fName).isOK()) {
- return new JavaModelStatus(IJavaModelStatusConstants.INVALID_NAME, fName);
+ IType[] types = cu.getTypes();
+ if (types.length > 0) {
+ createBefore(types[0]);
+ return;
}
- return JavaModelStatus.VERIFIED_OK;
+ } catch (JavaModelException npe) {
}
-
+}
+/**
+ * Possible failures: <ul>
+ * <li>NO_ELEMENTS_TO_PROCESS - no compilation unit was supplied to the operation
+ * <li>INVALID_NAME - a name supplied to the operation was not a valid
+ * package declaration name.
+ * </ul>
+ * @see IJavaModelStatus
+ * @see JavaNamingConventions
+ */
+public IJavaModelStatus verify() {
+ IJavaModelStatus status = super.verify();
+ if (!status.isOK()) {
+ return status;
+ }
+ if (!JavaConventions.validatePackageName(fName).isOK()) {
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_NAME, fName);
+ }
+ return JavaModelStatus.VERIFIED_OK;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreatePackageFragmentOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreatePackageFragmentOperation.java
index 0c45b07607..8e9c69ec77 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreatePackageFragmentOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreatePackageFragmentOperation.java
@@ -34,103 +34,96 @@ public class CreatePackageFragmentOperation extends JavaModelOperation {
* The fully qualified, dot-delimited, package name.
*/
protected String fName;
- /**
- * When executed, this operation will create a package fragment with the given name
- * under the given package fragment root. The dot-separated name is broken into
- * segments. Intermediate folders are created as required for each segment.
- * If the folders already exist, this operation has no effect.
- */
- public CreatePackageFragmentOperation(
- IPackageFragmentRoot parentElement,
- String packageName,
- boolean force) {
- super(null, new IJavaElement[] { parentElement }, force);
- fName = packageName;
+/**
+ * When executed, this operation will create a package fragment with the given name
+ * under the given package fragment root. The dot-separated name is broken into
+ * segments. Intermediate folders are created as required for each segment.
+ * If the folders already exist, this operation has no effect.
+ */
+public CreatePackageFragmentOperation(IPackageFragmentRoot parentElement, String packageName, boolean force) {
+ super(null, new IJavaElement[]{parentElement}, force);
+ fName = packageName;
+}
+/**
+ * Execute the operation - creates the new package fragment and any
+ * side effect package fragments.
+ *
+ * @exception JavaModelException if the operation is unable to complete
+ */
+protected void executeOperation() throws JavaModelException {
+ JavaElementDelta delta = newJavaElementDelta();
+ IPackageFragmentRoot root = (IPackageFragmentRoot) getParentElement();
+ String[] names = Signature.getSimpleNames(fName);
+ beginTask(Util.bind("operation.createPackageFragmentProgress"/*nonNLS*/), names.length);
+ IContainer parentFolder = (IContainer) root.getUnderlyingResource();
+ String sideEffectPackageName = ""/*nonNLS*/;
+ Vector resultElements = new Vector(names.length);
+ int i;
+ for (i = 0; i < names.length; i++) {
+ String subFolderName = names[i];
+ sideEffectPackageName += subFolderName;
+ IResource subFolder = parentFolder.findMember(subFolderName);
+ if (subFolder == null) {
+ createFolder(parentFolder, subFolderName, fForce);
+ parentFolder = parentFolder.getFolder(new Path(subFolderName));
+ IPackageFragment addedFrag = root.getPackageFragment(sideEffectPackageName);
+ delta.added(addedFrag);
+ resultElements.addElement(addedFrag);
+ } else {
+ parentFolder = (IContainer) subFolder;
+ }
+ sideEffectPackageName += '.';
+ worked(1);
}
-
- /**
- * Execute the operation - creates the new package fragment and any
- * side effect package fragments.
- *
- * @exception JavaModelException if the operation is unable to complete
- */
- protected void executeOperation() throws JavaModelException {
- JavaElementDelta delta = newJavaElementDelta();
- IPackageFragmentRoot root = (IPackageFragmentRoot) getParentElement();
- String[] names = Signature.getSimpleNames(fName);
- beginTask("Creating package fragment(s)...", names.length);
+ if (resultElements.size() > 0) {
+ fResultElements = new IJavaElement[resultElements.size()];
+ resultElements.copyInto(fResultElements);
+ addDelta(delta);
+ }
+ done();
+}
+/**
+ * Possible failures: <ul>
+ * <li>NO_ELEMENTS_TO_PROCESS - the root supplied to the operation is
+ * <code>null</code>.
+ * <li>INVALID_NAME - the name provided to the operation
+ * is <code>null</code> or is not a valid package fragment name.
+ * <li>READ_ONLY - the root provided to this operation is read only.
+ * <li>NAME_COLLISION - there is a pre-existing resource (file)
+ * with the same name as a folder in the package fragment's hierarchy.
+ * <li>ELEMENT_NOT_PRESENT - the underlying resource for the root is missing
+ * </ul>
+ * @see IJavaModelStatus
+ * @see JavaNamingConventions
+ */
+public IJavaModelStatus verify() {
+ if (getParentElement() == null) {
+ return new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
+ }
+
+ if (fName == null || (fName.length() > 0 && !JavaConventions.validatePackageName(fName).isOK())) {
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_NAME, fName);
+ }
+ IPackageFragmentRoot root = (IPackageFragmentRoot) getParentElement();
+ if (root.isReadOnly()) {
+ return new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, root);
+ }
+ String[] names = Signature.getSimpleNames(fName);
+ try {
IContainer parentFolder = (IContainer) root.getUnderlyingResource();
- String sideEffectPackageName = "";
- Vector resultElements = new Vector(names.length);
int i;
for (i = 0; i < names.length; i++) {
- String subFolderName = names[i];
- sideEffectPackageName += subFolderName;
- IResource subFolder = parentFolder.findMember(subFolderName);
- if (subFolder == null) {
- createFolder(parentFolder, subFolderName, fForce);
- parentFolder = parentFolder.getFolder(new Path(subFolderName));
- IPackageFragment addedFrag = root.getPackageFragment(sideEffectPackageName);
- delta.added(addedFrag);
- resultElements.addElement(addedFrag);
- } else {
- parentFolder = (IContainer) subFolder;
- }
- sideEffectPackageName += '.';
- worked(1);
- }
- if (resultElements.size() > 0) {
- fResultElements = new IJavaElement[resultElements.size()];
- resultElements.copyInto(fResultElements);
- addDelta(delta);
- }
- done();
- }
-
- /**
- * Possible failures: <ul>
- * <li>NO_ELEMENTS_TO_PROCESS - the root supplied to the operation is
- * <code>null</code>.
- * <li>INVALID_NAME - the name provided to the operation
- * is <code>null</code> or is not a valid package fragment name.
- * <li>READ_ONLY - the root provided to this operation is read only.
- * <li>NAME_COLLISION - there is a pre-existing resource (file)
- * with the same name as a folder in the package fragment's hierarchy.
- * <li>ELEMENT_NOT_PRESENT - the underlying resource for the root is missing
- * </ul>
- * @see IJavaModelStatus
- * @see JavaNamingConventions
- */
- public IJavaModelStatus verify() {
- if (getParentElement() == null) {
- return new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
- }
-
- if (fName == null
- || (fName.length() > 0 && !JavaConventions.validatePackageName(fName).isOK())) {
- return new JavaModelStatus(IJavaModelStatusConstants.INVALID_NAME, fName);
- }
- IPackageFragmentRoot root = (IPackageFragmentRoot) getParentElement();
- if (root.isReadOnly()) {
- return new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, root);
- }
- String[] names = Signature.getSimpleNames(fName);
- try {
- IContainer parentFolder = (IContainer) root.getUnderlyingResource();
- int i;
- for (i = 0; i < names.length; i++) {
- IResource subFolder = parentFolder.findMember(names[i]);
- if (subFolder != null) {
- if (subFolder.getType() != IResource.FOLDER) {
- return new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION);
- }
- parentFolder = (IContainer) subFolder;
+ IResource subFolder = parentFolder.findMember(names[i]);
+ if (subFolder != null) {
+ if (subFolder.getType() != IResource.FOLDER) {
+ return new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION);
}
+ parentFolder = (IContainer) subFolder;
}
- } catch (JavaModelException npe) {
- return npe.getJavaModelStatus();
}
- return JavaModelStatus.VERIFIED_OK;
+ } catch (JavaModelException npe) {
+ return npe.getJavaModelStatus();
}
-
+ return JavaModelStatus.VERIFIED_OK;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateTypeHierarchyOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateTypeHierarchyOperation.java
index e207b91092..d9667e2830 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateTypeHierarchyOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateTypeHierarchyOperation.java
@@ -27,82 +27,61 @@ public class CreateTypeHierarchyOperation extends JavaModelOperation {
* The generated type hierarchy
*/
protected TypeHierarchy fTypeHierarchy;
- /**
- * Constructs an operation to create a type hierarchy for the
- * given type within the specified region, in the context of
- * the given project.
- */
- public CreateTypeHierarchyOperation(
- IType element,
- IRegion region,
- IJavaProject project,
- boolean computeSubtypes)
- throws JavaModelException {
- super(element);
- fTypeHierarchy =
- new RegionBasedTypeHierarchy(region, project, element, computeSubtypes);
- }
-
- /**
- * Constructs an operation to create a type hierarchy for the
- * given type.
- */
- public CreateTypeHierarchyOperation(
- IType element,
- IJavaSearchScope scope,
- boolean computeSubtypes)
- throws JavaModelException {
- super(element);
- fTypeHierarchy = new TypeHierarchy(element, scope, computeSubtypes);
- }
-
- /**
- * Performs the operation - creates the type hierarchy
- * @exception JavaModelException The operation has failed.
- */
- protected void executeOperation() throws JavaModelException {
- fTypeHierarchy.refresh(this);
- }
-
- /**
- * Returns the generated type hierarchy.
- */
- public ITypeHierarchy getResult() {
- return fTypeHierarchy;
+/**
+ * Constructs an operation to create a type hierarchy for the
+ * given type within the specified region, in the context of
+ * the given project.
+ */
+public CreateTypeHierarchyOperation(IType element, IRegion region, IJavaProject project, boolean computeSubtypes) throws JavaModelException {
+ super(element);
+ fTypeHierarchy = new RegionBasedTypeHierarchy(region, project, element, computeSubtypes);
+}
+/**
+ * Constructs an operation to create a type hierarchy for the
+ * given type.
+ */
+public CreateTypeHierarchyOperation(IType element, IJavaSearchScope scope, boolean computeSubtypes) throws JavaModelException {
+ super(element);
+ fTypeHierarchy = new TypeHierarchy(element, scope, computeSubtypes);
+}
+/**
+ * Performs the operation - creates the type hierarchy
+ * @exception JavaModelException The operation has failed.
+ */
+protected void executeOperation() throws JavaModelException {
+ fTypeHierarchy.refresh(this);
+}
+/**
+ * Returns the generated type hierarchy.
+ */
+public ITypeHierarchy getResult() {
+ return fTypeHierarchy;
+}
+/**
+ * @see JavaModelOperation
+ */
+public boolean isReadOnly() {
+ return true;
+}
+/**
+ * Possible failures: <ul>
+ * <li>NO_ELEMENTS_TO_PROCESS - at least one of a type or region must
+ * be provided to generate a type hierarchy.
+ * <li>ELEMENT_NOT_PRESENT - the provided type or type's project does not exist
+ * </ul>
+ */
+public IJavaModelStatus verify() {
+ IJavaElement elementToProcess= getElementToProcess();
+ if (elementToProcess == null && !(fTypeHierarchy instanceof RegionBasedTypeHierarchy)) {
+ return new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
}
-
- /**
- * @see JavaModelOperation
- */
- public boolean isReadOnly() {
- return true;
+ if (elementToProcess != null && !elementToProcess.exists()) {
+ return new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, elementToProcess);
}
-
- /**
- * Possible failures: <ul>
- * <li>NO_ELEMENTS_TO_PROCESS - at least one of a type or region must
- * be provided to generate a type hierarchy.
- * <li>ELEMENT_NOT_PRESENT - the provided type or type's project does not exist
- * </ul>
- */
- public IJavaModelStatus verify() {
- IJavaElement elementToProcess = getElementToProcess();
- if (elementToProcess == null
- && !(fTypeHierarchy instanceof RegionBasedTypeHierarchy)) {
- return new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
- }
- if (elementToProcess != null && !elementToProcess.exists()) {
- return new JavaModelStatus(
- IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST,
- elementToProcess);
- }
- IJavaProject project = fTypeHierarchy.javaProject();
- if (project != null && !project.exists()) {
- return new JavaModelStatus(
- IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST,
- project);
- }
- return JavaModelStatus.VERIFIED_OK;
+ IJavaProject project = fTypeHierarchy.javaProject();
+ if (project != null && !project.exists()) {
+ return new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, project);
}
-
+ return JavaModelStatus.VERIFIED_OK;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateTypeMemberOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateTypeMemberOperation.java
index 1702e20066..58e4d3c878 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateTypeMemberOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateTypeMemberOperation.java
@@ -13,8 +13,7 @@ import org.eclipse.jdt.core.jdom.*;
* Implements functionality common to
* operations that create type members.
*/
-public abstract class CreateTypeMemberOperation
- extends CreateElementInCUOperation {
+public abstract class CreateTypeMemberOperation extends CreateElementInCUOperation {
/**
* The source code for the new member.
*/
@@ -29,116 +28,100 @@ public abstract class CreateTypeMemberOperation
* The JDOM document fragment representing the element that
* this operation created.
*/
- protected IDOMNode fDOMNode;
- /**
- * When executed, this operation will create a type member
- * in the given parent element with the specified source.
- */
- public CreateTypeMemberOperation(
- IJavaElement parentElement,
- String source,
- boolean force) {
- super(parentElement);
- fSource = source;
- fForce = force;
- }
-
- /**
- * @see CreateElementInCUOperation#generateNewCompilationUnitDOM
- */
- protected void generateNewCompilationUnitDOM(ICompilationUnit cu)
- throws JavaModelException {
- char[] prevSource = cu.getBuffer().getCharacters();
+ protected IDOMNode fDOMNode;
+/**
+ * When executed, this operation will create a type member
+ * in the given parent element with the specified source.
+ */
+public CreateTypeMemberOperation(IJavaElement parentElement, String source, boolean force) {
+ super(parentElement);
+ fSource= source;
+ fForce= force;
+}
+/**
+ * @see CreateElementInCUOperation#generateNewCompilationUnitDOM
+ */
+protected void generateNewCompilationUnitDOM(ICompilationUnit cu) throws JavaModelException {
+ char[] prevSource = cu.getBuffer().getCharacters();
- // create a JDOM for the compilation unit
- fCUDOM =
- (new DOMFactory()).createCompilationUnit(prevSource, cu.getElementName());
- IDOMNode parent = ((JavaElement) getParentElement()).findNode(fCUDOM);
- if (parent == null) {
- //#findNode does not work for autogenerated CUs as the contents are empty
- parent = fCUDOM;
- }
- IDOMNode child = generateElementDOM();
- if (child != null) {
- insertDOMNode(parent, child);
- }
- worked(1);
+ // create a JDOM for the compilation unit
+ fCUDOM = (new DOMFactory()).createCompilationUnit(prevSource, cu.getElementName());
+ IDOMNode parent = ((JavaElement) getParentElement()).findNode(fCUDOM);
+ if (parent == null) {
+ //#findNode does not work for autogenerated CUs as the contents are empty
+ parent = fCUDOM;
}
-
- /**
- * Generates a <code>IDOMNode</code> based on the source of this operation
- * when there is likely a syntax error in the source.
- */
- protected IDOMNode generateSyntaxIncorrectDOM() throws JavaModelException {
- //create some dummy source to generate a dom node
- StringBuffer buff = new StringBuffer();
- buff.append(
- JavaModelManager.LINE_SEPARATOR
- + " public class A {"
- + JavaModelManager.LINE_SEPARATOR);
- buff.append(fSource);
- buff.append(JavaModelManager.LINE_SEPARATOR).append('}');
- IDOMCompilationUnit domCU =
- (new DOMFactory()).createCompilationUnit(buff.toString(), "A.java");
- IDOMNode node = (IDOMNode) domCU.getChild("A").getChildren().nextElement();
- if (node != null) {
- node.remove();
- }
- return node;
+ IDOMNode child = generateElementDOM();
+ if (child != null) {
+ insertDOMNode(parent, child);
}
-
- /**
- * Returns the IType the member is to be created in.
- */
- protected IType getType() {
- return (IType) getParentElement();
+ worked(1);
+}
+/**
+ * Generates a <code>IDOMNode</code> based on the source of this operation
+ * when there is likely a syntax error in the source.
+ */
+protected IDOMNode generateSyntaxIncorrectDOM() throws JavaModelException {
+ //create some dummy source to generate a dom node
+ StringBuffer buff = new StringBuffer();
+ buff.append(JavaModelManager.LINE_SEPARATOR + " public class A {"/*nonNLS*/ + JavaModelManager.LINE_SEPARATOR);
+ buff.append(fSource);
+ buff.append(JavaModelManager.LINE_SEPARATOR).append('}');
+ IDOMCompilationUnit domCU = (new DOMFactory()).createCompilationUnit(buff.toString(), "A.java"/*nonNLS*/);
+ IDOMNode node = (IDOMNode) domCU.getChild("A"/*nonNLS*/).getChildren().nextElement();
+ if (node != null) {
+ node.remove();
}
-
- /**
- * Sets the name of the <code>DOMNode</code> that will be used to
- * create this new element.
- * Used by the <code>CopyElementsOperation</code> for renaming
- */
- protected void setAlteredName(String newName) {
- fAlteredName = newName;
+ return node;
+}
+/**
+ * Returns the IType the member is to be created in.
+ */
+protected IType getType() {
+ return (IType)getParentElement();
+}
+/**
+ * Sets the name of the <code>DOMNode</code> that will be used to
+ * create this new element.
+ * Used by the <code>CopyElementsOperation</code> for renaming
+ */
+protected void setAlteredName(String newName) {
+ fAlteredName = newName;
+}
+/**
+ * Possible failures: <ul>
+ * <li>NO_ELEMENTS_TO_PROCESS - the parent element supplied to the operation is
+ * <code>null</code>.
+ * <li>INVALID_CONTENTS - The source is <code>null</code> or has serious syntax errors.
+ * <li>NAME_COLLISION - A name collision occurred in the destination
+ * </ul>
+ */
+public IJavaModelStatus verify() {
+ IJavaModelStatus status = super.verify();
+ if (!status.isOK()) {
+ return status;
}
-
- /**
- * Possible failures: <ul>
- * <li>NO_ELEMENTS_TO_PROCESS - the parent element supplied to the operation is
- * <code>null</code>.
- * <li>INVALID_CONTENTS - The source is <code>null</code> or has serious syntax errors.
- * <li>NAME_COLLISION - A name collision occurred in the destination
- * </ul>
- */
- public IJavaModelStatus verify() {
- IJavaModelStatus status = super.verify();
- if (!status.isOK()) {
- return status;
- }
- if (fSource == null) {
- return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS);
- }
- if (!fForce) {
- //check for name collisions
- try {
- IDOMNode node = generateElementDOM();
- if (node == null) {
- return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS);
- }
- } catch (JavaModelException jme) {
+ if (fSource == null) {
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS);
+ }
+ if (!fForce) {
+ //check for name collisions
+ try {
+ IDOMNode node= generateElementDOM();
+ if (node == null) {
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_CONTENTS);
}
- return verifyNameCollision();
+ } catch (JavaModelException jme) {
}
-
- return JavaModelStatus.VERIFIED_OK;
+ return verifyNameCollision();
}
-
- /**
- * Verify for a name collision in the destination container.
- */
- protected IJavaModelStatus verifyNameCollision() {
- return JavaModelStatus.VERIFIED_OK;
- }
-
+
+ return JavaModelStatus.VERIFIED_OK;
+}
+/**
+ * Verify for a name collision in the destination container.
+ */
+protected IJavaModelStatus verifyNameCollision() {
+ return JavaModelStatus.VERIFIED_OK;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateTypeOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateTypeOperation.java
index 891744b2e0..9a1a08d0bc 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateTypeOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/CreateTypeOperation.java
@@ -19,83 +19,73 @@ import org.eclipse.jdt.core.jdom.*;
* </ul>
*/
public class CreateTypeOperation extends CreateTypeMemberOperation {
- /**
- * When executed, this operation will create a type unit
- * in the given parent element (a compilation unit, type)
- */
- public CreateTypeOperation(
- IJavaElement parentElement,
- String source,
- boolean force) {
- super(parentElement, source, force);
- }
-
- /**
- * @see CreateTypeMemberOperation#generateElementDOM
- */
- protected IDOMNode generateElementDOM() throws JavaModelException {
+/**
+ * When executed, this operation will create a type unit
+ * in the given parent element (a compilation unit, type)
+ */
+public CreateTypeOperation(IJavaElement parentElement, String source, boolean force) {
+ super(parentElement, source, force);
+}
+/**
+ * @see CreateTypeMemberOperation#generateElementDOM
+ */
+protected IDOMNode generateElementDOM() throws JavaModelException {
+ if (fDOMNode == null) {
+ fDOMNode = (new DOMFactory()).createType(fSource);
if (fDOMNode == null) {
- fDOMNode = (new DOMFactory()).createType(fSource);
- if (fDOMNode == null) {
- fDOMNode = generateSyntaxIncorrectDOM();
- }
- if (fAlteredName != null && fDOMNode != null) {
- fDOMNode.setName(fAlteredName);
- }
+ fDOMNode = generateSyntaxIncorrectDOM();
+ }
+ if (fAlteredName != null && fDOMNode != null) {
+ fDOMNode.setName(fAlteredName);
}
- return fDOMNode;
- }
-
- /**
- * @see CreateElementInCUOperation#generateResultHandle
- */
- protected IJavaElement generateResultHandle() {
- IJavaElement parent = getParentElement();
- int type = parent.getElementType();
- if (type == IJavaElement.TYPE) {
- return ((IType) parent).getType(fDOMNode.getName());
- } else
- if (type == IJavaElement.COMPILATION_UNIT) {
- return ((ICompilationUnit) parent).getType(fDOMNode.getName());
- }
- return null;
}
-
- /**
- * @see CreateElementInCUOperation#getMainTaskName
- */
- public String getMainTaskName() {
- return "Creating a type...";
+ return fDOMNode;
+}
+/**
+ * @see CreateElementInCUOperation#generateResultHandle
+ */
+protected IJavaElement generateResultHandle() {
+ IJavaElement parent= getParentElement();
+ int type= parent.getElementType();
+ if (type == IJavaElement.TYPE) {
+ return ((IType)parent).getType(fDOMNode.getName());
+ } else if (type == IJavaElement.COMPILATION_UNIT) {
+ return ((ICompilationUnit)parent).getType(fDOMNode.getName());
+ }
+ return null;
+}
+/**
+ * @see CreateElementInCUOperation#getMainTaskName
+ */
+public String getMainTaskName(){
+ return Util.bind("operation.createTypeProgress"/*nonNLS*/);
+}
+/**
+ * Returns the <code>IType</code> the member is to be created in.
+ */
+protected IType getType() {
+ IJavaElement parent = getParentElement();
+ if (parent.getElementType() == IJavaElement.TYPE) {
+ return (IType) parent;
}
-
- /**
- * Returns the <code>IType</code> the member is to be created in.
- */
- protected IType getType() {
- IJavaElement parent = getParentElement();
- if (parent.getElementType() == IJavaElement.TYPE) {
- return (IType) parent;
+ return null;
+}
+/**
+ * @see CreateTypeMemberOperation#verifyNameCollision
+ */
+protected IJavaModelStatus verifyNameCollision() {
+ IJavaElement parent = getParentElement();
+ int type = parent.getElementType();
+ if (type == IJavaElement.TYPE) {
+ if (((IType) parent).getType(fDOMNode.getName()).exists()) {
+ return new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION);
}
- return null;
- }
-
- /**
- * @see CreateTypeMemberOperation#verifyNameCollision
- */
- protected IJavaModelStatus verifyNameCollision() {
- IJavaElement parent = getParentElement();
- int type = parent.getElementType();
- if (type == IJavaElement.TYPE) {
- if (((IType) parent).getType(fDOMNode.getName()).exists()) {
+ } else
+ if (type == IJavaElement.COMPILATION_UNIT) {
+ if (((ICompilationUnit) parent).getType(fDOMNode.getName()).exists()) {
return new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION);
}
- } else
- if (type == IJavaElement.COMPILATION_UNIT) {
- if (((ICompilationUnit) parent).getType(fDOMNode.getName()).exists()) {
- return new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION);
- }
- }
- return JavaModelStatus.VERIFIED_OK;
- }
-
+ }
+ return JavaModelStatus.VERIFIED_OK;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/DeleteElementsOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/DeleteElementsOperation.java
index ccd6c88727..1f1a2e7b71 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/DeleteElementsOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/DeleteElementsOperation.java
@@ -27,143 +27,127 @@ public class DeleteElementsOperation extends MultiOperation {
* @see processElements(). Keys are compilation units,
* values are <code>IRegion</code>s of elements to be processed in each
* compilation unit.
- */
+ */
protected Hashtable fChildrenToRemove;
/**
* The <code>DOMFactory</code> used to manipulate the source code of
* <code>ICompilationUnit</code>s.
*/
protected DOMFactory fFactory;
- /**
- * When executed, this operation will delete the given elements. The elements
- * to delete cannot be <code>null</code> or empty, and must be contained within a
- * compilation unit.
- */
- public DeleteElementsOperation(
- IJavaElement[] elementsToDelete,
- boolean force) {
- super(elementsToDelete, force);
- fFactory = new DOMFactory();
- }
-
- /**
- * Saves the new contents of the compilation unit that has had
- * a member element deleted.
- */
- protected void commitChanges(IDOMCompilationUnit cuDOM, ICompilationUnit cu)
- throws JavaModelException {
- // save the resources that need to be saved
- char[] newContents = cuDOM.getCharacters();
- if (newContents == null) {
- newContents = new char[0];
- }
- ((Buffer) cu.getBuffer()).setContents(newContents, true);
- cu.save(getSubProgressMonitor(1), fForce);
- }
-
- /**
- * @see MultiOperation
- */
- protected String getMainTaskName() {
- return "Deleting elements...";
+/**
+ * When executed, this operation will delete the given elements. The elements
+ * to delete cannot be <code>null</code> or empty, and must be contained within a
+ * compilation unit.
+ */
+public DeleteElementsOperation(IJavaElement[] elementsToDelete, boolean force) {
+ super(elementsToDelete, force);
+ fFactory = new DOMFactory();
+}
+/**
+ * Saves the new contents of the compilation unit that has had
+ * a member element deleted.
+ */
+protected void commitChanges(IDOMCompilationUnit cuDOM, ICompilationUnit cu) throws JavaModelException {
+ // save the resources that need to be saved
+ char[] newContents = cuDOM.getCharacters();
+ if (newContents == null) {
+ newContents = new char[0];
}
-
- /**
- * Groups the elements to be processed by their compilation unit.
- * If parent/child combinations are present, children are
- * discarded (only the parents are processed). Removes any
- * duplicates specified in elements to be processed.
- */
- protected void groupElements() throws JavaModelException {
- fChildrenToRemove = new Hashtable(1);
- int uniqueCUs = 0;
- for (int i = 0, length = fElementsToProcess.length; i < length; i++) {
- IJavaElement e = fElementsToProcess[i];
- ICompilationUnit cu = getCompilationUnitFor(e);
- if (cu == null) {
- throw new JavaModelException(new JavaModelStatus(JavaModelStatus.READ_ONLY, e));
- } else {
- IRegion region = (IRegion) fChildrenToRemove.get(cu);
- if (region == null) {
- region = new Region();
- fChildrenToRemove.put(cu, region);
- uniqueCUs += 1;
- }
- region.add(e);
+ ((Buffer)cu.getBuffer()).setContents(newContents, true);
+ cu.save(getSubProgressMonitor(1), fForce);
+}
+/**
+ * @see MultiOperation
+ */
+protected String getMainTaskName() {
+ return Util.bind("operation.deleteElementProgress"/*nonNLS*/);
+}
+/**
+ * Groups the elements to be processed by their compilation unit.
+ * If parent/child combinations are present, children are
+ * discarded (only the parents are processed). Removes any
+ * duplicates specified in elements to be processed.
+ */
+protected void groupElements() throws JavaModelException {
+ fChildrenToRemove = new Hashtable(1);
+ int uniqueCUs = 0;
+ for (int i = 0, length = fElementsToProcess.length; i < length; i++) {
+ IJavaElement e = fElementsToProcess[i];
+ ICompilationUnit cu = getCompilationUnitFor(e);
+ if (cu == null) {
+ throw new JavaModelException(new JavaModelStatus(JavaModelStatus.READ_ONLY, e));
+ } else {
+ IRegion region = (IRegion) fChildrenToRemove.get(cu);
+ if (region == null) {
+ region = new Region();
+ fChildrenToRemove.put(cu, region);
+ uniqueCUs += 1;
}
- }
- fElementsToProcess = new IJavaElement[uniqueCUs];
- Enumeration enum = fChildrenToRemove.keys();
- int i = 0;
- while (enum.hasMoreElements()) {
- fElementsToProcess[i++] = (IJavaElement) enum.nextElement();
+ region.add(e);
}
}
+ fElementsToProcess = new IJavaElement[uniqueCUs];
+ Enumeration enum = fChildrenToRemove.keys();
+ int i = 0;
+ while (enum.hasMoreElements()) {
+ fElementsToProcess[i++] = (IJavaElement) enum.nextElement();
+ }
+}
+/**
+ * Deletes this element from its compilation unit.
+ * @see MultiOperation
+ */
+protected void processElement(IJavaElement element) throws JavaModelException {
+ ICompilationUnit cu = (ICompilationUnit) element;
- /**
- * Deletes this element from its compilation unit.
- * @see MultiOperation
- */
- protected void processElement(IJavaElement element) throws JavaModelException {
- ICompilationUnit cu = (ICompilationUnit) element;
-
- // keep track of the import statements - if all are removed, delete
- // the import container (i.e. report it in the delta)
- int numberOfImports = cu.getImports().length;
+ // keep track of the import statements - if all are removed, delete
+ // the import container (i.e. report it in the delta)
+ int numberOfImports = cu.getImports().length;
- IDOMCompilationUnit cuDOM =
- fFactory.createCompilationUnit(
- cu.getBuffer().getCharacters(),
- cu.getElementName());
- JavaElementDelta delta = new JavaElementDelta(cu);
- IJavaElement[] cuElements = ((IRegion) fChildrenToRemove.get(cu)).getElements();
- for (int i = 0; i < cuElements.length; i++) {
- IJavaElement e = cuElements[i];
- if (e.exists()) {
- IDOMNode node = ((JavaElement) e).findNode(cuDOM);
- // TBD
- Assert.isTrue(
- node != null,
- "Failed to locate " + e.getElementName() + " in " + cuDOM.getName());
- node.remove();
- delta.removed(e);
- if (e.getElementType() == IJavaElement.IMPORT_DECLARATION) {
- numberOfImports--;
- if (numberOfImports == 0) {
- delta.removed(cu.getImportContainer());
- }
+ IDOMCompilationUnit cuDOM = fFactory.createCompilationUnit(cu.getBuffer().getCharacters(), cu.getElementName());
+ JavaElementDelta delta = new JavaElementDelta(cu);
+ IJavaElement[] cuElements = ((IRegion) fChildrenToRemove.get(cu)).getElements();
+ for (int i = 0; i < cuElements.length; i++) {
+ IJavaElement e = cuElements[i];
+ if (e.exists()) {
+ IDOMNode node = ((JavaElement) e).findNode(cuDOM);
+ // TBD
+ Assert.isTrue(node != null, Util.bind("element.cannotLocate"/*nonNLS*/, e.getElementName(), cuDOM.getName()));
+ node.remove();
+ delta.removed(e);
+ if (e.getElementType() == IJavaElement.IMPORT_DECLARATION) {
+ numberOfImports--;
+ if (numberOfImports == 0) {
+ delta.removed(cu.getImportContainer());
}
}
}
- if (delta.getAffectedChildren().length > 0) {
- commitChanges(cuDOM, cu);
- addDelta(delta);
- }
}
-
- /**
- * @see MultiOperation
- * This method first group the elements by <code>ICompilationUnit</code>,
- * and then processes the <code>ICompilationUnit</code>.
- */
- protected void processElements() throws JavaModelException {
- groupElements();
- super.processElements();
+ if (delta.getAffectedChildren().length > 0) {
+ commitChanges(cuDOM, cu);
+ addDelta(delta);
}
-
- /**
- * @see MultiOperation
- */
- protected void verify(IJavaElement element) throws JavaModelException {
- IJavaElement[] children =
- ((IRegion) fChildrenToRemove.get(element)).getElements();
- for (int i = 0; i < children.length; i++) {
- IJavaElement child = children[i];
- if (child.getCorrespondingResource() != null)
- error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, child);
- if (child.isReadOnly())
- error(IJavaModelStatusConstants.READ_ONLY, child);
- }
+}
+/**
+ * @see MultiOperation
+ * This method first group the elements by <code>ICompilationUnit</code>,
+ * and then processes the <code>ICompilationUnit</code>.
+ */
+protected void processElements() throws JavaModelException {
+ groupElements();
+ super.processElements();
+}
+/**
+ * @see MultiOperation
+ */
+protected void verify(IJavaElement element) throws JavaModelException {
+ IJavaElement[] children = ((IRegion) fChildrenToRemove.get(element)).getElements();
+ for (int i = 0; i < children.length; i++) {
+ IJavaElement child = children[i];
+ if (child.getCorrespondingResource() != null)
+ error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, child);
+ if (child.isReadOnly())
+ error(IJavaModelStatusConstants.READ_ONLY, child);
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/DeleteResourceElementsOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/DeleteResourceElementsOperation.java
index 74cefd18f5..682e12f5ac 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/DeleteResourceElementsOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/DeleteResourceElementsOperation.java
@@ -21,110 +21,92 @@ import java.util.Enumeration;
* (eg GIF files).
*/
public class DeleteResourceElementsOperation extends MultiOperation {
- /**
- * When executed, this operation will delete the given elements. The elements
- * to delete cannot be <code>null</code> or empty, and must have a corresponding
- * resource.
- */
- protected DeleteResourceElementsOperation(
- IJavaElement[] elementsToProcess,
- boolean force) {
- super(elementsToProcess, force);
- }
-
- /**
- * Deletes the direct children of <code>frag</code> corresponding to its kind
- * (K_SOURCE or K_BINARY), and deletes the corresponding folder if it is then
- * empty.
- */
- private void deletePackageFragment(IPackageFragment frag)
- throws JavaModelException {
- IResource res = frag.getCorrespondingResource();
- if (res != null && res.getType() == IResource.FOLDER) {
- // collect the children to remove
- IJavaElement[] childrenOfInterest;
- if (frag.getKind() == IPackageFragmentRoot.K_SOURCE) {
- childrenOfInterest = frag.getCompilationUnits();
- } else { // K_BINARY
- childrenOfInterest = frag.getClassFiles();
- }
- if (childrenOfInterest.length > 0) {
- IResource[] resources = new IResource[childrenOfInterest.length];
- // remove the children
- for (int i = 0; i < childrenOfInterest.length; i++) {
- resources[i] = childrenOfInterest[i].getCorrespondingResource();
- }
- deleteResources(resources, fForce);
- }
-
- // Discard non-java resources
- Object[] nonJavaResources = frag.getNonJavaResources();
- int actualResourceCount = 0;
- for (int i = 0, max = nonJavaResources.length; i < max; i++) {
- if (nonJavaResources[i] instanceof IResource)
- actualResourceCount++;
- }
- IResource[] actualNonJavaResources = new IResource[actualResourceCount];
- for (int i = 0, max = nonJavaResources.length, index = 0; i < max; i++) {
- if (nonJavaResources[i] instanceof IResource)
- actualNonJavaResources[index++] = (IResource) nonJavaResources[i];
- }
- deleteResources(actualNonJavaResources, fForce);
-
- // remove the folder if it is empty
- IResource[] members;
- try {
- members = ((IFolder) res).members();
- } catch (CoreException ce) {
- throw new JavaModelException(ce);
- }
- if (members.length == 0) {
- deleteEmptyPackageFragment(frag, fForce);
+/**
+ * When executed, this operation will delete the given elements. The elements
+ * to delete cannot be <code>null</code> or empty, and must have a corresponding
+ * resource.
+ */
+protected DeleteResourceElementsOperation(IJavaElement[] elementsToProcess, boolean force) {
+ super(elementsToProcess, force);
+}
+/**
+ * Deletes the direct children of <code>frag</code> corresponding to its kind
+ * (K_SOURCE or K_BINARY), and deletes the corresponding folder if it is then
+ * empty.
+ */
+private void deletePackageFragment(IPackageFragment frag)
+ throws JavaModelException {
+ IResource res = frag.getCorrespondingResource();
+ if (res != null && res.getType() == IResource.FOLDER) {
+ // collect the children to remove
+ IJavaElement[] childrenOfInterest = frag.getChildren();
+ if (childrenOfInterest.length > 0) {
+ IResource[] resources = new IResource[childrenOfInterest.length];
+ // remove the children
+ for (int i = 0; i < childrenOfInterest.length; i++) {
+ resources[i] = childrenOfInterest[i].getCorrespondingResource();
}
+ deleteResources(resources, fForce);
}
- }
-
- /**
- * @see MultiOperation
- */
- protected String getMainTaskName() {
- return "Deleting resources...";
- }
- /**
- * @see MultiOperation. This method delegate to <code>deleteResource</code> or
- * <code>deletePackageFragment</code> depending on the type of <code>element</code>.
- */
- protected void processElement(IJavaElement element) throws JavaModelException {
- switch (element.getElementType()) {
- case IJavaElement.CLASS_FILE :
- case IJavaElement.COMPILATION_UNIT :
- deleteResource(element.getCorrespondingResource(), fForce);
- break;
- case IJavaElement.PACKAGE_FRAGMENT :
- deletePackageFragment((IPackageFragment) element);
- break;
- default :
- throw new JavaModelException(
- new JavaModelStatus(JavaModelStatus.INVALID_ELEMENT_TYPES, element));
+ // Discard non-java resources
+ Object[] nonJavaResources = frag.getNonJavaResources();
+ int actualResourceCount = 0;
+ for (int i = 0, max = nonJavaResources.length; i < max; i++){
+ if (nonJavaResources[i] instanceof IResource) actualResourceCount++;
+ }
+ IResource[] actualNonJavaResources = new IResource[actualResourceCount];
+ for (int i = 0, max = nonJavaResources.length, index = 0; i < max; i++){
+ if (nonJavaResources[i] instanceof IResource) actualNonJavaResources[index++] = (IResource)nonJavaResources[i];
+ }
+ deleteResources(actualNonJavaResources, fForce);
+
+ // remove the folder if it is empty
+ IResource[] members;
+ try {
+ members = ((IFolder) res).members();
+ } catch (CoreException ce) {
+ throw new JavaModelException(ce);
+ }
+ if (members.length == 0) {
+ deleteEmptyPackageFragment(frag, fForce);
}
}
-
- /**
- * @see MultiOperation
- */
- protected void verify(IJavaElement element) throws JavaModelException {
- if (element == null || !element.exists())
- error(JavaModelStatus.ELEMENT_DOES_NOT_EXIST, element);
-
- int type = element.getElementType();
- if (type <= IJavaElement.PACKAGE_FRAGMENT_ROOT
- || type > IJavaElement.COMPILATION_UNIT)
- error(JavaModelStatus.INVALID_ELEMENT_TYPES, element);
- else
- if (type == IJavaElement.PACKAGE_FRAGMENT
- && element instanceof JarPackageFragment)
- error(JavaModelStatus.INVALID_ELEMENT_TYPES, element);
+}
+/**
+ * @see MultiOperation
+ */
+protected String getMainTaskName() {
+ return Util.bind("operation.deleteResourceProgress"/*nonNLS*/);
+}
+/**
+ * @see MultiOperation. This method delegate to <code>deleteResource</code> or
+ * <code>deletePackageFragment</code> depending on the type of <code>element</code>.
+ */
+protected void processElement(IJavaElement element) throws JavaModelException {
+ switch (element.getElementType()) {
+ case IJavaElement.CLASS_FILE :
+ case IJavaElement.COMPILATION_UNIT :
+ deleteResource(element.getCorrespondingResource(), fForce);
+ break;
+ case IJavaElement.PACKAGE_FRAGMENT :
+ deletePackageFragment((IPackageFragment) element);
+ break;
+ default :
+ throw new JavaModelException(new JavaModelStatus(JavaModelStatus.INVALID_ELEMENT_TYPES, element));
}
+}
+/**
+ * @see MultiOperation
+ */
+protected void verify(IJavaElement element) throws JavaModelException {
+ if (element == null || !element.exists())
+ error(JavaModelStatus.ELEMENT_DOES_NOT_EXIST, element);
+ int type = element.getElementType();
+ if (type <= IJavaElement.PACKAGE_FRAGMENT_ROOT || type > IJavaElement.COMPILATION_UNIT)
+ error(JavaModelStatus.INVALID_ELEMENT_TYPES, element);
+ else if (type == IJavaElement.PACKAGE_FRAGMENT && element instanceof JarPackageFragment)
+ error(JavaModelStatus.INVALID_ELEMENT_TYPES, element);
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/DeltaProcessor.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/DeltaProcessor.java
index d765993ec0..5b36f6f281 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/DeltaProcessor.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/DeltaProcessor.java
@@ -156,6 +156,9 @@ public static void checkProjectPropertyFileUpdate(IResourceDelta delta, IJavaEle
switch (resource.getType()) {
+ case IResource.ROOT :
+ processChildren = true;
+ break;
case IResource.PROJECT :
try {
if (((IProject) resource).hasNature(JavaCore.NATURE_ID)) {
@@ -311,7 +314,7 @@ protected Openable[] createElements(IResource resource) {
if (resource == null) return null;
String extension = resource.getFileExtension();
extension = extension == null ? null : extension.toLowerCase();
- if ("jar".equals(extension) || "zip".equals(extension)) {
+ if ("jar"/*nonNLS*/.equals(extension) || "zip"/*nonNLS*/.equals(extension)) {
IJavaProject[] projects = null;
try {
projects = JavaModelManager.getJavaModel(resource.getWorkspace()).getJavaProjects();
@@ -737,42 +740,29 @@ protected void traverseDelta(IResourceDelta delta, Openable parentElement) {
updateIndex(element, delta);
switch (delta.getKind()) {
case IResourceDelta.ADDED:
- switch(res.getType()) {
- case IResource.FILE :
- case IResource.FOLDER:
- IProject fileProject = delta.getResource().getProject();
- IJavaProject project = (IJavaProject) JavaCore.create(fileProject);
- try {
- IPackageFragmentRoot pkgRoot;
- if (parentElement != null
- && ((pkgRoot = parentElement.getPackageFragmentRoot()) != null)
- && !pkgRoot.exists()) {
- nonJavaResourcesChanged(parentElement, delta);
- break;
- }
- } catch(JavaModelException e) {
- }
- break;
+ PackageFragmentRoot pkgRoot;
+ if (res.getType() == IResource.FILE
+ && parentElement != null
+ && !parentElement.equals(element.getParent())
+ && ((pkgRoot = element.getPackageFragmentRoot()) == null || !isOnClasspath(pkgRoot))){
+ try { // fake compilation/class file scenario (see JavaCore.createCompilationUnitFrom & createClassFileFrom
+ nonJavaResourcesChanged(parentElement, delta);
+ break;
+ } catch(JavaModelException e) {
+ }
}
elementAdded(element, delta);
break;
case IResourceDelta.REMOVED:
- switch(res.getType()) {
- case IResource.FILE :
- case IResource.FOLDER:
- IProject fileProject = delta.getResource().getProject();
- IJavaProject project = (IJavaProject) JavaCore.create(fileProject);
- try {
- IPackageFragmentRoot pkgRoot;
- if (parentElement != null
- && ((pkgRoot = parentElement.getPackageFragmentRoot()) != null)
- && !pkgRoot.exists()) {
- nonJavaResourcesChanged(parentElement, delta);
- break;
- }
- } catch(JavaModelException e) {
- }
- break;
+ if (res.getType() == IResource.FILE
+ && parentElement != null
+ && !parentElement.equals(element.getParent())
+ && ((pkgRoot = element.getPackageFragmentRoot()) == null || !isOnClasspath(pkgRoot))){
+ try { // fake compilation/class file scenario (see JavaCore.createCompilationUnitFrom & createClassFileFrom
+ nonJavaResourcesChanged(parentElement, delta);
+ break;
+ } catch(JavaModelException e) {
+ }
}
elementRemoved(element, delta);
break;
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ElementCache.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ElementCache.java
index 11cfdf8ec8..b9c4d66ab2 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ElementCache.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ElementCache.java
@@ -14,48 +14,51 @@ import org.eclipse.jdt.internal.core.util.LRUCache;
* An LRU cache of <code>JavaElements</code>.
*/
public class ElementCache extends OverflowingLRUCache {
- /**
- * Constructs a new element cache of the given size.
- */
- public ElementCache(int size) {
- super(size);
- }
-
- /**
- * Constructs a new element cache of the given size.
- */
- public ElementCache(int size, int overflow) {
- super(size, overflow);
- }
-
- /**
- * Returns true if the element is successfully closed and
- * removed from the cache, otherwise false.
- *
- * <p>NOTE: this triggers an external removal of this element
- * by closing the element.
- */
- protected boolean close(LRUCacheEntry entry) {
- IOpenable element = (IOpenable) entry._fKey;
- synchronized (element) {
- try {
- if (element.hasUnsavedChanges()) {
- return false;
+/**
+ * Constructs a new element cache of the given size.
+ */
+public ElementCache(int size) {
+ super(size);
+}
+/**
+ * Constructs a new element cache of the given size.
+ */
+public ElementCache(int size, int overflow) {
+ super(size, overflow);
+}
+/**
+ * Returns true if the element is successfully closed and
+ * removed from the cache, otherwise false.
+ *
+ * <p>NOTE: this triggers an external removal of this element
+ * by closing the element.
+ */
+protected boolean close(LRUCacheEntry entry) {
+ IOpenable element = (IOpenable) entry._fKey;
+ synchronized (element) {
+ try {
+ if (element.hasUnsavedChanges()) {
+ return false;
+ } else {
+ // We must close an entire JarPackageFragmentRoot at once.
+ if (element instanceof JarPackageFragment) {
+ JarPackageFragment packageFragment= (JarPackageFragment) element;
+ JarPackageFragmentRoot root = (JarPackageFragmentRoot) packageFragment.getParent();
+ root.close();
} else {
element.close();
- return true;
}
- } catch (JavaModelException npe) {
- return false;
+ return true;
}
+ } catch (JavaModelException npe) {
+ return false;
}
}
-
+}
/**
* Returns a new instance of the reciever.
*/
protected LRUCache newInstance(int size, int overflow) {
return new ElementCache(size, overflow);
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/FailedReconciliationException.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/FailedReconciliationException.java
index 0efac3a1d4..6f799b4eb5 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/FailedReconciliationException.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/FailedReconciliationException.java
@@ -1,19 +1,17 @@
package org.eclipse.jdt.internal.core;
public class FailedReconciliationException extends RuntimeException {
- /**
- * FailReconciliationException constructor comment.
- */
- public FailedReconciliationException() {
- super();
- }
-
- /**
- * FailReconciliationException constructor comment.
- * @param s java.lang.String
- */
- public FailedReconciliationException(String s) {
- super(s);
- }
-
+/**
+ * FailReconciliationException constructor comment.
+ */
+public FailedReconciliationException() {
+ super();
+}
+/**
+ * FailReconciliationException constructor comment.
+ * @param s java.lang.String
+ */
+public FailedReconciliationException(String s) {
+ super(s);
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/HandleFactory.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/HandleFactory.java
index 5c23c24f6d..5c81de4270 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/HandleFactory.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/HandleFactory.java
@@ -34,9 +34,8 @@ public class HandleFactory {
public HandleFactory(IWorkspaceRoot workspaceRoot, JavaModelManager manager) {
this.workspaceRoot = workspaceRoot;
- this.manager = manager;
+ this.manager= manager;
}
-
/**
* Creates an Openable handle from the given resource path.
* The resource path can be a path to a file in the workbench (eg. /Proj/com/ibm/jdt/core/HandleFactory.java)
@@ -48,136 +47,125 @@ public class HandleFactory {
*/
public Openable createOpenable(String resourcePath) {
int separatorIndex;
- if ((separatorIndex =
- resourcePath.indexOf(JarFileEntryDocument.JAR_FILE_ENTRY_SEPARATOR))
- > -1) {
+ if ((separatorIndex= resourcePath.indexOf(JarFileEntryDocument.JAR_FILE_ENTRY_SEPARATOR)) > -1) {
// path to a class file inside a jar
- String jarPath = resourcePath.substring(0, separatorIndex);
+ String jarPath= resourcePath.substring(0, separatorIndex);
// Optimization: cache package fragment root handle and package handles
if (!jarPath.equals(this.lastPkgFragmentRootPath)) {
- this.lastPkgFragmentRootPath = jarPath;
- this.lastPkgFragmentRoot = this.getJarPkgFragmentRoot(jarPath);
- this.packageHandles = new Hashtable(5);
+ this.lastPkgFragmentRootPath= jarPath;
+ this.lastPkgFragmentRoot= this.getJarPkgFragmentRoot(jarPath);
+ this.packageHandles= new Hashtable(5);
}
// create handle
- String classFilePath = resourcePath.substring(separatorIndex + 1);
- int lastSlash = classFilePath.lastIndexOf('/');
- String packageName =
- lastSlash > -1
- ? classFilePath.substring(0, lastSlash).replace('/', '.')
- : IPackageFragment.DEFAULT_PACKAGE_NAME;
- IPackageFragment pkgFragment =
- (IPackageFragment) this.packageHandles.get(packageName);
+ String classFilePath= resourcePath.substring(separatorIndex + 1);
+ int lastSlash= classFilePath.lastIndexOf('/');
+ String packageName= lastSlash > -1 ? classFilePath.substring(0, lastSlash).replace('/', '.') : IPackageFragment.DEFAULT_PACKAGE_NAME;
+ IPackageFragment pkgFragment= (IPackageFragment) this.packageHandles.get(packageName);
if (pkgFragment == null) {
- pkgFragment = this.lastPkgFragmentRoot.getPackageFragment(packageName);
+ pkgFragment= this.lastPkgFragmentRoot.getPackageFragment(packageName);
this.packageHandles.put(packageName, pkgFragment);
}
- IClassFile classFile =
- pkgFragment.getClassFile(classFilePath.substring(lastSlash + 1));
+ IClassFile classFile= pkgFragment.getClassFile(classFilePath.substring(lastSlash + 1));
return (Openable) classFile;
} else {
// path to a file in a directory
// Optimization: cache package fragment root handle and package handles
int length = -1;
- if (this.lastPkgFragmentRootPath == null
- || !(resourcePath.startsWith(this.lastPkgFragmentRootPath)
+ if (this.lastPkgFragmentRootPath == null
+ || !(resourcePath.startsWith(this.lastPkgFragmentRootPath)
&& (length = this.lastPkgFragmentRootPath.length()) > 0
&& resourcePath.charAt(length) == '/')) {
- IPackageFragmentRoot root = this.getPkgFragmentRoot(resourcePath);
+ IPackageFragmentRoot root= this.getPkgFragmentRoot(resourcePath);
if (root == null)
return null; // match is outside classpath
- this.lastPkgFragmentRoot = root;
- this.lastPkgFragmentRootPath = this.lastPkgFragmentRoot.getPath().toString();
- this.packageHandles = new Hashtable(5);
+ this.lastPkgFragmentRoot= root;
+ this.lastPkgFragmentRootPath= this.lastPkgFragmentRoot.getPath().toString();
+ this.packageHandles= new Hashtable(5);
}
// create handle
- int lastSlash = resourcePath.lastIndexOf(IPath.SEPARATOR);
- String packageName =
- lastSlash > (length = this.lastPkgFragmentRootPath.length())
- ? resourcePath.substring(length + 1, lastSlash).replace(IPath.SEPARATOR, '.')
- : IPackageFragment.DEFAULT_PACKAGE_NAME;
- IPackageFragment pkgFragment =
- (IPackageFragment) this.packageHandles.get(packageName);
+ int lastSlash= resourcePath.lastIndexOf(IPath.SEPARATOR);
+ String packageName= lastSlash > (length= this.lastPkgFragmentRootPath.length()) ? resourcePath.substring(length + 1, lastSlash).replace(IPath.SEPARATOR, '.') : IPackageFragment.DEFAULT_PACKAGE_NAME;
+ IPackageFragment pkgFragment= (IPackageFragment) this.packageHandles.get(packageName);
if (pkgFragment == null) {
- pkgFragment = this.lastPkgFragmentRoot.getPackageFragment(packageName);
+ pkgFragment= this.lastPkgFragmentRoot.getPackageFragment(packageName);
this.packageHandles.put(packageName, pkgFragment);
}
- String simpleName = resourcePath.substring(lastSlash + 1);
- if (simpleName.endsWith(".java")) {
- ICompilationUnit unit = pkgFragment.getCompilationUnit(simpleName);
+ String simpleName= resourcePath.substring(lastSlash + 1);
+ if (Util.isJavaFileName(simpleName)) {
+ ICompilationUnit unit= pkgFragment.getCompilationUnit(simpleName);
return (Openable) unit;
} else {
- IClassFile classFile = pkgFragment.getClassFile(simpleName);
+ IClassFile classFile= pkgFragment.getClassFile(simpleName);
return (Openable) classFile;
}
}
}
-
- /**
+/**
* Returns the package fragment root that corresponds to the given jar path.
* See createOpenable(...) for the format of the jar path string.
*/
private IPackageFragmentRoot getJarPkgFragmentRoot(String jarPathString) {
- IPath jarPath = new Path(jarPathString);
- JavaModel javaModel =
- this.manager.getJavaModel(this.workspaceRoot.getWorkspace());
- IResource jarFile = this.workspaceRoot.findMember(jarPath);
+ IPath jarPath= new Path(jarPathString);
+ JavaModel javaModel= this.manager.getJavaModel(this.workspaceRoot.getWorkspace());
+ IResource jarFile= this.workspaceRoot.findMember(jarPath);
if (jarFile != null) {
// internal jar
return javaModel.getJavaProject(jarFile).getPackageFragmentRoot(jarFile);
} else {
// external jar: walk all projects and find the first one that has the given jar path in its classpath
- try {
- IProject[] projects = this.workspaceRoot.getProjects();
- for (int i = 0, projectCount = projects.length; i < projectCount; i++) {
+ IProject[] projects= this.workspaceRoot.getProjects();
+ for (int i= 0, projectCount= projects.length; i < projectCount; i++) {
+ try {
IProject project = projects[i];
- if (project.isAccessible()) {
- IJavaProject javaProject = javaModel.getJavaProject(project);
- IClasspathEntry[] classpathEntries = javaProject.getResolvedClasspath(true);
- for (int j = 0, entryCount = classpathEntries.length; j < entryCount; j++) {
- if (classpathEntries[j].getPath().equals(jarPath)) {
- return javaProject.getPackageFragmentRoot(jarPathString);
- }
+ if (!project.isAccessible()
+ || !project.hasNature(JavaCore.NATURE_ID)) continue;
+ IJavaProject javaProject= javaModel.getJavaProject(project);
+ IClasspathEntry[] classpathEntries= javaProject.getResolvedClasspath(true);
+ for (int j= 0, entryCount= classpathEntries.length; j < entryCount; j++) {
+ if (classpathEntries[j].getPath().equals(jarPath)) {
+ return javaProject.getPackageFragmentRoot(jarPathString);
}
}
+ } catch (CoreException e) {
+ // CoreException from hasNature - should not happen since we check that the project is accessible
+ // JavaModelException from getResolvedClasspath - a problem occured while accessing project: nothing we can do, ignore
}
- } catch (JavaModelException e) {
- e.printStackTrace();
}
return null;
}
}
-
- /**
+/**
* Returns the package fragment root that contains the given resource path.
*/
private IPackageFragmentRoot getPkgFragmentRoot(String pathString) {
- IPath path = new Path(pathString);
- try {
- JavaModel javaModel =
- this.manager.getJavaModel(this.workspaceRoot.getWorkspace());
- IProject[] projects = this.workspaceRoot.getProjects();
- for (int i = 0, max = projects.length; i < max; i++) {
- IJavaProject javaProject = javaModel.getJavaProject(projects[i]);
- IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
- for (int j = 0, rootCount = roots.length; j < rootCount; j++) {
- IPackageFragmentRoot root = roots[j];
+ IPath path= new Path(pathString);
+ JavaModel javaModel= this.manager.getJavaModel(this.workspaceRoot.getWorkspace());
+ IProject[] projects= this.workspaceRoot.getProjects();
+ for (int i= 0, max= projects.length; i < max; i++) {
+ try {
+ IProject project = projects[i];
+ if (!project.isAccessible()
+ || !project.hasNature(JavaCore.NATURE_ID)) continue;
+ IJavaProject javaProject= javaModel.getJavaProject(project);
+ IPackageFragmentRoot[] roots= javaProject.getPackageFragmentRoots();
+ for (int j= 0, rootCount= roots.length; j < rootCount; j++) {
+ IPackageFragmentRoot root= roots[j];
if (root.getPath().isPrefixOf(path)) {
return root;
}
}
+ } catch (CoreException e) {
+ // CoreException from hasNature - should not happen since we check that the project is accessible
+ // JavaModelException from getPackageFragmentRoots - a problem occured while accessing project: nothing we can do, ignore
}
- } catch (JavaModelException e) {
- e.printStackTrace();
}
return null;
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/IBufferManager.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/IBufferManager.java
index 3166079b8b..870d92e463 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/IBufferManager.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/IBufferManager.java
@@ -17,12 +17,12 @@ import java.util.Hashtable;
*/
public interface IBufferManager {
- /**
- * Returns the open buffer associated with the given owner,
- * or <code>null</code> if the owner does not have an open
- * buffer associated with it.
- */
- IBuffer getBuffer(IOpenable owner);
+/**
+ * Returns the open buffer associated with the given owner,
+ * or <code>null</code> if the owner does not have an open
+ * buffer associated with it.
+ */
+IBuffer getBuffer(IOpenable owner);
/**
* Returns an enumeration of all open buffers.
*
@@ -35,20 +35,10 @@ public interface IBufferManager {
*
* @exception IllegalArgumentException if contents or owner is <code>null</code>
*/
- public IBuffer openBuffer(
- char[] contents,
- IProgressMonitor progress,
- IOpenable owner,
- boolean readOnly)
- throws IllegalArgumentException;
- /**
- * Opens a buffer on the current contents of the specified file,
- * assigned to the specified owner.
- */
- public IBuffer openBuffer(
- IFile file,
- IProgressMonitor progress,
- IOpenable owner,
- boolean readOnly)
- throws JavaModelException;
+ public IBuffer openBuffer(char[] contents, IProgressMonitor progress, IOpenable owner, boolean readOnly) throws IllegalArgumentException;
+/**
+ * Opens a buffer on the current contents of the specified file,
+ * assigned to the specified owner.
+ */
+public IBuffer openBuffer(IFile file, IProgressMonitor progress, IOpenable owner, boolean readOnly) throws JavaModelException;
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/IJavaElementRequestor.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/IJavaElementRequestor.java
index 8295ea517f..4b33b36675 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/IJavaElementRequestor.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/IJavaElementRequestor.java
@@ -16,15 +16,15 @@ import org.eclipse.jdt.core.*;
* <code>true</code> to <code>#isCancelled</code>.
*/
public interface IJavaElementRequestor {
- public void acceptField(IField field);
- public void acceptInitializer(IInitializer initializer);
- public void acceptMemberType(IType type);
- public void acceptMethod(IMethod method);
- public void acceptPackageFragment(IPackageFragment packageFragment);
- public void acceptType(IType type);
- /**
- * Returns <code>true</code> if this IJavaElementRequestor does
- * not want to receive any more results.
- */
- boolean isCanceled();
+public void acceptField(IField field);
+public void acceptInitializer(IInitializer initializer);
+public void acceptMemberType(IType type);
+public void acceptMethod(IMethod method);
+public void acceptPackageFragment(IPackageFragment packageFragment);
+public void acceptType(IType type);
+/**
+ * Returns <code>true</code> if this IJavaElementRequestor does
+ * not want to receive any more results.
+ */
+boolean isCanceled();
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/IJavaReconciler.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/IJavaReconciler.java
index 76d05e0714..d407ea71c2 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/IJavaReconciler.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/IJavaReconciler.java
@@ -1,42 +1,42 @@
package org.eclipse.jdt.internal.core;
public interface IJavaReconciler {
- /**
- * Reconciles a deletion of contiguous text.
- *
- * <p>Reports deltas for any elements added/removed from the compilation
- * unit. If a container (<code>IParent</code>), is added/removed, deltas
- * are not reported for any of its children - only the top level
- * container. For example, if a type is removed, deltas are not
- * provided for its deleted members.
- *
- * <p>Updates children properties and source ranges for elements
- * in the compilation unit.
- *
- * <p>It is assumed that the <code>IBuffer</code> of the
- * <code>ICompilationUnit</code> used in the creation of this
- * <code>IncrementalReconciler</code> has already been updated with
- * the text deletion, but the structure of the <code>ICompilationUnit</code>
- * has not.
- */
- public void textDeleted(int position, int length);
- /**
- * Reconciles a insertion of contiguous text.
- *
- * <p>Reports deltas for any elements added/removed from the compilation
- * unit. If a container (<code>IParent</code>), is added/removed, deltas
- * are not reported for any of its children - only the top level
- * container. For example, if a type is removed, deltas are not
- * provided for its deleted members.
- *
- * <p>Updates children properties and source ranges for elements
- * in the compilation unit.
- *
- * <p>It is assumed that the <code>IBuffer</code> of the
- * <code>ICompilationUnit</code> used in the creation of this
- * <code>IncrementalReconciler</code> has already been updated with
- * the text deletion, but the structure of the <code>ICompilationUnit</code>
- * has not.
- */
- public void textInserted(int position, int length);
+/**
+ * Reconciles a deletion of contiguous text.
+ *
+ * <p>Reports deltas for any elements added/removed from the compilation
+ * unit. If a container (<code>IParent</code>), is added/removed, deltas
+ * are not reported for any of its children - only the top level
+ * container. For example, if a type is removed, deltas are not
+ * provided for its deleted members.
+ *
+ * <p>Updates children properties and source ranges for elements
+ * in the compilation unit.
+ *
+ * <p>It is assumed that the <code>IBuffer</code> of the
+ * <code>ICompilationUnit</code> used in the creation of this
+ * <code>IncrementalReconciler</code> has already been updated with
+ * the text deletion, but the structure of the <code>ICompilationUnit</code>
+ * has not.
+ */
+public void textDeleted(int position, int length);
+/**
+ * Reconciles a insertion of contiguous text.
+ *
+ * <p>Reports deltas for any elements added/removed from the compilation
+ * unit. If a container (<code>IParent</code>), is added/removed, deltas
+ * are not reported for any of its children - only the top level
+ * container. For example, if a type is removed, deltas are not
+ * provided for its deleted members.
+ *
+ * <p>Updates children properties and source ranges for elements
+ * in the compilation unit.
+ *
+ * <p>It is assumed that the <code>IBuffer</code> of the
+ * <code>ICompilationUnit</code> used in the creation of this
+ * <code>IncrementalReconciler</code> has already been updated with
+ * the text deletion, but the structure of the <code>ICompilationUnit</code>
+ * has not.
+ */
+public void textInserted(int position, int length);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/INameLookup.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/INameLookup.java
index 55fdb4f10b..f2f20f7834 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/INameLookup.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/INameLookup.java
@@ -35,117 +35,105 @@ public interface INameLookup {
* Accept flag for specifying interfaces.
*/
public static final int ACCEPT_INTERFACES = 0x00000004;
- /**
- * Returns the <code>ICompilationUnit</code> which defines the type
- * named <code>qualifiedTypeName</code>, or <code>null</code> if
- * none exists. The domain of the search is bounded by the classpath
- * of the <code>IJavaProject</code> this <code>INameLookup</code> was
- * obtained from.
- * <p>
- * The name must be fully qualified (eg "java.lang.Object", "java.util.Hashtable$Entry")
- */
- ICompilationUnit findCompilationUnit(String qualifiedTypeName);
- /**
- * Returns the package fragment whose path matches the given
- * (absolute) path, or <code>null</code> if none exist. The domain of
- * the search is bounded by the classpath of the <code>IJavaProject</code>
- * this <code>INameLookup</code> was obtained from.
- * The path can be:
- * - internal to the workbench: "/Project/src"
- * - external to the workbench: "c:/jdk/classes.zip/java/lang"
- */
- IPackageFragment findPackageFragment(IPath path);
- /**
- * Returns the package fragment root whose path matches the given
- * (absolute) path, or <code>null</code> if none exist. The domain of
- * the search is bounded by the classpath of the <code>IJavaProject</code>
- * this <code>INameLookup</code> was obtained from.
- * The path can be:
- * - internal to the workbench: "/Compiler/src"
- * - external to the workbench: "c:/jdk/classes.zip"
- */
- IPackageFragmentRoot findPackageFragmentRoot(IPath path);
- /**
- * Returns the package fragments whose name matches the given
- * (qualified) name, or <code>null</code> if none exist.
- *
- * The name can be:
- * - empty: ""
- * - qualified: "pack.pack1.pack2"
- * @param partialMatch partial name matches qualify when <code>true</code>,
- * only exact name matches qualify when <code>false</code>
- */
- IPackageFragment[] findPackageFragments(String name, boolean partialMatch);
- /**
- * Returns the first type in the given package whose name
- * matches the given (unqualified) name, or <code>null</code> if none
- * exist. Specifying a <code>null</code> package will result in no matches.
- * The domain of the search is bounded by the Java project from which
- * this name lookup was obtained.
- *
- * @name the name of the type to find
- * @pkg the package to search
- * @param partialMatch partial name matches qualify when <code>true</code>,
- * only exact name matches qualify when <code>false</code>
- * @param acceptFlags a bit mask describing if classes, interfaces or both classes and interfaces
- * are desired results. If no flags are specified, all types are returned.
- *
- * @see ACCEPT_CLASSES
- * @see ACCEPT_INTERFACES
- */
- IType findType(
- String name,
- IPackageFragment pkg,
- boolean partialMatch,
- int acceptFlags);
- /**
- * Returns the type specified by the qualified name, or <code>null</code>
- * if none exist. The domain of
- * the search is bounded by the Java project from which this name lookup was obtained.
- *
- * @name the name of the type to find
- * @param partialMatch partial name matches qualify when <code>true</code>,
- * only exact name matches qualify when <code>false</code>
- * @param acceptFlags a bit mask describing if classes, interfaces or both classes and interfaces
- * are desired results. If no flags are specified, all types are returned.
- *
- * @see ACCEPT_CLASSES
- * @see ACCEPT_INTERFACES
- */
- public IType findType(String name, boolean partialMatch, int acceptFlags);
- /**
- * Notifies the given requestor of all package fragments with the
- * given name. Checks the requestor at regular intervals to see if the
- * requestor has canceled. The domain of
- * the search is bounded by the <code>IJavaProject</code>
- * this <code>INameLookup</code> was obtained from.
- *
- * @param partialMatch partial name matches qualify when <code>true</code>;
- * only exact name matches qualify when <code>false</code>
- */
- public void seekPackageFragments(
- String name,
- boolean partialMatch,
- IJavaElementRequestor requestor);
- /**
- * Notifies the given requestor of all types (classes and interfaces) in the
- * given package fragment with the given (unqualified) name.
- * Checks the requestor at regular intervals to see if the requestor
- * has canceled. If the given package fragment is <code>null</code>, all types in the
- * project whose simple name matches the given name are found.
- *
- * @param partialMatch partial name matches qualify when <code>true</code>;
- * only exact name matches qualify when <code>false</code>
- * @param acceptFlags a bit mask describing if classes, interfaces or both classes and interfaces
- * are desired results. If no flags are specified, all types are returned.
- *
- * @see ACCEPT_CLASSES
- * @see ACCEPT_INTERFACES
- */
- public void seekTypes(
- String name,
- IPackageFragment pkg,
- boolean partialMatch,
- int acceptFlags,
- IJavaElementRequestor requestor);
+/**
+ * Returns the <code>ICompilationUnit</code> which defines the type
+ * named <code>qualifiedTypeName</code>, or <code>null</code> if
+ * none exists. The domain of the search is bounded by the classpath
+ * of the <code>IJavaProject</code> this <code>INameLookup</code> was
+ * obtained from.
+ * <p>
+ * The name must be fully qualified (eg "java.lang.Object", "java.util.Hashtable$Entry")
+ */
+ICompilationUnit findCompilationUnit(String qualifiedTypeName);
+/**
+ * Returns the package fragment whose path matches the given
+ * (absolute) path, or <code>null</code> if none exist. The domain of
+ * the search is bounded by the classpath of the <code>IJavaProject</code>
+ * this <code>INameLookup</code> was obtained from.
+ * The path can be:
+ * - internal to the workbench: "/Project/src"
+ * - external to the workbench: "c:/jdk/classes.zip/java/lang"
+ */
+IPackageFragment findPackageFragment(IPath path);
+/**
+ * Returns the package fragment root whose path matches the given
+ * (absolute) path, or <code>null</code> if none exist. The domain of
+ * the search is bounded by the classpath of the <code>IJavaProject</code>
+ * this <code>INameLookup</code> was obtained from.
+ * The path can be:
+ * - internal to the workbench: "/Compiler/src"
+ * - external to the workbench: "c:/jdk/classes.zip"
+ */
+IPackageFragmentRoot findPackageFragmentRoot(IPath path);
+/**
+ * Returns the package fragments whose name matches the given
+ * (qualified) name, or <code>null</code> if none exist.
+ *
+ * The name can be:
+ * - empty: ""
+ * - qualified: "pack.pack1.pack2"
+ * @param partialMatch partial name matches qualify when <code>true</code>,
+ * only exact name matches qualify when <code>false</code>
+ */
+IPackageFragment[] findPackageFragments(String name, boolean partialMatch);
+/**
+ * Returns the first type in the given package whose name
+ * matches the given (unqualified) name, or <code>null</code> if none
+ * exist. Specifying a <code>null</code> package will result in no matches.
+ * The domain of the search is bounded by the Java project from which
+ * this name lookup was obtained.
+ *
+ * @name the name of the type to find
+ * @pkg the package to search
+ * @param partialMatch partial name matches qualify when <code>true</code>,
+ * only exact name matches qualify when <code>false</code>
+ * @param acceptFlags a bit mask describing if classes, interfaces or both classes and interfaces
+ * are desired results. If no flags are specified, all types are returned.
+ *
+ * @see ACCEPT_CLASSES
+ * @see ACCEPT_INTERFACES
+ */
+IType findType(String name, IPackageFragment pkg, boolean partialMatch, int acceptFlags);
+/**
+ * Returns the type specified by the qualified name, or <code>null</code>
+ * if none exist. The domain of
+ * the search is bounded by the Java project from which this name lookup was obtained.
+ *
+ * @name the name of the type to find
+ * @param partialMatch partial name matches qualify when <code>true</code>,
+ * only exact name matches qualify when <code>false</code>
+ * @param acceptFlags a bit mask describing if classes, interfaces or both classes and interfaces
+ * are desired results. If no flags are specified, all types are returned.
+ *
+ * @see ACCEPT_CLASSES
+ * @see ACCEPT_INTERFACES
+ */
+public IType findType(String name, boolean partialMatch, int acceptFlags);
+/**
+ * Notifies the given requestor of all package fragments with the
+ * given name. Checks the requestor at regular intervals to see if the
+ * requestor has canceled. The domain of
+ * the search is bounded by the <code>IJavaProject</code>
+ * this <code>INameLookup</code> was obtained from.
+ *
+ * @param partialMatch partial name matches qualify when <code>true</code>;
+ * only exact name matches qualify when <code>false</code>
+ */
+public void seekPackageFragments(String name, boolean partialMatch, IJavaElementRequestor requestor);
+/**
+ * Notifies the given requestor of all types (classes and interfaces) in the
+ * given package fragment with the given (unqualified) name.
+ * Checks the requestor at regular intervals to see if the requestor
+ * has canceled. If the given package fragment is <code>null</code>, all types in the
+ * project whose simple name matches the given name are found.
+ *
+ * @param partialMatch partial name matches qualify when <code>true</code>;
+ * only exact name matches qualify when <code>false</code>
+ * @param acceptFlags a bit mask describing if classes, interfaces or both classes and interfaces
+ * are desired results. If no flags are specified, all types are returned.
+ *
+ * @see ACCEPT_CLASSES
+ * @see ACCEPT_INTERFACES
+ */
+public void seekTypes(String name, IPackageFragment pkg, boolean partialMatch, int acceptFlags, IJavaElementRequestor requestor);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/IPathRequestor.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/IPathRequestor.java
index 8b923df3ee..90e7c7ae49 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/IPathRequestor.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/IPathRequestor.java
@@ -1,5 +1,5 @@
package org.eclipse.jdt.internal.core;
public interface IPathRequestor {
- void acceptPath(String path);
+void acceptPath(String path);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ImportContainer.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ImportContainer.java
index f3259fa679..99db352704 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ImportContainer.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ImportContainer.java
@@ -11,77 +11,62 @@ import org.eclipse.jdt.core.*;
/**
* @see IImportContainer
*/
-public class ImportContainer
- extends SourceRefElement
- implements IImportContainer {
- protected ImportContainer(ICompilationUnit parent) {
- super(IMPORT_CONTAINER, parent, "");
- }
-
- /**
- * @see JavaElement#getHandleMemento()
- */
- public String getHandleMemento() {
- return ((JavaElement) getParent()).getHandleMemento();
- }
-
- /**
- * @see JavaElement#getHandleMemento()
- */
- protected char getHandleMementoDelimiter() {
- throw new Error("should not be called");
- }
-
- /**
- * @see IImportContainer
- */
- public IImportDeclaration getImport(String name) {
- return new ImportDeclaration(this, name);
- }
-
- /**
- * @see ISourceReference
- */
- public ISourceRange getSourceRange() throws JavaModelException {
- IJavaElement[] imports = getChildren();
- ISourceRange firstRange = ((ISourceReference) imports[0]).getSourceRange();
- ISourceRange lastRange =
- ((ISourceReference) imports[imports.length - 1]).getSourceRange();
- SourceRange range =
- new SourceRange(
- firstRange.getOffset(),
- lastRange.getOffset() + lastRange.getLength() - firstRange.getOffset());
- return range;
- }
-
- /**
- * Import containers only exist if they have children.
- * @see IParent
- */
- public boolean hasChildren() throws JavaModelException {
- return true;
- }
-
- /**
- */
- public String readableName() {
-
- return null;
- }
+public class ImportContainer extends SourceRefElement implements IImportContainer {
+protected ImportContainer(ICompilationUnit parent) {
+ super(IMPORT_CONTAINER, parent, ""/*nonNLS*/);
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+public String getHandleMemento(){
+ return ((JavaElement)getParent()).getHandleMemento();
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+protected char getHandleMementoDelimiter() {
+ Assert.isTrue(false, Util.bind("assert.shouldNotImplement"/*nonNLS*/));
+ return 0;
+}
+/**
+ * @see IImportContainer
+ */
+public IImportDeclaration getImport(String name) {
+ return new ImportDeclaration(this, name);
+}
+/**
+ * @see ISourceReference
+ */
+public ISourceRange getSourceRange() throws JavaModelException {
+ IJavaElement[] imports= getChildren();
+ ISourceRange firstRange= ((ISourceReference)imports[0]).getSourceRange();
+ ISourceRange lastRange= ((ISourceReference)imports[imports.length - 1]).getSourceRange();
+ SourceRange range= new SourceRange(firstRange.getOffset(), lastRange.getOffset() + lastRange.getLength() - firstRange.getOffset());
+ return range;
+}
+/**
+ * Import containers only exist if they have children.
+ * @see IParent
+ */
+public boolean hasChildren() throws JavaModelException {
+ return true;
+}
+/**
+ */
+public String readableName() {
- /**
- * @private Debugging purposes
- */
- protected void toString(int tab, StringBuffer buffer) {
- Object info = fgJavaModelManager.getInfo(this);
- if (info == null || !(info instanceof JavaElementInfo))
- return;
- IJavaElement[] children = ((JavaElementInfo) info).getChildren();
- for (int i = 0; i < children.length; i++) {
- if (i > 0)
- buffer.append("\n");
- ((JavaElement) children[i]).toString(tab, buffer);
- }
+ return null;
+}
+/**
+ * @private Debugging purposes
+ */
+protected void toString(int tab, StringBuffer buffer) {
+ Object info = fgJavaModelManager.getInfo(this);
+ if (info == null || !(info instanceof JavaElementInfo)) return;
+ IJavaElement[] children = ((JavaElementInfo)info).getChildren();
+ for (int i = 0; i < children.length; i++) {
+ if (i > 0) buffer.append("\n"/*nonNLS*/);
+ ((JavaElement)children[i]).toString(tab, buffer);
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ImportDeclaration.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ImportDeclaration.java
index 36e789a412..bd6f12069c 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ImportDeclaration.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ImportDeclaration.java
@@ -13,57 +13,48 @@ import org.eclipse.jdt.core.jdom.IDOMNode;
* @see IImportDeclaration
*/
-/* package */
-class ImportDeclaration
- extends SourceRefElement
- implements IImportDeclaration {
+/* package */ class ImportDeclaration extends SourceRefElement implements IImportDeclaration {
- /**
- * Constructs an ImportDeclartaion in the given import container
- * with the given name.
- */
- protected ImportDeclaration(IImportContainer parent, String name) {
- super(IMPORT_DECLARATION, parent, name);
- }
-
- /**
- * @see JavaElement#equalsDOMNode
- */
- protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
- return (node.getNodeType() == IDOMNode.IMPORT)
- && getElementName().equals(node.getName());
- }
-
- /**
- * @see JavaElement#getHandleMemento()
- */
- protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_IMPORTDECLARATION;
- }
-
- /**
- * Returns true if the import is on-demand (ends with ".*")
- */
- public boolean isOnDemand() {
- return fName.endsWith(".*");
- }
- /**
- */
- public String readableName() {
-
- return null;
- }
+/**
+ * Constructs an ImportDeclartaion in the given import container
+ * with the given name.
+ */
+protected ImportDeclaration(IImportContainer parent, String name) {
+ super(IMPORT_DECLARATION, parent, name);
+}
+/**
+ * @see JavaElement#equalsDOMNode
+ */
+protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
+ return (node.getNodeType() == IDOMNode.IMPORT) && getElementName().equals(node.getName());
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+protected char getHandleMementoDelimiter() {
+ return JavaElement.JEM_IMPORTDECLARATION;
+}
+/**
+ * Returns true if the import is on-demand (ends with ".*")
+ */
+public boolean isOnDemand() {
+ return fName.endsWith(".*"/*nonNLS*/);
+}
+/**
+ */
+public String readableName() {
- /**
- * @private Debugging purposes
- */
- protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
- buffer.append("import ");
- buffer.append(getElementName());
- if (info == null) {
- buffer.append(" (not open)");
- }
+ return null;
+}
+/**
+ * @private Debugging purposes
+ */
+protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
+ buffer.append("import "/*nonNLS*/);
+ buffer.append(getElementName());
+ if (info == null) {
+ buffer.append(" (not open)"/*nonNLS*/);
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Initializer.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Initializer.java
index 81f9bb6322..9bcbca58d5 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Initializer.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Initializer.java
@@ -15,84 +15,72 @@ import org.eclipse.jdt.core.jdom.IDOMNode;
* @see IInitializer
*/
-/* package */
-class Initializer extends Member implements IInitializer {
+/* package */ class Initializer extends Member implements IInitializer {
- protected Initializer(IType parent, int occurrenceCount) {
- super(INITIALIZER, parent, "");
- // 0 is not valid: this first occurrence is occurrence 1.
- if (occurrenceCount <= 0)
- throw new IllegalArgumentException();
- fOccurrenceCount = occurrenceCount;
- }
-
- /**
- * @see JavaElement#equalsDOMNode
- */
- protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
- if (node.getNodeType() == IDOMNode.INITIALIZER) {
- IDOMInitializer i = (IDOMInitializer) node;
- return node.getContents().trim().equals(getSource());
- } else {
- return false;
- }
- }
-
- /**
- * @see JavaElement#getHandleMemento()
- */
- public String getHandleMemento() {
- StringBuffer buff =
- new StringBuffer(((JavaElement) getParent()).getHandleMemento());
- buff.append(getHandleMementoDelimiter());
- buff.append(fOccurrenceCount);
- return buff.toString();
- }
-
- /**
- * @see JavaElement#getHandleMemento()
- */
- protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_INITIALIZER;
- }
-
- public int hashCode() {
- return Util.combineHashCodes(fParent.hashCode(), fOccurrenceCount);
- }
-
- /**
- */
- public String readableName() {
-
- return ((JavaElement) getDeclaringType()).readableName();
- }
-
- /**
- * @see ISourceManipulation
- */
- public void rename(String name, boolean force, IProgressMonitor monitor)
- throws JavaModelException {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this));
+protected Initializer(IType parent, int occurrenceCount) {
+ super(INITIALIZER, parent, ""/*nonNLS*/);
+ // 0 is not valid: this first occurrence is occurrence 1.
+ if (occurrenceCount <= 0)
+ throw new IllegalArgumentException();
+ fOccurrenceCount = occurrenceCount;
+}
+/**
+ * @see JavaElement#equalsDOMNode
+ */
+protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
+ if (node.getNodeType() == IDOMNode.INITIALIZER) {
+ IDOMInitializer i = (IDOMInitializer) node;
+ return node.getContents().trim().equals(getSource());
+ } else {
+ return false;
}
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+public String getHandleMemento(){
+ StringBuffer buff= new StringBuffer(((JavaElement)getParent()).getHandleMemento());
+ buff.append(getHandleMementoDelimiter());
+ buff.append(fOccurrenceCount);
+ return buff.toString();
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+protected char getHandleMementoDelimiter() {
+ return JavaElement.JEM_INITIALIZER;
+}
+public int hashCode() {
+ return Util.combineHashCodes(fParent.hashCode(), fOccurrenceCount);
+}
+/**
+ */
+public String readableName() {
- /**
- * @private Debugging purposes
- */
- protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
- if (info == null) {
- buffer.append("<initializer>");
- buffer.append(" (not open)");
- } else {
- try {
- if (Flags.isStatic(this.getFlags())) {
- buffer.append("static ");
- }
- buffer.append("initializer");
- } catch (JavaModelException e) {
- buffer.append("<JavaModelException in toString of " + getElementName());
+ return ((JavaElement)getDeclaringType()).readableName();
+}
+/**
+ * @see ISourceManipulation
+ */
+public void rename(String name, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this));
+}
+/**
+ * @private Debugging purposes
+ */
+protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
+ if (info == null) {
+ buffer.append("<initializer>"/*nonNLS*/);
+ buffer.append(" (not open)"/*nonNLS*/);
+ } else {
+ try {
+ if (Flags.isStatic(this.getFlags())) {
+ buffer.append("static "/*nonNLS*/);
}
+ buffer.append("initializer"/*nonNLS*/);
+ } catch (JavaModelException e) {
+ buffer.append("<JavaModelException in toString of "/*nonNLS*/ + getElementName());
}
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/InitializerElementInfo.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/InitializerElementInfo.java
index 6e7a34be7d..96a591738b 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/InitializerElementInfo.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/InitializerElementInfo.java
@@ -9,6 +9,5 @@ import org.eclipse.core.resources.*;
/**
* Element info for IInitializer elements.
*/
-/* package */
-class InitializerElementInfo extends MemberElementInfo {
+/* package */ class InitializerElementInfo extends MemberElementInfo {
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarEntryFile.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarEntryFile.java
index ff47e72c5c..72d09145f5 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarEntryFile.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarEntryFile.java
@@ -21,54 +21,47 @@ public class JarEntryFile extends PlatformObject implements IStorage {
private String entryName;
private String zipName;
private IPath path;
-
- public JarEntryFile(String entryName, String zipName) {
+
+ public JarEntryFile(String entryName, String zipName){
this.entryName = entryName;
this.zipName = zipName;
this.path = new Path(this.entryName);
}
+public InputStream getContents() throws CoreException {
- public InputStream getContents() throws CoreException {
-
- try {
- ZipFile zipFile = new ZipFile(this.zipName);
- ZipEntry zipEntry = zipFile.getEntry(this.entryName);
- if (zipEntry == null) {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, this.entryName));
- }
- return zipFile.getInputStream(zipEntry);
- } catch (IOException e) {
- throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
+ try {
+ ZipFile zipFile = new ZipFile(this.zipName);
+ ZipEntry zipEntry = zipFile.getEntry(this.entryName);
+ if (zipEntry == null){
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, this.entryName));
}
+ return zipFile.getInputStream(zipEntry);
+ } catch (IOException e){
+ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
}
-
- /**
- * @see IStorage#getFullPath
- */
- public IPath getFullPath() {
- return this.path;
- }
-
- /**
- * @see IStorage#getName
- */
- public String getName() {
- return this.path.lastSegment();
- }
-
- /**
- * @see IStorage#isReadOnly()
- */
- public boolean isReadOnly() {
- return true;
- }
-
- /**
- * @see IStorage#isReadOnly()
- */
- public String toString() {
- return "JarEntryFile[" + this.zipName + "::" + this.entryName + "]";
- }
-
+}
+/**
+ * @see IStorage#getFullPath
+ */
+public IPath getFullPath() {
+ return this.path;
+}
+/**
+ * @see IStorage#getName
+ */
+public String getName() {
+ return this.path.lastSegment();
+}
+/**
+ * @see IStorage#isReadOnly()
+ */
+public boolean isReadOnly() {
+ return true;
+}
+/**
+ * @see IStorage#isReadOnly()
+ */
+public String toString() {
+ return "JarEntryFile["/*nonNLS*/+this.zipName+"::"/*nonNLS*/+this.entryName+"]"/*nonNLS*/;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragment.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragment.java
index 3857d6843b..ac87573443 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragment.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragment.java
@@ -18,143 +18,119 @@ import java.util.zip.*;
* @see IPackageFragment
*/
class JarPackageFragment extends PackageFragment {
- /**
- * Constructs a package fragment that is contained within a jar or a zip.
- */
- protected JarPackageFragment(IPackageFragmentRoot root, String name) {
- super(root, name);
- }
-
- /**
- * Compute the children of this package fragment. Children of jar package fragments
- * can only be IClassFile (representing .class files).
- */
- protected boolean computeChildren(OpenableElementInfo info) {
- Vector vChildren = new Vector();
- JarPackageFragmentInfo jInfo = (JarPackageFragmentInfo) info;
- for (Enumeration e = jInfo.fEntryNames.elements(); e.hasMoreElements();) {
- String child = (String) e.nextElement();
- IClassFile classFile = getClassFile(child);
- vChildren.addElement(classFile);
- }
- vChildren.trimToSize();
- IJavaElement[] children = new IJavaElement[vChildren.size()];
- vChildren.copyInto(children);
- info.setChildren(children);
- return true;
- }
-
- /**
- * Compute all the non-java resources according to the entry name found in the jar file.
- */
- /* package */
- void computeNonJavaResources(
- String[] resNames,
- JarPackageFragmentInfo info,
- String zipName) {
- if (resNames == null) {
- info.setNonJavaResources(null);
- return;
- }
- int max = resNames.length;
- Object[] res = new Object[max];
- for (int i = 0; i < max; i++) {
- res[i] = new JarEntryFile(resNames[i], zipName);
- }
- info.setNonJavaResources(res);
- }
-
- /**
- * Returns true if this fragment contains at least one java resource.
- * Returns false otherwise.
- */
- public boolean containsJavaResources() throws JavaModelException {
- return ((JarPackageFragmentInfo) getElementInfo()).containsJavaResources();
- }
-
- /**
- * @see IPackageFragment
- */
- public ICompilationUnit createCompilationUnit(
- String name,
- String contents,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
- }
-
- /**
- * @see JavaElement
- */
- protected OpenableElementInfo createElementInfo() {
- return new JarPackageFragmentInfo();
- }
-
- /**
- * @see IPackageFragment
- */
- public IClassFile[] getClassFiles() throws JavaModelException {
- Vector v = getChildrenOfType(CLASS_FILE);
- IClassFile[] array = new IClassFile[v.size()];
- v.copyInto(array);
- return array;
- }
-
- /**
- * A jar package fragment never contains compilation units.
- * @see IPackageFragment
- */
- public ICompilationUnit[] getCompilationUnits() throws JavaModelException {
- return fgEmptyCompilationUnitList;
- }
-
- /**
- * A package fragment in a jar has no corresponding resource.
- *
- * @see IJavaElement
- */
- public IResource getCorrespondingResource() throws JavaModelException {
- return null;
- }
-
- /**
- * Returns an array of non-java resources contained in the receiver.
- */
- public Object[] getNonJavaResources() throws JavaModelException {
- if (this.isDefaultPackage()) {
- // We don't want to show non java resources of the default package (see PR #1G58NB8)
- return JavaElementInfo.NO_NON_JAVA_RESOURCES;
- } else {
- return this.storedNonJavaResources();
- }
- }
-
- /**
- * Jars and jar entries are all read only
- */
- public boolean isReadOnly() {
- return true;
- }
-
- /**
- * @see Openable#openWhenClosed()
- */
- protected void openWhenClosed(IProgressMonitor pm) throws JavaModelException {
- // Open my jar
- getOpenableParent().open(pm);
+/**
+ * Constructs a package fragment that is contained within a jar or a zip.
+ */
+protected JarPackageFragment(IPackageFragmentRoot root, String name) {
+ super(root, name);
+}
+/**
+ * Compute the children of this package fragment. Children of jar package fragments
+ * can only be IClassFile (representing .class files).
+ */
+protected boolean computeChildren(OpenableElementInfo info) {
+ Vector vChildren = new Vector();
+ JarPackageFragmentInfo jInfo= (JarPackageFragmentInfo)info;
+ for (Enumeration e = jInfo.fEntryNames.elements(); e.hasMoreElements();) {
+ String child = (String) e.nextElement();
+ IClassFile classFile = getClassFile(child);
+ vChildren.addElement(classFile);
}
-
- /**
- * A package fragment in an archive cannot refresh its children.
- */
- public void refreshChildren() {
- // do nothing
+ vChildren.trimToSize();
+ IJavaElement[] children= new IJavaElement[vChildren.size()];
+ vChildren.copyInto(children);
+ info.setChildren(children);
+ return true;
+}
+/**
+ * Compute all the non-java resources according to the entry name found in the jar file.
+ */
+/* package */ void computeNonJavaResources(String[] resNames, JarPackageFragmentInfo info, String zipName) {
+ if (resNames == null) {
+ info.setNonJavaResources(null);
+ return;
}
-
- protected Object[] storedNonJavaResources() throws JavaModelException {
- return ((JarPackageFragmentInfo) getElementInfo()).getNonJavaResources();
+ int max = resNames.length;
+ Object[] res = new Object[max];
+ for (int i = 0; i < max; i++) {
+ res[i] = new JarEntryFile(resNames[i], zipName);
+ }
+ info.setNonJavaResources(res);
+}
+/**
+ * Returns true if this fragment contains at least one java resource.
+ * Returns false otherwise.
+ */
+public boolean containsJavaResources() throws JavaModelException {
+ return ((JarPackageFragmentInfo) getElementInfo()).containsJavaResources();
+}
+/**
+ * @see IPackageFragment
+ */
+public ICompilationUnit createCompilationUnit(String name, String contents, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
+}
+/**
+ * @see JavaElement
+ */
+protected OpenableElementInfo createElementInfo() {
+ return new JarPackageFragmentInfo();
+}
+/**
+ * @see IPackageFragment
+ */
+public IClassFile[] getClassFiles() throws JavaModelException {
+ Vector v= getChildrenOfType(CLASS_FILE);
+ IClassFile[] array= new IClassFile[v.size()];
+ v.copyInto(array);
+ return array;
+}
+/**
+ * A jar package fragment never contains compilation units.
+ * @see IPackageFragment
+ */
+public ICompilationUnit[] getCompilationUnits() throws JavaModelException {
+ return fgEmptyCompilationUnitList;
+}
+/**
+ * A package fragment in a jar has no corresponding resource.
+ *
+ * @see IJavaElement
+ */
+public IResource getCorrespondingResource() throws JavaModelException {
+ return null;
+}
+/**
+ * Returns an array of non-java resources contained in the receiver.
+ */
+public Object[] getNonJavaResources() throws JavaModelException {
+ if (this.isDefaultPackage()) {
+ // We don't want to show non java resources of the default package (see PR #1G58NB8)
+ return JavaElementInfo.NO_NON_JAVA_RESOURCES;
+ } else {
+ return this.storedNonJavaResources();
}
-
+}
+/**
+ * Jars and jar entries are all read only
+ */
+public boolean isReadOnly() {
+ return true;
+}
+/**
+ * @see Openable#openWhenClosed()
+ */
+protected void openWhenClosed(IProgressMonitor pm) throws JavaModelException {
+ // Open my jar
+ getOpenableParent().open(pm);
+}
+/**
+ * A package fragment in an archive cannot refresh its children.
+ */
+public void refreshChildren() {
+ // do nothing
+}
+protected Object[] storedNonJavaResources() throws JavaModelException {
+ return ((JarPackageFragmentInfo) getElementInfo()).getNonJavaResources();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragmentInfo.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragmentInfo.java
index ae7f9e2487..f0671a06d3 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragmentInfo.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragmentInfo.java
@@ -20,26 +20,23 @@ class JarPackageFragmentInfo extends PackageFragmentInfo {
* The names of the zip entries that are the class files associated
* with this package fragment info in the JAR file of the JarPackageFragmentRootInfo.
*/
- protected Vector fEntryNames = new Vector();
- /**
- */
- boolean containsJavaResources() {
- return fEntryNames.size() != 0;
- }
-
- /**
- * Returns an array of non-java resources contained in the receiver.
- */
- Object[] getNonJavaResources() {
- return fNonJavaResources;
- }
-
- /**
- * Set the names of the zip entries that are the types associated
- * with this package fragment info in the JAR file of the JarPackageFragmentRootInfo.
- */
- protected void setEntryNames(Vector entries) {
- fEntryNames = entries;
- }
-
+ protected Vector fEntryNames= new Vector();
+/**
+ */
+boolean containsJavaResources() {
+ return fEntryNames.size() != 0;
+}
+/**
+ * Returns an array of non-java resources contained in the receiver.
+ */
+Object[] getNonJavaResources() {
+ return fNonJavaResources;
+}
+/**
+ * Set the names of the zip entries that are the types associated
+ * with this package fragment info in the JAR file of the JarPackageFragmentRootInfo.
+ */
+protected void setEntryNames(Vector entries) {
+ fEntryNames = entries;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
index 1e2b1f361e..945ac02508 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragmentRoot.java
@@ -65,7 +65,7 @@ public class JarPackageFragmentRoot extends PackageFragmentRoot {
try {
verifyAttachSource(zipPath);
if (monitor != null) {
- monitor.beginTask("Attaching source...", 2);
+ monitor.beginTask(Util.bind("element.attachingSource"/*nonNLS*/), 2);
}
SourceMapper mapper= null;
SourceMapper oldMapper= getSourceMapper();
@@ -231,7 +231,7 @@ protected void computeJarChildren(JarPackageFragmentRootInfo info, Vector vChild
packageFragToTypes.put(eName, temp);
}
} else {
- if (eName.toUpperCase().endsWith(".CLASS")) {
+ if (Util.isClassFileName(eName)) {
//only interested in class files
//store the class file entry name to be cached in the appropriate package fragment
//zip entries only use '/'
@@ -374,17 +374,17 @@ public IClasspathEntry findSourceAttachmentRecommendation() {
try {
entry = parentProject.getClasspathEntryFor(rootPath);
if (entry != null){
- Object target = JavaModel.getTarget(workspaceRoot, entry.getSourceAttachmentPath());
+ Object target = JavaModel.getTarget(workspaceRoot, entry.getSourceAttachmentPath(), true);
if (target instanceof IFile){
IFile file = (IFile) target;
- if ("jar".equalsIgnoreCase(file.getFileExtension()) || "zip".equalsIgnoreCase(file.getFileExtension())){
+ if ("jar"/*nonNLS*/.equalsIgnoreCase(file.getFileExtension()) || "zip"/*nonNLS*/.equalsIgnoreCase(file.getFileExtension())){
return entry;
}
}
if (target instanceof java.io.File){
java.io.File file = (java.io.File) target;
- String name = file.getName().toLowerCase();
- if (name.endsWith(".jar") || name.endsWith(".zip")){
+ String name = file.getName();
+ if (Util.endsWithIgnoreCase(name, ".jar"/*nonNLS*/) || Util.endsWithIgnoreCase(name, ".zip"/*nonNLS*/)){
return entry;
}
}
@@ -401,17 +401,18 @@ public IClasspathEntry findSourceAttachmentRecommendation() {
try {
entry = jProject.getClasspathEntryFor(rootPath);
if (entry != null){
- Object target = JavaModel.getTarget(workspaceRoot, entry.getSourceAttachmentPath());
+ Object target = JavaModel.getTarget(workspaceRoot, entry.getSourceAttachmentPath(), true);
if (target instanceof IFile){
IFile file = (IFile) target;
- if ("jar".equalsIgnoreCase(file.getFileExtension()) || "zip".equalsIgnoreCase(file.getFileExtension())){
+ String name = file.getName();
+ if (Util.endsWithIgnoreCase(name, ".jar"/*nonNLS*/) || Util.endsWithIgnoreCase(name, ".zip"/*nonNLS*/)){
return entry;
}
}
if (target instanceof java.io.File){
java.io.File file = (java.io.File) target;
- String name = file.getName().toLowerCase();
- if (name.endsWith(".jar") || name.endsWith(".zip")){
+ String name = file.getName();
+ if (Util.endsWithIgnoreCase(name, ".jar"/*nonNLS*/) || Util.endsWithIgnoreCase(name, ".zip"/*nonNLS*/)){
return entry;
}
}
@@ -424,15 +425,6 @@ public IClasspathEntry findSourceAttachmentRecommendation() {
return null;
}
-/**
- * @see JavaElement#getHandleMemento()
- */
-public String getHandleMemento(){
- StringBuffer buff= new StringBuffer(((JavaElement)getParent()).getHandleMemento());
- buff.append(getHandleMementoDelimiter());
- buff.append(this.fJarPath.toString()); // 1GEP51U
- return buff.toString();
-}
/**
* Returns the underlying ZipFile for this Jar package fragment root.
*
@@ -491,6 +483,7 @@ public String getHandleMemento(){
return null;
}
int index= serverPathString.lastIndexOf(ATTACHMENT_PROPERTY_DELIMITER);
+ if (index < 0) return null;
String serverZipPathString= serverPathString.substring(0, index);
return new Path(serverZipPathString);
}
@@ -510,7 +503,7 @@ public String getHandleMemento(){
if (recommendation != null){
propertyString = recommendation.getSourceAttachmentPath().toString()
+ ATTACHMENT_PROPERTY_DELIMITER
- + (recommendation.getSourceAttachmentRootPath() == null ? "" : recommendation.getSourceAttachmentRootPath().toString());
+ + (recommendation.getSourceAttachmentRootPath() == null ? ""/*nonNLS*/ : recommendation.getSourceAttachmentRootPath().toString());
getWorkspace().getRoot().setPersistentProperty(qName, propertyString);
}
}
@@ -527,7 +520,7 @@ public String getHandleMemento(){
ZipFile jarFile = null;
try {
jarFile = getJar();
- return new QualifiedName(JavaCore.PLUGIN_ID, "sourceattachment: " + jarFile.getName());
+ return new QualifiedName(JavaCore.PLUGIN_ID, "sourceattachment: "/*nonNLS*/ + jarFile.getName());
} catch (CoreException e) {
throw new JavaModelException(e);
} finally {
@@ -658,4 +651,14 @@ public String getHandleMemento(){
throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.RELATIVE_PATH, zipPath));
}
}
+
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+public String getHandleMemento(){
+ StringBuffer buff= new StringBuffer(((JavaElement)getParent()).getHandleMemento());
+ buff.append(getHandleMementoDelimiter());
+ buff.append(this.fJarPath.toString()); // 1GEP51U
+ return buff.toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragmentRootInfo.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragmentRootInfo.java
index 9d12eecc95..bb2a66ab11 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragmentRootInfo.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JarPackageFragmentRootInfo.java
@@ -14,28 +14,25 @@ class JarPackageFragmentRootInfo extends PackageFragmentRootInfo {
* The SourceMapper for this JAR (or <code>null</code> if
* this JAR does not have source attached).
*/
- protected SourceMapper fSourceMapper = null;
- /**
- * Returns an array of non-java resources contained in the receiver.
- */
- public Object[] getNonJavaResources() {
- fNonJavaResources = NO_NON_JAVA_RESOURCES;
- return fNonJavaResources;
- }
-
- /**
- * Retuns the SourceMapper for this JAR, or <code>null</code>
- * if this JAR does not have attached source.
- */
- protected SourceMapper getSourceMapper() {
- return fSourceMapper;
- }
-
- /**
- * Sets the SourceMapper for this JAR.
- */
- protected void setSourceMapper(SourceMapper mapper) {
- fSourceMapper = mapper;
- }
-
+ protected SourceMapper fSourceMapper= null;
+/**
+ * Returns an array of non-java resources contained in the receiver.
+ */
+public Object[] getNonJavaResources() {
+ fNonJavaResources = NO_NON_JAVA_RESOURCES;
+ return fNonJavaResources;
+}
+/**
+ * Retuns the SourceMapper for this JAR, or <code>null</code>
+ * if this JAR does not have attached source.
+ */
+protected SourceMapper getSourceMapper() {
+ return fSourceMapper;
+}
+/**
+ * Sets the SourceMapper for this JAR.
+ */
+protected void setSourceMapper(SourceMapper mapper) {
+ fSourceMapper= mapper;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElement.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElement.java
index 465e998269..286bcd3f32 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElement.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElement.java
@@ -17,21 +17,19 @@ import java.util.Vector;
*
* @see IJavaElement
*/
-public abstract class JavaElement
- extends PlatformObject
- implements IJavaElement {
+public abstract class JavaElement extends PlatformObject implements IJavaElement {
- public static final char JEM_JAVAPROJECT = '=';
- public static final char JEM_PACKAGEFRAGMENTROOT = Path.SEPARATOR;
- public static final char JEM_PACKAGEFRAGMENT = '<';
- public static final char JEM_FIELD = '^';
- public static final char JEM_METHOD = '~';
- public static final char JEM_INITIALIZER = '|';
- public static final char JEM_COMPILATIONUNIT = '{';
- public static final char JEM_CLASSFILE = '(';
- public static final char JEM_TYPE = '[';
- public static final char JEM_PACKAGEDECLARATION = '%';
- public static final char JEM_IMPORTDECLARATION = '#';
+ public static final char JEM_JAVAPROJECT= '=';
+ public static final char JEM_PACKAGEFRAGMENTROOT= Path.SEPARATOR;
+ public static final char JEM_PACKAGEFRAGMENT= '<';
+ public static final char JEM_FIELD= '^';
+ public static final char JEM_METHOD= '~';
+ public static final char JEM_INITIALIZER= '|';
+ public static final char JEM_COMPILATIONUNIT= '{';
+ public static final char JEM_CLASSFILE= '(';
+ public static final char JEM_TYPE= '[';
+ public static final char JEM_PACKAGEDECLARATION= '%';
+ public static final char JEM_IMPORTDECLARATION= '#';
/**
* A count to uniquely identify this element in the case
@@ -43,6 +41,7 @@ public abstract class JavaElement
*/
protected int fOccurrenceCount = 1;
+
/**
* This element's type - one of the constants defined
* in IJavaLanguageElementTypes.
@@ -64,603 +63,535 @@ public abstract class JavaElement
/**
* Direct access to the Java Model Manager
*/
- protected static JavaModelManager fgJavaModelManager =
- JavaModelManager.getJavaModelManager();
-
- /**
- * Constructs a handle for a java element of the specified type, with
- * the given parent element and name.
- *
- * @param type - one of the constants defined in IJavaLanguageElementTypes
- *
- * @exception IllegalArgumentException if the type is not one of the valid
- * Java element type constants
- *
- */
- protected JavaElement(int type, IJavaElement parent, String name)
- throws IllegalArgumentException {
- if (type < JAVA_MODEL || type > IMPORT_DECLARATION) {
- throw new IllegalArgumentException("type is not one of the defined constants");
- }
- fLEType = type;
- fParent = parent;
- fName = name;
+ protected static JavaModelManager fgJavaModelManager = JavaModelManager.getJavaModelManager();
+
+/**
+ * Constructs a handle for a java element of the specified type, with
+ * the given parent element and name.
+ *
+ * @param type - one of the constants defined in IJavaLanguageElement
+ *
+ * @exception IllegalArgumentException if the type is not one of the valid
+ * Java element type constants
+ *
+ */
+protected JavaElement(int type, IJavaElement parent, String name) throws IllegalArgumentException {
+ if (type < JAVA_MODEL || type > IMPORT_DECLARATION) {
+ throw new IllegalArgumentException(Util.bind("element.invalidType"/*nonNLS*/));
}
-
- /**
- * @see IOpenable
- */
- public void close() throws JavaModelException {
- Object info = fgJavaModelManager.peekAtInfo(this);
- if (info != null) {
- if (this instanceof IParent) {
- IJavaElement[] children = ((JavaElementInfo) info).getChildren();
- for (int i = 0, size = children.length; i < size; ++i) {
- JavaElement child = (JavaElement) children[i];
- child.close();
- }
+ fLEType= type;
+ fParent= parent;
+ fName= name;
+}
+/**
+ * @see IOpenable
+ */
+public void close() throws JavaModelException {
+ Object info = fgJavaModelManager.peekAtInfo(this);
+ if (info != null) {
+ if (this instanceof IParent) {
+ IJavaElement[] children = ((JavaElementInfo) info).getChildren();
+ for (int i = 0, size = children.length; i < size; ++i) {
+ JavaElement child = (JavaElement) children[i];
+ child.close();
}
- closing(info);
- fgJavaModelManager.removeInfo(this);
}
+ closing(info);
+ fgJavaModelManager.removeInfo(this);
}
-
- /**
- * This element is being closed. Do any necessary cleanup.
- */
- protected void closing(Object info) throws JavaModelException {
- }
-
- /**
- * Returns true if this handle represents the same Java element
- * as the given handle. By default, two handles represent the same
- * element if they are identical or if they represent the same type
- * of element, have equal names, parents, and occurrence counts.
- *
- * <p>If a subclass has other requirements for equality, this method
- * must be overridden.
- *
- * @see Object#equals
- */
- public boolean equals(Object o) {
- if (this == o)
- return true;
- if (o instanceof JavaElement) {
- JavaElement other = (JavaElement) o;
- if (fLEType != other.fLEType)
- return false;
- return fName.equals(other.fName)
- && fParent.equals(other.fParent)
- && fOccurrenceCount == other.fOccurrenceCount;
- }
- return false;
+}
+/**
+ * This element is being closed. Do any necessary cleanup.
+ */
+protected void closing(Object info) throws JavaModelException {
+}
+/**
+ * Returns true if this handle represents the same Java element
+ * as the given handle. By default, two handles represent the same
+ * element if they are identical or if they represent the same type
+ * of element, have equal names, parents, and occurrence counts.
+ *
+ * <p>If a subclass has other requirements for equality, this method
+ * must be overridden.
+ *
+ * @see Object#equals
+ */
+public boolean equals(Object o) {
+ if (this == o)
+ return true;
+ if (o instanceof JavaElement) {
+ JavaElement other = (JavaElement) o;
+ if (fLEType != other.fLEType)
+ return false;
+ return fName.equals(other.fName) &&
+ fParent.equals(other.fParent) &&
+ fOccurrenceCount == other.fOccurrenceCount;
}
-
- /**
- * Returns true if this <code>JavaElement</code> is equivalent to the given
- * <code>IDOMNode</code>.
- */
- protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
+ return false;
+}
+/**
+ * Returns true if this <code>JavaElement</code> is equivalent to the given
+ * <code>IDOMNode</code>.
+ */
+protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
+ return false;
+}
+/**
+ * @see IJavaElement
+ */
+public boolean exists() {
+ try {
+ getRawInfo();
+ return true;
+ } catch (JavaModelException e) {
return false;
}
-
- /**
- * @see IJavaElement
- */
- public boolean exists() {
- try {
- getRawInfo();
- return true;
- } catch (JavaModelException e) {
- return false;
- }
- }
-
- /**
- * Returns the <code>IDOMNode</code> that corresponds to this <code>JavaElement</code>
- * or <code>null</code> if there is no corresponding node.
- */
- public IDOMNode findNode(IDOMCompilationUnit dom) {
- int type = getElementType();
- if (type == IJavaElement.COMPILATION_UNIT
- || type == IJavaElement.FIELD
- || type == IJavaElement.IMPORT_DECLARATION
- || type == IJavaElement.INITIALIZER
- || type == IJavaElement.METHOD
- || type == IJavaElement.PACKAGE_DECLARATION
- || type == IJavaElement.TYPE) {
- Vector path = new Vector();
- IJavaElement element = this;
- while (element != null
- && element.getElementType() != IJavaElement.COMPILATION_UNIT) {
- if (element.getElementType() != IJavaElement.IMPORT_CONTAINER) {
- // the DOM does not have import containers, so skip them
- path.insertElementAt(element, 0);
- }
- element = element.getParent();
+}
+/**
+ * Returns the <code>IDOMNode</code> that corresponds to this <code>JavaElement</code>
+ * or <code>null</code> if there is no corresponding node.
+ */
+public IDOMNode findNode(IDOMCompilationUnit dom) {
+ int type = getElementType();
+ if (type == IJavaElement.COMPILATION_UNIT ||
+ type == IJavaElement.FIELD ||
+ type == IJavaElement.IMPORT_DECLARATION ||
+ type == IJavaElement.INITIALIZER ||
+ type == IJavaElement.METHOD ||
+ type == IJavaElement.PACKAGE_DECLARATION ||
+ type == IJavaElement.TYPE) {
+ Vector path = new Vector();
+ IJavaElement element = this;
+ while (element != null && element.getElementType() != IJavaElement.COMPILATION_UNIT) {
+ if (element.getElementType() != IJavaElement.IMPORT_CONTAINER) {
+ // the DOM does not have import containers, so skip them
+ path.insertElementAt(element, 0);
}
- if (path.size() == 0) {
- try {
- if (equalsDOMNode(dom)) {
- return dom;
- } else {
- return null;
- }
- } catch (JavaModelException e) {
+ element = element.getParent();
+ }
+ if (path.size() == 0) {
+ try {
+ if (equalsDOMNode(dom)) {
+ return dom;
+ } else {
return null;
}
+ } catch(JavaModelException e) {
+ return null;
}
- return ((JavaElement) path.elementAt(0)).followPath(
- path,
- 0,
- dom.getFirstChild());
- } else {
- return null;
}
+ return ((JavaElement) path.elementAt(0)).followPath(path, 0, dom.getFirstChild());
+ } else {
+ return null;
}
-
- /**
- */
- protected IDOMNode followPath(Vector path, int position, IDOMNode node) {
-
- try {
- if (equalsDOMNode(node)) {
- if (position == (path.size() - 1)) {
- return node;
- } else {
- if (node.getFirstChild() != null) {
- position++;
- return ((JavaElement) path.elementAt(position)).followPath(
- path,
- position,
- node.getFirstChild());
- } else {
- return null;
- }
- }
- } else
- if (node.getNextNode() != null) {
- return followPath(path, position, node.getNextNode());
+}
+/**
+ */
+protected IDOMNode followPath(Vector path, int position, IDOMNode node) {
+
+ try {
+ if (equalsDOMNode(node)) {
+ if (position == (path.size() - 1)) {
+ return node;
+ } else {
+ if (node.getFirstChild() != null) {
+ position++;
+ return ((JavaElement)path.elementAt(position)).followPath(path, position, node.getFirstChild());
} else {
return null;
}
- } catch (JavaModelException e) {
- return null;
- }
-
- }
-
- /**
- * @see IParent
- */
- public IJavaElement[] getChildren() throws JavaModelException {
- return getElementInfo().getChildren();
- }
-
- /**
- * Returns a collection of (immediate) children of this node of the
- * specified type.
- *
- * @param type - one of constants defined by IJavaLanguageElementTypes
- */
- public Vector getChildrenOfType(int type) throws JavaModelException {
- IJavaElement[] children = getChildren();
- int size = children.length;
- Vector v = new Vector(size);
- for (int i = 0; i < size; ++i) {
- JavaElement elt = (JavaElement) children[i];
- if (elt.getElementType() == type) {
- v.addElement(elt);
}
+ } else if (node.getNextNode() != null) {
+ return followPath(path, position, node.getNextNode());
+ } else {
+ return null;
}
- return v;
- }
-
- /**
- * @see IMember
- */
- public IClassFile getClassFile() {
+ } catch (JavaModelException e) {
return null;
}
- /**
- * @see IMember
- */
- public ICompilationUnit getCompilationUnit() {
- return null;
- }
-
- /**
- * Returns the info for this handle.
- * If this element is not already open, it and all of its parents are opened.
- * Does not return null.
- *
- * @exception JavaModelException if the element is not present or not accessible
- */
- protected JavaElementInfo getElementInfo() throws JavaModelException {
- synchronized (fgJavaModelManager) {
- Object info = fgJavaModelManager.getInfo(this);
- if (info == null) {
- openHierarchy();
- info = fgJavaModelManager.getInfo(this);
- if (info == null) {
- throw newNotPresentException();
- }
- }
- return (JavaElementInfo) info;
+}
+/**
+ * @see IParent
+ */
+public IJavaElement[] getChildren() throws JavaModelException {
+ return getElementInfo().getChildren();
+}
+/**
+ * Returns a collection of (immediate) children of this node of the
+ * specified type.
+ *
+ * @param type - one of constants defined by IJavaLanguageElementTypes
+ */
+public Vector getChildrenOfType(int type) throws JavaModelException {
+ IJavaElement[] children = getChildren();
+ int size = children.length;
+ Vector v = new Vector(size);
+ for (int i = 0; i < size; ++i) {
+ JavaElement elt = (JavaElement)children[i];
+ if (elt.getElementType() == type) {
+ v.addElement(elt);
}
}
-
- /**
- * @see IAdaptable
- */
- public String getElementName() {
- return fName;
- }
-
- /**
- * @see IJavaElement
- */
- public int getElementType() {
- return fLEType;
- }
-
- /**
- * @see IJavaElement
- */
- public String getHandleIdentifier() {
- return getHandleMemento();
- }
-
- /**
- * @see JavaElement#getHandleMemento()
- */
- public String getHandleMemento() {
- StringBuffer buff =
- new StringBuffer(((JavaElement) getParent()).getHandleMemento());
- buff.append(getHandleMementoDelimiter());
- buff.append(getElementName());
- return buff.toString();
- }
-
- /**
- * Returns the <code>char</code> that marks the start of this handles
- * contribution to a memento.
- */
- protected abstract char getHandleMementoDelimiter();
- /**
- * @see IJavaElement
- */
- public IJavaModel getJavaModel() {
- return getParent().getJavaModel();
- }
-
- /**
- * Returns the JavaModelManager
- */
- public JavaModelManager getJavaModelManager() {
- return fgJavaModelManager;
- }
-
- /**
- * @see IJavaElement
- */
- public IJavaProject getJavaProject() {
- return getParent().getJavaProject();
- }
-
- /**
- * Returns the occurrence count of the handle.
- */
- protected int getOccurrenceCount() {
- return fOccurrenceCount;
- }
-
- /**
- * Return the first instance of IOpenable in the parent
- * hierarchy of this element.
- *
- * <p>Subclasses that are not IOpenable's must override this method.
- */
- public IOpenable getOpenableParent() {
-
- return (IOpenable) fParent;
- }
-
- /**
- * @see IJavaElement
- */
- public IJavaElement getParent() {
- return fParent;
- }
-
- /**
- * Returns the info for this handle.
- * If this element is not already open, it and all of its parents are opened.
- * Does not return null.
- *
- * @exception JavaModelException if the element is not present or not accessible
- */
- public Object getRawInfo() throws JavaModelException {
+ return v;
+}
+/**
+ * @see IMember
+ */
+public IClassFile getClassFile() {
+ return null;
+}
+/**
+ * @see IMember
+ */
+public ICompilationUnit getCompilationUnit() {
+ return null;
+}
+/**
+ * Returns the info for this handle.
+ * If this element is not already open, it and all of its parents are opened.
+ * Does not return null.
+ *
+ * @exception JavaModelException if the element is not present or not accessible
+ */
+protected JavaElementInfo getElementInfo() throws JavaModelException {
+ synchronized(fgJavaModelManager){
Object info = fgJavaModelManager.getInfo(this);
if (info == null) {
openHierarchy();
- info = fgJavaModelManager.getInfo(this);
+ info= fgJavaModelManager.getInfo(this);
if (info == null) {
throw newNotPresentException();
}
}
- return info;
- }
-
- /**
- * Returns the element that is located at the given source position
- * in this element. This is a helper method for <code>ICompilationUnit#getElementAt</code>,
- * and only works on compilation units and types. The position given is
- * known to be within this element's source range already, and if no finer
- * grained element is found at the position, this element is returned.
- */
- protected IJavaElement getSourceElementAt(int position)
- throws JavaModelException {
- if (this instanceof ISourceReference) {
- IJavaElement[] children = getChildren();
- int i;
- for (i = 0; i < children.length; i++) {
- IJavaElement aChild = children[i];
- if (aChild instanceof SourceRefElement) {
- SourceRefElement child = (SourceRefElement) children[i];
- ISourceRange range = child.getSourceRange();
- if (position < range.getOffset() + range.getLength()
- && position >= range.getOffset()) {
- if (child.getElementType() == TYPE) {
- return child.getSourceElementAt(position);
- } else {
- return child;
- }
- }
- }
- }
- } else {
- // should not happen
- Assert.isTrue(false);
- }
- return this;
- }
-
- /**
- * Returns the SourceMapper facility for this element, or
- * <code>null</code> if this element does not have a
- * SourceMapper.
- */
- public SourceMapper getSourceMapper() {
- return ((JavaElement) getParent()).getSourceMapper();
- }
-
- public abstract IResource getUnderlyingResource() throws JavaModelException;
- /**
- * Returns the workspace associated with this object.
- */
- public IWorkspace getWorkspace() {
- return getJavaModel().getWorkspace();
- }
-
- /**
- * Returns the hash code for this Java element. By default,
- * the hash code for an element is a combination of its name
- * and parent's hash code. Elements with other requirements must
- * override this method.
- */
- public int hashCode() {
- return Util.combineHashCodes(fName.hashCode(), fParent.hashCode());
+ return (JavaElementInfo)info;
}
-
- /**
- * Returns true if this element is an ancestor of the given element,
- * otherwise false.
- */
- protected boolean isAncestorOf(IJavaElement e) {
- IJavaElement parent = e.getParent();
- while (parent != null && !parent.equals(this)) {
- parent = parent.getParent();
+}
+/**
+ * @see IAdaptable
+ */
+public String getElementName() {
+ return fName;
+}
+/**
+ * @see IJavaElement
+ */
+public int getElementType() {
+ return fLEType;
+}
+/**
+ * @see IJavaElement
+ */
+public String getHandleIdentifier() {
+ return getHandleMemento();
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+public String getHandleMemento(){
+ StringBuffer buff= new StringBuffer(((JavaElement)getParent()).getHandleMemento());
+ buff.append(getHandleMementoDelimiter());
+ buff.append(getElementName());
+ return buff.toString();
+}
+/**
+ * Returns the <code>char</code> that marks the start of this handles
+ * contribution to a memento.
+ */
+protected abstract char getHandleMementoDelimiter();
+/**
+ * @see IJavaElement
+ */
+public IJavaModel getJavaModel() {
+ return getParent().getJavaModel();
+}
+/**
+ * Returns the JavaModelManager
+ */
+public JavaModelManager getJavaModelManager() {
+ return fgJavaModelManager;
+}
+/**
+ * @see IJavaElement
+ */
+public IJavaProject getJavaProject() {
+ return getParent().getJavaProject();
+}
+/**
+ * Returns the occurrence count of the handle.
+ */
+protected int getOccurrenceCount() {
+ return fOccurrenceCount;
+}
+/**
+ * Return the first instance of IOpenable in the parent
+ * hierarchy of this element.
+ *
+ * <p>Subclasses that are not IOpenable's must override this method.
+ */
+public IOpenable getOpenableParent() {
+
+ return (IOpenable)fParent;
+}
+/**
+ * @see IJavaElement
+ */
+public IJavaElement getParent() {
+ return fParent;
+}
+/**
+ * Returns the info for this handle.
+ * If this element is not already open, it and all of its parents are opened.
+ * Does not return null.
+ *
+ * @exception JavaModelException if the element is not present or not accessible
+ */
+public Object getRawInfo() throws JavaModelException {
+ Object info = fgJavaModelManager.getInfo(this);
+ if (info == null) {
+ openHierarchy();
+ info= fgJavaModelManager.getInfo(this);
+ if (info == null) {
+ throw newNotPresentException();
}
- return parent != null;
- }
-
- /**
- * @see IJavaElement
- */
- public boolean isReadOnly() {
- return false;
- }
-
- /**
- * @see IJavaElement
- */
- public boolean isStructureKnown() throws JavaModelException {
- return getElementInfo().isStructureKnown();
- }
-
- /**
- * Creates and returns and not present exception for this element.
- */
- protected JavaModelException newNotPresentException() {
- return new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, this));
- }
-
- /**
- * Default is to not do any source indices updates.
- */
- public void offsetSourceEndAndChildren(int amount, IJavaElement child) {
-
}
-
- /**
- * Default behaviour is not to change the source range
- * for the Java element
- */
- public void offsetSourceRange(int amount) {
- }
-
- /**
- * Opens this element and all parents that are not already open.
- *
- * @exception JavaModelException this element is not present or accessible
- */
- protected void openHierarchy() throws JavaModelException {
- if (this instanceof IOpenable) {
- ((Openable) this).openWhenClosed(null);
- } else {
- Openable openableParent = (Openable) getOpenableParent();
- if (openableParent != null) {
- JavaElementInfo openableParentInfo =
- (JavaElementInfo) fgJavaModelManager.getInfo((IJavaElement) openableParent);
- if (openableParentInfo == null) {
- openableParent.openWhenClosed(null);
- } else {
- throw newNotPresentException();
+ return info;
+}
+/**
+ * Returns the element that is located at the given source position
+ * in this element. This is a helper method for <code>ICompilationUnit#getElementAt</code>,
+ * and only works on compilation units and types. The position given is
+ * known to be within this element's source range already, and if no finer
+ * grained element is found at the position, this element is returned.
+ */
+protected IJavaElement getSourceElementAt(int position) throws JavaModelException {
+ if (this instanceof ISourceReference) {
+ IJavaElement[] children = getChildren();
+ int i;
+ for (i = 0; i < children.length; i++) {
+ IJavaElement aChild = children[i];
+ if (aChild instanceof SourceRefElement) {
+ SourceRefElement child = (SourceRefElement) children[i];
+ ISourceRange range = child.getSourceRange();
+ if (position < range.getOffset() + range.getLength() && position >= range.getOffset()) {
+ if (child.getElementType() == TYPE) {
+ return child.getSourceElementAt(position);
+ } else {
+ return child;
+ }
}
}
}
+ } else {
+ // should not happen
+ Assert.isTrue(false);
}
-
- /**
- * This element has just been opened. Do any necessary setup.
- */
- protected void opening(Object info) {
- }
-
- /**
- */
- public String readableName() {
-
- return this.getElementName();
+ return this;
+}
+/**
+ * Returns the SourceMapper facility for this element, or
+ * <code>null</code> if this element does not have a
+ * SourceMapper.
+ */
+public SourceMapper getSourceMapper() {
+ return ((JavaElement)getParent()).getSourceMapper();
+}
+public abstract IResource getUnderlyingResource() throws JavaModelException;
+/**
+ * Returns the workspace associated with this object.
+ */
+public IWorkspace getWorkspace() {
+ return getJavaModel().getWorkspace();
+}
+/**
+ * Returns the hash code for this Java element. By default,
+ * the hash code for an element is a combination of its name
+ * and parent's hash code. Elements with other requirements must
+ * override this method.
+ */
+public int hashCode() {
+ return Util.combineHashCodes(fName.hashCode(), fParent.hashCode());
+}
+/**
+ * Returns true if this element is an ancestor of the given element,
+ * otherwise false.
+ */
+protected boolean isAncestorOf(IJavaElement e) {
+ IJavaElement parent= e.getParent();
+ while (parent != null && !parent.equals(this)) {
+ parent= parent.getParent();
}
-
- /**
- * Removes all cached info from the Java Model, including all children,
- * but does not close this element.
- */
- protected void removeInfo() {
- Object info = fgJavaModelManager.peekAtInfo(this);
- if (info != null) {
- if (this instanceof IParent) {
- IJavaElement[] children = ((JavaElementInfo) info).getChildren();
- for (int i = 0, size = children.length; i < size; ++i) {
- JavaElement child = (JavaElement) children[i];
- child.removeInfo();
- }
+ return parent != null;
+}
+/**
+ * @see IJavaElement
+ */
+public boolean isReadOnly() {
+ return false;
+}
+/**
+ * @see IJavaElement
+ */
+public boolean isStructureKnown() throws JavaModelException {
+ return getElementInfo().isStructureKnown();
+}
+/**
+ * Creates and returns and not present exception for this element.
+ */
+protected JavaModelException newNotPresentException() {
+ return new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, this));
+}
+/**
+ * Default is to not do any source indices updates.
+ */
+public void offsetSourceEndAndChildren(int amount, IJavaElement child) {
+
+}
+/**
+ * Default behaviour is not to change the source range
+ * for the Java element
+ */
+public void offsetSourceRange(int amount) {
+}
+/**
+ * Opens this element and all parents that are not already open.
+ *
+ * @exception JavaModelException this element is not present or accessible
+ */
+protected void openHierarchy() throws JavaModelException {
+ if (this instanceof IOpenable) {
+ ((Openable) this).openWhenClosed(null);
+ } else {
+ Openable openableParent = (Openable)getOpenableParent();
+ if (openableParent != null) {
+ JavaElementInfo openableParentInfo = (JavaElementInfo) fgJavaModelManager.getInfo((IJavaElement) openableParent);
+ if (openableParentInfo == null) {
+ openableParent.openWhenClosed(null);
+ } else {
+ throw newNotPresentException();
}
- fgJavaModelManager.removeInfo(this);
- }
- }
-
- /**
- * Runs a Java Model Operation
- */
- protected void runOperation(
- JavaModelOperation operation,
- IProgressMonitor monitor)
- throws JavaModelException {
- fgJavaModelManager.runOperation(operation, monitor);
- }
-
- /**
- * Sets the occurrence count of the handle.
- */
- protected void setOccurrenceCount(int count) {
- fOccurrenceCount = count;
- }
-
- protected String tabString(int tab) {
- StringBuffer buffer = new StringBuffer();
- for (int i = tab; i > 0; i--)
- buffer.append(" ");
- return buffer.toString();
- }
-
- /**
- * @private Debugging purposes
- */
- protected String toDebugString() {
- StringBuffer buffer = new StringBuffer();
- Object info = fgJavaModelManager.getInfo(this);
- this.toStringInfo(0, buffer, info);
- return buffer.toString();
- }
-
- /**
- * @private Debugging purposes
- */
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- toString(0, buffer);
- return buffer.toString();
- }
-
- /**
- * @private Debugging purposes
- */
- protected void toString(int tab, StringBuffer buffer) {
- buffer.append(this.tabString(tab));
- Object info = fgJavaModelManager.getInfo(this);
- this.toStringInfo(tab, buffer, info);
- if (tab == 0) {
- this.toStringAncestors(buffer);
- }
- this.toStringChildren(tab, buffer, info);
- }
-
- /**
- * @private Debugging purposes
- */
- protected void toStringAncestors(StringBuffer buffer) {
- JavaElement parent = (JavaElement) this.getParent();
- if (parent != null) {
- buffer.append(" [in ");
- Object parentInfo = fgJavaModelManager.getInfo(parent);
- parent.toStringInfo(0, buffer, parentInfo);
- parent.toStringAncestors(buffer);
- buffer.append("]");
}
}
+}
+/**
+ * This element has just been opened. Do any necessary setup.
+ */
+protected void opening(Object info) {
+}
+/**
+ */
+public String readableName() {
- /**
- * @private Debugging purposes
- */
- protected void toStringChildren(int tab, StringBuffer buffer, Object info) {
- if (info == null || !(info instanceof JavaElementInfo))
- return;
- IJavaElement[] children = ((JavaElementInfo) info).getChildren();
- for (int i = 0; i < children.length; i++) {
- buffer.append("\n");
- ((JavaElement) children[i]).toString(tab + 1, buffer);
+ return this.getElementName();
+}
+/**
+ * Removes all cached info from the Java Model, including all children,
+ * but does not close this element.
+ */
+protected void removeInfo() {
+ Object info = fgJavaModelManager.peekAtInfo(this);
+ if (info != null) {
+ if (this instanceof IParent) {
+ IJavaElement[] children = ((JavaElementInfo)info).getChildren();
+ for (int i = 0, size = children.length; i < size; ++i) {
+ JavaElement child = (JavaElement) children[i];
+ child.removeInfo();
+ }
}
+ fgJavaModelManager.removeInfo(this);
}
-
- /**
- * @private Debugging purposes
- */
- protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
- buffer.append(getElementName());
- if (info == null) {
- buffer.append(" (not open)");
- }
+}
+/**
+ * Runs a Java Model Operation
+ */
+protected void runOperation(JavaModelOperation operation, IProgressMonitor monitor) throws JavaModelException {
+ fgJavaModelManager.runOperation(operation, monitor);
+}
+/**
+ * Sets the occurrence count of the handle.
+ */
+protected void setOccurrenceCount(int count) {
+ fOccurrenceCount = count;
+}
+protected String tabString(int tab) {
+ StringBuffer buffer = new StringBuffer();
+ for (int i = tab; i > 0; i--)
+ buffer.append(" "/*nonNLS*/);
+ return buffer.toString();
+}
+/**
+ * @private Debugging purposes
+ */
+protected String toDebugString() {
+ StringBuffer buffer = new StringBuffer();
+ Object info = fgJavaModelManager.getInfo(this);
+ this.toStringInfo(0, buffer, info);
+ return buffer.toString();
+}
+/**
+ * @private Debugging purposes
+ */
+public String toString() {
+ StringBuffer buffer = new StringBuffer();
+ toString(0, buffer);
+ return buffer.toString();
+}
+/**
+ * @private Debugging purposes
+ */
+protected void toString(int tab, StringBuffer buffer) {
+ buffer.append(this.tabString(tab));
+ Object info = fgJavaModelManager.getInfo(this);
+ this.toStringInfo(tab, buffer, info);
+ if (tab == 0) {
+ this.toStringAncestors(buffer);
+ }
+ this.toStringChildren(tab, buffer, info);
+}
+/**
+ * @private Debugging purposes
+ */
+protected void toStringAncestors(StringBuffer buffer) {
+ JavaElement parent = (JavaElement)this.getParent();
+ if (parent != null) {
+ buffer.append(" [in "/*nonNLS*/);
+ Object parentInfo = fgJavaModelManager.getInfo(parent);
+ parent.toStringInfo(0, buffer, parentInfo);
+ parent.toStringAncestors(buffer);
+ buffer.append("]"/*nonNLS*/);
}
-
- /**
- * Updates the source end position for this element.
- * Default behaviour is to do nothing.
- */
- public void triggerSourceEndOffset(int amount, int nameStart, int nameEnd) {
+}
+/**
+ * @private Debugging purposes
+ */
+protected void toStringChildren(int tab, StringBuffer buffer, Object info) {
+ if (info == null || !(info instanceof JavaElementInfo)) return;
+ IJavaElement[] children = ((JavaElementInfo)info).getChildren();
+ for (int i = 0; i < children.length; i++) {
+ buffer.append("\n"/*nonNLS*/);
+ ((JavaElement)children[i]).toString(tab + 1, buffer);
}
-
- /**
- * Updates the source positions for this element.
- * Default behaviour is to do nothing.
- */
- public void triggerSourceRangeOffset(int amount, int nameStart, int nameEnd) {
-
+}
+/**
+ * @private Debugging purposes
+ */
+protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
+ buffer.append(getElementName());
+ if (info == null) {
+ buffer.append(" (not open)"/*nonNLS*/);
}
+}
+/**
+ * Updates the source end position for this element.
+ * Default behaviour is to do nothing.
+ */
+public void triggerSourceEndOffset(int amount, int nameStart, int nameEnd) {
+}
+/**
+ * Updates the source positions for this element.
+ * Default behaviour is to do nothing.
+ */
+public void triggerSourceRangeOffset(int amount, int nameStart, int nameEnd) {
}
+}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementDelta.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementDelta.java
index 094fc89bc4..35fd0e08dc 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementDelta.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementDelta.java
@@ -52,594 +52,518 @@ public class JavaElementDelta implements IJavaElementDelta {
/**
* Empty array of IJavaElementDelta
*/
- protected static IJavaElementDelta[] fgEmptyDelta = new IJavaElementDelta[] {
- };
-
- /**
- * Creates the root delta. To create the nested delta
- * hierarchies use the following convenience methods. The root
- * delta can be created at any level (i.e. project, package root,
- * package fragment...).
- * <ul>
- * <li><code>added(IJavaElement)</code>
- * <li><code>changed(IJavaElement)</code>
- * <li><code>moved(IJavaElement, IJavaElement)</code>
- * <li><code>removed(IJavaElement)</code>
- * <li><code>renamed(IJavaElement, IJavaElement)</code>
- * </ul>
- */
- public JavaElementDelta(IJavaElement element) {
- super();
- fChangedElement = element;
- fKind = CHANGED;
- fChangeFlags = F_CHILDREN;
- }
-
- /**
- * Adds the child delta to the collection of affected children. If the
- * child is already in the collection, walk down the hierarchy.
- */
- protected void addAffectedChild(JavaElementDelta child) {
- if (fAffectedChildren.length == 0) {
- fAffectedChildren = new IJavaElementDelta[] { child };
- return;
- }
- IJavaElementDelta sameChild = null;
- if (fAffectedChildren != null) {
- for (int i = 0; i < fAffectedChildren.length; i++) {
- if (this
- .equalsAndSameParent(
- fAffectedChildren[i].getElement(),
- child.getElement())) {
- // handle case of two jars that can be equals but not in the same project
- sameChild = fAffectedChildren[i];
- break;
- }
- }
- }
- if (sameChild == null) { //new affected child
-
- fAffectedChildren = growAndAddToArray(fAffectedChildren, child);
- } else {
- IJavaElementDelta[] children = child.getAffectedChildren();
- for (int i = 0; i < children.length; i++) {
- JavaElementDelta childsChild = (JavaElementDelta) children[i];
- ((JavaElementDelta) sameChild).addAffectedChild(childsChild);
+ protected static IJavaElementDelta[] fgEmptyDelta= new IJavaElementDelta[] {};
+/**
+ * Creates the root delta. To create the nested delta
+ * hierarchies use the following convenience methods. The root
+ * delta can be created at any level (i.e. project, package root,
+ * package fragment...).
+ * <ul>
+ * <li><code>added(IJavaElement)</code>
+ * <li><code>changed(IJavaElement)</code>
+ * <li><code>moved(IJavaElement, IJavaElement)</code>
+ * <li><code>removed(IJavaElement)</code>
+ * <li><code>renamed(IJavaElement, IJavaElement)</code>
+ * </ul>
+ */
+public JavaElementDelta(IJavaElement element) {
+ super();
+ fChangedElement = element;
+ fKind = CHANGED;
+ fChangeFlags = F_CHILDREN;
+}
+/**
+ * Adds the child delta to the collection of affected children. If the
+ * child is already in the collection, walk down the hierarchy.
+ */
+protected void addAffectedChild(JavaElementDelta child) {
+ if (fAffectedChildren.length == 0) {
+ fAffectedChildren = new IJavaElementDelta[] {child};
+ return;
+ }
+ IJavaElementDelta sameChild = null;
+ if (fAffectedChildren != null) {
+ for (int i = 0; i < fAffectedChildren.length; i++) {
+ if (this.equalsAndSameParent(fAffectedChildren[i].getElement(), child.getElement())) { // handle case of two jars that can be equals but not in the same project
+ sameChild = fAffectedChildren[i];
+ break;
}
}
}
+ if (sameChild == null) { //new affected child
- /**
- * Creates the nested deltas resulting from an add operation.
- * Convenience method for creating add deltas.
- * The constructor should be used to create the root delta
- * and then an add operation should call this method.
- */
- public void added(IJavaElement element) {
- JavaElementDelta addedDelta = new JavaElementDelta(element);
- addedDelta.fKind = ADDED;
- addedDelta.fChangeFlags = 0;
- insertDeltaTree(element, addedDelta);
- }
-
- /**
- * Adds the child delta to the collection of affected children. If the
- * child is already in the collection, walk down the hierarchy.
- */
- protected void addResourceDelta(IResourceDelta child) {
- if (resourceDeltas == null) {
- resourceDeltas = new IResourceDelta[5];
- resourceDeltas[resourceDeltasCounter++] = child;
- return;
- }
- if (resourceDeltas.length == resourceDeltasCounter) {
- // need a resize
- System.arraycopy(
- resourceDeltas,
- 0,
- (resourceDeltas = new IResourceDelta[resourceDeltasCounter * 2]),
- 0,
- resourceDeltasCounter);
+ fAffectedChildren= growAndAddToArray(fAffectedChildren, child);
+ } else {
+ IJavaElementDelta[] children = child.getAffectedChildren();
+ for (int i = 0; i < children.length; i++) {
+ JavaElementDelta childsChild = (JavaElementDelta) children[i];
+ ((JavaElementDelta) sameChild).addAffectedChild(childsChild);
}
+ }
+}
+/**
+ * Creates the nested deltas resulting from an add operation.
+ * Convenience method for creating add deltas.
+ * The constructor should be used to create the root delta
+ * and then an add operation should call this method.
+ */
+public void added(IJavaElement element) {
+ JavaElementDelta addedDelta = new JavaElementDelta(element);
+ addedDelta.fKind = ADDED;
+ addedDelta.fChangeFlags= 0;
+ insertDeltaTree(element, addedDelta);
+}
+/**
+ * Adds the child delta to the collection of affected children. If the
+ * child is already in the collection, walk down the hierarchy.
+ */
+protected void addResourceDelta(IResourceDelta child) {
+ if (resourceDeltas == null) {
+ resourceDeltas = new IResourceDelta[5];
resourceDeltas[resourceDeltasCounter++] = child;
+ return;
}
-
- /**
- * Creates the nested deltas resulting from a change operation.
- * Convenience method for creating change deltas.
- * The constructor should be used to create the root delta
- * and then a change operation should call this method.
- */
- public void changed(IJavaElement element, int changeFlag) {
- JavaElementDelta changedDelta = new JavaElementDelta(element);
- changedDelta.fKind = CHANGED;
- changedDelta.fChangeFlags = changeFlag;
- insertDeltaTree(element, changedDelta);
+ if (resourceDeltas.length == resourceDeltasCounter) {
+ // need a resize
+ System.arraycopy(resourceDeltas, 0, (resourceDeltas = new IResourceDelta[resourceDeltasCounter * 2]), 0, resourceDeltasCounter);
}
-
- /**
- * Creates the nested deltas for a closed element.
- */
- public void closed(IJavaElement element) {
- JavaElementDelta delta = new JavaElementDelta(element);
- delta.fKind = CHANGED;
- delta.fChangeFlags = F_CLOSED;
- insertDeltaTree(element, delta);
- }
-
- /**
- * Creates the nested delta deltas based on the affected element
- * its delta, and the root of this delta tree. Returns the root
- * of the created delta tree.
- */
- protected JavaElementDelta createDeltaTree(
- IJavaElement element,
- JavaElementDelta delta) {
- JavaElementDelta childDelta = delta;
- Vector ancestors = getAncestors(element);
- if (ancestors == null) {
- if (this.equalsAndSameParent(delta.getElement(), getElement())) {
- // handle case of two jars that can be equals but not in the same project
- // the element being changed is the root element
- fKind = delta.fKind;
- fChangeFlags = delta.fChangeFlags;
- fMovedToHandle = delta.fMovedToHandle;
- fMovedFromHandle = delta.fMovedFromHandle;
- } else {
- // the given delta is not the root or a child - illegal
- Assert.isTrue(false);
- }
+ resourceDeltas[resourceDeltasCounter++] = child;
+}
+/**
+ * Creates the nested deltas resulting from a change operation.
+ * Convenience method for creating change deltas.
+ * The constructor should be used to create the root delta
+ * and then a change operation should call this method.
+ */
+public void changed(IJavaElement element, int changeFlag) {
+ JavaElementDelta changedDelta = new JavaElementDelta(element);
+ changedDelta.fKind = CHANGED;
+ changedDelta.fChangeFlags = changeFlag;
+ insertDeltaTree(element, changedDelta);
+}
+/**
+ * Creates the nested deltas for a closed element.
+ */
+public void closed(IJavaElement element) {
+ JavaElementDelta delta = new JavaElementDelta(element);
+ delta.fKind = CHANGED;
+ delta.fChangeFlags= F_CLOSED;
+ insertDeltaTree(element, delta);
+}
+/**
+ * Creates the nested delta deltas based on the affected element
+ * its delta, and the root of this delta tree. Returns the root
+ * of the created delta tree.
+ */
+protected JavaElementDelta createDeltaTree(IJavaElement element, JavaElementDelta delta) {
+ JavaElementDelta childDelta = delta;
+ Vector ancestors= getAncestors(element);
+ if (ancestors == null) {
+ if (this.equalsAndSameParent(delta.getElement(), getElement())) { // handle case of two jars that can be equals but not in the same project
+ // the element being changed is the root element
+ fKind= delta.fKind;
+ fChangeFlags= delta.fChangeFlags;
+ fMovedToHandle= delta.fMovedToHandle;
+ fMovedFromHandle= delta.fMovedFromHandle;
} else {
- for (int i = 0, size = ancestors.size(); i < size; i++) {
- IJavaElement ancestor = (IJavaElement) ancestors.elementAt(i);
- JavaElementDelta ancestorDelta = new JavaElementDelta(ancestor);
- ancestorDelta.addAffectedChild(childDelta);
- ancestorDelta.fKind = CHANGED;
- ancestorDelta.fChangeFlags = F_CHILDREN;
- childDelta = ancestorDelta;
- }
+ // the given delta is not the root or a child - illegal
+ Assert.isTrue(false);
+ }
+ } else {
+ for (int i = 0, size = ancestors.size(); i < size; i++) {
+ IJavaElement ancestor = (IJavaElement) ancestors.elementAt(i);
+ JavaElementDelta ancestorDelta = new JavaElementDelta(ancestor);
+ ancestorDelta.addAffectedChild(childDelta);
+ ancestorDelta.fKind = CHANGED;
+ ancestorDelta.fChangeFlags = F_CHILDREN;
+ childDelta = ancestorDelta;
}
- return childDelta;
- }
-
- /**
- * Returns whether the two java elements are equals and have the same parent.
- */
- protected boolean equalsAndSameParent(IJavaElement e1, IJavaElement e2) {
- IJavaElement parent1;
- return e1.equals(e2)
- && ((parent1 = e1.getParent()) != null)
- && parent1.equals(e2.getParent());
}
-
- /**
- * Returns the <code>JavaElementDelta</code> for the given element
- * in the delta tree, or null, if no delta for the given element is found.
- */
- protected JavaElementDelta find(IJavaElement e) {
- if (this.equalsAndSameParent(fChangedElement, e)) {
- // handle case of two jars that can be equals but not in the same project
- return this;
- } else {
- for (int i = 0; i < fAffectedChildren.length; i++) {
- JavaElementDelta delta = ((JavaElementDelta) fAffectedChildren[i]).find(e);
- if (delta != null) {
- return delta;
- }
+ return childDelta;
+}
+/**
+ * Returns whether the two java elements are equals and have the same parent.
+ */
+protected boolean equalsAndSameParent(IJavaElement e1, IJavaElement e2) {
+ IJavaElement parent1;
+ return e1.equals(e2) && ((parent1 = e1.getParent()) != null) && parent1.equals(e2.getParent());
+}
+/**
+ * Returns the <code>JavaElementDelta</code> for the given element
+ * in the delta tree, or null, if no delta for the given element is found.
+ */
+protected JavaElementDelta find(IJavaElement e) {
+ if (this.equalsAndSameParent(fChangedElement, e)) { // handle case of two jars that can be equals but not in the same project
+ return this;
+ } else {
+ for (int i = 0; i < fAffectedChildren.length; i++) {
+ JavaElementDelta delta = ((JavaElementDelta)fAffectedChildren[i]).find(e);
+ if (delta != null) {
+ return delta;
}
}
- return null;
- }
-
- /**
- * @see IJavaElementDelta
- */
- public IJavaElementDelta[] getAddedChildren() {
- return getChildrenOfType(ADDED);
}
-
- /**
- * @see IJavaElementDelta
- */
- public IJavaElementDelta[] getAffectedChildren() {
- return fAffectedChildren;
+ return null;
+}
+/**
+ * @see IJavaElementDelta
+ */
+public IJavaElementDelta[] getAddedChildren() {
+ return getChildrenOfType(ADDED);
+}
+/**
+ * @see IJavaElementDelta
+ */
+public IJavaElementDelta[] getAffectedChildren() {
+ return fAffectedChildren;
+}
+/**
+ * Returns a collection of all the parents of this element up to (but
+ * not including) the root of this tree in bottom-up order. If the given
+ * element is not a descendant of the root of this tree, <code>null</code>
+ * is returned.
+ */
+private Vector getAncestors(IJavaElement element) {
+ IJavaElement parent = element.getParent();
+ if (parent == null) {
+ return null;
}
-
- /**
- * Returns a collection of all the parents of this element up to (but
- * not including) the root of this tree in bottom-up order. If the given
- * element is not a descendant of the root of this tree, <code>null</code>
- * is returned.
- */
- private Vector getAncestors(IJavaElement element) {
- IJavaElement parent = element.getParent();
+ Vector parents = new Vector();
+ while (!parent.equals(fChangedElement)) {
+ parents.addElement(parent);
+ parent = parent.getParent();
if (parent == null) {
return null;
}
- Vector parents = new Vector();
- while (!parent.equals(fChangedElement)) {
- parents.addElement(parent);
- parent = parent.getParent();
- if (parent == null) {
- return null;
- }
- }
- parents.trimToSize();
- return parents;
- }
-
- /**
- * @see IJavaElementDelta
- */
- public IJavaElementDelta[] getChangedChildren() {
- return getChildrenOfType(CHANGED);
}
-
- /**
- * @see IJavaElementDelta
- */
- protected IJavaElementDelta[] getChildrenOfType(int type) {
- int length = fAffectedChildren.length;
- if (length == 0) {
- return new IJavaElementDelta[] {
- };
- }
- Vector children = new Vector(length);
- for (int i = 0; i < length; i++) {
- if (fAffectedChildren[i].getKind() == type) {
- children.addElement(fAffectedChildren[i]);
- }
+ parents.trimToSize();
+ return parents;
+}
+/**
+ * @see IJavaElementDelta
+ */
+public IJavaElementDelta[] getChangedChildren() {
+ return getChildrenOfType(CHANGED);
+}
+/**
+ * @see IJavaElementDelta
+ */
+protected IJavaElementDelta[] getChildrenOfType(int type) {
+ int length = fAffectedChildren.length;
+ if (length == 0) {
+ return new IJavaElementDelta[] {};
+ }
+ Vector children= new Vector(length);
+ for (int i = 0; i < length; i++) {
+ if (fAffectedChildren[i].getKind() == type) {
+ children.addElement(fAffectedChildren[i]);
}
-
- IJavaElementDelta[] childrenOfType = new IJavaElementDelta[children.size()];
- children.copyInto(childrenOfType);
-
- return childrenOfType;
}
- /**
- * Returns the delta for a given element. Only looks below this
- * delta.
- */
- protected JavaElementDelta getDeltaFor(IJavaElement element) {
- if (this.equalsAndSameParent(getElement(), element))
- // handle case of two jars that can be equals but not in the same project
- return this;
- if (fAffectedChildren.length == 0)
- return null;
- int childrenCount = fAffectedChildren.length;
- for (int i = 0; i < childrenCount; i++) {
- JavaElementDelta delta = (JavaElementDelta) fAffectedChildren[i];
- if (this.equalsAndSameParent(delta.getElement(), element)) {
- // handle case of two jars that can be equals but not in the same project
- return delta;
- } else {
- delta = ((JavaElementDelta) delta).getDeltaFor(element);
- if (delta != null)
- return delta;
- }
- }
+ IJavaElementDelta[] childrenOfType = new IJavaElementDelta[children.size()];
+ children.copyInto(childrenOfType);
+
+ return childrenOfType;
+}
+/**
+ * Returns the delta for a given element. Only looks below this
+ * delta.
+ */
+protected JavaElementDelta getDeltaFor(IJavaElement element) {
+ if (this.equalsAndSameParent(getElement(), element)) // handle case of two jars that can be equals but not in the same project
+ return this;
+ if (fAffectedChildren.length == 0)
return null;
- }
-
- /**
- * @see IJavaElementDelta
- */
- public IJavaElement getElement() {
- return fChangedElement;
- }
-
- /**
- * @see IJavaElementDelta
- */
- public int getFlags() {
- return fChangeFlags;
- }
-
- /**
- * @see IJavaElementDelta
- */
- public int getKind() {
- return fKind;
- }
-
- /**
- * @see IJavaElementDelta
- */
- public IJavaElement getMovedFromElement() {
- return fMovedFromHandle;
- }
-
- /**
- * @see IJavaElementDelta
- */
- public IJavaElement getMovedToElement() {
- return fMovedToHandle;
- }
-
- /**
- * @see IJavaElementDelta
- */
- public IJavaElementDelta[] getRemovedChildren() {
- return getChildrenOfType(REMOVED);
- }
-
- /**
- * Return the collection of resource deltas. Return null if none.
- */
- public IResourceDelta[] getResourceDeltas() {
- if (resourceDeltas == null)
- return null;
- if (resourceDeltas.length != resourceDeltasCounter) {
- System.arraycopy(
- resourceDeltas,
- 0,
- resourceDeltas = new IResourceDelta[resourceDeltasCounter],
- 0,
- resourceDeltasCounter);
- }
- return resourceDeltas;
- }
-
- /**
- * Adds the new element to a new array that contains all of the elements of the old array.
- * Returns the new array.
- */
- protected IJavaElementDelta[] growAndAddToArray(
- IJavaElementDelta[] array,
- IJavaElementDelta addition) {
- IJavaElementDelta[] old = array;
- array = new IJavaElementDelta[old.length + 1];
- System.arraycopy(old, 0, array, 0, old.length);
- array[old.length] = addition;
- return array;
- }
-
- /**
- * Creates the delta tree for the given element and delta, and then
- * inserts the tree as an affected child of this node.
- */
- protected void insertDeltaTree(IJavaElement element, JavaElementDelta delta) {
- JavaElementDelta childDelta = createDeltaTree(element, delta);
- if (!this.equalsAndSameParent(element, getElement())) {
- // handle case of two jars that can be equals but not in the same project
- addAffectedChild(childDelta);
+ int childrenCount = fAffectedChildren.length;
+ for (int i = 0; i < childrenCount; i++) {
+ JavaElementDelta delta = (JavaElementDelta)fAffectedChildren[i];
+ if (this.equalsAndSameParent(delta.getElement(), element)) { // handle case of two jars that can be equals but not in the same project
+ return delta;
+ } else {
+ delta = ((JavaElementDelta)delta).getDeltaFor(element);
+ if (delta != null)
+ return delta;
}
}
-
- /**
- * Creates the nested deltas resulting from an move operation.
- * Convenience method for creating the "move from" delta.
- * The constructor should be used to create the root delta
- * and then the move operation should call this method.
- */
- public void movedFrom(
- IJavaElement movedFromElement,
- IJavaElement movedToElement) {
- JavaElementDelta removedDelta = new JavaElementDelta(movedFromElement);
- removedDelta.fKind = REMOVED;
- removedDelta.fChangeFlags = F_MOVED_TO;
- removedDelta.fMovedToHandle = movedToElement;
- insertDeltaTree(movedFromElement, removedDelta);
- }
-
- /**
- * Creates the nested deltas resulting from an move operation.
- * Convenience method for creating the "move to" delta.
- * The constructor should be used to create the root delta
- * and then the move operation should call this method.
- */
- public void movedTo(
- IJavaElement movedToElement,
- IJavaElement movedFromElement) {
- JavaElementDelta addedDelta = new JavaElementDelta(movedToElement);
- addedDelta.fKind = ADDED;
- addedDelta.fChangeFlags = F_MOVED_FROM;
- addedDelta.fMovedFromHandle = movedFromElement;
- insertDeltaTree(movedToElement, addedDelta);
+ return null;
+}
+/**
+ * @see IJavaElementDelta
+ */
+public IJavaElement getElement() {
+ return fChangedElement;
+}
+/**
+ * @see IJavaElementDelta
+ */
+public int getFlags() {
+ return fChangeFlags;
+}
+/**
+ * @see IJavaElementDelta
+ */
+public int getKind() {
+ return fKind;
+}
+/**
+ * @see IJavaElementDelta
+ */
+public IJavaElement getMovedFromElement() {
+ return fMovedFromHandle;
+}
+/**
+ * @see IJavaElementDelta
+ */
+public IJavaElement getMovedToElement() {
+ return fMovedToHandle;
+}
+/**
+ * @see IJavaElementDelta
+ */
+public IJavaElementDelta[] getRemovedChildren() {
+ return getChildrenOfType(REMOVED);
+}
+/**
+ * Return the collection of resource deltas. Return null if none.
+ */
+public IResourceDelta[] getResourceDeltas() {
+ if (resourceDeltas == null) return null;
+ if (resourceDeltas.length != resourceDeltasCounter) {
+ System.arraycopy(resourceDeltas, 0, resourceDeltas = new IResourceDelta[resourceDeltasCounter], 0, resourceDeltasCounter);
}
-
- /**
- * Creates the nested deltas for an opened element.
- */
- public void opened(IJavaElement element) {
- JavaElementDelta delta = new JavaElementDelta(element);
- delta.fKind = CHANGED;
- delta.fChangeFlags = F_OPENED;
- insertDeltaTree(element, delta);
+ return resourceDeltas;
+}
+/**
+ * Adds the new element to a new array that contains all of the elements of the old array.
+ * Returns the new array.
+ */
+protected IJavaElementDelta[] growAndAddToArray(IJavaElementDelta[] array, IJavaElementDelta addition) {
+ IJavaElementDelta[] old = array;
+ array = new IJavaElementDelta[old.length + 1];
+ System.arraycopy(old, 0, array, 0, old.length);
+ array[old.length] = addition;
+ return array;
+}
+/**
+ * Creates the delta tree for the given element and delta, and then
+ * inserts the tree as an affected child of this node.
+ */
+protected void insertDeltaTree(IJavaElement element, JavaElementDelta delta) {
+ JavaElementDelta childDelta= createDeltaTree(element, delta);
+ if (!this.equalsAndSameParent(element, getElement())) { // handle case of two jars that can be equals but not in the same project
+ addAffectedChild(childDelta);
}
-
- /**
- * Removes the child delta from the collection of affected children.
- */
- protected void removeAffectedChild(JavaElementDelta child) {
- int index = -1;
- if (fAffectedChildren != null) {
- for (int i = 0; i < fAffectedChildren.length; i++) {
- if (this
- .equalsAndSameParent(
- fAffectedChildren[i].getElement(),
- child.getElement())) {
- // handle case of two jars that can be equals but not in the same project
- index = i;
- break;
- }
+}
+/**
+ * Creates the nested deltas resulting from an move operation.
+ * Convenience method for creating the "move from" delta.
+ * The constructor should be used to create the root delta
+ * and then the move operation should call this method.
+ */
+public void movedFrom(IJavaElement movedFromElement, IJavaElement movedToElement) {
+ JavaElementDelta removedDelta = new JavaElementDelta(movedFromElement);
+ removedDelta.fKind = REMOVED;
+ removedDelta.fChangeFlags = F_MOVED_TO;
+ removedDelta.fMovedToHandle = movedToElement;
+ insertDeltaTree(movedFromElement, removedDelta);
+}
+/**
+ * Creates the nested deltas resulting from an move operation.
+ * Convenience method for creating the "move to" delta.
+ * The constructor should be used to create the root delta
+ * and then the move operation should call this method.
+ */
+public void movedTo(IJavaElement movedToElement, IJavaElement movedFromElement) {
+ JavaElementDelta addedDelta = new JavaElementDelta(movedToElement);
+ addedDelta.fKind = ADDED;
+ addedDelta.fChangeFlags = F_MOVED_FROM;
+ addedDelta.fMovedFromHandle = movedFromElement;
+ insertDeltaTree(movedToElement, addedDelta);
+}
+/**
+ * Creates the nested deltas for an opened element.
+ */
+public void opened(IJavaElement element) {
+ JavaElementDelta delta = new JavaElementDelta(element);
+ delta.fKind = CHANGED;
+ delta.fChangeFlags= F_OPENED;
+ insertDeltaTree(element, delta);
+}
+/**
+ * Removes the child delta from the collection of affected children.
+ */
+protected void removeAffectedChild(JavaElementDelta child) {
+ int index = -1;
+ if (fAffectedChildren != null) {
+ for (int i = 0; i < fAffectedChildren.length; i++) {
+ if (this.equalsAndSameParent(fAffectedChildren[i].getElement(), child.getElement())) { // handle case of two jars that can be equals but not in the same project
+ index = i;
+ break;
}
}
- if (index >= 0) {
- fAffectedChildren = removeAndShrinkArray(fAffectedChildren, index);
- }
}
-
- /**
- * Removes the element from the array.
- * Returns the a new array which has shrunk.
- */
- protected IJavaElementDelta[] removeAndShrinkArray(
- IJavaElementDelta[] old,
- int index) {
- IJavaElementDelta[] array = new IJavaElementDelta[old.length - 1];
- if (index > 0)
- System.arraycopy(old, 0, array, 0, index);
- int rest = old.length - index - 1;
- if (rest > 0)
- System.arraycopy(old, index + 1, array, index, rest);
- return array;
+ if (index >= 0) {
+ fAffectedChildren= removeAndShrinkArray(fAffectedChildren, index);
}
-
- /**
- * Creates the nested deltas resulting from an delete operation.
- * Convenience method for creating removed deltas.
- * The constructor should be used to create the root delta
- * and then the delete operation should call this method.
- */
- public void removed(IJavaElement element) {
- JavaElementDelta removedDelta = new JavaElementDelta(element);
- insertDeltaTree(element, removedDelta);
- JavaElementDelta actualDelta = getDeltaFor(element);
- if (actualDelta != null) {
- actualDelta.fKind = REMOVED;
- actualDelta.fChangeFlags = 0;
- actualDelta.fAffectedChildren = fgEmptyDelta;
- }
- }
-
- /**
- * Sets the change flags of this delta.
- */
- protected void setFlags(int flags) {
- fChangeFlags = flags;
- }
-
- /**
- * Creates the nested deltas resulting from a change operation.
- * Convenience method for creating change deltas.
- * The constructor should be used to create the root delta
- * and then a change operation should call this method.
- */
- public void sourceAttached(IJavaElement element) {
- JavaElementDelta attachedDelta = new JavaElementDelta(element);
- attachedDelta.fKind = CHANGED;
- attachedDelta.fChangeFlags = F_SOURCEATTACHED;
- insertDeltaTree(element, attachedDelta);
- }
-
- /**
- * Creates the nested deltas resulting from a change operation.
- * Convenience method for creating change deltas.
- * The constructor should be used to create the root delta
- * and then a change operation should call this method.
- */
- public void sourceDetached(IJavaElement element) {
- JavaElementDelta detachedDelta = new JavaElementDelta(element);
- detachedDelta.fKind = CHANGED;
- detachedDelta.fChangeFlags = F_SOURCEDETACHED;
- insertDeltaTree(element, detachedDelta);
+}
+/**
+ * Removes the element from the array.
+ * Returns the a new array which has shrunk.
+ */
+protected IJavaElementDelta[] removeAndShrinkArray(IJavaElementDelta[] old, int index) {
+ IJavaElementDelta[] array = new IJavaElementDelta[old.length - 1];
+ if (index > 0)
+ System.arraycopy(old, 0, array, 0, index);
+ int rest = old.length - index - 1;
+ if (rest > 0)
+ System.arraycopy(old, index + 1, array, index, rest);
+ return array;
+}
+/**
+ * Creates the nested deltas resulting from an delete operation.
+ * Convenience method for creating removed deltas.
+ * The constructor should be used to create the root delta
+ * and then the delete operation should call this method.
+ */
+public void removed(IJavaElement element) {
+ JavaElementDelta removedDelta= new JavaElementDelta(element);
+ insertDeltaTree(element, removedDelta);
+ JavaElementDelta actualDelta = getDeltaFor(element);
+ if (actualDelta != null) {
+ actualDelta.fKind= REMOVED;
+ actualDelta.fChangeFlags= 0;
+ actualDelta.fAffectedChildren = fgEmptyDelta;
}
-
- /**
- * Returns a string representation of this delta's
- * structure suitable for debug purposes.
- *
- * @see toString
- */
- public String toDebugString(int depth) {
- StringBuffer buffer = new StringBuffer();
- for (int i = 0; i < depth; i++) {
- buffer.append('\t');
- }
- buffer.append(((JavaElement) getElement()).toDebugString());
- buffer.append("[");
- switch (getKind()) {
- case IJavaElementDelta.ADDED :
- buffer.append('+');
- break;
- case IJavaElementDelta.REMOVED :
- buffer.append('-');
- break;
- case IJavaElementDelta.CHANGED :
- buffer.append('*');
- break;
- default :
- buffer.append('?');
- break;
- }
- buffer.append("]: {");
- int changeFlags = getFlags();
- boolean prev = false;
- if ((changeFlags & IJavaElementDelta.F_CHILDREN) != 0) {
- if (prev)
- buffer.append(" | ");
- buffer.append("CHILDREN");
- prev = true;
- }
- if ((changeFlags & IJavaElementDelta.F_CONTENT) != 0) {
- if (prev)
- buffer.append(" | ");
- buffer.append("CONTENT");
- prev = true;
- }
- if ((changeFlags & IJavaElementDelta.F_MOVED_FROM) != 0) {
- if (prev)
- buffer.append(" | ");
- buffer.append(
- "MOVED_FROM(" + ((JavaElement) getMovedFromElement()).toDebugString() + ")");
- prev = true;
- }
- if ((changeFlags & IJavaElementDelta.F_MOVED_TO) != 0) {
- if (prev)
- buffer.append(" | ");
- buffer.append(
- "MOVED_TO(" + ((JavaElement) getMovedToElement()).toDebugString() + ")");
- prev = true;
- }
- if ((changeFlags & IJavaElementDelta.F_ADDED_TO_CLASSPATH) != 0) {
- if (prev)
- buffer.append(" | ");
- buffer.append("ADDED TO CLASSPATH");
- prev = true;
- }
- if ((changeFlags & IJavaElementDelta.F_REMOVED_FROM_CLASSPATH) != 0) {
- if (prev)
- buffer.append(" | ");
- buffer.append("REMOVED FROM CLASSPATH");
- prev = true;
- }
- if ((changeFlags & IJavaElementDelta.F_CLASSPATH_REORDER) != 0) {
- if (prev)
- buffer.append(" | ");
- buffer.append("REORDERED IN CLASSPATH");
- prev = true;
- }
- if ((changeFlags & IJavaElementDelta.F_MODIFIERS) != 0) {
- if (prev)
- buffer.append(" | ");
- buffer.append("MODIFIERS CHANGED");
- prev = true;
- }
- if ((changeFlags & IJavaElementDelta.F_SUPER_TYPES) != 0) {
- if (prev)
- buffer.append(" | ");
- buffer.append("SUPER TYPES CHANGED");
- prev = true;
- }
- buffer.append("}");
- IJavaElementDelta[] children = getAffectedChildren();
- if (children != null) {
- for (int i = 0; i < children.length; ++i) {
- buffer.append("\n");
- buffer.append(((JavaElementDelta) children[i]).toDebugString(depth + 1));
- }
+}
+/**
+ * Sets the change flags of this delta.
+ */
+protected void setFlags(int flags) {
+ fChangeFlags = flags;
+}
+/**
+ * Creates the nested deltas resulting from a change operation.
+ * Convenience method for creating change deltas.
+ * The constructor should be used to create the root delta
+ * and then a change operation should call this method.
+ */
+public void sourceAttached(IJavaElement element) {
+ JavaElementDelta attachedDelta = new JavaElementDelta(element);
+ attachedDelta.fKind = CHANGED;
+ attachedDelta.fChangeFlags = F_SOURCEATTACHED;
+ insertDeltaTree(element, attachedDelta);
+}
+/**
+ * Creates the nested deltas resulting from a change operation.
+ * Convenience method for creating change deltas.
+ * The constructor should be used to create the root delta
+ * and then a change operation should call this method.
+ */
+public void sourceDetached(IJavaElement element) {
+ JavaElementDelta detachedDelta = new JavaElementDelta(element);
+ detachedDelta.fKind = CHANGED;
+ detachedDelta.fChangeFlags = F_SOURCEDETACHED;
+ insertDeltaTree(element, detachedDelta);
+}
+/**
+ * Returns a string representation of this delta's
+ * structure suitable for debug purposes.
+ *
+ * @see toString
+ */
+public String toDebugString(int depth) {
+ StringBuffer buffer = new StringBuffer();
+ for (int i= 0; i < depth; i++) {
+ buffer.append('\t');
+ }
+ buffer.append(((JavaElement)getElement()).toDebugString());
+ buffer.append("["/*nonNLS*/);
+ switch (getKind()) {
+ case IJavaElementDelta.ADDED :
+ buffer.append('+');
+ break;
+ case IJavaElementDelta.REMOVED :
+ buffer.append('-');
+ break;
+ case IJavaElementDelta.CHANGED :
+ buffer.append('*');
+ break;
+ default :
+ buffer.append('?');
+ break;
+ }
+ buffer.append("]: {"/*nonNLS*/);
+ int changeFlags = getFlags();
+ boolean prev = false;
+ if ((changeFlags & IJavaElementDelta.F_CHILDREN) != 0) {
+ if (prev)
+ buffer.append(" | "/*nonNLS*/);
+ buffer.append("CHILDREN"/*nonNLS*/);
+ prev = true;
+ }
+ if ((changeFlags & IJavaElementDelta.F_CONTENT) != 0) {
+ if (prev)
+ buffer.append(" | "/*nonNLS*/);
+ buffer.append("CONTENT"/*nonNLS*/);
+ prev = true;
+ }
+ if ((changeFlags & IJavaElementDelta.F_MOVED_FROM) != 0) {
+ if (prev)
+ buffer.append(" | "/*nonNLS*/);
+ buffer.append("MOVED_FROM("/*nonNLS*/ + ((JavaElement)getMovedFromElement()).toDebugString() + ")"/*nonNLS*/);
+ prev = true;
+ }
+ if ((changeFlags & IJavaElementDelta.F_MOVED_TO) != 0) {
+ if (prev)
+ buffer.append(" | "/*nonNLS*/);
+ buffer.append("MOVED_TO("/*nonNLS*/ + ((JavaElement)getMovedToElement()).toDebugString() + ")"/*nonNLS*/);
+ prev = true;
+ }
+ if ((changeFlags & IJavaElementDelta.F_ADDED_TO_CLASSPATH) != 0) {
+ if (prev)
+ buffer.append(" | "/*nonNLS*/);
+ buffer.append("ADDED TO CLASSPATH"/*nonNLS*/);
+ prev = true;
+ }
+ if ((changeFlags & IJavaElementDelta.F_REMOVED_FROM_CLASSPATH) != 0) {
+ if (prev)
+ buffer.append(" | "/*nonNLS*/);
+ buffer.append("REMOVED FROM CLASSPATH"/*nonNLS*/);
+ prev = true;
+ }
+ if ((changeFlags & IJavaElementDelta.F_CLASSPATH_REORDER) != 0) {
+ if (prev)
+ buffer.append(" | "/*nonNLS*/);
+ buffer.append("REORDERED IN CLASSPATH"/*nonNLS*/);
+ prev = true;
+ }
+ if ((changeFlags & IJavaElementDelta.F_MODIFIERS) != 0) {
+ if (prev)
+ buffer.append(" | "/*nonNLS*/);
+ buffer.append("MODIFIERS CHANGED"/*nonNLS*/);
+ prev = true;
+ }
+ if ((changeFlags & IJavaElementDelta.F_SUPER_TYPES) != 0) {
+ if (prev)
+ buffer.append(" | "/*nonNLS*/);
+ buffer.append("SUPER TYPES CHANGED"/*nonNLS*/);
+ prev = true;
+ }
+ buffer.append("}"/*nonNLS*/);
+ IJavaElementDelta[] children = getAffectedChildren();
+ if (children != null) {
+ for (int i = 0; i < children.length; ++i) {
+ buffer.append("\n"/*nonNLS*/);
+ buffer.append(((JavaElementDelta) children[i]).toDebugString(depth + 1));
}
- return buffer.toString();
- }
-
- /**
- * Returns a string representation of this delta's
- * structure suitable for debug purposes.
- */
- public String toString() {
- return toDebugString(0);
}
-
+ return buffer.toString();
+}
+/**
+ * Returns a string representation of this delta's
+ * structure suitable for debug purposes.
+ */
+public String toString() {
+ return toDebugString(0);
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementDeltaBuilder.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementDeltaBuilder.java
index 55ff78c486..3a9be1d0d8 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementDeltaBuilder.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementDeltaBuilder.java
@@ -62,7 +62,7 @@ public class JavaElementDeltaBuilder {
* List of removed elements
*/
Vector removed;
-
+
/**
* Doubly linked list item
*/
@@ -75,425 +75,371 @@ public class JavaElementDeltaBuilder {
this.next = next;
}
}
-
- /**
- * Creates a java element comparator on a java element
- * looking as deep as necessary.
- */
- public JavaElementDeltaBuilder(IJavaElement javaElement) {
- this.javaElement = javaElement;
- this.initialize();
- this.recordElementInfo(
- javaElement,
- (JavaModel) this.javaElement.getJavaModel(),
- 0);
+/**
+ * Creates a java element comparator on a java element
+ * looking as deep as necessary.
+ */
+public JavaElementDeltaBuilder(IJavaElement javaElement) {
+ this.javaElement = javaElement;
+ this.initialize();
+ this.recordElementInfo(
+ javaElement,
+ (JavaModel)this.javaElement.getJavaModel(),
+ 0);
+}
+/**
+ * Creates a java element comparator on a java element
+ * looking only 'maxDepth' levels deep.
+ */
+public JavaElementDeltaBuilder(IJavaElement javaElement, int maxDepth) {
+ this.javaElement = javaElement;
+ this.maxDepth = maxDepth;
+ this.initialize();
+ this.recordElementInfo(
+ javaElement,
+ (JavaModel)this.javaElement.getJavaModel(),
+ 0);
+}
+/**
+ * Repairs the positioning information
+ * after an element has been added
+ */
+private void added(IJavaElement element) {
+ this.added.addElement(element);
+ ListItem current = this.getNewPosition(element);
+ ListItem previous = null, next = null;
+ if (current.previous != null)
+ previous = this.getNewPosition(current.previous);
+ if (current.next != null)
+ next = this.getNewPosition(current.next);
+ if (previous != null)
+ previous.next = current.next;
+ if (next != null)
+ next.previous = current.previous;
+}
+/**
+ * Builds the java element deltas between the old content of the compilation
+ * unit and its new content.
+ */
+public void buildDeltas() {
+ this.recordNewPositions(this.javaElement, 0);
+ this.findAdditions(this.javaElement, 0);
+ this.findDeletions();
+ this.findChangesInPositioning(this.javaElement, 0);
+ this.trimDelta(this.delta);
+}
+/**
+ * Finds elements which have been added or changed.
+ */
+private void findAdditions(IJavaElement newElement, int depth) {
+ JavaElementInfo oldInfo = this.getElementInfo(newElement);
+ if (oldInfo == null && depth < this.maxDepth) {
+ this.delta.added(newElement);
+ added(newElement);
+ } else {
+ this.removeElementInfo(newElement);
}
-
- /**
- * Creates a java element comparator on a java element
- * looking only 'maxDepth' levels deep.
- */
- public JavaElementDeltaBuilder(IJavaElement javaElement, int maxDepth) {
- this.javaElement = javaElement;
- this.maxDepth = maxDepth;
- this.initialize();
- this.recordElementInfo(
- javaElement,
- (JavaModel) this.javaElement.getJavaModel(),
- 0);
+
+ if (depth >= this.maxDepth) {
+ // mark element as changed
+ this.delta.changed(newElement, IJavaElementDelta.F_CONTENT);
+ return;
}
- /**
- * Repairs the positioning information
- * after an element has been added
- */
- private void added(IJavaElement element) {
- this.added.addElement(element);
- ListItem current = this.getNewPosition(element);
- ListItem previous = null, next = null;
- if (current.previous != null)
- previous = this.getNewPosition(current.previous);
- if (current.next != null)
- next = this.getNewPosition(current.next);
- if (previous != null)
- previous.next = current.next;
- if (next != null)
- next.previous = current.previous;
+ JavaElementInfo newInfo = null;
+ try {
+ newInfo = ((JavaElement)newElement).getElementInfo();
+ } catch (JavaModelException npe) {
+ return;
}
-
- /**
- * Builds the java element deltas between the old content of the compilation
- * unit and its new content.
- */
- public void buildDeltas() {
- this.recordNewPositions(this.javaElement, 0);
- this.findAdditions(this.javaElement, 0);
- this.findDeletions();
- this.findChangesInPositioning(this.javaElement, 0);
- this.trimDelta(this.delta);
+
+ this.findContentChange(oldInfo, newInfo, newElement);
+
+ if (oldInfo != null && newElement instanceof IParent) {
+
+ IJavaElement[] children = newInfo.getChildren();
+ if (children != null) {
+ int length = children.length;
+ for(int i = 0; i < length; i++) {
+ this.findAdditions(children[i], depth + 1);
+ }
+ }
}
-
- /**
- * Finds elements which have been added or changed.
- */
- private void findAdditions(IJavaElement newElement, int depth) {
- JavaElementInfo oldInfo = this.getElementInfo(newElement);
- if (oldInfo == null && depth < this.maxDepth) {
- this.delta.added(newElement);
- added(newElement);
- } else {
- this.removeElementInfo(newElement);
- }
-
- if (depth >= this.maxDepth) {
- // mark element as changed
- this.delta.changed(newElement, IJavaElementDelta.F_CONTENT);
- return;
- }
-
- JavaElementInfo newInfo = null;
- try {
- newInfo = ((JavaElement) newElement).getElementInfo();
+}
+/**
+ * Looks for changed positioning of elements.
+ */
+private void findChangesInPositioning(IJavaElement element, int depth) {
+ if (depth >= this.maxDepth || this.added.contains(element) || this.removed.contains(element))
+ return;
+
+ if (!isPositionedCorrectly(element)) {
+ this.delta.removed(element);
+ this.delta.added(element);
+ }
+
+ if (element instanceof IParent) {
+ JavaElementInfo info = null;
+ try {
+ info = ((JavaElement)element).getElementInfo();
} catch (JavaModelException npe) {
return;
}
- this.findContentChange(oldInfo, newInfo, newElement);
-
- if (oldInfo != null && newElement instanceof IParent) {
-
- IJavaElement[] children = newInfo.getChildren();
- if (children != null) {
- int length = children.length;
- for (int i = 0; i < length; i++) {
- this.findAdditions(children[i], depth + 1);
- }
+ IJavaElement[] children = info.getChildren();
+ if (children != null) {
+ int length = children.length;
+ for(int i = 0; i < length; i++) {
+ this.findChangesInPositioning(children[i], depth + 1);
}
- }
+ }
}
-
- /**
- * Looks for changed positioning of elements.
- */
- private void findChangesInPositioning(IJavaElement element, int depth) {
- if (depth >= this.maxDepth
- || this.added.contains(element)
- || this.removed.contains(element))
- return;
-
- if (!isPositionedCorrectly(element)) {
- this.delta.removed(element);
- this.delta.added(element);
- }
-
- if (element instanceof IParent) {
- JavaElementInfo info = null;
- try {
- info = ((JavaElement) element).getElementInfo();
- } catch (JavaModelException npe) {
- return;
- }
-
- IJavaElement[] children = info.getChildren();
- if (children != null) {
- int length = children.length;
- for (int i = 0; i < length; i++) {
- this.findChangesInPositioning(children[i], depth + 1);
- }
+}
+/**
+ * The elements are equivalent, but might have content changes.
+ */
+private void findContentChange(JavaElementInfo oldInfo, JavaElementInfo newInfo, IJavaElement newElement) {
+ if (oldInfo instanceof MemberElementInfo && newInfo instanceof MemberElementInfo) {
+ if (((MemberElementInfo)oldInfo).getModifiers() != ((MemberElementInfo)newInfo).getModifiers()) {
+ this.delta.changed(newElement, IJavaElementDelta.F_MODIFIERS);
+ } else if (oldInfo instanceof SourceMethodElementInfo && newInfo instanceof SourceMethodElementInfo) {
+ if (!CharOperation.equals(
+ ((SourceMethodElementInfo)oldInfo).getReturnTypeName(),
+ ((SourceMethodElementInfo)newInfo).getReturnTypeName())) {
+ this.delta.changed(newElement, IJavaElementDelta.F_CONTENT);
}
- }
- }
-
- /**
- * The elements are equivalent, but might have content changes.
- */
- private void findContentChange(
- JavaElementInfo oldInfo,
- JavaElementInfo newInfo,
- IJavaElement newElement) {
- if (oldInfo instanceof MemberElementInfo
- && newInfo instanceof MemberElementInfo) {
- if (((MemberElementInfo) oldInfo).getModifiers()
- != ((MemberElementInfo) newInfo).getModifiers()) {
- this.delta.changed(newElement, IJavaElementDelta.F_MODIFIERS);
- } else
- if (oldInfo instanceof SourceMethodElementInfo
- && newInfo instanceof SourceMethodElementInfo) {
- if (!CharOperation
- .equals(
- ((SourceMethodElementInfo) oldInfo).getReturnTypeName(),
- ((SourceMethodElementInfo) newInfo).getReturnTypeName())) {
- this.delta.changed(newElement, IJavaElementDelta.F_CONTENT);
- }
- } else
- if (oldInfo instanceof SourceFieldElementInfo
- && newInfo instanceof SourceFieldElementInfo) {
- if (!CharOperation
- .equals(
- ((SourceFieldElementInfo) oldInfo).getTypeName(),
- ((SourceFieldElementInfo) newInfo).getTypeName())) {
- this.delta.changed(newElement, IJavaElementDelta.F_CONTENT);
- }
- }
- }
- if (oldInfo instanceof SourceTypeElementInfo
- && newInfo instanceof SourceTypeElementInfo) {
- SourceTypeElementInfo oldSourceTypeInfo = (SourceTypeElementInfo) oldInfo;
- SourceTypeElementInfo newSourceTypeInfo = (SourceTypeElementInfo) newInfo;
- if (!CharOperation
- .equals(
- oldSourceTypeInfo.getSuperclassName(),
- newSourceTypeInfo.getSuperclassName())
- || !CharOperation.equals(
- oldSourceTypeInfo.getInterfaceNames(),
- newSourceTypeInfo.getInterfaceNames())) {
- this.delta.changed(newElement, IJavaElementDelta.F_SUPER_TYPES);
+ } else if (oldInfo instanceof SourceFieldElementInfo && newInfo instanceof SourceFieldElementInfo) {
+ if (!CharOperation.equals(
+ ((SourceFieldElementInfo)oldInfo).getTypeName(),
+ ((SourceFieldElementInfo)newInfo).getTypeName())) {
+ this.delta.changed(newElement, IJavaElementDelta.F_CONTENT);
}
}
}
-
- /**
- * Adds removed deltas for any handles left in the table
- */
- private void findDeletions() {
- Enumeration keys = this.infos.keys();
- while (keys.hasMoreElements()) {
- IJavaElement element = (IJavaElement) keys.nextElement();
- this.delta.removed(element);
- this.removed(element);
+ if (oldInfo instanceof SourceTypeElementInfo && newInfo instanceof SourceTypeElementInfo) {
+ SourceTypeElementInfo oldSourceTypeInfo = (SourceTypeElementInfo)oldInfo;
+ SourceTypeElementInfo newSourceTypeInfo = (SourceTypeElementInfo)newInfo;
+ if (!CharOperation.equals(oldSourceTypeInfo.getSuperclassName(), newSourceTypeInfo.getSuperclassName())
+ || !CharOperation.equals(oldSourceTypeInfo.getInterfaceNames(), newSourceTypeInfo.getInterfaceNames())) {
+ this.delta.changed(newElement, IJavaElementDelta.F_SUPER_TYPES);
}
}
-
- private JavaElementInfo getElementInfo(IJavaElement element) {
- return (JavaElementInfo) this.infos.get(element);
- }
-
- private ListItem getNewPosition(IJavaElement element) {
- return (ListItem) this.newPositions.get(element);
- }
-
- private ListItem getOldPosition(IJavaElement element) {
- return (ListItem) this.oldPositions.get(element);
- }
-
- private void initialize() {
- this.infos = new Hashtable(20);
- this.oldPositions = new Hashtable(20);
- this.newPositions = new Hashtable(20);
- this.putOldPosition(this.javaElement, new ListItem(null, null));
- this.putNewPosition(this.javaElement, new ListItem(null, null));
- this.delta = new JavaElementDelta(javaElement);
- this.added = new Vector(5);
- this.removed = new Vector(5);
- }
-
- /**
- * Inserts position information for the elements into the new or old positions table
- */
- private void insertPositions(IJavaElement[] elements, boolean isNew) {
- int length = elements.length;
- IJavaElement previous = null,
- current = null,
- next = (length > 0) ? elements[0] : null;
- for (int i = 0; i < length; i++) {
- previous = current;
- current = next;
- next = (i + 1 < length) ? elements[i + 1] : null;
- if (isNew) {
- this.putNewPosition(current, new ListItem(previous, next));
- } else {
- this.putOldPosition(current, new ListItem(previous, next));
- }
- }
+}
+/**
+ * Adds removed deltas for any handles left in the table
+ */
+private void findDeletions() {
+ Enumeration keys = this.infos.keys();
+ while(keys.hasMoreElements()) {
+ IJavaElement element = (IJavaElement)keys.nextElement();
+ this.delta.removed(element);
+ this.removed(element);
}
-
- /**
- * Returns true if the given elements represent the an equivalent declaration.
- *
- * <p>NOTE: Since this comparison can be done with handle info only,
- * none of the internal calls need to use the locally cached contents
- * of the old compilation unit.
- */
- private boolean isIdentical(JavaElement e1, JavaElement e2) {
- if (e1 == null ^ e2 == null)
- return false;
- if (e1 == null)
- return true;
-
- if (e1.fLEType == e2.fLEType) {
- if (e1.getOccurrenceCount() != e2.getOccurrenceCount())
- return false;
- switch (e1.fLEType) {
- case IJavaElement.FIELD :
- case IJavaElement.IMPORT_DECLARATION :
- case IJavaElement.PACKAGE_DECLARATION :
- case IJavaElement.COMPILATION_UNIT :
- return e1.getElementName().equals(e2.getElementName());
- case IJavaElement.TYPE :
- IType t1 = (IType) e1;
- IType t2 = (IType) e2;
- try {
- return (
- !(t1.isClass() ^ t2.isClass())
- && t1.getElementName().equals(t2.getElementName()));
- } catch (JavaModelException e) {
- return false;
- }
- case IJavaElement.METHOD :
- IMethod m1 = (IMethod) e1;
- IMethod m2 = (IMethod) e2;
- try {
- return m1.getElementName().equals(m2.getElementName())
- && m1.getSignature().equals(m2.getSignature());
- } catch (JavaModelException e) {
- return false;
- }
- case IJavaElement.INITIALIZER :
- case IJavaElement.IMPORT_CONTAINER :
- return true;
- default :
- return false;
- }
+}
+private JavaElementInfo getElementInfo(IJavaElement element) {
+ return (JavaElementInfo)this.infos.get(element);
+}
+private ListItem getNewPosition(IJavaElement element) {
+ return (ListItem)this.newPositions.get(element);
+}
+private ListItem getOldPosition(IJavaElement element) {
+ return (ListItem)this.oldPositions.get(element);
+}
+private void initialize() {
+ this.infos = new Hashtable(20);
+ this.oldPositions = new Hashtable(20);
+ this.newPositions = new Hashtable(20);
+ this.putOldPosition(this.javaElement, new ListItem(null, null));
+ this.putNewPosition(this.javaElement, new ListItem(null, null));
+ this.delta = new JavaElementDelta(javaElement);
+ this.added = new Vector(5);
+ this.removed = new Vector(5);
+}
+/**
+ * Inserts position information for the elements into the new or old positions table
+ */
+private void insertPositions(IJavaElement[] elements, boolean isNew) {
+ int length = elements.length;
+ IJavaElement previous = null, current = null, next = (length > 0) ? elements[0] : null;
+ for(int i = 0; i < length; i++) {
+ previous = current;
+ current = next;
+ next = (i + 1 < length) ? elements[i + 1] : null;
+ if (isNew) {
+ this.putNewPosition(current, new ListItem(previous, next));
} else {
- return false;
+ this.putOldPosition(current, new ListItem(previous, next));
}
}
-
- /**
- * Answers true if the elements position has not changed.
- * Takes into account additions so that elements following
- * new elements will not appear out of place.
- */
- private boolean isPositionedCorrectly(IJavaElement element) {
- ListItem oldListItem = this.getOldPosition(element);
- if (oldListItem == null)
- return false;
- IJavaElement oldPrevious = oldListItem.previous;
- ListItem newListItem = this.getNewPosition(element);
- if (newListItem == null)
+}
+/**
+ * Returns true if the given elements represent the an equivalent declaration.
+ *
+ * <p>NOTE: Since this comparison can be done with handle info only,
+ * none of the internal calls need to use the locally cached contents
+ * of the old compilation unit.
+ */
+private boolean isIdentical(JavaElement e1, JavaElement e2) {
+ if (e1 == null ^ e2 == null)
+ return false;
+ if (e1 == null)
+ return true;
+
+ if (e1.fLEType == e2.fLEType) {
+ if (e1.getOccurrenceCount() != e2.getOccurrenceCount())
return false;
- IJavaElement newPrevious = newListItem.previous;
- if (oldPrevious == newPrevious)
- return true;
- IJavaElement lastNewPrevious = null;
- while (lastNewPrevious != newPrevious) {
- if (isIdentical((JavaElement) oldPrevious, (JavaElement) newPrevious))
+ switch (e1.fLEType) {
+ case IJavaElement.FIELD:
+ case IJavaElement.IMPORT_DECLARATION:
+ case IJavaElement.PACKAGE_DECLARATION:
+ case IJavaElement.COMPILATION_UNIT:
+ return e1.getElementName().equals(e2.getElementName());
+ case IJavaElement.TYPE:
+ IType t1= (IType)e1;
+ IType t2= (IType)e2;
+ try {
+ return (!(t1.isClass() ^ t2.isClass()) && t1.getElementName().equals(t2.getElementName()));
+ } catch (JavaModelException e) {
+ return false;
+ }
+ case IJavaElement.METHOD:
+ IMethod m1= (IMethod)e1;
+ IMethod m2= (IMethod)e2;
+ try {
+ return m1.getElementName().equals(m2.getElementName()) && m1.getSignature().equals(m2.getSignature());
+ } catch (JavaModelException e) {
+ return false;
+ }
+ case IJavaElement.INITIALIZER:
+ case IJavaElement.IMPORT_CONTAINER:
return true;
- lastNewPrevious = newPrevious;
- // if newPrevious is null at this time we should exit the loop.
- if (newPrevious == null)
- break;
- newPrevious = (this.getNewPosition(newPrevious)).previous;
+ default:
+ return false;
}
+ } else {
return false;
}
-
- private void putElementInfo(IJavaElement element, JavaElementInfo info) {
- this.infos.put(element, info);
+}
+/**
+ * Answers true if the elements position has not changed.
+ * Takes into account additions so that elements following
+ * new elements will not appear out of place.
+ */
+private boolean isPositionedCorrectly(IJavaElement element) {
+ ListItem oldListItem = this.getOldPosition(element);
+ if (oldListItem == null)
+ return false;
+ IJavaElement oldPrevious = oldListItem.previous;
+ ListItem newListItem = this.getNewPosition(element);
+ if (newListItem == null)
+ return false;
+ IJavaElement newPrevious = newListItem.previous;
+ if (oldPrevious == newPrevious)
+ return true;
+ IJavaElement lastNewPrevious = null;
+ while(lastNewPrevious != newPrevious) {
+ if (isIdentical((JavaElement)oldPrevious, (JavaElement)newPrevious))
+ return true;
+ lastNewPrevious = newPrevious;
+ // if newPrevious is null at this time we should exit the loop.
+ if (newPrevious == null) break;
+ newPrevious = (this.getNewPosition(newPrevious)).previous;
}
-
- private void putNewPosition(IJavaElement element, ListItem position) {
- this.newPositions.put(element, position);
+ return false;
+}
+private void putElementInfo(IJavaElement element, JavaElementInfo info) {
+ this.infos.put(element, info);
+}
+private void putNewPosition(IJavaElement element, ListItem position) {
+ this.newPositions.put(element, position);
+}
+private void putOldPosition(IJavaElement element, ListItem position) {
+ this.oldPositions.put(element, position);
+}
+/**
+ * Records this elements info, and attempts
+ * to record the info for the children.
+ */
+private void recordElementInfo(IJavaElement element, JavaModel model, int depth) {
+ if (depth >= this.maxDepth) {
+ return;
}
-
- private void putOldPosition(IJavaElement element, ListItem position) {
- this.oldPositions.put(element, position);
+ JavaElementInfo info = (JavaElementInfo)model.fgJavaModelManager.getInfo(element);
+ if (info == null) // no longer in the java model.
+ return;
+ this.putElementInfo(element, info);
+
+ if (element instanceof IParent) {
+ IJavaElement[] children = info.getChildren();
+ if (children != null) {
+ insertPositions(children, false);
+ for(int i = 0, length = children.length; i < length; i++)
+ recordElementInfo(children[i], model, depth + 1);
+ }
}
-
- /**
- * Records this elements info, and attempts
- * to record the info for the children.
- */
- private void recordElementInfo(
- IJavaElement element,
- JavaModel model,
- int depth) {
- if (depth >= this.maxDepth) {
+}
+/**
+ * Fills the newPositions hashtable with the new position information
+ */
+private void recordNewPositions(IJavaElement newElement, int depth) {
+ if (depth < this.maxDepth && newElement instanceof IParent) {
+ JavaElementInfo info = null;
+ try {
+ info = ((JavaElement)newElement).getElementInfo();
+ } catch (JavaModelException npe) {
return;
}
- JavaElementInfo info =
- (JavaElementInfo) model.fgJavaModelManager.getInfo(element);
- if (info == null) // no longer in the java model.
- return;
- this.putElementInfo(element, info);
- if (element instanceof IParent) {
- IJavaElement[] children = info.getChildren();
- if (children != null) {
- insertPositions(children, false);
- for (int i = 0, length = children.length; i < length; i++)
- recordElementInfo(children[i], model, depth + 1);
+ IJavaElement[] children = info.getChildren();
+ if (children != null) {
+ insertPositions(children, true);
+ for(int i = 0, length = children.length; i < length; i++) {
+ recordNewPositions(children[i], depth + 1);
}
}
}
-
- /**
- * Fills the newPositions hashtable with the new position information
- */
- private void recordNewPositions(IJavaElement newElement, int depth) {
- if (depth < this.maxDepth && newElement instanceof IParent) {
- JavaElementInfo info = null;
- try {
- info = ((JavaElement) newElement).getElementInfo();
- } catch (JavaModelException npe) {
- return;
- }
-
- IJavaElement[] children = info.getChildren();
- if (children != null) {
- insertPositions(children, true);
- for (int i = 0, length = children.length; i < length; i++) {
- recordNewPositions(children[i], depth + 1);
- }
- }
+}
+/**
+ * Repairs the positioning information
+ * after an element has been removed
+ */
+private void removed(IJavaElement element) {
+ this.removed.addElement(element);
+ ListItem current = this.getOldPosition(element);
+ ListItem previous = null, next = null;
+ if (current.previous != null)
+ previous = this.getOldPosition(current.previous);
+ if (current.next != null)
+ next = this.getOldPosition(current.next);
+ if (previous != null)
+ previous.next = current.next;
+ if (next != null)
+ next.previous = current.previous;
+
+}
+private void removeElementInfo(IJavaElement element) {
+ this.infos.remove(element);
+}
+public String toString() {
+ StringBuffer buffer = new StringBuffer();
+ buffer.append("Built delta:\n"/*nonNLS*/);
+ buffer.append(this.delta.toString());
+ return buffer.toString();
+}
+/**
+ * Trims deletion deltas to only report the highest level of deletion
+ */
+private void trimDelta(JavaElementDelta delta) {
+ if (delta.getKind() == IJavaElementDelta.REMOVED) {
+ IJavaElementDelta[] children = delta.getAffectedChildren();
+ for(int i = 0, length = children.length; i < length; i++) {
+ delta.removeAffectedChild((JavaElementDelta)children[i]);
}
- }
-
- /**
- * Repairs the positioning information
- * after an element has been removed
- */
- private void removed(IJavaElement element) {
- this.removed.addElement(element);
- ListItem current = this.getOldPosition(element);
- ListItem previous = null, next = null;
- if (current.previous != null)
- previous = this.getOldPosition(current.previous);
- if (current.next != null)
- next = this.getOldPosition(current.next);
- if (previous != null)
- previous.next = current.next;
- if (next != null)
- next.previous = current.previous;
-
- }
-
- private void removeElementInfo(IJavaElement element) {
- this.infos.remove(element);
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append("Built delta:\n");
- buffer.append(this.delta.toString());
- return buffer.toString();
- }
-
- /**
- * Trims deletion deltas to only report the highest level of deletion
- */
- private void trimDelta(JavaElementDelta delta) {
- if (delta.getKind() == IJavaElementDelta.REMOVED) {
- IJavaElementDelta[] children = delta.getAffectedChildren();
- for (int i = 0, length = children.length; i < length; i++) {
- delta.removeAffectedChild((JavaElementDelta) children[i]);
- }
- } else {
- IJavaElementDelta[] children = delta.getAffectedChildren();
- for (int i = 0, length = children.length; i < length; i++) {
- trimDelta((JavaElementDelta) children[i]);
- }
+ } else {
+ IJavaElementDelta[] children = delta.getAffectedChildren();
+ for(int i = 0, length = children.length; i < length; i++) {
+ trimDelta((JavaElementDelta)children[i]);
}
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementInfo.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementInfo.java
index d065723c4d..c2fec4143a 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementInfo.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementInfo.java
@@ -15,8 +15,7 @@ import java.util.Vector;
* Holds cached structure and properties for a Java element.
* Subclassed to carry properties for specific kinds of elements.
*/
-/* package */
-class JavaElementInfo {
+/* package */ class JavaElementInfo {
/**
* Collection of handles of immediate children of this
@@ -28,9 +27,7 @@ class JavaElementInfo {
/**
* Shared empty collection used for efficiency.
*/
- protected static IJavaElement[] fgEmptyChildren = new IJavaElement[] {
- };
-
+ protected static IJavaElement[] fgEmptyChildren = new IJavaElement[]{};
/**
* Is the structure of this element known
* @see IJavaElement.isStructureKnown()
@@ -40,107 +37,91 @@ class JavaElementInfo {
/**
* Shared empty collection used for efficiency.
*/
- static Object[] NO_NON_JAVA_RESOURCES = new Object[] {
- };
-
- protected JavaElementInfo() {
- fChildren = fgEmptyChildren;
- }
-
- public void addChild(IJavaElement child) {
- if (fChildren == fgEmptyChildren) {
- setChildren(new IJavaElement[] { child });
- } else {
- if (!includesChild(child)) {
- setChildren(growAndAddToArray(fChildren, child));
- }
- }
- }
-
- public Object clone() {
- try {
- return super.clone();
- } catch (CloneNotSupportedException e) {
- throw new Error();
+ static Object[] NO_NON_JAVA_RESOURCES = new Object[] {};
+protected JavaElementInfo() {
+ fChildren = fgEmptyChildren;
+}
+public void addChild(IJavaElement child) {
+ if (fChildren == fgEmptyChildren) {
+ setChildren(new IJavaElement[] {child});
+ } else {
+ if (!includesChild(child)) {
+ setChildren(growAndAddToArray(fChildren, child));
}
}
-
- public IJavaElement[] getChildren() {
- return fChildren;
- }
-
- /**
- * Adds the new element to a new array that contains all of the elements of the old array.
- * Returns the new array.
- */
- protected IJavaElement[] growAndAddToArray(
- IJavaElement[] array,
- IJavaElement addition) {
- IJavaElement[] old = array;
- array = new IJavaElement[old.length + 1];
- System.arraycopy(old, 0, array, 0, old.length);
- array[old.length] = addition;
- return array;
- }
-
- /**
- * Returns <code>true</code> if this child is in my children collection
- */
- protected boolean includesChild(IJavaElement child) {
-
- for (int i = 0; i < fChildren.length; i++) {
- if (fChildren[i].equals(child)) {
- return true;
- }
- }
- return false;
+}
+public Object clone() {
+ try {
+ return super.clone();
}
-
- /**
- * @see IJavaElement.isStructureKnown()
- */
- public boolean isStructureKnown() {
- return fIsStructureKnown;
+ catch (CloneNotSupportedException e) {
+ throw new Error();
}
-
- /**
- * Returns an array with all the same elements as the specified array except for
- * the element to remove. Assumes that the deletion is contained in the array.
- */
- protected IJavaElement[] removeAndShrinkArray(
- IJavaElement[] array,
- IJavaElement deletion) {
- IJavaElement[] old = array;
- array = new IJavaElement[old.length - 1];
- int j = 0;
- for (int i = 0; i < old.length; i++) {
- if (!old[i].equals(deletion)) {
- array[j] = old[i];
- } else {
- System.arraycopy(old, i + 1, array, j, old.length - (i + 1));
- return array;
- }
- j++;
+}
+public IJavaElement[] getChildren() {
+ return fChildren;
+}
+/**
+ * Adds the new element to a new array that contains all of the elements of the old array.
+ * Returns the new array.
+ */
+protected IJavaElement[] growAndAddToArray(IJavaElement[] array, IJavaElement addition) {
+ IJavaElement[] old = array;
+ array = new IJavaElement[old.length + 1];
+ System.arraycopy(old, 0, array, 0, old.length);
+ array[old.length] = addition;
+ return array;
+}
+/**
+ * Returns <code>true</code> if this child is in my children collection
+ */
+protected boolean includesChild(IJavaElement child) {
+
+ for (int i= 0; i < fChildren.length; i++) {
+ if (fChildren[i].equals(child)) {
+ return true;
}
- return array;
}
-
- public void removeChild(IJavaElement child) {
- if (includesChild(child)) {
- setChildren(removeAndShrinkArray(fChildren, child));
+ return false;
+}
+/**
+ * @see IJavaElement.isStructureKnown()
+ */
+public boolean isStructureKnown() {
+ return fIsStructureKnown;
+}
+/**
+ * Returns an array with all the same elements as the specified array except for
+ * the element to remove. Assumes that the deletion is contained in the array.
+ */
+protected IJavaElement[] removeAndShrinkArray(IJavaElement[] array, IJavaElement deletion) {
+ IJavaElement[] old = array;
+ array = new IJavaElement[old.length - 1];
+ int j = 0;
+ for (int i = 0; i < old.length; i++) {
+ if (!old[i].equals(deletion)) {
+ array[j] = old[i];
+ } else {
+ System.arraycopy(old, i + 1, array, j, old.length - (i + 1));
+ return array;
}
+ j++;
}
-
- public void setChildren(IJavaElement[] children) {
- fChildren = children;
- }
-
- /**
- * Sets whether the structure of this element known
- * @see IJavaElement.isStructureKnown()
- */
- public void setIsStructureKnown(boolean newIsStructureKnown) {
- fIsStructureKnown = newIsStructureKnown;
+ return array;
+}
+public void removeChild(IJavaElement child) {
+ if (includesChild(child)) {
+ setChildren(removeAndShrinkArray(fChildren, child));
}
-
+}
+public void setChildren(IJavaElement[] children) {
+ fChildren = children;
+}
+/**
+ * Sets whether the structure of this element known
+ * @see IJavaElement.isStructureKnown()
+ */
+public void setIsStructureKnown(boolean newIsStructureKnown) {
+ fIsStructureKnown = newIsStructureKnown;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementRequestor.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementRequestor.java
index f54a7db183..cfa562935c 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementRequestor.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementRequestor.java
@@ -19,216 +19,200 @@ public class JavaElementRequestor implements IJavaElementRequestor {
* True if this requestor no longer wants to receive
* results from its <code>IRequestorNameLookup</code>.
*/
- protected boolean fCanceled = false;
-
+ protected boolean fCanceled= false;
+
/**
* A collection of the resulting fields, or <code>null</code>
* if no field results have been received.
*/
- protected Vector fFields = null;
+ protected Vector fFields= null;
/**
* A collection of the resulting initializers, or <code>null</code>
* if no initializer results have been received.
*/
- protected Vector fInitializers = null;
+ protected Vector fInitializers= null;
/**
* A collection of the resulting member types, or <code>null</code>
* if no member type results have been received.
*/
- protected Vector fMemberTypes = null;
+ protected Vector fMemberTypes= null;
/**
* A collection of the resulting methods, or <code>null</code>
* if no method results have been received.
*/
- protected Vector fMethods = null;
+ protected Vector fMethods= null;
/**
* A collection of the resulting package fragments, or <code>null</code>
* if no package fragment results have been received.
*/
- protected Vector fPackageFragments = null;
+ protected Vector fPackageFragments= null;
/**
* A collection of the resulting types, or <code>null</code>
* if no type results have been received.
*/
- protected Vector fTypes = null;
+ protected Vector fTypes= null;
/**
* Empty arrays used for efficiency
*/
- protected static IField[] fgEmptyFieldArray = new IField[0];
- protected static IInitializer[] fgEmptyInitializerArray = new IInitializer[0];
- protected static IType[] fgEmptyTypeArray = new IType[0];
- protected static IPackageFragment[] fgEmptyPackageFragmentArray =
- new IPackageFragment[0];
- protected static IMethod[] fgEmptyMethodArray = new IMethod[0];
- /**
- * @see IJavaElementRequestor
- */
- public void acceptField(IField field) {
- if (fFields == null) {
- fFields = new Vector();
- }
- fFields.addElement(field);
- }
-
- /**
- * @see IJavaElementRequestor
- */
- public void acceptInitializer(IInitializer initializer) {
- if (fInitializers == null) {
- fInitializers = new Vector();
- }
- fInitializers.addElement(initializer);
- }
-
- /**
- * @see IJavaElementRequestor
- */
- public void acceptMemberType(IType type) {
- if (fMemberTypes == null) {
- fMemberTypes = new Vector();
- }
- fMemberTypes.addElement(type);
- }
-
- /**
- * @see IJavaElementRequestor
- */
- public void acceptMethod(IMethod method) {
- if (fMethods == null) {
- fMethods = new Vector();
- }
- fMethods.addElement(method);
+ protected static IField[] fgEmptyFieldArray= new IField[0];
+ protected static IInitializer[] fgEmptyInitializerArray= new IInitializer[0];
+ protected static IType[] fgEmptyTypeArray= new IType[0];
+ protected static IPackageFragment[] fgEmptyPackageFragmentArray= new IPackageFragment[0];
+ protected static IMethod[] fgEmptyMethodArray= new IMethod[0];
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptField(IField field) {
+ if (fFields == null) {
+ fFields= new Vector();
}
-
- /**
- * @see IJavaElementRequestor
- */
- public void acceptPackageFragment(IPackageFragment packageFragment) {
- if (fPackageFragments == null) {
- fPackageFragments = new Vector();
- }
- fPackageFragments.addElement(packageFragment);
+ fFields.addElement(field);
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptInitializer(IInitializer initializer) {
+ if (fInitializers == null) {
+ fInitializers= new Vector();
}
-
- /**
- * @see IJavaElementRequestor
- */
- public void acceptType(IType type) {
- if (fTypes == null) {
- fTypes = new Vector();
- }
- fTypes.addElement(type);
+ fInitializers.addElement(initializer);
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptMemberType(IType type) {
+ if (fMemberTypes == null) {
+ fMemberTypes= new Vector();
}
-
- /**
- * @see IJavaElementRequestor
- */
- public IField[] getFields() {
- if (fFields == null) {
- return fgEmptyFieldArray;
- }
- int size = fFields.size();
- IField[] results = new IField[size];
- fFields.copyInto(results);
- return results;
+ fMemberTypes.addElement(type);
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptMethod(IMethod method) {
+ if (fMethods == null) {
+ fMethods = new Vector();
}
-
- /**
- * @see IJavaElementRequestor
- */
- public IInitializer[] getInitializers() {
- if (fInitializers == null) {
- return fgEmptyInitializerArray;
- }
- int size = fInitializers.size();
- IInitializer[] results = new IInitializer[size];
- fInitializers.copyInto(results);
- return results;
+ fMethods.addElement(method);
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptPackageFragment(IPackageFragment packageFragment) {
+ if (fPackageFragments== null) {
+ fPackageFragments= new Vector();
}
-
- /**
- * @see IJavaElementRequestor
- */
- public IType[] getMemberTypes() {
- if (fMemberTypes == null) {
- return fgEmptyTypeArray;
- }
- int size = fMemberTypes.size();
- IType[] results = new IType[size];
- fMemberTypes.copyInto(results);
- return results;
+ fPackageFragments.addElement(packageFragment);
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptType(IType type) {
+ if (fTypes == null) {
+ fTypes= new Vector();
}
-
- /**
- * @see IJavaElementRequestor
- */
- public IMethod[] getMethods() {
- if (fMethods == null) {
- return fgEmptyMethodArray;
- }
- int size = fMethods.size();
- IMethod[] results = new IMethod[size];
- fMethods.copyInto(results);
- return results;
+ fTypes.addElement(type);
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public IField[] getFields() {
+ if (fFields == null) {
+ return fgEmptyFieldArray;
}
-
- /**
- * @see IJavaElementRequestor
- */
- public IPackageFragment[] getPackageFragments() {
- if (fPackageFragments == null) {
- return fgEmptyPackageFragmentArray;
- }
- int size = fPackageFragments.size();
- IPackageFragment[] results = new IPackageFragment[size];
- fPackageFragments.copyInto(results);
- return results;
+ int size = fFields.size();
+ IField[] results = new IField[size];
+ fFields.copyInto(results);
+ return results;
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public IInitializer[] getInitializers() {
+ if (fInitializers == null) {
+ return fgEmptyInitializerArray;
}
-
- /**
- * @see IJavaElementRequestor
- */
- public IType[] getTypes() {
- if (fTypes == null) {
- return fgEmptyTypeArray;
- }
- int size = fTypes.size();
- IType[] results = new IType[size];
- fTypes.copyInto(results);
- return results;
+ int size = fInitializers.size();
+ IInitializer[] results = new IInitializer[size];
+ fInitializers.copyInto(results);
+ return results;
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public IType[] getMemberTypes() {
+ if (fMemberTypes == null) {
+ return fgEmptyTypeArray;
}
-
- /**
- * @see IJavaElementRequestor
- */
- public boolean isCanceled() {
- return fCanceled;
+ int size = fMemberTypes.size();
+ IType[] results = new IType[size];
+ fMemberTypes.copyInto(results);
+ return results;
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public IMethod[] getMethods() {
+ if (fMethods == null) {
+ return fgEmptyMethodArray;
}
-
- /**
- * Reset the state of this requestor.
- */
- public void reset() {
- fCanceled = false;
- fFields = null;
- fInitializers = null;
- fMemberTypes = null;
- fMethods = null;
- fPackageFragments = null;
- fTypes = null;
+ int size = fMethods.size();
+ IMethod[] results = new IMethod[size];
+ fMethods.copyInto(results);
+ return results;
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public IPackageFragment[] getPackageFragments() {
+ if (fPackageFragments== null) {
+ return fgEmptyPackageFragmentArray;
}
-
- /**
- * Sets the #isCanceled state of this requestor to true or false.
- */
- public void setCanceled(boolean b) {
- fCanceled = b;
+ int size = fPackageFragments.size();
+ IPackageFragment[] results = new IPackageFragment[size];
+ fPackageFragments.copyInto(results);
+ return results;
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public IType[] getTypes() {
+ if (fTypes== null) {
+ return fgEmptyTypeArray;
}
-
+ int size = fTypes.size();
+ IType[] results = new IType[size];
+ fTypes.copyInto(results);
+ return results;
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public boolean isCanceled() {
+ return fCanceled;
+}
+/**
+ * Reset the state of this requestor.
+ */
+public void reset() {
+ fCanceled = false;
+ fFields = null;
+ fInitializers = null;
+ fMemberTypes = null;
+ fMethods = null;
+ fPackageFragments = null;
+ fTypes = null;
+}
+/**
+ * Sets the #isCanceled state of this requestor to true or false.
+ */
+public void setCanceled(boolean b) {
+ fCanceled= b;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModel.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModel.java
index 4a194fb330..a359be8acc 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModel.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModel.java
@@ -29,619 +29,483 @@ public class JavaModel extends Openable implements IJavaModel {
*/
protected IWorkspace workspace = null;
- /**
- * Constructs a new Java Model on the given workspace.
- *
- * @exception Error if called more than once
- */
- protected JavaModel(IWorkspace workspace) throws Error {
- super(JAVA_MODEL, null, "" /*workspace has empty name*/);
- this.workspace = workspace;
- }
-
- private void cleanupCycleMarkers() {
- try {
- IMarker[] markers =
- workspace.getRoot().findMarkers(
- IJavaModelMarker.TRANSIENT_PROBLEM,
- true,
- IResource.DEPTH_ONE);
- for (int i = 0, length = markers.length; i < length; i++) {
- IMarker marker = markers[i];
- if (marker.getAttribute(IJavaModelMarker.CYCLE_DETECTED) != null) {
- workspace.deleteMarkers(new IMarker[] { marker });
- }
+/**
+ * Constructs a new Java Model on the given workspace.
+ *
+ * @exception Error if called more than once
+ */
+protected JavaModel(IWorkspace workspace) throws Error {
+ super(JAVA_MODEL, null, ""/*nonNLS*/ /*workspace has empty name*/);
+ this.workspace = workspace;
+}
+private void cleanupCycleMarkers() {
+ try {
+ IMarker[] markers = workspace.getRoot().findMarkers(IJavaModelMarker.TRANSIENT_PROBLEM, true, IResource.DEPTH_ONE);
+ for (int i = 0, length = markers.length; i < length; i++) {
+ IMarker marker = markers[i];
+ if (marker.getAttribute(IJavaModelMarker.CYCLE_DETECTED) != null) {
+ workspace.deleteMarkers(new IMarker[] {marker});
}
- } catch (CoreException e) {
- e.printStackTrace();
}
+ } catch (CoreException e) {
+ e.printStackTrace();
}
-
- /**
- * Remove the Java Model from the cache
- */
- protected void closing(Object info) throws JavaModelException {
- JavaModelManager.fgManager.fModelInfo.close();
- JavaModelManager.fgManager.fModelInfo = null;
+}
+/**
+ * Remove the Java Model from the cache
+ */
+protected void closing(Object info) throws JavaModelException {
+ JavaModelManager.fgManager.fModelInfo.close();
+ JavaModelManager.fgManager.fModelInfo= null;
+}
+/**
+ * Computes the build order of the Java Projects in this Java Model.
+ * The order is computed by following the class path of the projects.
+ * Prerequesite projects appear first in the list, dependent projects
+ * appear last.
+ * If specified, reports an error against a project using a marker if a cycle
+ * is detected. Otherwise throws a JavaModelException.
+ */
+public String[] computeBuildOrder(boolean generateMarkerOnError) throws JavaModelException {
+ // Remove markers indicating cycle
+ if (generateMarkerOnError) {
+ this.cleanupCycleMarkers();
}
- /**
- * Computes the build order of the Java Projects in this Java Model.
- * The order is computed by following the class path of the projects.
- * Prerequesite projects appear first in the list, dependent projects
- * appear last.
- * If specified, reports an error against a project using a marker if a cycle
- * is detected. Otherwise throws a JavaModelException.
- */
- public String[] computeBuildOrder(boolean generateMarkerOnError)
- throws JavaModelException {
- // Remove markers indicating cycle
- if (generateMarkerOnError) {
- this.cleanupCycleMarkers();
- }
-
- // Compute depth of each project and detect cycle
- StringHashtableOfInt depthTable = new StringHashtableOfInt();
- IJavaProject[] projects = getJavaProjects();
- int length = projects.length;
- int maxDepth = -1;
- for (int i = 0; i < length; i++) {
- String projectName = projects[i].getElementName();
- maxDepth =
- Math.max(
- maxDepth,
- this.computeDepth(projectName, depthTable, projectName, generateMarkerOnError));
- }
-
- // Sort projects by depth
- return depthTable.sortedKeys(maxDepth);
+ // Compute depth of each project and detect cycle
+ StringHashtableOfInt depthTable = new StringHashtableOfInt();
+ IJavaProject[] projects = getJavaProjects();
+ int length = projects.length;
+ int maxDepth = -1;
+ for (int i = 0; i < length; i++) {
+ String projectName = projects[i].getElementName();
+ maxDepth =
+ Math.max(
+ maxDepth,
+ this.computeDepth(projectName, depthTable, projectName, generateMarkerOnError));
}
- /**
- * Computes the depth of the given java project following its classpath.
- * Only projects are taken into consideration. Store the depth in the given table.
- * Returns the depth.
- * Note that a project with no prerequisites has a depth of 0.
- * Returns -1 if a cycle is detected
- */
- protected int computeDepth(
- String projectName,
- StringHashtableOfInt depthTable,
- String dependentProjectName,
- boolean generateMarkerOnError)
- throws JavaModelException {
- int depth = depthTable.get(projectName);
- switch (depth) {
- case -2 : // project already visited -> it's a cycle
- if (generateMarkerOnError) {
- try {
- IMarker marker =
- this.workspace.getRoot().getProject(dependentProjectName).createMarker(
- IJavaModelMarker.TRANSIENT_PROBLEM);
- marker.setAttribute(
- IMarker.MESSAGE,
- "A cycle was detected in the project's classpath");
- marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH);
- marker.setAttribute(IMarker.LOCATION, dependentProjectName);
- marker.setAttribute(IJavaModelMarker.CYCLE_DETECTED, dependentProjectName);
- } catch (CoreException e) {
- e.printStackTrace();
- }
- } else {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION));
- }
- return -1;
- case -1 :
- depthTable.put(projectName, -2); // mark we're visiting the project
- int prereqDepth = -1;
- JavaProject project = (JavaProject) this.getJavaProject(projectName);
- String[] prerequisites = null;
+ // Sort projects by depth
+ return depthTable.sortedKeys(maxDepth);
+}
+/**
+ * Computes the depth of the given java project following its classpath.
+ * Only projects are taken into consideration. Store the depth in the given table.
+ * Returns the depth.
+ * Note that a project with no prerequisites has a depth of 0.
+ * Returns -1 if a cycle is detected
+ */
+protected int computeDepth(String projectName, StringHashtableOfInt depthTable, String dependentProjectName, boolean generateMarkerOnError) throws JavaModelException {
+ int depth = depthTable.get(projectName);
+ switch (depth) {
+ case -2: // project already visited -> it's a cycle
+ if (generateMarkerOnError) {
try {
- prerequisites = project.getRequiredProjectNames();
- } catch (JavaModelException e) {
- prerequisites = JavaProject.NO_PREREQUISITES;
+ IMarker marker = this.workspace.getRoot().getProject(dependentProjectName).createMarker(IJavaModelMarker.TRANSIENT_PROBLEM);
+ marker.setAttribute(IMarker.MESSAGE, Util.bind("classpath.cycle"/*nonNLS*/));
+ marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH);
+ marker.setAttribute(IMarker.LOCATION, dependentProjectName);
+ marker.setAttribute(IJavaModelMarker.CYCLE_DETECTED, dependentProjectName);
+ } catch (CoreException e) {
+ e.printStackTrace();
}
- for (int i = 0, length = prerequisites.length; i < length; i++) {
- String prerequisite = prerequisites[i];
- prereqDepth =
- Math.max(
- prereqDepth,
- this.computeDepth(
- prerequisite,
- depthTable,
- projectName,
- generateMarkerOnError));
- }
- depth = 1 + prereqDepth;
- depthTable.put(projectName, depth);
- return depth;
- default :
- return depth;
- }
- }
-
- /**
- * @see IJavaModel
- */
- public void copy(
- IJavaElement[] elements,
- IJavaElement[] containers,
- IJavaElement[] siblings,
- String[] renamings,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- if (elements != null
- && elements[0] != null
- && elements[0].getElementType() < IJavaElement.TYPE) {
- runOperation(
- new CopyResourceElementsOperation(elements, containers, force),
- elements,
- siblings,
- renamings,
- monitor);
- } else {
- runOperation(
- new CopyElementsOperation(elements, containers, force),
- elements,
- siblings,
- renamings,
- monitor);
- }
- }
-
- /**
- * Returns a new element info for this element.
- */
- protected OpenableElementInfo createElementInfo() {
- return new JavaModelInfo(this, this.workspace);
+ } else {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION));
+ }
+ return -1;
+ case -1:
+ depthTable.put(projectName, -2); // mark we're visiting the project
+ int prereqDepth = -1;
+ JavaProject project = (JavaProject)this.getJavaProject(projectName);
+ String[] prerequisites = null;
+ try {
+ prerequisites = project.getRequiredProjectNames();
+ } catch (JavaModelException e) {
+ prerequisites = JavaProject.NO_PREREQUISITES;
+ }
+ for (int i = 0, length = prerequisites.length; i < length; i++) {
+ String prerequisite = prerequisites[i];
+ prereqDepth =
+ Math.max(
+ prereqDepth,
+ this.computeDepth(prerequisite, depthTable, projectName, generateMarkerOnError)
+ );
+ }
+ depth = 1 + prereqDepth;
+ depthTable.put(projectName, depth);
+ return depth;
+ default:
+ return depth;
}
-
- /**
- * @see IJavaModel
- */
- public void delete(
- IJavaElement[] elements,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- if (elements != null
- && elements[0] != null
- && elements[0].getElementType() < IJavaElement.TYPE) {
- runOperation(new DeleteResourceElementsOperation(elements, force), monitor);
- } else {
- runOperation(new DeleteElementsOperation(elements, force), monitor);
- }
+}
+/**
+ * @see IJavaModel
+ */
+public void copy(IJavaElement[] elements, IJavaElement[] containers, IJavaElement[] siblings, String[] renamings, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ if (elements != null && elements[0] != null && elements[0].getElementType() < IJavaElement.TYPE) {
+ runOperation(new CopyResourceElementsOperation(elements, containers, force), elements, siblings, renamings, monitor);
+ } else {
+ runOperation(new CopyElementsOperation(elements, containers, force), elements, siblings, renamings, monitor);
}
-
- /**
- * Java Models are equal if their workspaces are equal
- *
- * @see Object#equals
- */
- public boolean equals(Object o) {
- if (this == o)
- return true;
- if (o instanceof JavaModel) {
- JavaModel other = (JavaModel) o;
- return this.workspace.equals(other.workspace);
- }
- return false;
+}
+/**
+ * Returns a new element info for this element.
+ */
+protected OpenableElementInfo createElementInfo() {
+ return new JavaModelInfo(this, this.workspace);
+}
+/**
+ * @see IJavaModel
+ */
+public void delete(IJavaElement[] elements, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ if (elements != null && elements[0] != null && elements[0].getElementType() < IJavaElement.TYPE) {
+ runOperation(new DeleteResourceElementsOperation(elements, force), monitor);
+ } else {
+ runOperation(new DeleteElementsOperation(elements, force), monitor);
}
-
- /**
- */
- protected boolean generateInfos(
- OpenableElementInfo info,
- IProgressMonitor pm,
- Hashtable newElements,
- IResource underlyingResource)
- throws JavaModelException {
-
- fgJavaModelManager.fModelInfo = (JavaModelInfo) info;
- // determine my children
- try {
- IProject[] projects = workspace.getRoot().getProjects();
- for (int i = 0, max = projects.length; i < max; i++) {
- IProject project = projects[i];
- if (project.isOpen() && project.hasNature(JavaCore.NATURE_ID)) {
- info.addChild(getJavaProject(project));
- }
- }
- } catch (CoreException e) {
- throw new JavaModelException(e);
- }
+}
+/**
+ * Java Models are equal if their workspaces are equal
+ *
+ * @see Object#equals
+ */
+public boolean equals(Object o) {
+ if (this == o)
return true;
+ if (o instanceof JavaModel) {
+ JavaModel other = (JavaModel) o;
+ return this.workspace.equals(other.workspace);
}
-
- /**
- * Returns the <code>IJavaElement</code> represented by the <code>String</code>
- * memento.
- * @see getHandleMemento()
- */
- protected IJavaElement getHandleFromMementoForBinaryMembers(
- String memento,
- IPackageFragmentRoot root,
- int rootEnd,
- int end)
- throws JavaModelException {
-
- //deal with class file and binary members
- IPackageFragment frag = null;
- if (rootEnd == end - 1) {
- //default package
- frag = root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
- } else {
- frag = root.getPackageFragment(memento.substring(rootEnd + 1, end));
- }
- int oldEnd = end;
- end = memento.indexOf(JavaElement.JEM_TYPE, oldEnd);
- if (end == -1) {
- //we ended with a class file
- return frag.getClassFile(memento.substring(oldEnd + 1));
- }
- IClassFile cf = frag.getClassFile(memento.substring(oldEnd + 1, end));
- oldEnd = end;
- end = memento.indexOf(JavaElement.JEM_TYPE, oldEnd);
- oldEnd = end;
- end = memento.indexOf(JavaElement.JEM_FIELD, end);
- if (end != -1) {
- //binary field
- IType type = cf.getType();
- return type.getField(memento.substring(end + 1));
- }
- end = memento.indexOf(JavaElement.JEM_METHOD, oldEnd);
- if (end != -1) {
- //binary method
- oldEnd = end;
- IType type = cf.getType();
- String methodName;
- end = memento.lastIndexOf(JavaElement.JEM_METHOD);
- String[] parameterTypes = null;
- if (end == oldEnd) {
- methodName = memento.substring(end + 1);
- //no parameter types
- parameterTypes = new String[] {
- };
- } else {
- String parameters = memento.substring(oldEnd + 1);
- StringTokenizer tokenizer =
- new StringTokenizer(
- parameters,
- new String(new char[] { JavaElement.JEM_METHOD }));
- parameterTypes = new String[tokenizer.countTokens() - 1];
- methodName = tokenizer.nextToken();
- int i = 0;
- while (tokenizer.hasMoreTokens()) {
- parameterTypes[i] = tokenizer.nextToken();
- i++;
- }
+ return false;
+}
+/**
+ */
+protected boolean generateInfos(
+ OpenableElementInfo info,
+ IProgressMonitor pm,
+ Hashtable newElements,
+ IResource underlyingResource)
+ throws JavaModelException {
+
+ fgJavaModelManager.fModelInfo = (JavaModelInfo) info;
+ // determine my children
+ try {
+ IProject[] projects = workspace.getRoot().getProjects();
+ for (int i = 0, max = projects.length; i < max; i++) {
+ IProject project = projects[i];
+ if (project.isOpen() && project.hasNature(JavaCore.NATURE_ID)) {
+ info.addChild(getJavaProject(project));
}
- return type.getMethod(methodName, parameterTypes);
}
-
- //binary type
- return cf.getType();
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
-
- /**
- * Returns the <code>IJavaElement</code> represented by the <code>String</code>
- * memento.
- * @see getHandleMemento()
- */
- protected IJavaElement getHandleFromMementoForSourceMembers(
- String memento,
- IPackageFragmentRoot root,
- int rootEnd,
- int end)
- throws JavaModelException {
-
- //deal with compilation units and source members
- IPackageFragment frag = null;
- if (rootEnd == end - 1) {
- //default package
- frag = root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
- } else {
- frag = root.getPackageFragment(memento.substring(rootEnd + 1, end));
- }
- int oldEnd = end;
- end = memento.indexOf(JavaElement.JEM_PACKAGEDECLARATION, end);
- if (end != -1) {
- //package declaration
- ICompilationUnit cu =
- frag.getCompilationUnit(memento.substring(oldEnd + 1, end));
- return cu.getPackageDeclaration(memento.substring(end + 1));
- }
- end = memento.indexOf(JavaElement.JEM_IMPORTDECLARATION, oldEnd);
- if (end != -1) {
- //import declaration
- ICompilationUnit cu =
- frag.getCompilationUnit(memento.substring(oldEnd + 1, end));
- return cu.getImport(memento.substring(end + 1));
- }
- int typeStart = memento.indexOf(JavaElement.JEM_TYPE, oldEnd);
- if (typeStart == -1) {
- //we ended with a compilation unit
- return frag.getCompilationUnit(memento.substring(oldEnd + 1));
- }
-
- //source members
- ICompilationUnit cu =
- frag.getCompilationUnit(memento.substring(oldEnd + 1, typeStart));
- end = memento.indexOf(JavaElement.JEM_FIELD, oldEnd);
- if (end != -1) {
- //source field
- IType type = getHandleFromMementoForSourceType(memento, cu, typeStart, end);
- return type.getField(memento.substring(end + 1));
- }
- end = memento.indexOf(JavaElement.JEM_METHOD, oldEnd);
- if (end != -1) {
- //source method
- IType type = getHandleFromMementoForSourceType(memento, cu, typeStart, end);
- oldEnd = end;
- String methodName;
- end = memento.lastIndexOf(JavaElement.JEM_METHOD);
- String[] parameterTypes = null;
- if (end == oldEnd) {
- methodName = memento.substring(end + 1);
- //no parameter types
- parameterTypes = new String[] {
- };
- } else {
- String parameters = memento.substring(oldEnd + 1);
- StringTokenizer mTokenizer =
- new StringTokenizer(
- parameters,
- new String(new char[] { JavaElement.JEM_METHOD }));
- parameterTypes = new String[mTokenizer.countTokens() - 1];
- methodName = mTokenizer.nextToken();
- int i = 0;
- while (mTokenizer.hasMoreTokens()) {
- parameterTypes[i] = mTokenizer.nextToken();
- i++;
- }
- }
- return type.getMethod(methodName, parameterTypes);
- }
-
- end = memento.indexOf(JavaElement.JEM_INITIALIZER, oldEnd);
- if (end != -1) {
- //initializer
- IType type = getHandleFromMementoForSourceType(memento, cu, typeStart, end);
- return type.getInitializer(Integer.parseInt(memento.substring(end + 1)));
- }
- //source type
- return getHandleFromMementoForSourceType(
- memento,
- cu,
- typeStart,
- memento.length());
- ;
+ return true;
+}
+/**
+ * Returns the <code>IJavaElement</code> represented by the <code>String</code>
+ * memento.
+ * @see getHandleMemento()
+ */
+protected IJavaElement getHandleFromMementoForBinaryMembers(String memento, IPackageFragmentRoot root, int rootEnd, int end) throws JavaModelException {
+
+ //deal with class file and binary members
+ IPackageFragment frag = null;
+ if (rootEnd == end - 1) {
+ //default package
+ frag= root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
+ } else {
+ frag= root.getPackageFragment(memento.substring(rootEnd + 1, end));
}
-
- /**
- * Returns the <code>IJavaElement</code> represented by the <code>String</code>
- * memento.
- * @see getHandleMemento()
- */
- protected IType getHandleFromMementoForSourceType(
- String memento,
- ICompilationUnit cu,
- int typeStart,
- int typeEnd)
- throws JavaModelException {
- int end = memento.lastIndexOf(JavaElement.JEM_TYPE);
- IType type = null;
- if (end == typeStart) {
- String typeName = memento.substring(typeStart + 1, typeEnd);
- type = cu.getType(typeName);
-
+ int oldEnd = end;
+ end = memento.indexOf(JavaElement.JEM_TYPE, oldEnd);
+ if (end == -1) {
+ //we ended with a class file
+ return frag.getClassFile(memento.substring(oldEnd + 1));
+ }
+ IClassFile cf = frag.getClassFile(memento.substring(oldEnd + 1, end));
+ oldEnd = end;
+ end = memento.indexOf(JavaElement.JEM_TYPE, oldEnd);
+ oldEnd = end;
+ end = memento.indexOf(JavaElement.JEM_FIELD, end);
+ if (end != -1) {
+ //binary field
+ IType type = cf.getType();
+ return type.getField(memento.substring(end + 1));
+ }
+ end = memento.indexOf(JavaElement.JEM_METHOD, oldEnd);
+ if (end != -1) {
+ //binary method
+ oldEnd = end;
+ IType type = cf.getType();
+ String methodName;
+ end = memento.lastIndexOf(JavaElement.JEM_METHOD);
+ String[] parameterTypes = null;
+ if (end == oldEnd) {
+ methodName = memento.substring(end + 1);
+ //no parameter types
+ parameterTypes = new String[] {};
} else {
- String typeNames = memento.substring(typeStart + 1, typeEnd);
- StringTokenizer tokenizer =
- new StringTokenizer(typeNames, new String(new char[] { JavaElement.JEM_TYPE }));
- type = cu.getType(tokenizer.nextToken());
+ String parameters = memento.substring(oldEnd + 1);
+ StringTokenizer tokenizer = new StringTokenizer(parameters, new String(new char[] {JavaElement.JEM_METHOD}));
+ parameterTypes = new String[tokenizer.countTokens() - 1];
+ methodName= tokenizer.nextToken();
+ int i = 0;
while (tokenizer.hasMoreTokens()) {
- //deal with inner types
- type = type.getType(tokenizer.nextToken());
+ parameterTypes[i] = tokenizer.nextToken();
+ i++;
}
}
- return type;
+ return type.getMethod(methodName, parameterTypes);
}
- /**
- * @see JavaElement#getHandleMemento()
- */
- public String getHandleMemento() {
- return getElementName();
- }
-
- /**
- * Returns the <code>char</code> that marks the start of this handles
- * contribution to a memento.
- */
- protected char getHandleMementoDelimiter() {
- throw new Error("should not be called");
+ //binary type
+ return cf.getType();
+}
+/**
+ * Returns the <code>IJavaElement</code> represented by the <code>String</code>
+ * memento.
+ * @see getHandleMemento()
+ */
+protected IJavaElement getHandleFromMementoForSourceMembers(String memento, IPackageFragmentRoot root, int rootEnd, int end) throws JavaModelException {
+
+ //deal with compilation units and source members
+ IPackageFragment frag = null;
+ if (rootEnd == end - 1) {
+ //default package
+ frag= root.getPackageFragment(IPackageFragment.DEFAULT_PACKAGE_NAME);
+ } else {
+ frag= root.getPackageFragment(memento.substring(rootEnd + 1, end));
}
-
- /**
- * @see IJavaElement
- */
- public IJavaModel getJavaModel() {
- return this;
+ int oldEnd = end;
+ end = memento.indexOf(JavaElement.JEM_PACKAGEDECLARATION, end);
+ if (end != -1) {
+ //package declaration
+ ICompilationUnit cu = frag.getCompilationUnit(memento.substring(oldEnd + 1, end));
+ return cu.getPackageDeclaration(memento.substring(end + 1));
}
-
- /**
- * @see IJavaElement
- */
- public IJavaProject getJavaProject() {
- return null;
+ end = memento.indexOf(JavaElement.JEM_IMPORTDECLARATION, oldEnd);
+ if (end != -1) {
+ //import declaration
+ ICompilationUnit cu = frag.getCompilationUnit(memento.substring(oldEnd + 1, end));
+ return cu.getImport(memento.substring(end + 1));
}
-
- /**
- * @see IJavaModel
- */
- public IJavaProject getJavaProject(String name) {
- return new JavaProject(this.workspace.getRoot().getProject(name), this);
+ int typeStart = memento.indexOf(JavaElement.JEM_TYPE, oldEnd);
+ if (typeStart == -1) {
+ //we ended with a compilation unit
+ return frag.getCompilationUnit(memento.substring(oldEnd + 1));
}
- /**
- * Returns the active Java project associated with the specified
- * resource, or <code>null</code> if no Java project yet exists
- * for the resource.
- *
- * @exception IllegalArgumentException if the given resource
- * is not one of an IProject, IFolder, or IFile.
- */
- public IJavaProject getJavaProject(IResource resource) {
- if (resource.getType() == IResource.FOLDER) {
- return new JavaProject(((IFolder) resource).getProject(), this);
- } else
- if (resource.getType() == IResource.FILE) {
- return new JavaProject(((IFile) resource).getProject(), this);
- } else
- if (resource.getType() == IResource.PROJECT) {
- return new JavaProject((IProject) resource, this);
- } else {
- throw new IllegalArgumentException("Illegal argument - must be one of IProject, IFolder, or IFile");
- }
+ //source members
+ ICompilationUnit cu = frag.getCompilationUnit(memento.substring(oldEnd + 1, typeStart));
+ end = memento.indexOf(JavaElement.JEM_FIELD, oldEnd);
+ if (end != -1) {
+ //source field
+ IType type = getHandleFromMementoForSourceType(memento, cu, typeStart, end);
+ return type.getField(memento.substring(end + 1));
}
-
- /**
- * @see IJavaModel
- */
- public IJavaProject[] getJavaProjects() throws JavaModelException {
- Vector v = getChildrenOfType(JAVA_PROJECT);
- IJavaProject[] array = new IJavaProject[v.size()];
- v.copyInto(array);
- return array;
-
+ end = memento.indexOf(JavaElement.JEM_METHOD, oldEnd);
+ if (end != -1) {
+ //source method
+ IType type = getHandleFromMementoForSourceType(memento, cu, typeStart, end);
+ oldEnd = end;
+ String methodName;
+ end = memento.lastIndexOf(JavaElement.JEM_METHOD);
+ String[] parameterTypes = null;
+ if (end == oldEnd) {
+ methodName = memento.substring(end + 1);
+ //no parameter types
+ parameterTypes = new String[] {};
+ } else {
+ String parameters = memento.substring(oldEnd + 1);
+ StringTokenizer mTokenizer = new StringTokenizer(parameters, new String(new char[] {JavaElement.JEM_METHOD}));
+ parameterTypes = new String[mTokenizer.countTokens() - 1];
+ methodName = mTokenizer.nextToken();
+ int i = 0;
+ while (mTokenizer.hasMoreTokens()) {
+ parameterTypes[i] = mTokenizer.nextToken();
+ i++;
+ }
+ }
+ return type.getMethod(methodName, parameterTypes);
}
-
- /**
- * Helper method - returns the targeted item (IResource if internal or java.io.File if external),
- * or null if unbound
- * Internal items must be referred to using container relative paths.
- */
- public static Object getTarget(IContainer container, IPath path) {
-
- if (path == null)
- return null;
-
- // lookup - inside the container
- IResource resource = container.findMember(path);
- if (resource != null)
- return resource;
-
- // lookup - outside the container
- File externalFile = new File(path.toOSString());
- if (externalFile.exists())
- return externalFile;
- return null;
+
+ end = memento.indexOf(JavaElement.JEM_INITIALIZER, oldEnd);
+ if (end != -1 ) {
+ //initializer
+ IType type = getHandleFromMementoForSourceType(memento, cu, typeStart, end);
+ return type.getInitializer(Integer.parseInt(memento.substring(end + 1)));
}
-
- /**
- * @see IOpenable
- */
- public IResource getUnderlyingResource() throws JavaModelException {
- return null;
+ //source type
+ return getHandleFromMementoForSourceType(memento, cu, typeStart, memento.length());
+ ;
+}
+/**
+ * Returns the <code>IJavaElement</code> represented by the <code>String</code>
+ * memento.
+ * @see getHandleMemento()
+ */
+protected IType getHandleFromMementoForSourceType(String memento, ICompilationUnit cu, int typeStart, int typeEnd) throws JavaModelException {
+ int end = memento.lastIndexOf(JavaElement.JEM_TYPE);
+ IType type = null;
+ if (end == typeStart) {
+ String typeName = memento.substring(typeStart + 1, typeEnd);
+ type = cu.getType(typeName);
+
+ } else {
+ String typeNames = memento.substring(typeStart + 1, typeEnd);
+ StringTokenizer tokenizer = new StringTokenizer(typeNames, new String(new char[] {JavaElement.JEM_TYPE}));
+ type = cu.getType(tokenizer.nextToken());
+ while (tokenizer.hasMoreTokens()) {
+ //deal with inner types
+ type= type.getType(tokenizer.nextToken());
+ }
}
-
- /**
- * Returns the workbench associated with this object.
- */
- public IWorkspace getWorkspace() {
- return this.workspace;
+ return type;
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+public String getHandleMemento(){
+ return getElementName();
+}
+/**
+ * Returns the <code>char</code> that marks the start of this handles
+ * contribution to a memento.
+ */
+protected char getHandleMementoDelimiter(){
+ Assert.isTrue(false, Util.bind("assert.shouldNotImplement"/*nonNLS*/));
+ return 0;
+}
+/**
+ * @see IJavaElement
+ */
+public IJavaModel getJavaModel() {
+ return this;
+}
+/**
+ * @see IJavaElement
+ */
+public IJavaProject getJavaProject() {
+ return null;
+}
+/**
+ * @see IJavaModel
+ */
+public IJavaProject getJavaProject(String name) {
+ return new JavaProject(this.workspace.getRoot().getProject(name), this);
+}
+/**
+ * Returns the active Java project associated with the specified
+ * resource, or <code>null</code> if no Java project yet exists
+ * for the resource.
+ *
+ * @exception IllegalArgumentException if the given resource
+ * is not one of an IProject, IFolder, or IFile.
+ */
+public IJavaProject getJavaProject(IResource resource) {
+ if (resource.getType() == IResource.FOLDER) {
+ return new JavaProject(((IFolder)resource).getProject(), this);
+ } else if (resource.getType() == IResource.FILE) {
+ return new JavaProject(((IFile)resource).getProject(), this);
+ } else if (resource.getType() == IResource.PROJECT) {
+ return new JavaProject((IProject)resource, this);
+ } else {
+ throw new IllegalArgumentException(Util.bind("element.invalidResourceForProject"/*nonNLS*/));
}
+}
+/**
+ * @see IJavaModel
+ */
+public IJavaProject[] getJavaProjects() throws JavaModelException {
+ Vector v= getChildrenOfType(JAVA_PROJECT);
+ IJavaProject[] array= new IJavaProject[v.size()];
+ v.copyInto(array);
+ return array;
- /**
- * The hashcode of a Java Model is that of its workspace.
- */
- public int hashCode() {
- return this.workspace.hashCode();
+}
+/**
+ * @see IOpenable
+ */
+public IResource getUnderlyingResource() throws JavaModelException {
+ return null;
+}
+/**
+ * Returns the workbench associated with this object.
+ */
+public IWorkspace getWorkspace() {
+ return this.workspace;
+}
+/**
+ * The hashcode of a Java Model is that of its workspace.
+ */
+public int hashCode() {
+ return this.workspace.hashCode();
+}
+/**
+ * @see IJavaModel
+ */
+public void move(IJavaElement[] elements, IJavaElement[] containers, IJavaElement[] siblings, String[] renamings, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ if (elements != null && elements[0] != null && elements[0].getElementType() < IJavaElement.TYPE) {
+ runOperation(new MoveResourceElementsOperation(elements, containers, force), elements, siblings, renamings, monitor);
+ } else {
+ runOperation(new MoveElementsOperation(elements, containers, force), elements, siblings, renamings, monitor);
}
-
- /**
- * @see IJavaModel
- */
- public void move(
- IJavaElement[] elements,
- IJavaElement[] containers,
- IJavaElement[] siblings,
- String[] renamings,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- if (elements != null
- && elements[0] != null
- && elements[0].getElementType() < IJavaElement.TYPE) {
- runOperation(
- new MoveResourceElementsOperation(elements, containers, force),
- elements,
- siblings,
- renamings,
- monitor);
- } else {
- runOperation(
- new MoveElementsOperation(elements, containers, force),
- elements,
- siblings,
- renamings,
- monitor);
- }
+}
+/**
+ * @see IJavaModel
+ */
+public void rename(IJavaElement[] elements, IJavaElement[] destinations, String[] renamings, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ MultiOperation op;
+ if (elements != null && elements[0] != null && elements[0].getElementType() < IJavaElement.TYPE) {
+ op = new RenameResourceElementsOperation(elements, destinations, renamings, force);
+ } else {
+ op = new RenameElementsOperation(elements, destinations, renamings, force);
}
-
- /**
- * @see IJavaModel
- */
- public void rename(
- IJavaElement[] elements,
- IJavaElement[] destinations,
- String[] renamings,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- MultiOperation op;
- if (elements != null
- && elements[0] != null
- && elements[0].getElementType() < IJavaElement.TYPE) {
- op =
- new RenameResourceElementsOperation(elements, destinations, renamings, force);
- } else {
- op = new RenameElementsOperation(elements, destinations, renamings, force);
+
+ runOperation(op, monitor);
+}
+/**
+ * Configures and runs the <code>MultiOperation</code>.
+ */
+protected void runOperation(MultiOperation op, IJavaElement[] elements, IJavaElement[] siblings, String[] renamings, IProgressMonitor monitor) throws JavaModelException {
+ op.setRenamings(renamings);
+ if (siblings != null) {
+ for (int i = 0; i < elements.length; i++) {
+ op.setInsertBefore(elements[i], siblings[i]);
}
-
- runOperation(op, monitor);
}
-
- /**
- * Configures and runs the <code>MultiOperation</code>.
- */
- protected void runOperation(
- MultiOperation op,
- IJavaElement[] elements,
- IJavaElement[] siblings,
- String[] renamings,
- IProgressMonitor monitor)
- throws JavaModelException {
- op.setRenamings(renamings);
- if (siblings != null) {
- for (int i = 0; i < elements.length; i++) {
- op.setInsertBefore(elements[i], siblings[i]);
- }
- }
- runOperation(op, monitor);
+ runOperation(op, monitor);
+}
+/**
+ * @private Debugging purposes
+ */
+protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
+ buffer.append("Java Model"/*nonNLS*/);
+ if (info == null) {
+ buffer.append(" (not open)"/*nonNLS*/);
}
+}
- /**
- * @private Debugging purposes
- */
- protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
- buffer.append("Java Model");
- if (info == null) {
- buffer.append(" (not open)");
- }
+/**
+ * Helper method - returns the targeted item (IResource if internal or java.io.File if external),
+ * or null if unbound
+ * Internal items must be referred to using container relative paths.
+ */
+public static Object getTarget(IContainer container, IPath path, boolean checkResourceExistence) {
+
+ if (path == null) return null;
+
+ // lookup - inside the container
+ IResource resource = container.findMember(path);
+ if (resource != null){
+ if (!checkResourceExistence ||resource.exists()) return resource;
+ return null;
}
+ // lookup - outside the container
+ File externalFile = new File(path.toOSString());
+ if (externalFile.exists()) return externalFile;
+ return null;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelInfo.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelInfo.java
index c29f5fd441..09c3802843 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelInfo.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelInfo.java
@@ -36,7 +36,7 @@ public class JavaModelInfo extends OpenableElementInfo {
/**
* Cache of open children of openable Java Model Java elements
*/
- protected Hashtable fChildrenCache = null;
+ protected Hashtable fChildrenCache= null;
/**
* Set of elements which are out of sync with their buffers.
@@ -46,43 +46,40 @@ public class JavaModelInfo extends OpenableElementInfo {
/**
* Backpointer to my Java Model handle
*/
- protected IJavaModel fJavaModel = null;
+ protected IJavaModel fJavaModel= null;
/**
* The workspace this Java Model Info corresponds to
*/
protected IWorkspace workspace;
- /**
- * Constructs a new Java Model Info
- */
- protected JavaModelInfo(IJavaModel javaModel, IWorkspace workspace) {
- this.workspace = workspace;
- this.fJavaModel = javaModel;
- this.fLRUCache = new ElementCache(5000);
- this.fChildrenCache = new Hashtable(30000);
- }
-
- /**
- * @see IJavaModel#close()
- */
- public void close() throws JavaModelException {
- //close any remaining "parent-less" handles in the LRUCache
- Enumeration handles = fLRUCache.keys();
- while (handles.hasMoreElements()) {
- IJavaElement handle = (IJavaElement) handles.nextElement();
- // can't close myself - (am in the process of that now)
- if (!handle.equals(fJavaModel)) {
- ((IOpenable) handle).close();
- }
+/**
+ * Constructs a new Java Model Info
+ */
+protected JavaModelInfo(IJavaModel javaModel, IWorkspace workspace) {
+ this.workspace = workspace;
+ this.fJavaModel= javaModel;
+ this.fLRUCache = new ElementCache(5000);
+ this.fChildrenCache= new Hashtable(30000);
+}
+/**
+ * @see IJavaModel#close()
+ */
+public void close() throws JavaModelException {
+ //close any remaining "parent-less" handles in the LRUCache
+ Enumeration handles = fLRUCache.keys();
+ while (handles.hasMoreElements()) {
+ IJavaElement handle= (IJavaElement)handles.nextElement();
+ // can't close myself - (am in the process of that now)
+ if (!handle.equals(fJavaModel)) {
+ ((IOpenable)handle).close();
}
}
-
- /**
- * Returns the Java Model for this info.
- */
- protected IJavaModel getJavaModel() {
- return fJavaModel;
- }
-
+}
+/**
+ * Returns the Java Model for this info.
+ */
+protected IJavaModel getJavaModel() {
+ return fJavaModel;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelManager.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelManager.java
index c12ff0f32a..7a88eb0ed6 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelManager.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelManager.java
@@ -15,7 +15,6 @@ import org.eclipse.jdt.core.*;
import org.eclipse.jdt.internal.core.builder.IDevelopmentContext;
import org.eclipse.jdt.internal.core.builder.IPackage;
import org.eclipse.jdt.internal.core.builder.IState;
-import org.eclipse.jdt.internal.core.builder.NotPresentException;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.core.builder.impl.*;
import org.eclipse.jdt.internal.core.search.indexing.*;
@@ -29,6 +28,8 @@ import org.apache.xml.serialize.*;
import org.w3c.dom.*;
import org.xml.sax.*;
+import org.eclipse.jdt.internal.core.builder.NotPresentException;
+
/**
* The <code>JavaModelManager</code> manages instances of <code>IJavaModel</code>.
* <code>IElementChangedListener</code>s register with the <code>JavaModelManager</code>,
@@ -92,12 +93,12 @@ public class JavaModelManager implements IResourceChangeListener, ISaveParticipa
/**
* Local Java workspace properties file name (generated inside JavaCore plugin state location)
*/
- private static final String WKS_PROP_FILENAME= "workspace.properties";
+ private static final String WKS_PROP_FILENAME= "workspace.properties"/*nonNLS*/;
/**
* Name of the handle id attribute in a Java marker
*/
- private static final String ATT_HANDLE_ID= "org.eclipse.jdt.internal.core.JavaModelManager.handleId";
+ private static final String ATT_HANDLE_ID= "org.eclipse.jdt.internal.core.JavaModelManager.handleId"/*nonNLS*/;
/**
* Table from IProject to PerProjectInfo.
@@ -128,7 +129,7 @@ public class JavaModelManager implements IResourceChangeListener, ISaveParticipa
/**
* Line separator to use throughout the JavaModel for any source edit operation
*/
- public static String LINE_SEPARATOR = System.getProperty("line.separator");
+ public static String LINE_SEPARATOR = System.getProperty("line.separator"/*nonNLS*/);
/**
* Constructs a new JavaModelManager
*/
@@ -358,6 +359,18 @@ public static ConfigurableOption[] convertConfigurableOptions(Hashtable optionMa
}
continue;
}
+ if (optionName.equals(JavaCore.COMPILER_PB_NON_EXTERNALIZED_STRING_LITERAL)){
+
+ if (optionValue.equals(JavaCore.WARNING)){
+ compilerOptions.handleNonExternalizedStringLiteralAsWarning(true);
+ continue;
+ }
+ if (optionValue.equals(JavaCore.IGNORE)){
+ compilerOptions.handleNonExternalizedStringLiteralAsWarning(false);
+ continue;
+ }
+ continue;
+ }
}
return compilerOptions.getConfigurableOptions(Locale.getDefault());
}
@@ -470,7 +483,7 @@ public void doneSaving(ISaveContext context){
return null;
}
JavaModel model= (JavaModel) getJavaModel(workspace);
- if (memento.equals("")){ // workspace memento
+ if (memento.equals(""/*nonNLS*/)){ // workspace memento
return model;
}
int modelEnd= memento.indexOf(JavaElement.JEM_JAVAPROJECT);
@@ -571,7 +584,7 @@ public void doneSaving(ISaveContext context){
try {
modelInfo.fJavaModel.close();
} catch (JavaModelException e) {
- Assert.isTrue(false, "Cannot instantiate more than one Java Model");
+ Assert.isTrue(false, Util.bind("element.onlyOneJavaModel"/*nonNLS*/));
return null;
}
}
@@ -579,7 +592,7 @@ public void doneSaving(ISaveContext context){
if (modelInfo == null || modelInfo.workspace.equals(workspace)) {
return new JavaModel(workspace);
} else {
- Assert.isTrue(false, "Cannot instantiate more than one Java Model");
+ Assert.isTrue(false, Util.bind("element.onlyOneJavaModel"/*nonNLS*/));
return null;
}
@@ -605,7 +618,7 @@ public void doneSaving(ISaveContext context){
if (state == null && JavaBuilder.SAVE_ENABLED && !info.triedRead) {
info.triedRead= true;
try {
- if (monitor != null) monitor.subTask("Reading saved built state of "+project.getName());
+ if (monitor != null) monitor.subTask(Util.bind("build.readStateProgress"/*nonNLS*/, project.getName()));
state= readState(info);
info.setLastBuiltState(state);
} catch (CoreException e) {
@@ -650,12 +663,12 @@ public void doneSaving(ISaveContext context){
if (!project.exists()) return null;
IPluginDescriptor descr= JavaCore.getJavaCore().getDescriptor();
IPath workingLocation= project.getPluginWorkingLocation(descr);
- return workingLocation.append("state.dat").toFile();
+ return workingLocation.append("state.dat"/*nonNLS*/).toFile();
}
public String getVariablesAsXMLString() throws CoreException {
Document document = new DocumentImpl();
- Element rootElement = document.createElement("variables");
+ Element rootElement = document.createElement("variables"/*nonNLS*/);
document.appendChild(rootElement);
String[] variables = JavaCore.getClasspathVariableNames();
@@ -663,9 +676,9 @@ public void doneSaving(ISaveContext context){
for (int i= 0; i < variables.length; ++i) {
String var = variables[i];
IPath varPath = JavaCore.getClasspathVariable(var);
- Element varElement= document.createElement("variable");
- varElement.setAttribute("name", var);
- varElement.setAttribute("path", varPath.toString());
+ Element varElement= document.createElement("variable"/*nonNLS*/);
+ varElement.setAttribute("name"/*nonNLS*/, var);
+ varElement.setAttribute("path"/*nonNLS*/, varPath.toString());
rootElement.appendChild(varElement);
}
@@ -707,7 +720,7 @@ public void doneSaving(ISaveContext context){
} else if (!path.isAbsolute()) {
file= root.getFile(path);
if (file == null || file.getType() != IResource.FILE) {
- throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, "file not found", null));
+ throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("file.notFound"/*nonNLS*/), null));
}
ensureLocal(file);
fileSystemPath= file.getLocation().toOSString();
@@ -718,7 +731,7 @@ public void doneSaving(ISaveContext context){
try {
return new ZipFile(fileSystemPath);
} catch (IOException e) {
- throw new CoreException(new Status(Status.ERROR, JavaCore.PLUGIN_ID, -1, "IOException", e));
+ throw new CoreException(new Status(Status.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("status.IOException"/*nonNLS*/), e));
}
}
/**
@@ -738,7 +751,7 @@ public void doneSaving(ISaveContext context){
public void loadVariables() throws CoreException {
String xmlString = ResourcesPlugin.getWorkspace().getRoot().getPersistentProperty(
- new QualifiedName(JavaCore.PLUGIN_ID, "variables"));
+ new QualifiedName(JavaCore.PLUGIN_ID, "variables"/*nonNLS*/));
try {
if (xmlString != null) readVariables(xmlString);
} catch(IOException e){
@@ -785,7 +798,7 @@ public void mergeDeltas() {
}
}
}
-}
+}
/**
* Returns the info for this element without
* disturbing the cache ordering.
@@ -833,13 +846,13 @@ public void prepareToSave(ISaveContext context) throws CoreException {
try {
String pluginID= in.readUTF();
if (!pluginID.equals(JavaCore.PLUGIN_ID))
- throw new IOException("Wrong file format");
+ throw new IOException(Util.bind("build.wrongFileFormat"/*nonNLS*/));
String kind= in.readUTF();
- if (!kind.equals("STATE"))
- throw new IOException("Wrong file format");
+ if (!kind.equals("STATE"/*nonNLS*/))
+ throw new IOException(Util.bind("build.wrongFileFormat"/*nonNLS*/));
int version= in.readInt();
if (version != 0x0001)
- throw new IOException("Unhandled version of file format");
+ throw new IOException(Util.bind("build.unhandledVersionFormat"/*nonNLS*/));
boolean hasState= in.readBoolean();
IState state= null;
if (hasState) {
@@ -863,15 +876,15 @@ public void prepareToSave(ISaveContext context) throws CoreException {
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
cpElement = parser.parse(new InputSource(reader)).getDocumentElement();
} catch(SAXException e) {
- throw new IOException("bad format");
+ throw new IOException(Util.bind("variable.badFormat"/*nonNLS*/));
} catch(ParserConfigurationException e){
reader.close();
- throw new IOException("bad format");
+ throw new IOException(Util.bind("variable.badFormat"/*nonNLS*/));
} finally {
reader.close();
}
- if (!cpElement.getNodeName().equalsIgnoreCase("variables")) {
- throw new IOException("bad format");
+ if (!cpElement.getNodeName().equalsIgnoreCase("variables"/*nonNLS*/)) {
+ throw new IOException(Util.bind("variable.badFormat"/*nonNLS*/));
}
NodeList list= cpElement.getChildNodes();
Vector variables = new Vector();
@@ -881,11 +894,11 @@ public void prepareToSave(ISaveContext context) throws CoreException {
short type= node.getNodeType();
if (type == Node.ELEMENT_NODE) {
Element element= (Element) node;
- if (element.getNodeName().equalsIgnoreCase("variable")) {
- String varName = element.getAttribute("name");
- String varPath = element.getAttribute("path");
+ if (element.getNodeName().equalsIgnoreCase("variable"/*nonNLS*/)) {
+ String varName = element.getAttribute("name"/*nonNLS*/);
+ String varPath = element.getAttribute("path"/*nonNLS*/);
try {
- JavaCore.setClasspathVariable(varName, new Path(varPath));
+ JavaCore.setClasspathVariable(varName, new Path(varPath), null);
} catch(JavaModelException e){
} catch(RuntimeException e){
}
@@ -893,7 +906,7 @@ public void prepareToSave(ISaveContext context) throws CoreException {
}
}
- }
+ }
/**
* Registers the given delta with this manager. This API is to be
* used to registerd deltas that are created explicitly by the Java
@@ -1044,7 +1057,7 @@ public void rollback(ISaveContext context){
if (vStats != null) {
IStatus[] stats= new IStatus[vStats.size()];
vStats.copyInto(stats);
- throw new CoreException(new MultiStatus(JavaCore.PLUGIN_ID, IStatus.ERROR, stats, "Error saving builder states", null));
+ throw new CoreException(new MultiStatus(JavaCore.PLUGIN_ID, IStatus.ERROR, stats, Util.bind("build.cannotSaveStates"/*nonNLS*/), null));
}
}
/**
@@ -1052,7 +1065,7 @@ public void rollback(ISaveContext context){
*/
private void saveState(PerProjectInfo info) throws CoreException {
- if (VERBOSE) System.out.println("Saving Java Image Builder state for project " + info.project.getName());
+ if (VERBOSE) System.out.println(Util.bind("build.saveStateProgress"/*nonNLS*/, info.project.getName()));
long t= System.currentTimeMillis();
File file= getSerializationFile(info.project);
if (file == null) return;
@@ -1060,7 +1073,7 @@ public void rollback(ISaveContext context){
DataOutputStream out= new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
try {
out.writeUTF(JavaCore.PLUGIN_ID);
- out.writeUTF("STATE");
+ out.writeUTF("STATE"/*nonNLS*/);
out.writeInt(0x0001);
IState state= info.getLastBuiltState();
if (state == null) {
@@ -1077,16 +1090,16 @@ public void rollback(ISaveContext context){
file.delete();
} catch(SecurityException se){
}
- throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error saving last build state for project "+ info.project.getFullPath(), e));
+ throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Util.bind("build.cannotSaveState"/*nonNLS*/, info.project.getName()), e));
} catch (IOException e) {
try {
file.delete();
} catch(SecurityException se){
}
- throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, "Error saving last build state for project "+ info.project.getFullPath(), e));
+ throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Util.bind("build.cannotSaveState"/*nonNLS*/, info.project.getName()), e));
}
t= System.currentTimeMillis() - t;
- if (VERBOSE) System.out.println(" Saved in " + t + "ms");
+ if (VERBOSE) System.out.println(Util.bind("build.saveStateComplete"/*nonNLS*/, String.valueOf(t)));
}
/**
* Saves the built state for the project if it has been changed since last save.
@@ -1106,7 +1119,7 @@ public void rollback(ISaveContext context){
}
public void saveVariables() throws CoreException {
ResourcesPlugin.getWorkspace().getRoot().setPersistentProperty(
- new QualifiedName(JavaCore.PLUGIN_ID, "variables"),
+ new QualifiedName(JavaCore.PLUGIN_ID, "variables"/*nonNLS*/),
getVariablesAsXMLString());
}
/**
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelOperation.java
index 8dae75ffc6..822686bbcd 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelOperation.java
@@ -14,8 +14,7 @@ import java.io.InputStream;
/**
* Defines behavior common to all Java Model operations
*/
-public abstract class JavaModelOperation
- implements IWorkspaceRunnable, IProgressMonitor {
+public abstract class JavaModelOperation implements IWorkspaceRunnable, IProgressMonitor {
/**
* The elements this operation operates on,
* or <code>null</code> if this operation
@@ -33,8 +32,7 @@ public abstract class JavaModelOperation
* empty result if no elements are created, or if this
* operation is not actually executed.
*/
- protected static IJavaElement[] fgEmptyResult = new IJavaElement[] {
- };
+ protected static IJavaElement[] fgEmptyResult= new IJavaElement[] {};
/**
* Collection of <code>IJavaElementDelta</code>s created by this operation.
@@ -43,17 +41,17 @@ public abstract class JavaModelOperation
* deltas. This collection is registered with the Java Model notification
* manager if the operation completes successfully.
*/
- protected IJavaElementDelta[] fDeltas = null;
+ protected IJavaElementDelta[] fDeltas= null;
/**
* The elements created by this operation - empty
* until the operation actually creates elements.
*/
- protected IJavaElement[] fResultElements = fgEmptyResult;
+ protected IJavaElement[] fResultElements= fgEmptyResult;
/**
* The progress monitor passed into this operation
*/
- protected IProgressMonitor fMonitor = null;
+ protected IProgressMonitor fMonitor= null;
/**
* A flag indicating whether this operation is nested.
*/
@@ -61,545 +59,471 @@ public abstract class JavaModelOperation
/**
* Conflict resolution policy - by default do not force (fail on a conflict).
*/
- protected boolean fForce = false;
- /**
- * A common constructor for all Java Model operations.
- */
- protected JavaModelOperation(IJavaElement[] elements) {
- fElementsToProcess = elements;
- }
-
- /**
- * Common constructor for all Java Model operations.
- */
- protected JavaModelOperation(
- IJavaElement[] elementsToProcess,
- IJavaElement[] parentElements) {
- fElementsToProcess = elementsToProcess;
- fParentElements = parentElements;
- }
-
- /**
- * A common constructor for all Java Model operations.
- */
- protected JavaModelOperation(
- IJavaElement[] elementsToProcess,
- IJavaElement[] parentElements,
- boolean force) {
- fElementsToProcess = elementsToProcess;
- fParentElements = parentElements;
- fForce = force;
- }
-
- /**
- * A common constructor for all Java Model operations.
- */
- protected JavaModelOperation(IJavaElement[] elements, boolean force) {
- fElementsToProcess = elements;
- fForce = force;
- }
-
- /**
- * Common constructor for all Java Model operations.
- */
- protected JavaModelOperation(IJavaElement element) {
- fElementsToProcess = new IJavaElement[] { element };
- }
-
- /**
- * A common constructor for all Java Model operations.
- */
- protected JavaModelOperation(IJavaElement element, boolean force) {
- fElementsToProcess = new IJavaElement[] { element };
- fForce = force;
+ protected boolean fForce= false;
+/**
+ * A common constructor for all Java Model operations.
+ */
+protected JavaModelOperation(IJavaElement[] elements) {
+ fElementsToProcess = elements;
+}
+/**
+ * Common constructor for all Java Model operations.
+ */
+protected JavaModelOperation(IJavaElement[] elementsToProcess, IJavaElement[] parentElements) {
+ fElementsToProcess = elementsToProcess;
+ fParentElements= parentElements;
+}
+/**
+ * A common constructor for all Java Model operations.
+ */
+protected JavaModelOperation(IJavaElement[] elementsToProcess, IJavaElement[] parentElements, boolean force) {
+ fElementsToProcess = elementsToProcess;
+ fParentElements= parentElements;
+ fForce= force;
+}
+/**
+ * A common constructor for all Java Model operations.
+ */
+protected JavaModelOperation(IJavaElement[] elements, boolean force) {
+ fElementsToProcess = elements;
+ fForce= force;
+}
+/**
+ * Common constructor for all Java Model operations.
+ */
+protected JavaModelOperation(IJavaElement element) {
+ fElementsToProcess = new IJavaElement[]{element};
+}
+/**
+ * A common constructor for all Java Model operations.
+ */
+protected JavaModelOperation(IJavaElement element, boolean force) {
+ fElementsToProcess = new IJavaElement[]{element};
+ fForce= force;
+}
+/**
+ * Adds the given delta to the collection of deltas
+ * that this operation has created. These deltas are
+ * automatically registered with the Java Model Manager
+ * when the operation completes.
+ */
+protected void addDelta(IJavaElementDelta delta) {
+ if (fDeltas == null) {
+ fDeltas= new IJavaElementDelta[] {delta};
+ } else {
+ IJavaElementDelta[] copy= new IJavaElementDelta[fDeltas.length + 1];
+ System.arraycopy(fDeltas, 0, copy, 0, fDeltas.length);
+ copy[fDeltas.length]= delta;
+ fDeltas= copy;
}
-
- /**
- * Adds the given delta to the collection of deltas
- * that this operation has created. These deltas are
- * automatically registered with the Java Model Manager
- * when the operation completes.
- */
- protected void addDelta(IJavaElementDelta delta) {
- if (fDeltas == null) {
- fDeltas = new IJavaElementDelta[] { delta };
- } else {
- IJavaElementDelta[] copy = new IJavaElementDelta[fDeltas.length + 1];
- System.arraycopy(fDeltas, 0, copy, 0, fDeltas.length);
- copy[fDeltas.length] = delta;
- fDeltas = copy;
- }
+}
+/**
+ * @see IProgressMonitor
+ */
+public void beginTask(String name, int totalWork) {
+ if (fMonitor != null) {
+ fMonitor.beginTask(name, totalWork);
}
-
- /**
- * @see IProgressMonitor
- */
- public void beginTask(String name, int totalWork) {
- if (fMonitor != null) {
- fMonitor.beginTask(name, totalWork);
- }
+}
+/**
+ * Checks with the progress monitor to see whether this operation
+ * should be canceled. An operation should regularly call this method
+ * during its operation so that the user can cancel it.
+ *
+ * @exception OperationCanceledException if cancelling the operation has been requested
+ * @see IProgressMonitor#isCanceled
+ */
+protected void checkCanceled() {
+ if (isCanceled()) {
+ throw new OperationCanceledException(Util.bind("operation.cancelled"/*nonNLS*/));
}
-
- /**
- * Checks with the progress monitor to see whether this operation
- * should be canceled. An operation should regularly call this method
- * during its operation so that the user can cancel it.
- *
- * @exception OperationCanceledException if cancelling the operation has been requested
- * @see IProgressMonitor#isCanceled
- */
- protected void checkCanceled() {
- if (isCanceled()) {
- throw new OperationCanceledException("Operation cancelled");
- }
+}
+/**
+ * Common code used to verify the elements this operation is processing.
+ * @see JavaModelOperation#verify()
+ */
+protected IJavaModelStatus commonVerify() {
+ if (fElementsToProcess == null || fElementsToProcess.length == 0) {
+ return new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
}
-
- /**
- * Common code used to verify the elements this operation is processing.
- * @see JavaModelOperation#verify()
- */
- protected IJavaModelStatus commonVerify() {
- if (fElementsToProcess == null || fElementsToProcess.length == 0) {
+ for (int i = 0; i < fElementsToProcess.length; i++) {
+ if (fElementsToProcess[i] == null) {
return new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
}
- for (int i = 0; i < fElementsToProcess.length; i++) {
- if (fElementsToProcess[i] == null) {
- return new JavaModelStatus(IJavaModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
- }
- }
- return JavaModelStatus.VERIFIED_OK;
}
-
- /**
- * Convenience method to copy resources
- */
- protected void copyResources(IResource[] resources, IPath destinationPath)
- throws JavaModelException {
- IProgressMonitor subProgressMonitor = getSubProgressMonitor(resources.length);
- IWorkspace workspace = resources[0].getWorkspace();
- try {
- workspace.copy(resources, destinationPath, false, subProgressMonitor);
- } catch (CoreException e) {
- throw new JavaModelException(e);
- }
+ return JavaModelStatus.VERIFIED_OK;
+}
+/**
+ * Convenience method to copy resources
+ */
+protected void copyResources(IResource[] resources, IPath destinationPath) throws JavaModelException {
+ IProgressMonitor subProgressMonitor = getSubProgressMonitor(resources.length);
+ IWorkspace workspace = resources[0].getWorkspace();
+ try {
+ workspace.copy(resources, destinationPath, false, subProgressMonitor);
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
-
- /**
- * Convenience method to create a file
- */
- protected void createFile(
- IContainer folder,
- String name,
- InputStream contents,
- boolean force)
- throws JavaModelException {
- IFile file = folder.getFile(new Path(name));
- try {
- file.create(contents, force, getSubProgressMonitor(1));
- } catch (CoreException e) {
- throw new JavaModelException(e);
- }
+}
+/**
+ * Convenience method to create a file
+ */
+protected void createFile(IContainer folder, String name, InputStream contents, boolean force) throws JavaModelException {
+ IFile file= folder.getFile(new Path(name));
+ try {
+ file.create(contents, force, getSubProgressMonitor(1));
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
-
- /**
- * Convenience method to create a folder
- */
- protected void createFolder(
- IContainer parentFolder,
- String name,
- boolean force)
- throws JavaModelException {
- IFolder folder = parentFolder.getFolder(new Path(name));
- try {
- // we should use true to create the file locally. Only VCM should use tru/false
- folder.create(force, true, getSubProgressMonitor(1));
- } catch (CoreException e) {
- throw new JavaModelException(e);
- }
+}
+/**
+ * Convenience method to create a folder
+ */
+protected void createFolder(IContainer parentFolder, String name, boolean force) throws JavaModelException {
+ IFolder folder= parentFolder.getFolder(new Path(name));
+ try {
+ // we should use true to create the file locally. Only VCM should use tru/false
+ folder.create(force, true, getSubProgressMonitor(1));
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
-
- /**
- * Convenience method to delete an empty package fragment
- */
- protected void deleteEmptyPackageFragment(
- IPackageFragment fragment,
- boolean force)
- throws JavaModelException {
-
- IContainer resource = (IContainer) fragment.getCorrespondingResource();
- IResource rootResource = fragment.getParent().getUnderlyingResource();
-
- try {
- resource.delete(force, getSubProgressMonitor(1));
- while (resource instanceof IFolder) {
- // deleting a package: delete the parent if it is empty (eg. deleting x.y where folder x doesn't have resources but y)
- // without deleting the package fragment root
- resource = resource.getParent();
- if (!resource.equals(rootResource) && resource.members().length == 0) {
- resource.delete(force, getSubProgressMonitor(1));
- }
+}
+/**
+ * Convenience method to delete an empty package fragment
+ */
+protected void deleteEmptyPackageFragment(
+ IPackageFragment fragment,
+ boolean force)
+ throws JavaModelException {
+
+ IContainer resource = (IContainer) fragment.getCorrespondingResource();
+ IResource rootResource = fragment.getParent().getUnderlyingResource();
+
+ try {
+ resource.delete(force, getSubProgressMonitor(1));
+ while (resource instanceof IFolder) {
+ // deleting a package: delete the parent if it is empty (eg. deleting x.y where folder x doesn't have resources but y)
+ // without deleting the package fragment root
+ resource = resource.getParent();
+ if (!resource.equals(rootResource) && resource.members().length == 0) {
+ resource.delete(force, getSubProgressMonitor(1));
}
- } catch (CoreException e) {
- throw new JavaModelException(e);
}
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
-
- /**
- * Convenience method to delete a resource
- */
- protected void deleteResource(IResource resource, boolean force)
- throws JavaModelException {
- try {
- resource.delete(force, getSubProgressMonitor(1));
- } catch (CoreException e) {
- throw new JavaModelException(e);
- }
- }
-
- /**
- * Convenience method to delete resources
- */
- protected void deleteResources(IResource[] resources, boolean force)
- throws JavaModelException {
- if (resources == null || resources.length == 0)
- return;
- IProgressMonitor subProgressMonitor = getSubProgressMonitor(resources.length);
- IWorkspace workspace = resources[0].getWorkspace();
- try {
- workspace.delete(resources, force, subProgressMonitor);
- } catch (CoreException e) {
- throw new JavaModelException(e);
- }
- }
-
- /**
- * @see IProgressMonitor
- */
- public void done() {
- if (fMonitor != null) {
- fMonitor.done();
- }
- }
-
- /**
- * Verifies the operation can proceed and executes the operation.
- * Subclasses should override <code>#verify</code> and
- * <code>executeOperation</code> to implement the specific operation behavior.
- *
- * @exception JavaModelException The operation has failed.
- */
- protected void execute() throws JavaModelException {
- IJavaModelStatus status = verify();
- if (status.isOK()) {
- executeOperation();
- } else {
- throw new JavaModelException(status);
- }
+}
+/**
+ * Convenience method to delete a resource
+ */
+protected void deleteResource(IResource resource, boolean force) throws JavaModelException {
+ try {
+ resource.delete(force, getSubProgressMonitor(1));
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
-
- /**
- * Convenience method to run an operation within this operation
- */
- public void executeNestedOperation(
- JavaModelOperation operation,
- int subWorkAmount)
- throws JavaModelException {
- IProgressMonitor subProgressMonitor = getSubProgressMonitor(subWorkAmount);
- // fix for 1FW7IKC, part (1)
- try {
- operation.setNested(true);
- operation.run(subProgressMonitor);
- //accumulate the nested operation deltas
- for (int i = 0; i < operation.fDeltas.length; i++) {
- addDelta(operation.fDeltas[i]);
- }
- } catch (CoreException ce) {
- if (ce instanceof JavaModelException) {
- throw (JavaModelException) ce;
- } else {
- // translate the core exception to a java model exception
- if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) {
- Throwable e = ce.getStatus().getException();
- if (e instanceof JavaModelException) {
- throw (JavaModelException) e;
- }
- }
- throw new JavaModelException(ce);
- }
- }
+}
+/**
+ * Convenience method to delete resources
+ */
+protected void deleteResources(IResource[] resources, boolean force) throws JavaModelException {
+ if (resources == null || resources.length == 0) return;
+ IProgressMonitor subProgressMonitor = getSubProgressMonitor(resources.length);
+ IWorkspace workspace = resources[0].getWorkspace();
+ try {
+ workspace.delete(resources, force, subProgressMonitor);
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
-
- /**
- * Performs the operation specific behavior. Subclasses must override.
- */
- protected abstract void executeOperation() throws JavaModelException;
- /**
- * Returns the compilation unit the given element is contained in,
- * or the element itself (if it is a compilation unit),
- * otherwise <code>null</code>.
- */
- protected ICompilationUnit getCompilationUnitFor(IJavaElement element) {
-
- return ((JavaElement) element).getCompilationUnit();
+}
+/**
+ * @see IProgressMonitor
+ */
+public void done() {
+ if (fMonitor != null) {
+ fMonitor.done();
}
-
- /**
- * Returns the elements to which this operation applies,
- * or <code>null</code> if not applicable.
- */
- protected IJavaElement[] getElementsToProcess() {
- return fElementsToProcess;
+}
+/**
+ * Verifies the operation can proceed and executes the operation.
+ * Subclasses should override <code>#verify</code> and
+ * <code>executeOperation</code> to implement the specific operation behavior.
+ *
+ * @exception JavaModelException The operation has failed.
+ */
+protected void execute() throws JavaModelException {
+ IJavaModelStatus status= verify();
+ if (status.isOK()) {
+ executeOperation();
+ } else {
+ throw new JavaModelException(status);
}
-
- /**
- * Returns the element to which this operation applies,
- * or <code>null</code> if not applicable.
- */
- protected IJavaElement getElementToProcess() {
- if (fElementsToProcess == null || fElementsToProcess.length == 0) {
- return null;
+}
+/**
+ * Convenience method to run an operation within this operation
+ */
+public void executeNestedOperation(JavaModelOperation operation, int subWorkAmount) throws JavaModelException {
+ IProgressMonitor subProgressMonitor = getSubProgressMonitor(subWorkAmount);
+ // fix for 1FW7IKC, part (1)
+ try {
+ operation.setNested(true);
+ operation.run(subProgressMonitor);
+ //accumulate the nested operation deltas
+ for (int i = 0; i < operation.fDeltas.length; i++) {
+ addDelta(operation.fDeltas[i]);
}
- return fElementsToProcess[0];
- }
-
- /**
- * Returns the Java Model this operation is operating in.
- */
- public IJavaModel getJavaModel() {
- if (fElementsToProcess == null || fElementsToProcess.length == 0) {
- return getParentElement().getJavaModel();
+ } catch (CoreException ce) {
+ if (ce instanceof JavaModelException) {
+ throw (JavaModelException)ce;
} else {
- return fElementsToProcess[0].getJavaModel();
- }
- }
-
- /**
- * Returns the parent element to which this operation applies,
- * or <code>null</code> if not applicable.
- */
- protected IJavaElement getParentElement() {
- if (fParentElements == null || fParentElements.length == 0) {
- return null;
+ // translate the core exception to a java model exception
+ if (ce.getStatus().getCode() == IResourceStatus.OPERATION_FAILED) {
+ Throwable e = ce.getStatus().getException();
+ if (e instanceof JavaModelException) {
+ throw (JavaModelException) e;
+ }
+ }
+ throw new JavaModelException(ce);
}
- return fParentElements[0];
- }
-
- /**
- * Returns the parent elements to which this operation applies,
- * or <code>null</code> if not applicable.
- */
- protected IJavaElement[] getParentElements() {
- return fParentElements;
}
+}
+/**
+ * Performs the operation specific behavior. Subclasses must override.
+ */
+protected abstract void executeOperation() throws JavaModelException;
+/**
+ * Returns the compilation unit the given element is contained in,
+ * or the element itself (if it is a compilation unit),
+ * otherwise <code>null</code>.
+ */
+protected ICompilationUnit getCompilationUnitFor(IJavaElement element) {
- /**
- * Returns the elements created by this operation.
- */
- public IJavaElement[] getResultElements() {
- return fResultElements;
+ return ((JavaElement)element).getCompilationUnit();
+}
+/**
+ * Returns the elements to which this operation applies,
+ * or <code>null</code> if not applicable.
+ */
+protected IJavaElement[] getElementsToProcess() {
+ return fElementsToProcess;
+}
+/**
+ * Returns the element to which this operation applies,
+ * or <code>null</code> if not applicable.
+ */
+protected IJavaElement getElementToProcess() {
+ if (fElementsToProcess == null || fElementsToProcess.length == 0) {
+ return null;
}
-
- /**
- * Creates and returns a subprogress monitor if appropriate.
- */
- protected IProgressMonitor getSubProgressMonitor(int workAmount) {
- IProgressMonitor sub = null;
- if (fMonitor != null) {
- sub =
- new SubProgressMonitor(
- fMonitor,
- workAmount,
- SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
- }
- return sub;
+ return fElementsToProcess[0];
+}
+/**
+ * Returns the Java Model this operation is operating in.
+ */
+public IJavaModel getJavaModel() {
+ if (fElementsToProcess == null || fElementsToProcess.length == 0) {
+ return getParentElement().getJavaModel();
+ } else {
+ return fElementsToProcess[0].getJavaModel();
}
-
- /**
- * Returns the <code>IWorkspace</code> this operation is working in, or
- * <code>null</code> if this operation has no elements to process.
- */
- protected IWorkspace getWorkspace() {
- if (fElementsToProcess != null && fElementsToProcess.length > 0) {
- IJavaProject project = fElementsToProcess[0].getJavaProject();
- if (project != null) {
- return project.getJavaModel().getWorkspace();
- }
- }
+}
+/**
+ * Returns the parent element to which this operation applies,
+ * or <code>null</code> if not applicable.
+ */
+protected IJavaElement getParentElement() {
+ if (fParentElements == null || fParentElements.length == 0) {
return null;
}
-
- public void internalWorked(double work) {
- if (fMonitor != null) {
- fMonitor.internalWorked(work);
- }
+ return fParentElements[0];
+}
+/**
+ * Returns the parent elements to which this operation applies,
+ * or <code>null</code> if not applicable.
+ */
+protected IJavaElement[] getParentElements() {
+ return fParentElements;
+}
+/**
+ * Returns the elements created by this operation.
+ */
+public IJavaElement[] getResultElements() {
+ return fResultElements;
+}
+/**
+ * Creates and returns a subprogress monitor if appropriate.
+ */
+protected IProgressMonitor getSubProgressMonitor(int workAmount) {
+ IProgressMonitor sub = null;
+ if (fMonitor != null) {
+ sub = new SubProgressMonitor(fMonitor, workAmount, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
}
-
- /**
- * @see IProgressMonitor
- */
- public boolean isCanceled() {
- if (fMonitor != null) {
- return fMonitor.isCanceled();
+ return sub;
+}
+/**
+ * Returns the <code>IWorkspace</code> this operation is working in, or
+ * <code>null</code> if this operation has no elements to process.
+ */
+protected IWorkspace getWorkspace() {
+ if (fElementsToProcess != null && fElementsToProcess.length > 0) {
+ IJavaProject project = fElementsToProcess[0].getJavaProject();
+ if (project != null) {
+ return project.getJavaModel().getWorkspace();
}
- return false;
- }
-
- /**
- * Returns <code>true</code> if this operation performs no resource modifications,
- * otherwise <code>false</code>. Subclasses must override.
- */
- public boolean isReadOnly() {
- return false;
}
-
- /**
- * Traverses the deltas for an working copies and makes them
- * consistent.
- */
- protected void makeWorkingCopiesConsistent(IJavaElementDelta[] deltas) {
- for (int i = 0; i < deltas.length; i++) {
- walkDeltaMakingWorkingCopiesConsistent(deltas[i]);
- }
+ return null;
+}
+public void internalWorked(double work) {
+ if (fMonitor != null) {
+ fMonitor.internalWorked(work);
}
-
- /**
- * Convenience method to move resources
- */
- protected void moveResources(IResource[] resources, IPath destinationPath)
- throws JavaModelException {
- IProgressMonitor subProgressMonitor = null;
- if (fMonitor != null) {
- subProgressMonitor =
- new SubProgressMonitor(
- fMonitor,
- resources.length,
- SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
- }
- IWorkspace workspace = resources[0].getWorkspace();
- try {
- workspace.move(resources, destinationPath, false, subProgressMonitor);
- } catch (CoreException e) {
- throw new JavaModelException(e);
- }
+}
+/**
+ * @see IProgressMonitor
+ */
+public boolean isCanceled() {
+ if (fMonitor != null) {
+ return fMonitor.isCanceled();
}
-
- /**
- * Creates and returns a new <code>IJavaElementDelta</code>
- * on the Java Model.
- */
- public JavaElementDelta newJavaElementDelta() {
- return new JavaElementDelta(getJavaModel());
+ return false;
+}
+/**
+ * Returns <code>true</code> if this operation performs no resource modifications,
+ * otherwise <code>false</code>. Subclasses must override.
+ */
+public boolean isReadOnly() {
+ return false;
+}
+/**
+ * Traverses the deltas for an working copies and makes them
+ * consistent.
+ */
+protected void makeWorkingCopiesConsistent(IJavaElementDelta[] deltas) {
+ for (int i= 0; i < deltas.length; i++) {
+ walkDeltaMakingWorkingCopiesConsistent(deltas[i]);
}
-
- /**
- * Registers any deltas this operation created, with the
- * Java Model manager.
- */
- protected void registerDeltas() {
- if (fDeltas != null && !fNested) {
- // hook to ensure working copies remain consistent
- makeWorkingCopiesConsistent(fDeltas);
- JavaModelManager manager =
- (JavaModelManager) JavaModelManager.getJavaModelManager();
- for (int i = 0; i < fDeltas.length; i++) {
- manager.registerJavaModelDelta(fDeltas[i]);
- }
- }
+}
+/**
+ * Convenience method to move resources
+ */
+protected void moveResources(IResource[] resources, IPath destinationPath) throws JavaModelException {
+ IProgressMonitor subProgressMonitor = null;
+ if (fMonitor != null) {
+ subProgressMonitor = new SubProgressMonitor(fMonitor, resources.length, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
}
-
- /**
- * Main entry point for Java Model operations. Executes this operation
- * and registers any deltas created.
- *
- * @see IWorkspaceRunnable
- * @exception CoreException if the operation fails
- */
- public void run(IProgressMonitor monitor) throws CoreException {
- try {
- fMonitor = monitor;
- execute();
- } finally {
- registerDeltas();
- }
+ IWorkspace workspace = resources[0].getWorkspace();
+ try {
+ workspace.move(resources, destinationPath, false, subProgressMonitor);
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
-
- /**
- * @see IProgressMonitor
- */
- public void setCanceled(boolean b) {
- if (fMonitor != null) {
- fMonitor.setCanceled(b);
+}
+/**
+ * Creates and returns a new <code>IJavaElementDelta</code>
+ * on the Java Model.
+ */
+public JavaElementDelta newJavaElementDelta() {
+ return new JavaElementDelta(getJavaModel());
+}
+/**
+ * Registers any deltas this operation created, with the
+ * Java Model manager.
+ */
+protected void registerDeltas() {
+ if (fDeltas != null && !fNested) {
+ // hook to ensure working copies remain consistent
+ makeWorkingCopiesConsistent(fDeltas);
+ JavaModelManager manager= (JavaModelManager)JavaModelManager.getJavaModelManager();
+ for (int i= 0; i < fDeltas.length; i++) {
+ manager.registerJavaModelDelta(fDeltas[i]);
}
}
-
- /**
- * Sets whether this operation is nested or not.
- * @see CreateElementInCUOperation#checkCanceled
- */
- protected void setNested(boolean nested) {
- fNested = nested;
+}
+/**
+ * Main entry point for Java Model operations. Executes this operation
+ * and registers any deltas created.
+ *
+ * @see IWorkspaceRunnable
+ * @exception CoreException if the operation fails
+ */
+public void run(IProgressMonitor monitor) throws CoreException {
+ try {
+ fMonitor = monitor;
+ execute();
+ } finally {
+ registerDeltas();
}
-
- /**
- * @see IProgressMonitor
- */
- public void setTaskName(String name) {
- if (fMonitor != null) {
- fMonitor.setTaskName(name);
- }
+}
+/**
+ * @see IProgressMonitor
+ */
+public void setCanceled(boolean b) {
+ if (fMonitor != null) {
+ fMonitor.setCanceled(b);
}
-
- /**
- * @see IProgressMonitor
- */
- public void subTask(String name) {
- if (fMonitor != null) {
- fMonitor.subTask(name);
- }
+}
+/**
+ * Sets whether this operation is nested or not.
+ * @see CreateElementInCUOperation#checkCanceled
+ */
+protected void setNested(boolean nested) {
+ fNested = nested;
+}
+/**
+ * @see IProgressMonitor
+ */
+public void setTaskName(String name) {
+ if (fMonitor != null) {
+ fMonitor.setTaskName(name);
}
-
- /**
- * Returns a status indicating if there is any known reason
- * this operation will fail. Operations are verified before they
- * are run.
- *
- * Subclasses must override if they have any conditions to verify
- * before this operation executes.
- *
- * @see IJavaModelStatus
- */
- protected IJavaModelStatus verify() {
- return commonVerify();
+}
+/**
+ * @see IProgressMonitor
+ */
+public void subTask(String name) {
+ if (fMonitor != null) {
+ fMonitor.subTask(name);
}
-
- /**
- * Traverses the delta making any working copies consistent
- */
- protected void walkDeltaMakingWorkingCopiesConsistent(IJavaElementDelta delta) {
- if (delta.getElement().getElementType() == IJavaElement.COMPILATION_UNIT) {
- ICompilationUnit unit = (ICompilationUnit) delta.getElement();
- if (unit.isWorkingCopy()) {
- try {
- unit.makeConsistent(null);
- } catch (JavaModelException e) {
- }
- }
- } else {
- IJavaElementDelta[] deltas = delta.getAffectedChildren();
- for (int i = 0; i < deltas.length; i++) {
- walkDeltaMakingWorkingCopiesConsistent(deltas[i]);
+}
+/**
+ * Returns a status indicating if there is any known reason
+ * this operation will fail. Operations are verified before they
+ * are run.
+ *
+ * Subclasses must override if they have any conditions to verify
+ * before this operation executes.
+ *
+ * @see IJavaModelStatus
+ */
+protected IJavaModelStatus verify() {
+ return commonVerify();
+}
+/**
+ * Traverses the delta making any working copies consistent
+ */
+protected void walkDeltaMakingWorkingCopiesConsistent(IJavaElementDelta delta) {
+ if (delta.getElement().getElementType() == IJavaElement.COMPILATION_UNIT) {
+ ICompilationUnit unit = (ICompilationUnit) delta.getElement();
+ if (unit.isWorkingCopy()) {
+ try {
+ unit.makeConsistent(null);
+ } catch (JavaModelException e) {
}
}
- }
-
- /**
- * @see IProgressMonitor
- */
- public void worked(int work) {
- if (fMonitor != null) {
- fMonitor.worked(work);
- checkCanceled();
+ } else {
+ IJavaElementDelta[] deltas = delta.getAffectedChildren();
+ for (int i = 0; i < deltas.length; i++) {
+ walkDeltaMakingWorkingCopiesConsistent(deltas[i]);
}
}
-
+}
+/**
+ * @see IProgressMonitor
+ */
+public void worked(int work) {
+ if (fMonitor != null) {
+ fMonitor.worked(work);
+ checkCanceled();
+ }
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelStatus.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelStatus.java
index 8080495902..c868e21682 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelStatus.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaModelStatus.java
@@ -21,9 +21,7 @@ import org.eclipse.core.runtime.CoreException;
* @see IJavaModelStatus
*/
-public class JavaModelStatus
- extends Status
- implements IJavaModelStatus, IJavaModelStatusConstants, IResourceStatus {
+public class JavaModelStatus extends Status implements IJavaModelStatus, IJavaModelStatusConstants, IResourceStatus {
/**
* The elements related to the failure, or <code>null</code>
@@ -47,312 +45,275 @@ public class JavaModelStatus
/**
* Empty children
*/
- protected final static IStatus[] fgEmptyChildren = new IStatus[] {
- };
-
- protected IStatus[] fChildren = fgEmptyChildren;
- /**
- * Constructs an Java model status with no corresponding elements.
- */
- public JavaModelStatus() {
- // no code for an multi-status
- super(ERROR, JavaCore.PLUGIN_ID, 0, "JavaModelStatus", null);
- }
-
- /**
- * Constructs an Java model status with no corresponding elements.
- */
- public JavaModelStatus(int code) {
- super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus", null);
- fElements = JavaElementInfo.fgEmptyChildren;
- }
-
- /**
- * Constructs an Java model status with the given corresponding
- * elements.
- */
- public JavaModelStatus(int code, IJavaElement[] elements) {
- super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus", null);
- fElements = elements;
- fPath = null;
- }
-
- /**
- * Constructs an Java model status with no corresponding elements.
- */
- public JavaModelStatus(int code, String string) {
- super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus", null);
- fElements = JavaElementInfo.fgEmptyChildren;
- fPath = null;
- fString = string;
- }
-
- /**
- * Constructs an Java model status with no corresponding elements.
- */
- public JavaModelStatus(int code, Throwable throwable) {
- super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus", throwable);
- fElements = JavaElementInfo.fgEmptyChildren;
- }
-
- /**
- * Constructs an Java model status with no corresponding elements.
- */
- public JavaModelStatus(int code, IPath path) {
- super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus", null);
- fElements = JavaElementInfo.fgEmptyChildren;
- fPath = path;
- }
-
- /**
- * Constructs an Java model status with the given corresponding
- * element.
- */
- public JavaModelStatus(int code, IJavaElement element) {
- this(code, new IJavaElement[] { element });
- }
-
- /**
- * Constructs an Java model status with the given corresponding
- * element and string
- */
- public JavaModelStatus(int code, IJavaElement element, String string) {
- this(code, new IJavaElement[] { element });
- fString = string;
- }
-
- /**
- * Constructs an Java model status with no corresponding elements.
- */
- public JavaModelStatus(CoreException coreException) {
- super(
- ERROR,
- JavaCore.PLUGIN_ID,
- CORE_EXCEPTION,
- "JavaModelStatus",
- coreException);
- fElements = JavaElementInfo.fgEmptyChildren;
- }
-
- protected int getBits() {
- int severity = 1 << (getCode() % 100 / 33);
- int category = 1 << ((getCode() / 100) + 3);
- return severity | category;
- }
-
- /**
- * @see IStatus
- */
- public IStatus[] getChildren() {
- return fChildren;
- }
-
- /**
- * @see IJavaModelStatus
- */
- public IJavaElement[] getElements() {
- return fElements;
- }
-
- /**
- * Returns the message that is relevant to the code of this status.
- */
- public String getMessage() {
- if (getException() == null) {
- switch (getCode()) {
- case CORE_EXCEPTION :
- return "Core exception.";
- case BUILDER_INITIALIZATION_ERROR :
- return "Builder initialization error.";
- case BUILDER_SERIALIZATION_ERROR :
- return "Builder serialization error.";
- case DEVICE_PATH :
- return "Operation requires a path with no device. Path specified was: "
- + getPath().toString();
- case DOM_EXCEPTION :
- return "JDOM error.";
- case ELEMENT_DOES_NOT_EXIST :
- return fElements[0].getElementName() + " does not exist.";
- case EVALUATION_ERROR :
- return "Evaluation error: " + getString();
- case INDEX_OUT_OF_BOUNDS :
- return "Index out of bounds.";
- case INVALID_CONTENTS :
- return "Invalid contents specified.";
- case INVALID_DESTINATION :
- return "Invalid destination: " + fElements[0].getElementName();
- case INVALID_ELEMENT_TYPES :
- StringBuffer buff =
- new StringBuffer("Operation not supported for specified element type(s): ");
- for (int i = 0; i < fElements.length; i++) {
- if (i > 0) {
- buff.append(", ");
- }
- buff.append(fElements[0].getElementName());
- }
- return buff.toString();
- case INVALID_NAME :
- return "Invalid name specified: " + getString();
- case INVALID_PACKAGE :
- return "Invalid package: " + getString();
- case INVALID_PATH :
- return "Invalid path: " + (getPath() == null ? "null" : getPath().toString());
- case INVALID_PROJECT :
- return "Invalid project: " + getString();
- case INVALID_RESOURCE :
- return "Invalid resource: " + getString();
- case INVALID_RESOURCE_TYPE :
- return "Invalid resource type for " + getString();
- case INVALID_SIBLING :
- return "Invalid sibling: " + fElements[0].getElementName();
- case IO_EXCEPTION :
- return "IO exception.";
- case NAME_COLLISION :
- if (fElements != null && fElements.length > 0) {
- IJavaElement element = fElements[0];
- String name = element.getElementName();
- if (element instanceof IPackageFragment
- && name.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) {
- return "Default package cannot be renamed.";
- }
+ protected final static IStatus[] fgEmptyChildren = new IStatus[] {};
+ protected IStatus[] fChildren= fgEmptyChildren;
+/**
+ * Constructs an Java model status with no corresponding elements.
+ */
+public JavaModelStatus() {
+ // no code for an multi-status
+ super(ERROR, JavaCore.PLUGIN_ID, 0, "JavaModelStatus"/*nonNLS*/, null);
+}
+/**
+ * Constructs an Java model status with no corresponding elements.
+ */
+public JavaModelStatus(int code) {
+ super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus"/*nonNLS*/, null);
+ fElements= JavaElementInfo.fgEmptyChildren;
+}
+/**
+ * Constructs an Java model status with the given corresponding
+ * elements.
+ */
+public JavaModelStatus(int code, IJavaElement[] elements) {
+ super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus"/*nonNLS*/, null);
+ fElements= elements;
+ fPath= null;
+}
+/**
+ * Constructs an Java model status with no corresponding elements.
+ */
+public JavaModelStatus(int code, String string) {
+ super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus"/*nonNLS*/, null);
+ fElements= JavaElementInfo.fgEmptyChildren;
+ fPath= null;
+ fString = string;
+}
+/**
+ * Constructs an Java model status with no corresponding elements.
+ */
+public JavaModelStatus(int code, Throwable throwable) {
+ super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus"/*nonNLS*/, throwable);
+ fElements= JavaElementInfo.fgEmptyChildren;
+}
+/**
+ * Constructs an Java model status with no corresponding elements.
+ */
+public JavaModelStatus(int code, IPath path) {
+ super(ERROR, JavaCore.PLUGIN_ID, code, "JavaModelStatus"/*nonNLS*/, null);
+ fElements= JavaElementInfo.fgEmptyChildren;
+ fPath= path;
+}
+/**
+ * Constructs an Java model status with the given corresponding
+ * element.
+ */
+public JavaModelStatus(int code, IJavaElement element) {
+ this(code, new IJavaElement[]{element});
+}
+/**
+ * Constructs an Java model status with the given corresponding
+ * element and string
+ */
+public JavaModelStatus(int code, IJavaElement element, String string) {
+ this(code, new IJavaElement[]{element});
+ fString= string;
+}
+/**
+ * Constructs an Java model status with no corresponding elements.
+ */
+public JavaModelStatus(CoreException coreException) {
+ super(ERROR, JavaCore.PLUGIN_ID, CORE_EXCEPTION, "JavaModelStatus"/*nonNLS*/, coreException);
+ fElements= JavaElementInfo.fgEmptyChildren;
+}
+protected int getBits() {
+ int severity = 1 << (getCode() % 100 / 33);
+ int category = 1 << ((getCode() / 100) + 3);
+ return severity | category;
+}
+/**
+ * @see IStatus
+ */
+public IStatus[] getChildren() {
+ return fChildren;
+}
+/**
+ * @see IJavaModelStatus
+ */
+public IJavaElement[] getElements() {
+ return fElements;
+}
+/**
+ * Returns the message that is relevant to the code of this status.
+ */
+public String getMessage() {
+ if (getException() == null) {
+ switch (getCode()) {
+ case CORE_EXCEPTION :
+ return Util.bind("status.coreException"/*nonNLS*/);
+ case BUILDER_INITIALIZATION_ERROR:
+ return Util.bind("build.initializationError"/*nonNLS*/);
+ case BUILDER_SERIALIZATION_ERROR:
+ return Util.bind("build.serializationError"/*nonNLS*/);
+ case DEVICE_PATH:
+ return Util.bind("status.cannotUseDeviceOnPath"/*nonNLS*/, getPath().toString());
+ case DOM_EXCEPTION:
+ return Util.bind("status.JDOMError"/*nonNLS*/);
+ case ELEMENT_DOES_NOT_EXIST:
+ return Util.bind("element.doesNotExist"/*nonNLS*/,fElements[0].getElementName());
+ case EVALUATION_ERROR:
+ return Util.bind("status.evaluationError"/*nonNLS*/, getString());
+ case INDEX_OUT_OF_BOUNDS:
+ return Util.bind("status.indexOutOfBounds"/*nonNLS*/);
+ case INVALID_CONTENTS:
+ return Util.bind("status.invalidContents"/*nonNLS*/);
+ case INVALID_DESTINATION:
+ return Util.bind("status.invalidDestination"/*nonNLS*/, fElements[0].getElementName());
+ case INVALID_ELEMENT_TYPES:
+ StringBuffer buff= new StringBuffer(Util.bind("operation.notSupported"/*nonNLS*/));
+ for (int i= 0; i < fElements.length; i++) {
+ if (i > 0) {
+ buff.append(", "/*nonNLS*/);
}
- return "Name collision.";
- case NO_ELEMENTS_TO_PROCESS :
- return "Operation requires one or more elements.";
- case NULL_NAME :
- return "Operation requires a name.";
- case NULL_PATH :
- return "Operation requires a path.";
- case NULL_STRING :
- return "Operation requires a string.";
- case PATH_OUTSIDE_PROJECT :
- return "Illegal path specified: " + getPath().toString();
- case READ_ONLY :
+ buff.append(fElements[0].getElementName());
+ }
+ return buff.toString();
+ case INVALID_NAME:
+ return Util.bind("status.invalidName"/*nonNLS*/, getString());
+ case INVALID_PACKAGE:
+ return Util.bind("status.invalidPackage"/*nonNLS*/, getString());
+ case INVALID_PATH:
+ return Util.bind("status.invalidPath"/*nonNLS*/, getPath() == null ? "null"/*nonNLS*/ : getPath().toString());
+ case INVALID_PROJECT:
+ return Util.bind("status.invalidProject"/*nonNLS*/, getString());
+ case INVALID_RESOURCE:
+ return Util.bind("status.invalidResource"/*nonNLS*/, getString());
+ case INVALID_RESOURCE_TYPE:
+ return Util.bind("status.invalidResourceType"/*nonNLS*/, getString());
+ case INVALID_SIBLING:
+ return Util.bind("status.invalidSibling"/*nonNLS*/, fElements[0].getElementName());
+ case IO_EXCEPTION:
+ return Util.bind("status.IOException"/*nonNLS*/);
+ case NAME_COLLISION:
+ if (fElements != null && fElements.length > 0) {
IJavaElement element = fElements[0];
String name = element.getElementName();
- if (element instanceof IPackageFragment
- && name.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) {
- name = "Default package";
+ if (element instanceof IPackageFragment && name.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) {
+ return Util.bind("operation.cannotRenameDefaultPackage"/*nonNLS*/);
}
- return name + " is read-only.";
- case RELATIVE_PATH :
- return "Operation requires an absolute path. Relative path specified was: "
- + getPath().toString();
- case TARGET_EXCEPTION :
- return "Target exception.";
- case UPDATE_CONFLICT :
- return "Update conflict.";
- case NO_LOCAL_CONTENTS :
- return "Cannot find local contents for resource: " + getPath().toString();
- }
- return getString();
- } else {
- if (getCode() == CORE_EXCEPTION) {
- return "Core exception: " + getException().getMessage();
- }
- return getException().getMessage();
+ }
+ return Util.bind("status.nameCollision"/*nonNLS*/);
+ case NO_ELEMENTS_TO_PROCESS:
+ return Util.bind("operation.needElements"/*nonNLS*/);
+ case NULL_NAME:
+ return Util.bind("operation.needName"/*nonNLS*/);
+ case NULL_PATH:
+ return Util.bind("operation.needPath"/*nonNLS*/);
+ case NULL_STRING:
+ return Util.bind("operation.needString"/*nonNLS*/);
+ case PATH_OUTSIDE_PROJECT:
+ return Util.bind("operation.pathOutsideProject"/*nonNLS*/, getString(), fElements[0].getElementName());
+ case READ_ONLY:
+ IJavaElement element = fElements[0];
+ String name = element.getElementName();
+ if (element instanceof IPackageFragment && name.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) {
+ return Util.bind("status.defaultPackageReadOnly"/*nonNLS*/);
+ }
+ return Util.bind("status.readOnly"/*nonNLS*/, name);
+ case RELATIVE_PATH:
+ return Util.bind("operation.needAbsolutePath"/*nonNLS*/, getPath().toString());
+ case TARGET_EXCEPTION:
+ return Util.bind("status.targetException"/*nonNLS*/);
+ case UPDATE_CONFLICT:
+ return Util.bind("status.updateConflict"/*nonNLS*/);
+ case NO_LOCAL_CONTENTS :
+ return Util.bind("status.noLocalContents"/*nonNLS*/, getPath().toString());
}
- }
-
- /**
- * @see IOperationStatus
- */
- public IPath getPath() {
- return fPath;
- }
-
- /**
- * @see IStatus
- */
- public int getSeverity() {
- if (fChildren == fgEmptyChildren)
- return super.getSeverity();
- int severity = -1;
- for (int i = 0, max = fChildren.length; i < max; i++) {
- int childrenSeverity = fChildren[i].getSeverity();
- if (childrenSeverity > severity) {
- severity = childrenSeverity;
- }
+ return getString();
+ } else {
+ if (getCode() == CORE_EXCEPTION){
+ return Util.bind("status.coreExceptionWithArg"/*nonNLS*/, getException().getMessage());
}
- return severity;
- }
-
- /**
- * @see IJavaModelStatus
- */
- public String getString() {
- return fString;
+ return getException().getMessage();
}
-
- /**
- * @see IJavaModelStatus
- */
- public boolean isDoesNotExist() {
- return getCode() == ELEMENT_DOES_NOT_EXIST;
- }
-
- /**
- * @see IStatus
- */
- public boolean isMultiStatus() {
- return fChildren != fgEmptyChildren;
- }
-
- /**
- * @see IJavaModelStatus
- */
- public boolean isOK() {
- return getCode() == OK;
- }
-
- /**
- * @see IStatus#matches
- */
- public boolean matches(int mask) {
- if (!isMultiStatus()) {
- return matches(this, mask);
- } else {
- for (int i = 0, max = fChildren.length; i < max; i++) {
- if (matches((JavaModelStatus) fChildren[i], mask))
- return true;
- }
- return false;
+}
+/**
+ * @see IOperationStatus
+ */
+public IPath getPath() {
+ return fPath;
+}
+/**
+ * @see IStatus
+ */
+public int getSeverity() {
+ if (fChildren == fgEmptyChildren) return super.getSeverity();
+ int severity = -1;
+ for (int i = 0, max = fChildren.length; i < max; i++) {
+ int childrenSeverity = fChildren[i].getSeverity();
+ if (childrenSeverity > severity) {
+ severity = childrenSeverity;
}
}
-
- /**
- * Helper for matches(int).
- */
- protected boolean matches(JavaModelStatus status, int mask) {
- int severityMask = mask & 0x7;
- int categoryMask = mask & ~0x7;
- int bits = status.getBits();
- return ((severityMask == 0) || (bits & severityMask) != 0)
- && ((categoryMask == 0) || (bits & categoryMask) != 0);
- }
-
- /**
- * Creates and returns a new <code>IJavaModelStatus</code> that is a
- * a multi-status status.
- *
- * @see IStatus#.isMultiStatus()
- */
- public static IJavaModelStatus newMultiStatus(IJavaModelStatus[] children) {
- JavaModelStatus jms = new JavaModelStatus();
- jms.fChildren = children;
- return jms;
- }
-
- /**
- * Returns a printable representation of this exception for debugging
- * purposes.
- */
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append("Java Model Status [");
- buffer.append(getMessage());
- buffer.append("]");
- return buffer.toString();
+ return severity;
+}
+/**
+ * @see IJavaModelStatus
+ */
+public String getString() {
+ return fString;
+}
+/**
+ * @see IJavaModelStatus
+ */
+public boolean isDoesNotExist() {
+ return getCode() == ELEMENT_DOES_NOT_EXIST;
+}
+/**
+ * @see IStatus
+ */
+public boolean isMultiStatus() {
+ return fChildren != fgEmptyChildren;
+}
+/**
+ * @see IJavaModelStatus
+ */
+public boolean isOK() {
+ return getCode() == OK;
+}
+/**
+ * @see IStatus#matches
+ */
+public boolean matches(int mask) {
+ if (! isMultiStatus()) {
+ return matches(this, mask);
+ } else {
+ for (int i = 0, max = fChildren.length; i < max; i++) {
+ if (matches((JavaModelStatus) fChildren[i], mask))
+ return true;
+ }
+ return false;
}
-
+}
+/**
+ * Helper for matches(int).
+ */
+protected boolean matches(JavaModelStatus status, int mask) {
+ int severityMask = mask & 0x7;
+ int categoryMask = mask & ~0x7;
+ int bits = status.getBits();
+ return ((severityMask == 0) || (bits & severityMask) != 0) && ((categoryMask == 0) || (bits & categoryMask) != 0);
+}
+/**
+ * Creates and returns a new <code>IJavaModelStatus</code> that is a
+ * a multi-status status.
+ *
+ * @see IStatus#.isMultiStatus()
+ */
+public static IJavaModelStatus newMultiStatus(IJavaModelStatus[] children) {
+ JavaModelStatus jms = new JavaModelStatus();
+ jms.fChildren = children;
+ return jms;
+}
+/**
+ * Returns a printable representation of this exception for debugging
+ * purposes.
+ */
+public String toString() {
+ StringBuffer buffer = new StringBuffer();
+ buffer.append("Java Model Status ["/*nonNLS*/);
+ buffer.append(getMessage());
+ buffer.append("]"/*nonNLS*/);
+ return buffer.toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaProject.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaProject.java
index 62117b893f..9ca7292b1a 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaProject.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaProject.java
@@ -202,7 +202,7 @@ public static IPath canonicalizedPath(IPath externalPath) {
* This is the project bin folder
*/
protected IPath defaultOutputLocation() throws JavaModelException {
- return getProject().getFullPath().append("bin");
+ return getProject().getFullPath().append("bin"/*nonNLS*/);
}
/**
* Returns true if this handle represents the same Java project
@@ -245,14 +245,14 @@ public static IPath canonicalizedPath(IPath externalPath) {
// default to the first one
return pkgFragments[0];
}
- } else if (extension.equalsIgnoreCase("java") || extension.equalsIgnoreCase("class")) {
+ } else if (extension.equalsIgnoreCase("java"/*nonNLS*/) || extension.equalsIgnoreCase("class"/*nonNLS*/)) {
IPath packagePath= path.removeLastSegments(1);
String packageName= packagePath.toString().replace(IPath.SEPARATOR, '.');
String typeName= path.lastSegment();
typeName= typeName.substring(0, typeName.length() - extension.length() - 1);
String qualifiedName= null;
if (packageName.length() > 0) {
- qualifiedName= packageName + "." + typeName;
+ qualifiedName= packageName + "."/*nonNLS*/ + typeName;
} else {
qualifiedName= typeName;
}
@@ -437,18 +437,11 @@ public static IPath canonicalizedPath(IPath externalPath) {
return getPackageFragmentRoots();
}
/**
- * @see IJavaProject
- * @deprecated
- */
- public IClasspathEntry[] getClasspath() throws JavaModelException {
- return getRawClasspath();
- }
- /**
* Returns the XML String encoding of the class path.
*/
protected String getClasspathAsXMLString(IClasspathEntry[] classpath, IPath outputLocation) throws JavaModelException {
Document doc= new DocumentImpl();
- Element cpElement= doc.createElement("classpath");
+ Element cpElement= doc.createElement("classpath"/*nonNLS*/);
doc.appendChild(cpElement);
for (int i= 0; i < classpath.length; ++i) {
@@ -459,9 +452,9 @@ public static IPath canonicalizedPath(IPath externalPath) {
if (outputLocation != null) {
outputLocation= outputLocation.removeFirstSegments(1);
outputLocation= outputLocation.makeRelative();
- Element oElement= doc.createElement("classpathentry");
- oElement.setAttribute("kind", kindToString(ClasspathEntry.K_OUTPUT));
- oElement.setAttribute("path", outputLocation.toOSString());
+ Element oElement= doc.createElement("classpathentry"/*nonNLS*/);
+ oElement.setAttribute("kind"/*nonNLS*/, kindToString(ClasspathEntry.K_OUTPUT));
+ oElement.setAttribute("path"/*nonNLS*/, outputLocation.toOSString());
cpElement.appendChild(oElement);
}
@@ -495,15 +488,15 @@ public static IPath canonicalizedPath(IPath externalPath) {
* of this project
*/
public QualifiedName getClasspathPropertyName() {
- return new QualifiedName(JavaCore.PLUGIN_ID, "classpath");
+ return new QualifiedName(JavaCore.PLUGIN_ID, "classpath"/*nonNLS*/);
}
/**
* Returns the XML String encoding of the class path.
*/
protected static Element getEntryAsXMLElement(Document document, IClasspathEntry entry, IPath prefixPath) throws JavaModelException {
- Element element= document.createElement("classpathentry");
- element.setAttribute("kind", kindToString(entry.getEntryKind()));
+ Element element= document.createElement("classpathentry"/*nonNLS*/);
+ element.setAttribute("kind"/*nonNLS*/, kindToString(entry.getEntryKind()));
IPath path= entry.getPath();
if (entry.getEntryKind() != IClasspathEntry.CPE_VARIABLE){
// translate to project relative from absolute (unless a device path)
@@ -518,12 +511,12 @@ public static IPath canonicalizedPath(IPath externalPath) {
}
}
}
- element.setAttribute("path", path.toString());
+ element.setAttribute("path"/*nonNLS*/, path.toString());
if (entry.getSourceAttachmentPath() != null){
- element.setAttribute("sourcepath", entry.getSourceAttachmentPath().toString());
+ element.setAttribute("sourcepath"/*nonNLS*/, entry.getSourceAttachmentPath().toString());
}
if (entry.getSourceAttachmentRootPath() != null){
- element.setAttribute("rootpath", entry.getSourceAttachmentRootPath().toString());
+ element.setAttribute("rootpath"/*nonNLS*/, entry.getSourceAttachmentRootPath().toString());
}
return element;
}
@@ -596,8 +589,8 @@ public static IPath canonicalizedPath(IPath externalPath) {
* @see IJavaProject
*/
public IPackageFragmentRoot getPackageFragmentRoot(IResource resource) {
- String name= resource.getName().toUpperCase();
- if (name.endsWith(".JAR") || name.endsWith(".ZIP")) {
+ String name= resource.getName();
+ if (Util.endsWithIgnoreCase(name,".jar"/*nonNLS*/) || Util.endsWithIgnoreCase(name,".zip"/*nonNLS*/)) {
return new JarPackageFragmentRoot(resource, this);
} else {
return new PackageFragmentRoot(resource, this);
@@ -683,7 +676,7 @@ public static IPath canonicalizedPath(IPath externalPath) {
if (entry.getContentKind() == IPackageFragmentRoot.K_BINARY) {
String ext= path.getFileExtension();
IPackageFragmentRoot root= null;
- if (ext != null && (ext.equalsIgnoreCase("zip") || ext.equalsIgnoreCase("jar"))) {
+ if (ext != null && (ext.equalsIgnoreCase("zip"/*nonNLS*/) || ext.equalsIgnoreCase("jar"/*nonNLS*/))) {
// jar
// removeFirstSegment removes the part relative to the project which is retrieve
// through workspace.getDefaultContentLocation
@@ -707,6 +700,7 @@ public static IPath canonicalizedPath(IPath externalPath) {
} else {
resource= workspaceRoot.findMember(path);
}
+ if (resource == null) return new IPackageFragmentRoot[]{};
IPackageFragmentRoot root= new PackageFragmentRoot(resource, this);
return new IPackageFragmentRoot[] {root};
} else {
@@ -721,7 +715,7 @@ public static IPath canonicalizedPath(IPath externalPath) {
try {
roots= javaProject.getPackageFragmentRoots();
} catch (JavaModelException e) {
- return new IPackageFragmentRoot[] {};
+ return new IPackageFragmentRoot[]{};
}
for (int i= 0; i < roots.length; i++) {
try {
@@ -775,8 +769,34 @@ public static IPath canonicalizedPath(IPath externalPath) {
* @see IJavaProject
*/
public IClasspathEntry[] getRawClasspath() throws JavaModelException {
- JavaProjectElementInfo info= getJavaProjectElementInfo();
- IClasspathEntry[] classpath= info.getRawClasspath();
+
+ IClasspathEntry[] classpath = null;
+ if (this.isOpen()){
+ JavaProjectElementInfo info= getJavaProjectElementInfo();
+ classpath= info.getRawClasspath();
+ if (classpath != null) {
+ return classpath;
+ }
+ return defaultClasspath();
+ }
+ // if not already opened, then read from file (avoid populating the model for CP question)
+ String sharedClasspath = loadClasspath();
+ if (sharedClasspath != null){
+ try {
+ classpath = readPaths(sharedClasspath);
+ } catch (IOException e){
+ } catch (RuntimeException e){
+ }
+ // extract out the output location
+ if (classpath != null && classpath.length > 0) {
+ IClasspathEntry entry= classpath[classpath.length - 1];
+ if (entry.getContentKind() == ClasspathEntry.K_OUTPUT) {
+ IClasspathEntry[] copy= new IClasspathEntry[classpath.length - 1];
+ System.arraycopy(classpath, 0, copy, 0, copy.length);
+ classpath= copy;
+ }
+ }
+ }
if (classpath != null) {
return classpath;
}
@@ -793,39 +813,7 @@ public String[] getRequiredProjectNames() throws JavaModelException {
*/
public IClasspathEntry[] getResolvedClasspath(boolean ignoreUnresolvedVariable) throws JavaModelException {
- IClasspathEntry[] classpath = getRawClasspath();
- IClasspathEntry[] resolvedPath = classpath; // clone only if necessary
- int length = classpath.length;
- int index = 0;
-
- for (int i = 0; i < length; i++){
-
- IClasspathEntry entry = classpath[i];
-
- /* resolve variables if any, unresolved ones are ignored */
- if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE){
-
- // clone original path
- if (resolvedPath == classpath){
- System.arraycopy(classpath, 0, resolvedPath = new IClasspathEntry[length], 0, i);
- }
- // resolve current variable (handling variable->variable->variable->entry
- IPath variablePath = entry.getPath(); // for error reporting
- entry = JavaCore.getResolvedClasspathEntry(entry);
- if (entry == null && !ignoreUnresolvedVariable){
- throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CP_VARIABLE_PATH_UNBOUND, variablePath.toString()));
- }
- }
- if (entry != null){
- resolvedPath[index++] = entry;
- }
- }
-
- // resize resolved classpath in case some variable entries could not be resolved
- if (index != length){
- System.arraycopy(resolvedPath, 0, resolvedPath = new IClasspathEntry[index], 0, index);
- }
- return resolvedPath;
+ return this.getResolvedClasspath(ignoreUnresolvedVariable, false);
}
/**
* @see IJavaProject
@@ -943,35 +931,37 @@ public String[] getRequiredProjectNames() throws JavaModelException {
* Returns the kind of a <code>PackageFragmentRoot</code> from its <code>String</code> form.
*/
static int kindFromString(String kindStr) {
- if (kindStr.equalsIgnoreCase("prj"))
+ if (kindStr.equalsIgnoreCase("prj"/*nonNLS*/))
return IClasspathEntry.CPE_PROJECT;
- if (kindStr.equalsIgnoreCase("var"))
+ if (kindStr.equalsIgnoreCase("var"/*nonNLS*/))
return IClasspathEntry.CPE_VARIABLE;
- if (kindStr.equalsIgnoreCase("src"))
+ if (kindStr.equalsIgnoreCase("src"/*nonNLS*/))
return IClasspathEntry.CPE_SOURCE;
- if (kindStr.equalsIgnoreCase("lib"))
+ if (kindStr.equalsIgnoreCase("lib"/*nonNLS*/))
return IClasspathEntry.CPE_LIBRARY;
- if (kindStr.equalsIgnoreCase("output"))
+ if (kindStr.equalsIgnoreCase("output"/*nonNLS*/))
return ClasspathEntry.K_OUTPUT;
return -1;
}
+
+
/**
* Returns a <code>String</code> for the kind of a class path entry.
*/
static String kindToString(int kind) {
switch (kind) {
case IClasspathEntry.CPE_PROJECT :
- return "src"; // backward compatibility
+ return "src"/*nonNLS*/; // backward compatibility
case IClasspathEntry.CPE_SOURCE :
- return "src";
+ return "src"/*nonNLS*/;
case IClasspathEntry.CPE_LIBRARY :
- return "lib";
+ return "lib"/*nonNLS*/;
case IClasspathEntry.CPE_VARIABLE :
- return "var";
+ return "var"/*nonNLS*/;
case ClasspathEntry.K_OUTPUT :
- return "output";
+ return "output"/*nonNLS*/;
default :
- return "unknown";
+ return "unknown"/*nonNLS*/;
}
}
/**
@@ -993,31 +983,10 @@ public String[] getRequiredProjectNames() throws JavaModelException {
}
/**
* @see IJavaProject
- * @deprecated
- */
- public IClasspathEntry newLibraryEntry(IPath path) {
- return JavaCore.newLibraryEntry(path, null, null);
- }
- /**
- * @see IJavaProject
- * @deprecated
- */
- public IClasspathEntry newProjectEntry(IPath path) {
- return JavaCore.newProjectEntry(path);
- }
- /**
- * @see IJavaProject
- * @deprecated
- */
- public IClasspathEntry newSourceEntry(IPath path) {
- return JavaCore.newSourceEntry(path);
- }
- /**
- * @see IJavaProject
*/
public ITypeHierarchy newTypeHierarchy(IRegion region, IProgressMonitor monitor) throws JavaModelException {
if (region == null) {
- throw new IllegalArgumentException("region cannot be null");
+ throw new IllegalArgumentException(Util.bind("hierarchy.nullRegion"/*nonNLS*/));
}
CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(null, region, this, true);
runOperation(op, monitor);
@@ -1028,10 +997,10 @@ public String[] getRequiredProjectNames() throws JavaModelException {
*/
public ITypeHierarchy newTypeHierarchy(IType type, IRegion region, IProgressMonitor monitor) throws JavaModelException {
if (type == null) {
- throw new IllegalArgumentException("type cannot be null");
+ throw new IllegalArgumentException(Util.bind("hierarchy.nullFocusType"/*nonNLS*/));
}
if (region == null) {
- throw new IllegalArgumentException("region cannot be null");
+ throw new IllegalArgumentException(Util.bind("hierarchy.nullRegion"/*nonNLS*/));
}
CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(type, region, this, true);
runOperation(op, monitor);
@@ -1098,15 +1067,15 @@ public String[] getRequiredProjectNames() throws JavaModelException {
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
cpElement = parser.parse(new InputSource(reader)).getDocumentElement();
} catch(SAXException e) {
- throw new IOException("bad format");
+ throw new IOException(Util.bind("file.badFormat"/*nonNLS*/));
} catch(ParserConfigurationException e){
reader.close();
- throw new IOException("bad format");
+ throw new IOException(Util.bind("file.badFormat"/*nonNLS*/));
} finally {
reader.close();
}
- if (!cpElement.getNodeName().equalsIgnoreCase("classpath")) {
- throw new IOException("bad format");
+ if (!cpElement.getNodeName().equalsIgnoreCase("classpath"/*nonNLS*/)) {
+ throw new IOException(Util.bind("file.badFormat"/*nonNLS*/));
}
NodeList list= cpElement.getChildNodes();
Vector paths= new Vector();
@@ -1116,9 +1085,9 @@ public String[] getRequiredProjectNames() throws JavaModelException {
short type= node.getNodeType();
if (type == Node.ELEMENT_NODE) {
Element cpeElement= (Element) node;
- if (cpeElement.getNodeName().equalsIgnoreCase("classpathentry")) {
- String cpeElementKind = cpeElement.getAttribute("kind");
- String pathStr = cpeElement.getAttribute("path");
+ if (cpeElement.getNodeName().equalsIgnoreCase("classpathentry"/*nonNLS*/)) {
+ String cpeElementKind = cpeElement.getAttribute("kind"/*nonNLS*/);
+ String pathStr = cpeElement.getAttribute("path"/*nonNLS*/);
// ensure path is absolute
IPath path= new Path(pathStr);
int kind= kindFromString(cpeElementKind);
@@ -1126,10 +1095,10 @@ public String[] getRequiredProjectNames() throws JavaModelException {
path= projectPath.append(path);
}
// source attachment info (optional)
- String sourceAttachmentPathStr = cpeElement.getAttribute("sourcepath");
- IPath sourceAttachmentPath = sourceAttachmentPathStr.equals("") ? null : new Path(sourceAttachmentPathStr);
- String sourceAttachmentRootPathStr = cpeElement.getAttribute("rootpath");
- IPath sourceAttachmentRootPath = sourceAttachmentRootPathStr.equals("") ? null : new Path(sourceAttachmentRootPathStr);
+ String sourceAttachmentPathStr = cpeElement.getAttribute("sourcepath"/*nonNLS*/);
+ IPath sourceAttachmentPath = sourceAttachmentPathStr.equals(""/*nonNLS*/) ? null : new Path(sourceAttachmentPathStr);
+ String sourceAttachmentRootPathStr = cpeElement.getAttribute("rootpath"/*nonNLS*/);
+ IPath sourceAttachmentRootPath = sourceAttachmentRootPathStr.equals(""/*nonNLS*/) ? null : new Path(sourceAttachmentRootPathStr);
IClasspathEntry entry= createClasspathEntry(path, kind, sourceAttachmentPath, sourceAttachmentRootPath);
if (entry == null) return null;
@@ -1254,13 +1223,6 @@ protected void resetNonJavaResourcesForPackageFragmentRoots() throws JavaModelEx
}
}
/**
- * @see IJavaProject
- * @deprecated
- */
- public void setClasspath(IClasspathEntry[] entries, IProgressMonitor monitor) throws JavaModelException {
- setRawClasspath(entries, monitor, true);
- }
- /**
* Update the Java command in the build spec (replace existing one if present,
* add one first if none).
*/
@@ -1295,7 +1257,7 @@ protected void resetNonJavaResourcesForPackageFragmentRoots() throws JavaModelEx
*/
public void setOutputLocation(IPath outputLocation, IProgressMonitor monitor) throws JavaModelException {
if (outputLocation == null) {
- throw new IllegalArgumentException("path cannot be null");
+ throw new IllegalArgumentException(Util.bind("path.nullpath"/*nonNLS*/));
}
if (outputLocation.equals(getOutputLocation())) {
return;
@@ -1390,13 +1352,8 @@ protected void resetNonJavaResourcesForPackageFragmentRoots() throws JavaModelEx
for (int j= 0; j < roots.length; j++) {
PackageFragmentRoot root= (PackageFragmentRoot)roots[j];
if (root.exists0()){
- if (root.isArchive()) {
- IResource rsc= root.getUnderlyingResource();
- if (rsc == null) {
- if (indexManager != null) indexManager.indexJarFile(root, getUnderlyingResource().getName());
- } else {
- if (indexManager != null) indexManager.indexJarFile((IFile) rsc, getUnderlyingResource().getName());
- }
+ if (root.isArchive()){
+ if (indexManager != null) indexManager.indexJarFile(root.getPath(), getUnderlyingResource().getName());
}
info.addChild(roots[j]);
}
@@ -1462,4 +1419,78 @@ protected void resetNonJavaResourcesForPackageFragmentRoots() throws JavaModelEx
}
return JavaModelStatus.VERIFIED_OK;
}
+
+ /**
+ * Record a new marker denoting a classpath problem for a given entry
+ */
+ private void createClasspathProblemMarker(IClasspathEntry entry, String message){
+ try {
+ IMarker marker = getProject().createMarker(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER);
+ marker.setAttribute(IMarker.MESSAGE, message);
+ marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
+ marker.setAttribute(IMarker.LOCATION, Util.bind("classpath.buildPath"/*nonNLS*/));
+ } catch (CoreException e) {
+ }
+ }
+
+ /**
+ * Remove all markers denoting classpath problems
+ */
+ protected void flushClasspathProblemMarkers(){
+ try {
+ IProject project = getProject();
+ if (project.exists()){
+ project.deleteMarkers(IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, false, IResource.DEPTH_ONE);
+ }
+ } catch (CoreException e) {
+ }
+ }
+
+ /**
+ * Internal variant which can create marker on project for invalid entries
+ */
+ public IClasspathEntry[] getResolvedClasspath(boolean ignoreUnresolvedVariable, boolean generateMarkerOnError) throws JavaModelException {
+
+ IClasspathEntry[] classpath = getRawClasspath();
+ IClasspathEntry[] resolvedPath = classpath; // clone only if necessary
+ int length = classpath.length;
+ int index = 0;
+
+ for (int i = 0; i < length; i++){
+
+ IClasspathEntry entry = classpath[i];
+
+ /* validation if needed */
+ if (generateMarkerOnError){
+ IJavaModelStatus status = JavaConventions.validateClasspathEntry(this, entry, false);
+ if (!status.isOK()) createClasspathProblemMarker(entry, status.getMessage());
+ }
+
+ /* resolve variables if any, unresolved ones are ignored */
+ if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE){
+
+ // clone original path
+ if (resolvedPath == classpath){
+ System.arraycopy(classpath, 0, resolvedPath = new IClasspathEntry[length], 0, i);
+ }
+ // resolve current variable (handling variable->variable->variable->entry
+ IPath variablePath = entry.getPath(); // for error reporting
+ entry = JavaCore.getResolvedClasspathEntry(entry);
+ if (entry == null){
+ if (!ignoreUnresolvedVariable){
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.CP_VARIABLE_PATH_UNBOUND, variablePath.toString()));
+ }
+ }
+ }
+ if (entry != null){
+ resolvedPath[index++] = entry;
+ }
+ }
+
+ // resize resolved classpath in case some variable entries could not be resolved
+ if (index != length){
+ System.arraycopy(resolvedPath, 0, resolvedPath = new IClasspathEntry[index], 0, index);
+ }
+ return resolvedPath;
+ }
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaProjectElementInfo.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaProjectElementInfo.java
index 4f28e9bb79..2faff793ba 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaProjectElementInfo.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaProjectElementInfo.java
@@ -22,8 +22,7 @@ import java.util.*;
* that are internal to the project, use <code>JavaProject#getChildren()</code>.
*/
-/* package */
-class JavaProjectElementInfo extends OpenableElementInfo {
+/* package */ class JavaProjectElementInfo extends OpenableElementInfo {
/**
* The classpath for this project
@@ -39,8 +38,8 @@ class JavaProjectElementInfo extends OpenableElementInfo {
* The searchable builder environment facility used
* with this project (doubles as the builder environment).
*/
- protected SearchableEnvironment fSearchableEnvironment = null;
-
+ protected SearchableEnvironment fSearchableEnvironment= null;
+
/**
* The output location for this project.
*/
@@ -51,145 +50,130 @@ class JavaProjectElementInfo extends OpenableElementInfo {
*/
private Object[] fNonJavaResources;
- /**
- * Create and initialize a new instance of the receiver
- */
- public JavaProjectElementInfo() {
- fNonJavaResources = null;
- }
-
- /**
- * Compute the non-java resources contained in this java project.
- */
- private Object[] computeNonJavaResources(JavaProject project) {
- Object[] nonJavaResources = new IResource[5];
- int nonJavaResourcesCounter = 0;
- try {
- IResource[] members = ((IContainer) project.getUnderlyingResource()).members();
- for (int i = 0, max = members.length; i < max; i++) {
- IResource res = members[i];
- switch (res.getType()) {
- case IResource.FILE :
- String extension = res.getProjectRelativePath().getFileExtension();
- if (!"java".equalsIgnoreCase(extension)
- && !"class".equalsIgnoreCase(extension)) {
- // check if this file might be a jar or a zip inside the build path
- IPath resFullPath = res.getFullPath();
- if (project.findPackageFragmentRoot(resFullPath) == null) {
- if (nonJavaResources.length == nonJavaResourcesCounter) {
- // resize
- System.arraycopy(
- nonJavaResources,
- 0,
- (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]),
- 0,
- nonJavaResourcesCounter);
- }
- nonJavaResources[nonJavaResourcesCounter++] = res;
- }
+/**
+ * Create and initialize a new instance of the receiver
+ */
+public JavaProjectElementInfo() {
+ fNonJavaResources = null;
+}
+/**
+ * Compute the non-java resources contained in this java project.
+ */
+private Object[] computeNonJavaResources(JavaProject project) {
+ Object[] nonJavaResources = new IResource[5];
+ int nonJavaResourcesCounter = 0;
+ try {
+ IResource[] members = ((IContainer) project.getUnderlyingResource()).members();
+ for (int i = 0, max = members.length; i < max; i++) {
+ IResource res = members[i];
+ switch (res.getType()) {
+ case IResource.FILE :
+ String extension = res.getProjectRelativePath().getFileExtension();
+ // check if this file might be a jar or a zip inside the build path
+ IPath resFullPath = res.getFullPath();
+ if (project.findPackageFragmentRoot(resFullPath) == null) {
+ if (nonJavaResources.length == nonJavaResourcesCounter) {
+ // resize
+ System.arraycopy(
+ nonJavaResources,
+ 0,
+ (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]),
+ 0,
+ nonJavaResourcesCounter);
}
- break;
- case IResource.FOLDER :
- IPath resFullPath = res.getFullPath();
- if (!resFullPath.equals(project.getOutputLocation())
- && project.findPackageFragmentRoot(resFullPath) == null
- && project.findPackageFragment(resFullPath) == null) {
- if (nonJavaResources.length == nonJavaResourcesCounter) {
- // resize
- System.arraycopy(
- nonJavaResources,
- 0,
- (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]),
- 0,
- nonJavaResourcesCounter);
- }
- nonJavaResources[nonJavaResourcesCounter++] = res;
+ nonJavaResources[nonJavaResourcesCounter++] = res;
+ }
+ break;
+ case IResource.FOLDER :
+ resFullPath = res.getFullPath();
+ if (!resFullPath.equals(project.getOutputLocation())
+ && project.findPackageFragmentRoot(resFullPath) == null
+ && project.findPackageFragment(resFullPath) == null) {
+ if (nonJavaResources.length == nonJavaResourcesCounter) {
+ // resize
+ System.arraycopy(
+ nonJavaResources,
+ 0,
+ (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]),
+ 0,
+ nonJavaResourcesCounter);
}
- }
+ nonJavaResources[nonJavaResourcesCounter++] = res;
+ }
}
- if (nonJavaResources.length != nonJavaResourcesCounter) {
- System.arraycopy(
- nonJavaResources,
- 0,
- (nonJavaResources = new IResource[nonJavaResourcesCounter]),
- 0,
- nonJavaResourcesCounter);
- }
- } catch (CoreException e) {
- nonJavaResources = NO_NON_JAVA_RESOURCES;
- nonJavaResourcesCounter = 0;
}
- return nonJavaResources;
- }
-
- /**
- * @see IJavaProject
- */
- protected NameLookup getNameLookup() {
- return fNameLookup;
- }
-
- /**
- * Returns an array of non-java resources contained in the receiver.
- */
- Object[] getNonJavaResources(JavaProject project) {
- Object[] nonJavaResources = fNonJavaResources;
- if (nonJavaResources == null) {
- nonJavaResources = computeNonJavaResources(project);
- fNonJavaResources = nonJavaResources;
+ if (nonJavaResources.length != nonJavaResourcesCounter) {
+ System.arraycopy(
+ nonJavaResources,
+ 0,
+ (nonJavaResources = new IResource[nonJavaResourcesCounter]),
+ 0,
+ nonJavaResourcesCounter);
}
- return nonJavaResources;
- }
-
- /**
- * @see IJavaProject
- */
- protected IPath getOutputLocation() {
- return fOutputLocation;
- }
-
- /**
- * Returns the classpath for this project
- */
- protected IClasspathEntry[] getRawClasspath() {
- return fClasspath;
- }
-
- /**
- * @see IJavaProject
- */
- protected SearchableEnvironment getSearchableEnvironment() {
- return fSearchableEnvironment;
+ } catch (CoreException e) {
+ nonJavaResources = NO_NON_JAVA_RESOURCES;
+ nonJavaResourcesCounter = 0;
}
-
- protected void setNameLookup(NameLookup newNameLookup) {
- fNameLookup = newNameLookup;
-
- // Reinitialize the searchable name environment since it caches
- // the name lookup.
- fSearchableEnvironment = null;
- }
-
- /**
- * Set the fNonJavaResources to res value
- */
- synchronized void setNonJavaResources(Object[] resources) {
- fNonJavaResources = resources;
- }
-
- protected void setOutputLocation(IPath newOutputLocation) {
- fOutputLocation = newOutputLocation;
- }
-
- /**
- * Sets the classpath for this project
- */
- protected void setRawClasspath(IClasspathEntry[] newClasspath) {
- fClasspath = newClasspath;
- }
-
- protected void setSearchableEnvironment(SearchableEnvironment newSearchableEnvironment) {
- fSearchableEnvironment = newSearchableEnvironment;
+ return nonJavaResources;
+}
+/**
+ * @see IJavaProject
+ */
+protected NameLookup getNameLookup() {
+ return fNameLookup;
+}
+/**
+ * Returns an array of non-java resources contained in the receiver.
+ */
+Object[] getNonJavaResources(JavaProject project) {
+ Object[] nonJavaResources = fNonJavaResources;
+ if (nonJavaResources == null) {
+ nonJavaResources = computeNonJavaResources(project);
+ fNonJavaResources = nonJavaResources;
}
+ return nonJavaResources;
+}
+/**
+ * @see IJavaProject
+ */
+protected IPath getOutputLocation() {
+ return fOutputLocation;
+}
+/**
+ * Returns the classpath for this project
+ */
+protected IClasspathEntry[] getRawClasspath() {
+ return fClasspath;
+}
+/**
+ * @see IJavaProject
+ */
+protected SearchableEnvironment getSearchableEnvironment() {
+ return fSearchableEnvironment;
+}
+protected void setNameLookup(NameLookup newNameLookup) {
+ fNameLookup = newNameLookup;
+ // Reinitialize the searchable name environment since it caches
+ // the name lookup.
+ fSearchableEnvironment = null;
+}
+/**
+ * Set the fNonJavaResources to res value
+ */
+synchronized void setNonJavaResources(Object[] resources) {
+ fNonJavaResources = resources;
+}
+protected void setOutputLocation(IPath newOutputLocation) {
+ fOutputLocation = newOutputLocation;
+}
+/**
+ * Sets the classpath for this project
+ */
+protected void setRawClasspath(IClasspathEntry[] newClasspath) {
+ fClasspath = newClasspath;
+}
+protected void setSearchableEnvironment(SearchableEnvironment newSearchableEnvironment) {
+ fSearchableEnvironment = newSearchableEnvironment;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/LRUCacheEnumerator.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/LRUCacheEnumerator.java
index 7f1423543b..e5048a7740 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/LRUCacheEnumerator.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/LRUCacheEnumerator.java
@@ -27,7 +27,7 @@ public class LRUCacheEnumerator implements Enumeration {
* Value returned by <code>nextElement()</code>;
*/
public Object fValue;
-
+
/**
* Next element
*/
@@ -40,28 +40,24 @@ public class LRUCacheEnumerator implements Enumeration {
fValue = value;
}
}
-
- /**
- * Creates a CacheEnumerator on the list of <code>LRUEnumeratorElements</code>.
- */
- public LRUCacheEnumerator(LRUEnumeratorElement firstElement) {
- fElementQueue = firstElement;
- }
-
- /**
- * Returns true if more elements exist.
- */
- public boolean hasMoreElements() {
- return fElementQueue != null;
- }
-
- /**
- * Returns the next element.
- */
- public Object nextElement() {
- Object temp = fElementQueue.fValue;
- fElementQueue = fElementQueue.fNext;
- return temp;
- }
-
+/**
+ * Creates a CacheEnumerator on the list of <code>LRUEnumeratorElements</code>.
+ */
+public LRUCacheEnumerator(LRUEnumeratorElement firstElement) {
+ fElementQueue = firstElement;
+}
+/**
+ * Returns true if more elements exist.
+ */
+public boolean hasMoreElements() {
+ return fElementQueue != null;
+}
+/**
+ * Returns the next element.
+ */
+public Object nextElement() {
+ Object temp = fElementQueue.fValue;
+ fElementQueue = fElementQueue.fNext;
+ return temp;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Member.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Member.java
index 3211307f65..daed33bd4f 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Member.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Member.java
@@ -15,169 +15,151 @@ import org.eclipse.jdt.internal.compiler.lookup.TypeIds;
* @see IMember
*/
-/* package */
-abstract class Member extends SourceRefElement implements IMember {
- protected Member(int type, IJavaElement parent, String name) {
- super(type, parent, name);
+/* package */ abstract class Member extends SourceRefElement implements IMember {
+protected Member(int type, IJavaElement parent, String name) {
+ super(type, parent, name);
+}
+/**
+ * Converts a field constant from the compiler's representation
+ * to the Java Model constant representation (Number or String).
+ */
+protected static Object convertConstant(Constant constant) {
+ if (constant == null)
+ return null;
+ if (constant == Constant.NotAConstant) {
+ return null;
}
-
- /**
- * Converts a field constant from the compiler's representation
- * to the Java Model constant representation (Number or String).
- */
- protected static Object convertConstant(Constant constant) {
- if (constant == null)
+ switch (constant.typeID()) {
+ case TypeIds.T_boolean :
+ return constant.booleanValue() ? Boolean.TRUE : Boolean.FALSE;
+ case TypeIds.T_byte :
+ return new Byte(constant.byteValue());
+ case TypeIds.T_char :
+ return new Character(constant.charValue());
+ case TypeIds.T_double :
+ return new Double(constant.doubleValue());
+ case TypeIds.T_float :
+ return new Float(constant.floatValue());
+ case TypeIds.T_int :
+ return new Integer(constant.intValue());
+ case TypeIds.T_long :
+ return new Long(constant.longValue());
+ case TypeIds.T_null :
return null;
- if (constant == Constant.NotAConstant) {
+ case TypeIds.T_short :
+ return new Short(constant.shortValue());
+ case TypeIds.T_String :
+ return constant.stringValue();
+ default :
return null;
- }
- switch (constant.typeID()) {
- case TypeIds.T_boolean :
- return constant.booleanValue() ? Boolean.TRUE : Boolean.FALSE;
- case TypeIds.T_byte :
- return new Byte(constant.byteValue());
- case TypeIds.T_char :
- return new Character(constant.charValue());
- case TypeIds.T_double :
- return new Double(constant.doubleValue());
- case TypeIds.T_float :
- return new Float(constant.floatValue());
- case TypeIds.T_int :
- return new Integer(constant.intValue());
- case TypeIds.T_long :
- return new Long(constant.longValue());
- case TypeIds.T_null :
- return null;
- case TypeIds.T_short :
- return new Short(constant.shortValue());
- case TypeIds.T_String :
- return constant.stringValue();
- default :
- return null;
- }
- }
-
- /**
- * @see JavaElement#equalsDOMNode
- */
- protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
- return getElementName().equals(node.getName());
- }
-
- /**
- * @see IMember
- */
- public IClassFile getClassFile() {
- return ((JavaElement) getParent()).getClassFile();
}
-
- /**
- * @see IMember
- */
- public IType getDeclaringType() {
- JavaElement parent = (JavaElement) getParent();
- if (parent.fLEType == TYPE) {
- return (IType) parent;
- }
- return null;
- }
-
- /**
- * @see IMember
- */
- public int getFlags() throws JavaModelException {
- MemberElementInfo info = (MemberElementInfo) getElementInfo();
- return info.getModifiers();
- }
-
- /**
- * @see JavaElement#getHandleMemento()
- */
- protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_TYPE;
+}
+/**
+ * @see JavaElement#equalsDOMNode
+ */
+protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
+ return getElementName().equals(node.getName());
+}
+/**
+ * @see IMember
+ */
+public IClassFile getClassFile() {
+ return ((JavaElement)getParent()).getClassFile();
+}
+/**
+ * @see IMember
+ */
+public IType getDeclaringType() {
+ JavaElement parent = (JavaElement)getParent();
+ if (parent.fLEType == TYPE) {
+ return (IType) parent;
}
-
- /**
- * @see IMember
- */
- public ISourceRange getNameRange() throws JavaModelException {
+ return null;
+}
+/**
+ * @see IMember
+ */
+public int getFlags() throws JavaModelException {
+ MemberElementInfo info = (MemberElementInfo) getElementInfo();
+ return info.getModifiers();
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+protected char getHandleMementoDelimiter() {
+ return JavaElement.JEM_TYPE;
+}
+/**
+ * @see IMember
+ */
+public ISourceRange getNameRange() throws JavaModelException {
+ MemberElementInfo info= (MemberElementInfo)getRawInfo();
+ return new SourceRange(info.getNameSourceStart(), info.getNameSourceEnd() - info.getNameSourceStart() + 1);
+}
+/**
+ * @see IMember
+ */
+public boolean isBinary() {
+ return false;
+}
+/**
+ * @see IJavaElement
+ */
+public boolean isReadOnly() {
+ return getClassFile() != null;
+}
+/**
+ * Changes the source indexes of this element. Updates the name range as well.
+ */
+public void offsetSourceRange(int amount) {
+ super.offsetSourceRange(amount);
+ try {
MemberElementInfo info = (MemberElementInfo) getRawInfo();
- return new SourceRange(
- info.getNameSourceStart(),
- info.getNameSourceEnd() - info.getNameSourceStart() + 1);
- }
-
- /**
- * @see IMember
- */
- public boolean isBinary() {
- return false;
- }
-
- /**
- * @see IJavaElement
- */
- public boolean isReadOnly() {
- return getClassFile() != null;
- }
-
- /**
- * Changes the source indexes of this element. Updates the name range as well.
- */
- public void offsetSourceRange(int amount) {
- super.offsetSourceRange(amount);
- try {
- MemberElementInfo info = (MemberElementInfo) getRawInfo();
- info.setNameSourceStart(info.getNameSourceStart() + amount);
- info.setNameSourceEnd(info.getNameSourceEnd() + amount);
- } catch (JavaModelException npe) {
- return;
- }
- }
-
- /**
- */
- public String readableName() {
-
- IJavaElement declaringType = getDeclaringType();
- if (declaringType != null) {
- String declaringName = ((JavaElement) getDeclaringType()).readableName();
- StringBuffer buffer = new StringBuffer(declaringName);
- buffer.append('.');
- buffer.append(this.getElementName());
- return buffer.toString();
- } else {
- return super.readableName();
- }
+ info.setNameSourceStart(info.getNameSourceStart() + amount);
+ info.setNameSourceEnd(info.getNameSourceEnd() + amount);
+ } catch (JavaModelException npe) {
+ return;
}
-
- /**
- * Updates the source positions for this element.
- */
- public void triggerSourceEndOffset(int amount, int nameStart, int nameEnd) {
- super.triggerSourceEndOffset(amount, nameStart, nameEnd);
- updateNameRange(nameStart, nameEnd);
- }
-
- /**
- * Updates the source positions for this element.
- */
- public void triggerSourceRangeOffset(int amount, int nameStart, int nameEnd) {
- super.triggerSourceRangeOffset(amount, nameStart, nameEnd);
- updateNameRange(nameStart, nameEnd);
+}
+/**
+ */
+public String readableName() {
+
+ IJavaElement declaringType = getDeclaringType();
+ if (declaringType != null) {
+ String declaringName = ((JavaElement) getDeclaringType()).readableName();
+ StringBuffer buffer = new StringBuffer(declaringName);
+ buffer.append('.');
+ buffer.append(this.getElementName());
+ return buffer.toString();
+ } else {
+ return super.readableName();
}
-
- /**
- * Updates the name range for this element.
- */
- protected void updateNameRange(int nameStart, int nameEnd) {
- try {
- MemberElementInfo info = (MemberElementInfo) getRawInfo();
- info.setNameSourceStart(nameStart);
- info.setNameSourceEnd(nameEnd);
- } catch (JavaModelException npe) {
- return;
- }
+}
+/**
+ * Updates the source positions for this element.
+ */
+public void triggerSourceEndOffset(int amount, int nameStart, int nameEnd) {
+ super.triggerSourceEndOffset(amount, nameStart, nameEnd);
+ updateNameRange(nameStart, nameEnd);
+}
+/**
+ * Updates the source positions for this element.
+ */
+public void triggerSourceRangeOffset(int amount, int nameStart, int nameEnd) {
+ super.triggerSourceRangeOffset(amount, nameStart, nameEnd);
+ updateNameRange(nameStart, nameEnd);
+}
+/**
+ * Updates the name range for this element.
+ */
+protected void updateNameRange(int nameStart, int nameEnd) {
+ try {
+ MemberElementInfo info = (MemberElementInfo) getRawInfo();
+ info.setNameSourceStart(nameStart);
+ info.setNameSourceEnd(nameEnd);
+ } catch (JavaModelException npe) {
+ return;
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/MemberElementInfo.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/MemberElementInfo.java
index 511f8fa6f9..d44032fb02 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/MemberElementInfo.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/MemberElementInfo.java
@@ -9,8 +9,7 @@ import org.eclipse.core.resources.*;
/**
*Element info for IMember elements.
*/
-/* package */
-abstract class MemberElementInfo extends SourceRefElementInfo {
+/* package */ abstract class MemberElementInfo extends SourceRefElementInfo {
/**
* The modifiers associated with this member.
*
@@ -22,78 +21,70 @@ abstract class MemberElementInfo extends SourceRefElementInfo {
* The start position of this member's name in the its
* openable's buffer.
*/
- protected int nameStart = -1;
+ protected int nameStart= -1;
/**
* The last position of this member's name in the its
* openable's buffer.
*/
- protected int nameEnd = -1;
+ protected int nameEnd= -1;
/**
* This member's name
*/
protected char[] name;
- /**
- * @see IGenericType
- * @see IGenericMethod
- * @see IGenericField
- */
- public int getModifiers() {
- return this.flags;
- }
-
- /**
- * @see ISourceType
- * @see ISourceField
- */
- public char[] getName() {
- return this.name;
- }
-
- /**
- * @see ISourceType
- * @see ISourceMethod
- * @see ISourceField
- */
- public int getNameSourceEnd() {
- return this.nameEnd;
- }
-
- /**
- * @see ISourceType
- * @see ISourceMethod
- * @see ISourceField
- */
- public int getNameSourceStart() {
- return this.nameStart;
- }
-
- protected void setFlags(int flags) {
- this.flags = flags;
- }
-
- /**
- * Sets this member's name
- */
- protected void setName(char[] name) {
- this.name = name;
- }
-
- /**
- * Sets the last position of this member's name, relative
- * to its openable's source buffer.
- */
- protected void setNameSourceEnd(int end) {
- this.nameEnd = end;
- }
-
- /**
- * Sets the start position of this member's name, relative
- * to its openable's source buffer.
- */
- protected void setNameSourceStart(int start) {
- this.nameStart = start;
- }
-
+/**
+ * @see IGenericType
+ * @see IGenericMethod
+ * @see IGenericField
+ */
+public int getModifiers() {
+ return this.flags;
+}
+/**
+ * @see ISourceType
+ * @see ISourceField
+ */
+public char[] getName() {
+ return this.name;
+}
+/**
+ * @see ISourceType
+ * @see ISourceMethod
+ * @see ISourceField
+ */
+public int getNameSourceEnd() {
+ return this.nameEnd;
+}
+/**
+ * @see ISourceType
+ * @see ISourceMethod
+ * @see ISourceField
+ */
+public int getNameSourceStart() {
+ return this.nameStart;
+}
+protected void setFlags(int flags) {
+ this.flags = flags;
+}
+/**
+ * Sets this member's name
+ */
+protected void setName(char[] name) {
+ this.name= name;
+}
+/**
+ * Sets the last position of this member's name, relative
+ * to its openable's source buffer.
+ */
+protected void setNameSourceEnd(int end) {
+ this.nameEnd= end;
+}
+/**
+ * Sets the start position of this member's name, relative
+ * to its openable's source buffer.
+ */
+protected void setNameSourceStart(int start) {
+ this.nameStart= start;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Messages.properties b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Messages.properties
new file mode 100644
index 0000000000..eeec379fbb
--- /dev/null
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Messages.properties
@@ -0,0 +1,136 @@
+### JavaModel messages.
+
+### assertion
+assert.nullArgument = null argument; {0}
+assert.failed = Assertion failed; {0}.
+assert.shouldNotImplement = Should not be called
+
+### hierarchy
+hierarchy.nullProject = Project argument cannot be null.
+hierarchy.nullRegion = Region cannot be null.
+hierarchy.nullFocusType = Type focus cannot be null.
+
+### java element
+element.doesNotExist = {0} does not exist.
+element.invalidClassFileName = Class file name must end with .class.
+element.invalidUnitName = Compilation unit name must end with .java.
+element.cannotReconcile = Must create reconciler on a working copy.
+element.attachingSource = Attaching source...
+element.invalidType = Type is not one of the defined constants.
+element.classpathCycle = A cycle was detected in the project's classpath.
+element.onlyOneJavaModel = Cannot instantiate more than one Java Model.
+element.projectDoesNotExist = Project {0} not present
+element.cannotLocate = Failed to locate {0} in {1}
+element.invalidResourceForProject = Illegal argument - must be one of IProject, IFolder, or IFile
+element.nullName = Name cannot be null.
+
+### java model operations
+operation.needElements = Operation requires one or more elements.
+operation.needName = Operation requires a name.
+operation.needPath = Operation requires a path.
+operation.needAbsolutePath = Operation requires an absolute path. Relative path specified was: {0}
+operation.needString = Operation requires a String.
+operation.notSupported = Operation not supported for specified element type(s):
+operation.cancelled = Operation cancelled.
+operation.nullContainer = Container cannot be null.
+operation.nullName = Name cannot be null.
+operation.copyElementProgress = Copying elements...
+operation.moveElementProgress = Moving elements...
+operation.renameElementProgress = Renaming elements...
+operation.copyResourceProgress = Copying resources...
+operation.moveResourceProgress = Moving resources...
+operation.renameResourceProgress = Renaming resources...
+operation.createUnitProgress = Creating a compilation unit...
+operation.createFieldProgress = Creating a field...
+operation.createImportsProgress = Creating imports...
+operation.createInitializerProgress = Creating an initializer...
+operation.createMethodProgress = Creating a method...
+operation.createPackageProgress = Creating a package declaration...
+operation.createPackageFragmentProgress = Creating package fragment(s)...
+operation.createTypeProgress = Creating a type...
+operation.deleteElementProgress = Deleting elements...
+operation.deleteResourceProgress = Deleting resources...
+operation.cannotRenameDefaultPackage = Default package cannot be renamed.
+operation.pathOutsideProject = Path {0} must denote location inside project {1}
+
+### working copy
+workingCopy.commit = Committing working copy...
+
+### build
+build.readStateProgress = Reading saved built state for project {0}.
+build.saveStateProgress = Saving built state for project {0}.
+build.saveStateComplete = " Saved in {0} ms
+build.wrongFileFormat = Wrong file format.
+build.unhandledVersionFormat = Unhandled version of file format.
+build.cannotSaveState = Error saving last build state for project {0}.
+build.cannotSaveStates = Error saving builder states
+build.initializationError = Builder initialization error.
+build.serializationError = Builder serialization error.
+build.analyzingPackage = Analyzing packages
+build.analyzingSources = Analyzing sources
+build.analyzing = Analyzing {0}
+build.preparingBuild = Preparing for build
+build.incompatibleParameterTypes = Incompatible parameter types.
+build.compiling = Compiling {0}
+build.compilingContent = Compiling content of {0}
+build.cloneException = Unexpected clone exception in DependencyGraph.clone().
+build.errorDeletingNode = Attempt to delete unknown node type from dependency graph.
+build.graphCorrupt = Internal Error: the dependency graph is corrupt, do a full build to workaround error.
+build.unknownNode = Unknown kind of node.
+build.unknownIndictment = Unexpected kind of indictment.
+build.readingDelta = Reading resource change information for : {0}
+build.completed = Java build completed
+build.builderName = Java Builder
+
+### status
+status.coreException = Core exception.
+status.coreExceptionWithArg = Core exception: {0}
+status.IOException = I/O exception.
+status.targetException = Target exception.
+status.cannotUseDeviceOnPath = Operation requires a path with no device. Path specified was: {0}
+status.JDOMError = JDOM error.
+status.indexOutOfBounds = Index out of bounds.
+status.evaluationError = Evaluation error: {0}.
+status.invalidContents = Invalid contents specified.
+status.invalidDestination = Invalid destination: {0}.
+status.invalidName = Invalid name specified: {0}.
+status.invalidPackage = Invalid package: {0}.
+status.invalidPath = Invalid path: {0}.
+status.invalidProject = Invalid project: {0}.
+status.invalidResource = Invalid resource: {0}.
+status.invalidResourceType = Invalid resource type for {0}.
+status.invalidSibling = Invalid sibling: {0}.
+status.nameCollision = Name collision.
+status.defaultPackeReadOnly = Default package is read-only.
+status.readOnly = {0} is read-only.
+status.updateConflict = Update conflict.
+status.noLocalContents = Cannot find local contents for resource: {0}
+
+### classpath
+classpath.cycle = A cycle was detected in the project's classpath.
+classpath.buildPath = Build path
+classpath.cannotNestSourceFolderInSource = Cannot nest source folder {0} inside source folder {1}.
+classpath.cannotNestSourceFolderInOutput = Cannot nest source folder {0} inside output location {1}.
+classpath.cannotNestOuputInSourceFolder = Cannot nest output location {0} inside source folder {1}.
+classpath.unboundVariablePath = Unbound variable path: {0}.
+classpath.illegalVariablePath = Illegal variable path: {0}.
+classpath.unboundSourceAttachment = Invalid source attachment: {0}.
+classpath.unboundLibrary = Missing library: {0}.
+classpath.illegalLibraryPath = Illegal library path: {0}.
+classpath.unboundProject = Missing Java project: {0}.
+classpath.illegalProjectPath = Illegal project path: {0}.
+classpath.unboundSourceFolder = Missing source folder: {0}.
+classpath.illegalSourceFolderPath = Illegal source folder path: {0}.
+classpath.settingProgress = Setting classpath...
+
+### miscellaneous
+file.notFound = File not found.
+file.badFormat = Bad format.
+variable.badFormat = Bad format for variables.
+path.nullPath = Path cannot be null.
+path.mustBeAbsolute = Path must be absolute.
+cache.invalidLoadFactor = Incorrect load factor
+
+### code assist
+codeAssist.nullRequestor = Requestor cannot be null.
+
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/MoveElementsOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/MoveElementsOperation.java
index 3acf61d4b1..e9cbfbf3f1 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/MoveElementsOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/MoveElementsOperation.java
@@ -17,29 +17,23 @@ import org.eclipse.jdt.core.IJavaElement;
* @see CopyElementsOperation
*/
public class MoveElementsOperation extends CopyElementsOperation {
- /**
- * When executed, this operation will move the given elements to the given containers.
- */
- public MoveElementsOperation(
- IJavaElement[] elementsToMove,
- IJavaElement[] destContainers,
- boolean force) {
- super(elementsToMove, destContainers, force);
- }
-
- /**
- * Returns the <code>String</code> to use as the main task name
- * for progress monitoring.
- */
- protected String getMainTaskName() {
- return "Moving elements...";
- }
-
- /**
- * @see CopyElementsOperation#isMove()
- */
- protected boolean isMove() {
- return true;
- }
-
+/**
+ * When executed, this operation will move the given elements to the given containers.
+ */
+public MoveElementsOperation(IJavaElement[] elementsToMove, IJavaElement[] destContainers, boolean force) {
+ super(elementsToMove, destContainers, force);
+}
+/**
+ * Returns the <code>String</code> to use as the main task name
+ * for progress monitoring.
+ */
+protected String getMainTaskName() {
+ return Util.bind("operation.moveElementProgress"/*nonNLS*/);
+}
+/**
+ * @see CopyElementsOperation#isMove()
+ */
+protected boolean isMove() {
+ return true;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/MoveResourceElementsOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/MoveResourceElementsOperation.java
index 91e798e569..895def8ebd 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/MoveResourceElementsOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/MoveResourceElementsOperation.java
@@ -16,30 +16,23 @@ import org.eclipse.jdt.core.IJavaElement;
*
* @see CopyResourceElementsOperation
*/
-public class MoveResourceElementsOperation
- extends CopyResourceElementsOperation {
- /**
- * When executed, this operation will move the given elements to the given containers.
- */
- public MoveResourceElementsOperation(
- IJavaElement[] elementsToMove,
- IJavaElement[] destContainers,
- boolean force) {
- super(elementsToMove, destContainers, force);
- }
-
- /**
- * @see MultiOperation
- */
- protected String getMainTaskName() {
- return "Moving resources...";
- }
-
- /**
- * @see CopyResourceElementsOperation#isMove()
- */
- protected boolean isMove() {
- return true;
- }
-
+public class MoveResourceElementsOperation extends CopyResourceElementsOperation {
+/**
+ * When executed, this operation will move the given elements to the given containers.
+ */
+public MoveResourceElementsOperation(IJavaElement[] elementsToMove, IJavaElement[] destContainers, boolean force) {
+ super(elementsToMove, destContainers, force);
+}
+/**
+ * @see MultiOperation
+ */
+protected String getMainTaskName() {
+ return Util.bind("operation.moveResourceProgress"/*nonNLS*/);
+}
+/**
+ * @see CopyResourceElementsOperation#isMove()
+ */
+protected boolean isMove() {
+ return true;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/MultiOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/MultiOperation.java
index 26f85ee971..a888a27e08 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/MultiOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/MultiOperation.java
@@ -24,7 +24,7 @@ public abstract class MultiOperation extends JavaModelOperation {
/**
* The list of renamings supplied to the operation
*/
- protected String[] fRenamingsList = null;
+ protected String[] fRenamingsList= null;
/**
* Table specifying the new parent for elements being
* copied/moved/renamed.
@@ -38,330 +38,285 @@ public abstract class MultiOperation extends JavaModelOperation {
* values are the corresponding insertion point.
* @see processElements(IProgressMonitor)
*/
- protected Hashtable fInsertBeforeElements = new Hashtable(1);
+ protected Hashtable fInsertBeforeElements= new Hashtable(1);
/**
* This table presents the data in <code>fRenamingList</code> in a more
* convenient way.
*/
protected Hashtable fRenamings;
- /**
- * Creates a new <code>MultiOperation</code>.
- */
- protected MultiOperation(
- IJavaElement[] elementsToProcess,
- IJavaElement[] parentElements,
- boolean force) {
- super(elementsToProcess, parentElements, force);
- fParentElements = new Hashtable(elementsToProcess.length);
- if (elementsToProcess.length == parentElements.length) {
- for (int i = 0; i < elementsToProcess.length; i++) {
- fParentElements.put(elementsToProcess[i], parentElements[i]);
- }
- } else { //same destination for all elements to be moved/copied/renamed
- for (int i = 0; i < elementsToProcess.length; i++) {
- fParentElements.put(elementsToProcess[i], parentElements[0]);
- }
+/**
+ * Creates a new <code>MultiOperation</code>.
+ */
+protected MultiOperation(IJavaElement[] elementsToProcess, IJavaElement[] parentElements, boolean force) {
+ super(elementsToProcess, parentElements, force);
+ fParentElements = new Hashtable(elementsToProcess.length);
+ if (elementsToProcess.length == parentElements.length) {
+ for (int i = 0; i < elementsToProcess.length; i++) {
+ fParentElements.put(elementsToProcess[i], parentElements[i]);
}
-
- }
-
- /**
- * Creates a new <code>MultiOperation</code> on <code>elementsToProcess</code>.
- */
- protected MultiOperation(IJavaElement[] elementsToProcess, boolean force) {
- super(elementsToProcess, force);
- }
-
- /**
- * Convenience method to create a <code>JavaModelException</code>
- * embending a <code>JavaModelStatus</code>.
- */
- protected void error(int code, IJavaElement element)
- throws JavaModelException {
- throw new JavaModelException(new JavaModelStatus(code, element));
- }
-
- /**
- * Executes the operation.
- *
- * @exception JavaModelException if one or several errors occured during the operation.
- * If multiple errors occured, the corresponding <code>JavaModelStatus</code> is a
- * multi-status. Otherwise, it is a simple one.
- */
- protected void executeOperation() throws JavaModelException {
- try {
- processElements();
- } catch (JavaModelException jme) {
- throw jme;
- } finally {
- mergeDeltas();
+ } else { //same destination for all elements to be moved/copied/renamed
+ for (int i = 0; i < elementsToProcess.length; i++) {
+ fParentElements.put(elementsToProcess[i], parentElements[0]);
}
}
- /**
- * Returns the parent of the element being copied/moved/renamed.
- */
- protected IJavaElement getDestinationParent(IJavaElement child) {
- return (IJavaElement) fParentElements.get(child);
- }
-
- /**
- * Returns the name to be used by the progress monitor.
- */
- protected abstract String getMainTaskName();
- /**
- * Returns the new name for <code>element</code>, or <code>null</code>
- * if there are no renamings specified.
- */
- protected String getNewNameFor(IJavaElement element) {
- if (fRenamings != null)
- return (String) fRenamings.get(element);
- else
- return null;
+}
+/**
+ * Creates a new <code>MultiOperation</code> on <code>elementsToProcess</code>.
+ */
+protected MultiOperation(IJavaElement[] elementsToProcess, boolean force) {
+ super(elementsToProcess, force);
+}
+/**
+ * Convenience method to create a <code>JavaModelException</code>
+ * embending a <code>JavaModelStatus</code>.
+ */
+protected void error(int code, IJavaElement element) throws JavaModelException {
+ throw new JavaModelException(new JavaModelStatus(code, element));
+}
+/**
+ * Executes the operation.
+ *
+ * @exception JavaModelException if one or several errors occured during the operation.
+ * If multiple errors occured, the corresponding <code>JavaModelStatus</code> is a
+ * multi-status. Otherwise, it is a simple one.
+ */
+protected void executeOperation() throws JavaModelException {
+ try {
+ processElements();
+ } catch (JavaModelException jme) {
+ throw jme;
+ } finally {
+ mergeDeltas();
}
-
- /**
- * Sets up the renamings hashtable - keys are the elements and
- * values are the new name.
- */
- private void initializeRenamings() {
- if (fRenamingsList != null
- && fRenamingsList.length == fElementsToProcess.length) {
- fRenamings = new Hashtable(fRenamingsList.length);
- for (int i = 0; i < fRenamingsList.length; i++) {
- if (fRenamingsList[i] != null) {
- fRenamings.put(fElementsToProcess[i], fRenamingsList[i]);
- }
+}
+/**
+ * Returns the parent of the element being copied/moved/renamed.
+ */
+protected IJavaElement getDestinationParent(IJavaElement child) {
+ return (IJavaElement)fParentElements.get(child);
+}
+/**
+ * Returns the name to be used by the progress monitor.
+ */
+protected abstract String getMainTaskName();
+/**
+ * Returns the new name for <code>element</code>, or <code>null</code>
+ * if there are no renamings specified.
+ */
+protected String getNewNameFor(IJavaElement element) {
+ if (fRenamings != null)
+ return (String) fRenamings.get(element);
+ else
+ return null;
+}
+/**
+ * Sets up the renamings hashtable - keys are the elements and
+ * values are the new name.
+ */
+private void initializeRenamings() {
+ if (fRenamingsList != null && fRenamingsList.length == fElementsToProcess.length) {
+ fRenamings = new Hashtable(fRenamingsList.length);
+ for (int i = 0; i < fRenamingsList.length; i++) {
+ if (fRenamingsList[i] != null) {
+ fRenamings.put(fElementsToProcess[i], fRenamingsList[i]);
}
}
}
-
- /**
- * Returns <code>true</code> if this operation represents a move or rename, <code>false</code>
- * if this operation represents a copy.<br>
- * Note: a rename is just a move within the same parent with a name change.
- */
- protected boolean isMove() {
- return false;
- }
-
- /**
- * Returns <code>true</code> if this operation represents a rename, <code>false</code>
- * if this operation represents a copy or move.
- */
- protected boolean isRename() {
- return false;
- }
-
- /**
- * Process all of the changed deltas generated by these operations.
- */
- protected void mergeDeltas() {
- if (fDeltas != null) {
- JavaElementDelta rootDelta = newJavaElementDelta();
- boolean insertedTree = false;
- for (int i = 0; i < fDeltas.length; i++) {
- IJavaElementDelta delta = fDeltas[i];
- IJavaElementDelta[] children = delta.getAffectedChildren();
- for (int j = 0; j < children.length; j++) {
- JavaElementDelta projectDelta = (JavaElementDelta) children[j];
- rootDelta.insertDeltaTree(projectDelta.getElement(), projectDelta);
- insertedTree = true;
- }
+}
+/**
+ * Returns <code>true</code> if this operation represents a move or rename, <code>false</code>
+ * if this operation represents a copy.<br>
+ * Note: a rename is just a move within the same parent with a name change.
+ */
+protected boolean isMove() {
+ return false;
+}
+/**
+ * Returns <code>true</code> if this operation represents a rename, <code>false</code>
+ * if this operation represents a copy or move.
+ */
+protected boolean isRename() {
+ return false;
+}
+/**
+ * Process all of the changed deltas generated by these operations.
+ */
+protected void mergeDeltas() {
+ if (fDeltas != null) {
+ JavaElementDelta rootDelta = newJavaElementDelta();
+ boolean insertedTree = false;
+ for (int i = 0; i < fDeltas.length; i++) {
+ IJavaElementDelta delta = fDeltas[i];
+ IJavaElementDelta[] children = delta.getAffectedChildren();
+ for (int j = 0; j < children.length; j++) {
+ JavaElementDelta projectDelta = (JavaElementDelta) children[j];
+ rootDelta.insertDeltaTree(projectDelta.getElement(), projectDelta);
+ insertedTree = true;
}
- if (insertedTree)
- fDeltas = new IJavaElementDelta[] { rootDelta };
- else
- fDeltas = null;
}
+ if (insertedTree)
+ fDeltas = new IJavaElementDelta[] {rootDelta};
+ else
+ fDeltas = null;
}
-
- /**
- * Subclasses must implement this method to process a given <code>IJavaElement</code>.
- */
- protected abstract void processElement(IJavaElement element)
- throws JavaModelException;
- /**
- * Processes all the <code>IJavaElement</code>s in turn, collecting errors
- * and updating the progress monitor.
- *
- * @exception JavaModelException if one or several operation(s) was unable to
- * be completed.
- */
- protected void processElements() throws JavaModelException {
- beginTask(getMainTaskName(), fElementsToProcess.length);
- IJavaModelStatus[] errors = new IJavaModelStatus[3];
- int errorsCounter = 0;
- for (int i = 0; i < fElementsToProcess.length; i++) {
- try {
- verify(fElementsToProcess[i]);
- processElement(fElementsToProcess[i]);
- } catch (JavaModelException jme) {
- if (errorsCounter == errors.length) {
- // resize
- System.arraycopy(
- errors,
- 0,
- (errors = new IJavaModelStatus[errorsCounter * 2]),
- 0,
- errorsCounter);
- }
- errors[errorsCounter++] = jme.getJavaModelStatus();
- } finally {
- worked(1);
+}
+/**
+ * Subclasses must implement this method to process a given <code>IJavaElement</code>.
+ */
+protected abstract void processElement(IJavaElement element) throws JavaModelException;
+/**
+ * Processes all the <code>IJavaElement</code>s in turn, collecting errors
+ * and updating the progress monitor.
+ *
+ * @exception JavaModelException if one or several operation(s) was unable to
+ * be completed.
+ */
+protected void processElements() throws JavaModelException {
+ beginTask(getMainTaskName(), fElementsToProcess.length);
+ IJavaModelStatus[] errors = new IJavaModelStatus[3];
+ int errorsCounter = 0;
+ for (int i = 0; i < fElementsToProcess.length; i++) {
+ try {
+ verify(fElementsToProcess[i]);
+ processElement(fElementsToProcess[i]);
+ } catch (JavaModelException jme) {
+ if (errorsCounter == errors.length) {
+ // resize
+ System.arraycopy(errors, 0, (errors = new IJavaModelStatus[errorsCounter*2]), 0, errorsCounter);
}
+ errors[errorsCounter++] = jme.getJavaModelStatus();
+ } finally {
+ worked(1);
}
- done();
- if (errorsCounter == 1) {
- throw new JavaModelException(errors[0]);
- } else
- if (errorsCounter > 1) {
- if (errorsCounter != errors.length) {
- // resize
- System.arraycopy(
- errors,
- 0,
- (errors = new IJavaModelStatus[errorsCounter]),
- 0,
- errorsCounter);
- }
- throw new JavaModelException(JavaModelStatus.newMultiStatus(errors));
- }
- }
-
- /**
- * Sets the insertion position in the new container for the modified element. The element
- * being modified will be inserted before the specified new sibling. The given sibling
- * must be a child of the destination container specified for the modified element.
- * The default is <code>null</code>, which indicates that the element is to be
- * inserted at the end of the container.
- */
- public void setInsertBefore(
- IJavaElement modifiedElement,
- IJavaElement newSibling) {
- fInsertBeforeElements.put(modifiedElement, newSibling);
}
-
- /**
- * Sets the new names to use for each element being copied. The renamings
- * correspond to the elements being processed, and the number of
- * renamings must match the number of elements being processed.
- * A <code>null</code> entry in the list indicates that an element
- * is not to be renamed.
- *
- * <p>Note that some renamings may not be used. If both a parent
- * and a child have been selected for copy/move, only the parent
- * is changed. Therefore, if a new name is specified for the child,
- * the child's name will not be changed.
- */
- public void setRenamings(String[] renamings) {
- fRenamingsList = renamings;
- initializeRenamings();
+ done();
+ if (errorsCounter == 1) {
+ throw new JavaModelException(errors[0]);
+ } else if (errorsCounter > 1) {
+ if (errorsCounter != errors.length) {
+ // resize
+ System.arraycopy(errors, 0, (errors = new IJavaModelStatus[errorsCounter]), 0, errorsCounter);
+ }
+ throw new JavaModelException(JavaModelStatus.newMultiStatus(errors));
}
-
- /**
- * This method is called for each <code>IJavaElement</code> before
- * <code>processElement</code>. It should check that this <code>element</code>
- * can be processed.
- */
- protected abstract void verify(IJavaElement element) throws JavaModelException;
- /**
- * Verifies that the <code>destination</code> specified for the <code>element</code> is valid for the types of the
- * <code>element</code> and <code>destination</code>.
- */
- protected void verifyDestination(
- IJavaElement element,
- IJavaElement destination)
- throws JavaModelException {
- if (destination == null || !destination.exists())
- error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, destination);
-
- int destType = destination.getElementType();
- switch (element.getElementType()) {
- case IJavaElement.PACKAGE_DECLARATION :
- case IJavaElement.IMPORT_DECLARATION :
- if (destType != IJavaElement.COMPILATION_UNIT)
- error(IJavaModelStatusConstants.INVALID_DESTINATION, element);
- break;
- case IJavaElement.TYPE :
- if (destType != IJavaElement.COMPILATION_UNIT && destType != IJavaElement.TYPE)
- error(IJavaModelStatusConstants.INVALID_DESTINATION, element);
- break;
- case IJavaElement.METHOD :
- case IJavaElement.FIELD :
- case IJavaElement.INITIALIZER :
- if (destType != IJavaElement.TYPE || destination instanceof BinaryType)
- error(IJavaModelStatusConstants.INVALID_DESTINATION, element);
- break;
- case IJavaElement.COMPILATION_UNIT :
- if (destType != IJavaElement.PACKAGE_FRAGMENT)
- error(IJavaModelStatusConstants.INVALID_DESTINATION, element);
- else
- if (isMove() && ((ICompilationUnit) element).isWorkingCopy())
- error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
- break;
- case IJavaElement.PACKAGE_FRAGMENT :
- IPackageFragment fragment = (IPackageFragment) element;
- IJavaElement parent = fragment.getParent();
- if (parent.isReadOnly())
- error(IJavaModelStatusConstants.READ_ONLY, element);
- else
- if (destType != IJavaElement.PACKAGE_FRAGMENT_ROOT)
- error(IJavaModelStatusConstants.INVALID_DESTINATION, element);
- break;
- default :
+}
+/**
+ * Sets the insertion position in the new container for the modified element. The element
+ * being modified will be inserted before the specified new sibling. The given sibling
+ * must be a child of the destination container specified for the modified element.
+ * The default is <code>null</code>, which indicates that the element is to be
+ * inserted at the end of the container.
+ */
+public void setInsertBefore(IJavaElement modifiedElement, IJavaElement newSibling) {
+ fInsertBeforeElements.put(modifiedElement, newSibling);
+}
+/**
+ * Sets the new names to use for each element being copied. The renamings
+ * correspond to the elements being processed, and the number of
+ * renamings must match the number of elements being processed.
+ * A <code>null</code> entry in the list indicates that an element
+ * is not to be renamed.
+ *
+ * <p>Note that some renamings may not be used. If both a parent
+ * and a child have been selected for copy/move, only the parent
+ * is changed. Therefore, if a new name is specified for the child,
+ * the child's name will not be changed.
+ */
+public void setRenamings(String[] renamings) {
+ fRenamingsList = renamings;
+ initializeRenamings();
+}
+/**
+ * This method is called for each <code>IJavaElement</code> before
+ * <code>processElement</code>. It should check that this <code>element</code>
+ * can be processed.
+ */
+protected abstract void verify(IJavaElement element) throws JavaModelException;
+/**
+ * Verifies that the <code>destination</code> specified for the <code>element</code> is valid for the types of the
+ * <code>element</code> and <code>destination</code>.
+ */
+protected void verifyDestination(IJavaElement element, IJavaElement destination) throws JavaModelException {
+ if (destination == null || !destination.exists())
+ error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, destination);
+
+ int destType = destination.getElementType();
+ switch (element.getElementType()) {
+ case IJavaElement.PACKAGE_DECLARATION :
+ case IJavaElement.IMPORT_DECLARATION :
+ if (destType != IJavaElement.COMPILATION_UNIT)
+ error(IJavaModelStatusConstants.INVALID_DESTINATION, element);
+ break;
+ case IJavaElement.TYPE :
+ if (destType != IJavaElement.COMPILATION_UNIT && destType != IJavaElement.TYPE)
+ error(IJavaModelStatusConstants.INVALID_DESTINATION, element);
+ break;
+ case IJavaElement.METHOD :
+ case IJavaElement.FIELD :
+ case IJavaElement.INITIALIZER :
+ if (destType != IJavaElement.TYPE || destination instanceof BinaryType)
+ error(IJavaModelStatusConstants.INVALID_DESTINATION, element);
+ break;
+ case IJavaElement.COMPILATION_UNIT :
+ if (destType != IJavaElement.PACKAGE_FRAGMENT)
+ error(IJavaModelStatusConstants.INVALID_DESTINATION, element);
+ else if (isMove() && ((ICompilationUnit) element).isWorkingCopy())
error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
- }
+ break;
+ case IJavaElement.PACKAGE_FRAGMENT :
+ IPackageFragment fragment = (IPackageFragment) element;
+ IJavaElement parent = fragment.getParent();
+ if (parent.isReadOnly())
+ error(IJavaModelStatusConstants.READ_ONLY, element);
+ else if (destType != IJavaElement.PACKAGE_FRAGMENT_ROOT)
+ error(IJavaModelStatusConstants.INVALID_DESTINATION, element);
+ break;
+ default :
+ error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
}
+}
+/**
+ * Verify that the new name specified for <code>element</code> is
+ * valid for that type of Java element.
+ */
+protected void verifyRenaming(IJavaElement element) throws JavaModelException {
+ String newName = getNewNameFor(element);
+ boolean isValid = true;
- /**
- * Verify that the new name specified for <code>element</code> is
- * valid for that type of Java element.
- */
- protected void verifyRenaming(IJavaElement element) throws JavaModelException {
- String newName = getNewNameFor(element);
- boolean isValid = true;
-
- switch (element.getElementType()) {
- case IJavaElement.PACKAGE_FRAGMENT :
- if (element.getElementName().equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) {
- // don't allow renaming of default package (see PR #1G47GUM)
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION, element));
- }
- isValid = JavaConventions.validatePackageName(newName).isOK();
- break;
- case IJavaElement.COMPILATION_UNIT :
- isValid = JavaConventions.validateCompilationUnitName(newName).isOK();
- break;
- case IJavaElement.INITIALIZER :
- isValid = false; //cannot rename initializers
- break;
- default :
- isValid = JavaConventions.validateIdentifier(newName).isOK();
- break;
- }
-
- if (!isValid) {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.INVALID_NAME, element, newName));
- }
+ switch (element.getElementType()) {
+ case IJavaElement.PACKAGE_FRAGMENT :
+ if (element.getElementName().equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) {
+ // don't allow renaming of default package (see PR #1G47GUM)
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.NAME_COLLISION, element));
+ }
+ isValid = JavaConventions.validatePackageName(newName).isOK();
+ break;
+ case IJavaElement.COMPILATION_UNIT :
+ isValid = JavaConventions.validateCompilationUnitName(newName).isOK();
+ break;
+ case IJavaElement.INITIALIZER :
+ isValid = false; //cannot rename initializers
+ break;
+ default :
+ isValid = JavaConventions.validateIdentifier(newName).isOK();
+ break;
}
- /**
- * Verifies that the positioning sibling specified for the <code>element</code> is exists and
- * its parent is the destination container of this <code>element</code>.
- */
- protected void verifySibling(IJavaElement element, IJavaElement destination)
- throws JavaModelException {
- IJavaElement insertBeforeElement =
- (IJavaElement) fInsertBeforeElements.get(element);
- if (insertBeforeElement != null) {
- if (!insertBeforeElement.exists()
- || !insertBeforeElement.getParent().equals(destination)) {
- error(IJavaModelStatusConstants.INVALID_SIBLING, insertBeforeElement);
- }
+ if (!isValid) {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_NAME, element, newName));
+ }
+}
+/**
+ * Verifies that the positioning sibling specified for the <code>element</code> is exists and
+ * its parent is the destination container of this <code>element</code>.
+ */
+protected void verifySibling(IJavaElement element, IJavaElement destination) throws JavaModelException {
+ IJavaElement insertBeforeElement = (IJavaElement) fInsertBeforeElements.get(element);
+ if (insertBeforeElement != null) {
+ if (!insertBeforeElement.exists() || !insertBeforeElement.getParent().equals(destination)) {
+ error(IJavaModelStatusConstants.INVALID_SIBLING, insertBeforeElement);
}
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/NameLookup.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/NameLookup.java
index 983c71333f..8ebdbe1ca6 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/NameLookup.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/NameLookup.java
@@ -27,7 +27,7 @@ public class NameLookup implements INameLookup {
* with the classpath of this NameLookup facility's
* project.
*/
- protected IPackageFragmentRoot[] fPackageFragmentRoots = null;
+ protected IPackageFragmentRoot[] fPackageFragmentRoots= null;
/**
* Table that maps package names to lists of package fragments for
* all package fragments in the package fragment roots known
@@ -41,13 +41,12 @@ public class NameLookup implements INameLookup {
* Singleton <code>SingleTypeRequestor</code>.
* @see findType(String, IPackageFragment, boolean, int)
*/
- protected SingleTypeRequestor fgSingleTypeRequestor = new SingleTypeRequestor();
+ protected SingleTypeRequestor fgSingleTypeRequestor= new SingleTypeRequestor();
/**
* Singleton <code>JavaElementRequestor</code>.
* @see findType(String, boolean, int)
*/
- protected JavaElementRequestor fgJavaElementRequestor =
- new JavaElementRequestor();
+ protected JavaElementRequestor fgJavaElementRequestor= new JavaElementRequestor();
/**
* The <code>IWorkspace</code> that this NameLookup
* is configure within.
@@ -57,7 +56,6 @@ public class NameLookup implements INameLookup {
public NameLookup(IJavaProject project) throws JavaModelException {
configureFromProject(project);
}
-
/**
* Returns true if:<ul>
* <li>the given type is an existing class and the flag's <code>ACCEPT_CLASSES</code>
@@ -82,36 +80,32 @@ public class NameLookup implements INameLookup {
return false; // the class is not present, do not accept.
}
}
-
/**
* Configures this <code>NameLookup</code> based on the
* info of the given <code>IJavaProject</code>.
*
* @throws JavaModelException if the <code>IJavaProject</code> has no classpath.
*/
- private void configureFromProject(IJavaProject project)
- throws JavaModelException {
- workspace = project.getJavaModel().getWorkspace();
- fPackageFragmentRoots = ((JavaProject) project).getAllPackageFragmentRoots();
- fPackageFragments = new Hashtable();
- IPackageFragment[] frags = ((JavaProject) project).getAllPackageFragments();
- for (int i = 0; i < frags.length; i++) {
- IPackageFragment fragment = frags[i];
- IPackageFragment[] entry =
- (IPackageFragment[]) fPackageFragments.get(fragment.getElementName());
+ private void configureFromProject(IJavaProject project) throws JavaModelException {
+ workspace= project.getJavaModel().getWorkspace();
+ fPackageFragmentRoots= ((JavaProject) project).getAllPackageFragmentRoots();
+ fPackageFragments= new Hashtable();
+ IPackageFragment[] frags= ((JavaProject) project).getAllPackageFragments();
+ for (int i= 0; i < frags.length; i++) {
+ IPackageFragment fragment= frags[i];
+ IPackageFragment[] entry= (IPackageFragment[]) fPackageFragments.get(fragment.getElementName());
if (entry == null) {
- entry = new IPackageFragment[1];
- entry[0] = fragment;
+ entry= new IPackageFragment[1];
+ entry[0]= fragment;
fPackageFragments.put(fragment.getElementName(), entry);
} else {
- IPackageFragment[] copy = new IPackageFragment[entry.length + 1];
+ IPackageFragment[] copy= new IPackageFragment[entry.length + 1];
System.arraycopy(entry, 0, copy, 0, entry.length);
- copy[entry.length] = fragment;
+ copy[entry.length]= fragment;
fPackageFragments.put(fragment.getElementName(), copy);
}
}
}
-
/**
* Finds every type in the project whose simple name matches
* the prefix, informing the requestor of each hit. The requestor
@@ -120,62 +114,52 @@ public class NameLookup implements INameLookup {
* <p>The <code>partialMatch</code> argument indicates partial matches
* should be considered.
*/
- private void findAllTypes(
- String prefix,
- boolean partialMatch,
- int acceptFlags,
- IJavaElementRequestor requestor) {
- int count = fPackageFragmentRoots.length;
- for (int i = 0; i < count; i++) {
+ private void findAllTypes(String prefix, boolean partialMatch, int acceptFlags, IJavaElementRequestor requestor) {
+ int count= fPackageFragmentRoots.length;
+ for (int i= 0; i < count; i++) {
if (requestor.isCanceled())
return;
- IPackageFragmentRoot root = fPackageFragmentRoots[i];
- IJavaElement[] packages = null;
+ IPackageFragmentRoot root= fPackageFragmentRoots[i];
+ IJavaElement[] packages= null;
try {
- packages = root.getChildren();
+ packages= root.getChildren();
} catch (JavaModelException npe) {
continue; // the root is not present, continue;
}
if (packages != null) {
- for (int j = 0, packageCount = packages.length; j < packageCount; j++) {
+ for (int j= 0, packageCount= packages.length; j < packageCount; j++) {
if (requestor.isCanceled())
return;
- seekTypes(
- prefix,
- (IPackageFragment) packages[j],
- partialMatch,
- acceptFlags,
- requestor);
+ seekTypes(prefix, (IPackageFragment) packages[j], partialMatch, acceptFlags, requestor);
}
}
}
}
-
/**
* @see INameLookup
*/
public ICompilationUnit findCompilationUnit(String qualifiedTypeName) {
- String pkgName = IPackageFragment.DEFAULT_PACKAGE_NAME;
- String cuName = qualifiedTypeName;
+ String pkgName= IPackageFragment.DEFAULT_PACKAGE_NAME;
+ String cuName= qualifiedTypeName;
- int index = qualifiedTypeName.lastIndexOf('.');
+ int index= qualifiedTypeName.lastIndexOf('.');
if (index != -1) {
- pkgName = qualifiedTypeName.substring(0, index);
- cuName = qualifiedTypeName.substring(index + 1);
+ pkgName= qualifiedTypeName.substring(0, index);
+ cuName= qualifiedTypeName.substring(index + 1);
}
- index = cuName.indexOf('$');
+ index= cuName.indexOf('$');
if (index != -1) {
- cuName = cuName.substring(0, index);
+ cuName= cuName.substring(0, index);
}
- cuName += ".java";
+ cuName += ".java"/*nonNLS*/;
- IPackageFragment[] frags = (IPackageFragment[]) fPackageFragments.get(pkgName);
+ IPackageFragment[] frags= (IPackageFragment[]) fPackageFragments.get(pkgName);
if (frags != null) {
- for (int i = 0; i < frags.length; i++) {
- IPackageFragment frag = frags[i];
+ for (int i= 0; i < frags.length; i++) {
+ IPackageFragment frag= frags[i];
if (!(frag instanceof JarPackageFragment)) {
- ICompilationUnit cu = frag.getCompilationUnit(cuName);
+ ICompilationUnit cu= frag.getCompilationUnit(cuName);
if (cu != null && cu.exists()) {
return cu;
}
@@ -184,131 +168,119 @@ public class NameLookup implements INameLookup {
}
return null;
}
-
- /**
- * @see INameLookup
- */
- public IPackageFragment findPackageFragment(IPath path) {
- if (!path.isAbsolute()) {
- throw new IllegalArgumentException("Path must be absolute");
- }
- IResource possibleFragment = workspace.getRoot().findMember(path);
- if (possibleFragment == null) {
- //external jar
- for (int i = 0; i < fPackageFragmentRoots.length; i++) {
- IPackageFragmentRoot root = fPackageFragmentRoots[i];
- if (!root.isExternal()) {
- continue;
+/**
+ * @see INameLookup
+ */
+public IPackageFragment findPackageFragment(IPath path) {
+ if (!path.isAbsolute()) {
+ throw new IllegalArgumentException(Util.bind("path.mustBeAbsolute"/*nonNLS*/));
+ }
+ IResource possibleFragment = workspace.getRoot().findMember(path);
+ if (possibleFragment == null) {
+ //external jar
+ for (int i = 0; i < fPackageFragmentRoots.length; i++) {
+ IPackageFragmentRoot root = fPackageFragmentRoots[i];
+ if (!root.isExternal()) {
+ continue;
+ }
+ IPath rootPath = root.getPath();
+ int matchingCount = rootPath.matchingFirstSegments(path);
+ if (matchingCount != 0) {
+ String name = path.toOSString();
+ // + 1 is for the File.separatorChar
+ name = name.substring(rootPath.toOSString().length() + 1, name.length());
+ name = name.replace(File.separatorChar, '.');
+ IJavaElement[] list = null;
+ try {
+ list = root.getChildren();
+ } catch (JavaModelException npe) {
+ continue; // the package fragment root is not present;
}
- IPath rootPath = root.getPath();
- int matchingCount = rootPath.matchingFirstSegments(path);
- if (matchingCount != 0) {
- String name = path.toOSString();
- // + 1 is for the File.separatorChar
- name = name.substring(rootPath.toOSString().length() + 1, name.length());
- name = name.replace(File.separatorChar, '.');
- IJavaElement[] list = null;
- try {
- list = root.getChildren();
- } catch (JavaModelException npe) {
- continue; // the package fragment root is not present;
- }
- int elementCount = list.length;
- for (int j = 0; j < elementCount; j++) {
- IPackageFragment packageFragment = (IPackageFragment) list[j];
- if (nameMatches(name, packageFragment, false)) {
- if (packageFragment.exists())
- return packageFragment;
- }
+ int elementCount = list.length;
+ for (int j = 0; j < elementCount; j++) {
+ IPackageFragment packageFragment = (IPackageFragment) list[j];
+ if (nameMatches(name, packageFragment, false)) {
+ if (packageFragment.exists())
+ return packageFragment;
}
}
}
- } else {
- IJavaElement fromFactory = JavaCore.create(possibleFragment);
- if (fromFactory == null) {
- return null;
- }
- if (fromFactory instanceof IPackageFragment) {
- return (IPackageFragment) fromFactory;
- } else
- if (fromFactory instanceof IJavaProject) {
- // default package in a default root
- JavaProject project = (JavaProject) fromFactory;
- try {
- IClasspathEntry entry = project.getClasspathEntryFor(path);
- if (entry != null) {
- IPackageFragmentRoot root =
- project.getPackageFragmentRoot(project.getUnderlyingResource());
- IPackageFragment[] pkgs =
- (IPackageFragment[]) fPackageFragments.get(
- IPackageFragment.DEFAULT_PACKAGE_NAME);
- if (pkgs == null) {
- return null;
- }
- for (int i = 0; i < pkgs.length; i++) {
- if (pkgs[i].getParent().equals(root)) {
- return pkgs[i];
- }
+ }
+ } else {
+ IJavaElement fromFactory = JavaCore.create(possibleFragment);
+ if (fromFactory == null) {
+ return null;
+ }
+ if (fromFactory instanceof IPackageFragment) {
+ return (IPackageFragment) fromFactory;
+ } else
+ if (fromFactory instanceof IJavaProject) {
+ // default package in a default root
+ JavaProject project = (JavaProject) fromFactory;
+ try {
+ IClasspathEntry entry = project.getClasspathEntryFor(path);
+ if (entry != null) {
+ IPackageFragmentRoot root =
+ project.getPackageFragmentRoot(project.getUnderlyingResource());
+ IPackageFragment[] pkgs = (IPackageFragment[]) fPackageFragments.get(IPackageFragment.DEFAULT_PACKAGE_NAME);
+ if (pkgs == null) {
+ return null;
+ }
+ for (int i = 0; i < pkgs.length; i++) {
+ if (pkgs[i].getParent().equals(root)) {
+ return pkgs[i];
}
}
- } catch (JavaModelException e) {
- return null;
}
+ } catch (JavaModelException e) {
+ return null;
}
- }
- return null;
+ }
}
-
+ return null;
+}
/**
* @see INameLookup
*/
public IPackageFragmentRoot findPackageFragmentRoot(IPath path) {
if (!path.isAbsolute()) {
- throw new IllegalArgumentException("Path must be absolute");
+ throw new IllegalArgumentException(Util.bind("path.mustBeAbsolute"/*nonNLS*/));
}
- for (int i = 0; i < fPackageFragmentRoots.length; i++) {
- IPackageFragmentRoot classpathRoot = fPackageFragmentRoots[i];
+ for (int i= 0; i < fPackageFragmentRoots.length; i++) {
+ IPackageFragmentRoot classpathRoot= fPackageFragmentRoots[i];
if (classpathRoot.getPath().equals(path)) {
return classpathRoot;
}
}
return null;
}
-
/**
* @see INameLookup
*/
- public IPackageFragment[] findPackageFragments(
- String name,
- boolean partialMatch) {
- int count = fPackageFragmentRoots.length;
+ public IPackageFragment[] findPackageFragments(String name, boolean partialMatch) {
+ int count= fPackageFragmentRoots.length;
if (partialMatch) {
- name = name.toLowerCase();
- for (int i = 0; i < count; i++) {
- IPackageFragmentRoot root = fPackageFragmentRoots[i];
- IJavaElement[] list = null;
+ name= name.toLowerCase();
+ for (int i= 0; i < count; i++) {
+ IPackageFragmentRoot root= fPackageFragmentRoots[i];
+ IJavaElement[] list= null;
try {
- list = root.getChildren();
+ list= root.getChildren();
} catch (JavaModelException npe) {
continue; // the package fragment root is not present;
}
- int elementCount = list.length;
+ int elementCount= list.length;
IPackageFragment[] result = new IPackageFragment[elementCount];
- int resultLength = 0;
- for (int j = 0; j < elementCount; j++) {
- IPackageFragment packageFragment = (IPackageFragment) list[j];
+ int resultLength = 0;
+ for (int j= 0; j < elementCount; j++) {
+ IPackageFragment packageFragment= (IPackageFragment) list[j];
if (nameMatches(name, packageFragment, true)) {
if (packageFragment.exists())
result[resultLength++] = packageFragment;
}
}
if (resultLength > 0) {
- System.arraycopy(
- result,
- 0,
- result = new IPackageFragment[resultLength],
- 0,
- resultLength);
+ System.arraycopy(result, 0, result = new IPackageFragment[resultLength], 0, resultLength);
return result;
} else {
return null;
@@ -316,22 +288,17 @@ public class NameLookup implements INameLookup {
}
} else {
// Return only fragments that exists
- IPackageFragment[] fragments = (IPackageFragment[]) fPackageFragments.get(name);
+ IPackageFragment[] fragments= (IPackageFragment[]) fPackageFragments.get(name);
if (fragments != null) {
IPackageFragment[] result = new IPackageFragment[fragments.length];
- int resultLength = 0;
- for (int i = 0; i < fragments.length; i++) {
- IPackageFragment packageFragment = fragments[i];
+ int resultLength = 0;
+ for (int i= 0; i < fragments.length; i++) {
+ IPackageFragment packageFragment= fragments[i];
if (packageFragment.exists())
result[resultLength++] = packageFragment;
}
if (resultLength > 0) {
- System.arraycopy(
- result,
- 0,
- result = new IPackageFragment[resultLength],
- 0,
- resultLength);
+ System.arraycopy(result, 0, result = new IPackageFragment[resultLength], 0, resultLength);
return result;
} else {
return null;
@@ -340,65 +307,53 @@ public class NameLookup implements INameLookup {
}
return null;
}
-
/**
*
*/
- public IType findType(
- String typeName,
- String packageName,
- boolean partialMatch,
- int acceptFlags) {
+ public IType findType(String typeName, String packageName, boolean partialMatch, int acceptFlags) {
if (packageName == null) {
- packageName = IPackageFragment.DEFAULT_PACKAGE_NAME;
+ packageName= IPackageFragment.DEFAULT_PACKAGE_NAME;
}
seekPackageFragments(packageName, false, fgJavaElementRequestor);
- IPackageFragment[] packages = fgJavaElementRequestor.getPackageFragments();
+ IPackageFragment[] packages= fgJavaElementRequestor.getPackageFragments();
fgJavaElementRequestor.reset();
- for (int i = 0, length = packages.length; i < length; i++) {
- IType type = findType(typeName, packages[i], partialMatch, acceptFlags);
+ for (int i= 0, length= packages.length; i < length; i++) {
+ IType type= findType(typeName, packages[i], partialMatch, acceptFlags);
if (type != null)
return type;
}
return null;
}
-
/**
* @see INameLookup
*/
- public IType findType(
- String name,
- IPackageFragment pkg,
- boolean partialMatch,
- int acceptFlags) {
+ public IType findType(String name, IPackageFragment pkg, boolean partialMatch, int acceptFlags) {
if (pkg == null) {
return null;
}
// Return first found (ignore duplicates).
seekTypes(name, pkg, partialMatch, acceptFlags, fgSingleTypeRequestor);
- IType type = fgSingleTypeRequestor.getType();
+ IType type= fgSingleTypeRequestor.getType();
fgSingleTypeRequestor.reset();
return type;
}
-
/**
* @see INameLookup
*/
public IType findType(String name, boolean partialMatch, int acceptFlags) {
- int index = name.lastIndexOf('.');
- String className = null, packageName = null;
+ int index= name.lastIndexOf('.');
+ String className= null, packageName= null;
if (index == -1) {
- packageName = IPackageFragment.DEFAULT_PACKAGE_NAME;
- className = name;
+ packageName= IPackageFragment.DEFAULT_PACKAGE_NAME;
+ className= name;
} else {
- packageName = name.substring(0, index);
- className = name.substring(index + 1);
+ packageName= name.substring(0, index);
+ className= name.substring(index + 1);
}
return findType(className, packageName, partialMatch, acceptFlags);
}
-
/**
* Returns true if the given element's name matches the
* specified <code>searchName</code>, otherwise false.
@@ -408,10 +363,7 @@ public class NameLookup implements INameLookup {
* NOTE: in partialMatch mode, the case will be ignored, and the searchName must already have
* been lowercased.
*/
- protected boolean nameMatches(
- String searchName,
- IJavaElement element,
- boolean partialMatch) {
+ protected boolean nameMatches(String searchName, IJavaElement element, boolean partialMatch) {
if (partialMatch) {
// partial matches are used in completion mode, thus case insensitive mode
return element.getElementName().toLowerCase().startsWith(searchName);
@@ -419,37 +371,32 @@ public class NameLookup implements INameLookup {
return element.getElementName().equals(searchName);
}
}
-
/**
* @see INameLookup
*/
- public void seekPackageFragments(
- String name,
- boolean partialMatch,
- IJavaElementRequestor requestor) {
- int count = fPackageFragmentRoots.length;
- String matchName = partialMatch ? name.toLowerCase() : name;
- for (int i = 0; i < count; i++) {
+ public void seekPackageFragments(String name, boolean partialMatch, IJavaElementRequestor requestor) {
+ int count= fPackageFragmentRoots.length;
+ String matchName= partialMatch ? name.toLowerCase() : name;
+ for (int i= 0; i < count; i++) {
if (requestor.isCanceled())
return;
- IPackageFragmentRoot root = fPackageFragmentRoots[i];
- IJavaElement[] list = null;
+ IPackageFragmentRoot root= fPackageFragmentRoots[i];
+ IJavaElement[] list= null;
try {
- list = root.getChildren();
+ list= root.getChildren();
} catch (JavaModelException npe) {
continue; // this root package fragment is not present
}
- int elementCount = list.length;
- for (int j = 0; j < elementCount; j++) {
+ int elementCount= list.length;
+ for (int j= 0; j < elementCount; j++) {
if (requestor.isCanceled())
return;
- IPackageFragment packageFragment = (IPackageFragment) list[j];
+ IPackageFragment packageFragment= (IPackageFragment) list[j];
if (nameMatches(matchName, packageFragment, partialMatch))
requestor.acceptPackageFragment(packageFragment);
}
}
}
-
/**
* Notifies the given requestor of all types (classes and interfaces) in the
* given type with the given (possibly qualified) name. Checks
@@ -459,65 +406,51 @@ public class NameLookup implements INameLookup {
* @param partialMatch partial name matches qualify when <code>true</code>,
* only exact name matches qualify when <code>false</code>
*/
- protected void seekQualifiedMemberTypes(
- String qualifiedName,
- IType type,
- boolean partialMatch,
- IJavaElementRequestor requestor) {
+ protected void seekQualifiedMemberTypes(String qualifiedName, IType type, boolean partialMatch, IJavaElementRequestor requestor) {
if (type == null)
return;
- IType[] types = null;
+ IType[] types= null;
try {
- types = type.getTypes();
+ types= type.getTypes();
} catch (JavaModelException npe) {
return; // the enclosing type is not present
}
- String matchName = qualifiedName;
- int index = qualifiedName.indexOf('$');
- boolean nested = false;
+ String matchName= qualifiedName;
+ int index= qualifiedName.indexOf('$');
+ boolean nested= false;
if (index != -1) {
- matchName = qualifiedName.substring(0, index);
- nested = true;
+ matchName= qualifiedName.substring(0, index);
+ nested= true;
}
- int length = types.length;
- for (int i = 0; i < length; i++) {
+ int length= types.length;
+ for (int i= 0; i < length; i++) {
if (requestor.isCanceled())
return;
- IType memberType = types[i];
+ IType memberType= types[i];
if (nameMatches(matchName, memberType, partialMatch))
if (nested) {
- seekQualifiedMemberTypes(
- qualifiedName.substring(index + 1, qualifiedName.length()),
- memberType,
- partialMatch,
- requestor);
+ seekQualifiedMemberTypes(qualifiedName.substring(index + 1, qualifiedName.length()), memberType, partialMatch, requestor);
} else {
requestor.acceptMemberType(memberType);
}
}
}
-
/**
* @see INameLookup
*/
- public void seekTypes(
- String name,
- IPackageFragment pkg,
- boolean partialMatch,
- int acceptFlags,
- IJavaElementRequestor requestor) {
+ public void seekTypes(String name, IPackageFragment pkg, boolean partialMatch, int acceptFlags, IJavaElementRequestor requestor) {
- String matchName = partialMatch ? name.toLowerCase() : name;
+ String matchName= partialMatch ? name.toLowerCase() : name;
if (matchName.indexOf('.') >= 0) { //looks for member type A.B
- matchName = matchName.replace('.', '$');
+ matchName= matchName.replace('.', '$');
}
if (pkg == null) {
findAllTypes(matchName, partialMatch, acceptFlags, requestor);
return;
}
- IPackageFragmentRoot root = (IPackageFragmentRoot) pkg.getParent();
+ IPackageFragmentRoot root= (IPackageFragmentRoot) pkg.getParent();
try {
- int packageFlavor = root.getKind();
+ int packageFlavor= root.getKind();
switch (packageFlavor) {
case IPackageFragmentRoot.K_BINARY :
seekTypesInBinaryPackage(matchName, pkg, partialMatch, acceptFlags, requestor);
@@ -532,82 +465,66 @@ public class NameLookup implements INameLookup {
return;
}
}
-
/**
* Performs type search in a binary package.
*/
- protected void seekTypesInBinaryPackage(
- String name,
- IPackageFragment pkg,
- boolean partialMatch,
- int acceptFlags,
- IJavaElementRequestor requestor) {
- IClassFile[] classFiles = null;
+ protected void seekTypesInBinaryPackage(String name, IPackageFragment pkg, boolean partialMatch, int acceptFlags, IJavaElementRequestor requestor) {
+ IClassFile[] classFiles= null;
try {
- classFiles = pkg.getClassFiles();
+ classFiles= pkg.getClassFiles();
} catch (JavaModelException npe) {
return; // the package is not present
}
- int length = classFiles.length;
+ int length= classFiles.length;
- String unqualifiedName = name;
- int index = name.lastIndexOf('$');
+ String unqualifiedName= name;
+ int index= name.lastIndexOf('$');
if (index != -1) {
//the type name of the inner type
- unqualifiedName = name.substring(index + 1, name.length());
+ unqualifiedName= name.substring(index + 1, name.length());
}
- String lowerName = name.toLowerCase();
- for (int i = 0; i < length; i++) {
+ String lowerName= name.toLowerCase();
+ for (int i= 0; i < length; i++) {
if (requestor.isCanceled())
return;
- IClassFile classFile = classFiles[i];
+ IClassFile classFile= classFiles[i];
/**
* In the following call to nameMatches we must always send true
* for the partialMatch argument since name will never have the
* extension ".class" and the classFile always will.
*/
if (nameMatches(lowerName, classFile, true)) {
- IType type = null;
+ IType type= null;
try {
- type = classFile.getType();
+ type= classFile.getType();
} catch (JavaModelException npe) {
continue; // the classFile is not present
}
- if (!partialMatch
- || (type.getElementName().length() > 0
- && !Character.isDigit(
- type.getElementName().charAt(0)))) { //not an anonymous type
- if (nameMatches(unqualifiedName, type, partialMatch)
- && acceptType(type, acceptFlags))
+ if (!partialMatch || (type.getElementName().length() > 0 && !Character.isDigit(type.getElementName().charAt(0)))) { //not an anonymous type
+ if (nameMatches(unqualifiedName, type, partialMatch) && acceptType(type, acceptFlags))
requestor.acceptType(type);
}
}
}
}
-
/**
* Performs type search in a source package.
*/
- protected void seekTypesInSourcePackage(
- String name,
- IPackageFragment pkg,
- boolean partialMatch,
- int acceptFlags,
- IJavaElementRequestor requestor) {
- ICompilationUnit[] compilationUnits = null;
+ protected void seekTypesInSourcePackage(String name, IPackageFragment pkg, boolean partialMatch, int acceptFlags, IJavaElementRequestor requestor) {
+ ICompilationUnit[] compilationUnits= null;
try {
- compilationUnits = pkg.getCompilationUnits();
+ compilationUnits= pkg.getCompilationUnits();
} catch (JavaModelException npe) {
return; // the package is not present
}
- int length = compilationUnits.length;
- String matchName = name;
- int index = name.indexOf('$');
- boolean memberType = false;
+ int length= compilationUnits.length;
+ String matchName= name;
+ int index= name.indexOf('$');
+ boolean memberType= false;
if (index != -1) {
//the compilation unit name of the inner type
- matchName = name.substring(0, index);
- memberType = true;
+ matchName= name.substring(0, index);
+ memberType= true;
}
/**
@@ -615,39 +532,33 @@ public class NameLookup implements INameLookup {
* the compilationUnits always will. So add it if we're looking for
* an exact match.
*/
- String unitName = partialMatch ? matchName.toLowerCase() : matchName + ".java";
+ String unitName= partialMatch ? matchName.toLowerCase() : matchName + ".java"/*nonNLS*/;
- for (int i = 0; i < length; i++) {
+ for (int i= 0; i < length; i++) {
if (requestor.isCanceled())
return;
- ICompilationUnit compilationUnit = compilationUnits[i];
+ ICompilationUnit compilationUnit= compilationUnits[i];
if (nameMatches(unitName, compilationUnit, partialMatch)) {
- IType[] types = null;
+ IType[] types= null;
try {
- types = compilationUnit.getTypes();
+ types= compilationUnit.getTypes();
} catch (JavaModelException npe) {
continue; // the compilation unit is not present
}
- int typeLength = types.length;
- for (int j = 0; j < typeLength; j++) {
+ int typeLength= types.length;
+ for (int j= 0; j < typeLength; j++) {
if (requestor.isCanceled())
return;
- IType type = types[j];
- if (nameMatches(matchName, type, partialMatch)
- && acceptType(type, acceptFlags))
+ IType type= types[j];
+ if (nameMatches(matchName, type, partialMatch) && acceptType(type, acceptFlags))
if (!memberType) {
requestor.acceptType(type);
} else {
- seekQualifiedMemberTypes(
- name.substring(index + 1, name.length()),
- type,
- partialMatch,
- requestor);
+ seekQualifiedMemberTypes(name.substring(index + 1, name.length()), type, partialMatch, requestor);
}
}
}
}
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/NonVoidMethodRequestor.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/NonVoidMethodRequestor.java
index 40545699d1..e79947fcca 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/NonVoidMethodRequestor.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/NonVoidMethodRequestor.java
@@ -16,21 +16,19 @@ import org.eclipse.jdt.core.Signature;
* functionality by only accepting methods with return types that are not void.
*/
public class NonVoidMethodRequestor extends SearchableEnvironmentRequestor {
- /**
- * NonVoidMethodRequestor constructor comment.
- * @param requestor org.eclipse.jdt.internal.codeassist.ISearchRequestor
- */
- public NonVoidMethodRequestor(ISearchRequestor requestor) {
- super(requestor);
- }
-
- public void acceptMethod(IMethod method) {
- try {
- if (!Signature.getReturnType(method.getSignature()).equals("V")) {
- super.acceptMethod(method);
- }
- } catch (JavaModelException npe) {
+/**
+ * NonVoidMethodRequestor constructor comment.
+ * @param requestor org.eclipse.jdt.internal.codeassist.ISearchRequestor
+ */
+public NonVoidMethodRequestor(ISearchRequestor requestor) {
+ super(requestor);
+}
+public void acceptMethod(IMethod method) {
+ try {
+ if (!Signature.getReturnType(method.getSignature()).equals("V"/*nonNLS*/)) {
+ super.acceptMethod(method);
}
+ } catch (JavaModelException npe) {
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Openable.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Openable.java
index f29961c7e1..cc6944b475 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Openable.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Openable.java
@@ -22,19 +22,17 @@ import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
+
/**
* Abstract class for implementations of java elements which are IOpenable.
*
* @see IJavaElement, IOpenable
*/
-public abstract class Openable
- extends JavaElement
- implements IOpenable, IBufferChangedListener {
-
- protected Openable(int type, IJavaElement parent, String name) {
- super(type, parent, name);
- }
+public abstract class Openable extends JavaElement implements IOpenable, IBufferChangedListener {
+protected Openable(int type, IJavaElement parent, String name) {
+ super(type, parent, name);
+}
/**
* The buffer associated with this element has changed. Registers
* this element as being out of synch with its buffer's contents.
@@ -50,395 +48,333 @@ public abstract class Openable
fgJavaModelManager.getElementsOutOfSynchWithBuffers().put(this, this);
}
}
-
- /**
- * Updates the info objects for this element and all of its children by
- * removing the current infos, generating new infos, and then placing
- * the new infos into the Java Model cache tables.
- */
- protected void buildStructure(OpenableElementInfo info, IProgressMonitor pm)
- throws JavaModelException {
-
- // remove existing (old) infos
- removeInfo();
- Hashtable newElements = new Hashtable(11);
- info.setIsStructureKnown(
- generateInfos(info, pm, newElements, getUnderlyingResource()));
+/**
+ * Updates the info objects for this element and all of its children by
+ * removing the current infos, generating new infos, and then placing
+ * the new infos into the Java Model cache tables.
+ */
+protected void buildStructure(OpenableElementInfo info, IProgressMonitor pm) throws JavaModelException {
+
+ // remove existing (old) infos
+ removeInfo();
+ Hashtable newElements = new Hashtable(11);
+ info.setIsStructureKnown(generateInfos(info, pm, newElements, getUnderlyingResource()));
+ fgJavaModelManager.getElementsOutOfSynchWithBuffers().remove(this);
+ for (Enumeration e = newElements.keys(); e.hasMoreElements();) {
+ IJavaElement key = (IJavaElement) e.nextElement();
+ Object value = newElements.get(key);
+ fgJavaModelManager.putInfo(key, value);
+ }
+ // add the info for this at the end, to ensure that a getInfo cannot reply null in case the LRU cache needs
+ // to be flushed. Might lead to performance issues.
+ // see PR 1G2K5S7: ITPJCORE:ALL - NPE when accessing source for a binary type
+ fgJavaModelManager.putInfo(this, info);
+}
+/**
+ * Close the buffer associated with this element, if any.
+ */
+protected void closeBuffer(OpenableElementInfo info) {
+ IBuffer buffer = null;
+ buffer = getBufferManager().getBuffer(this);
+ if (buffer != null) {
+ buffer.removeBufferChangedListener(this);
+ buffer.close();
fgJavaModelManager.getElementsOutOfSynchWithBuffers().remove(this);
- for (Enumeration e = newElements.keys(); e.hasMoreElements();) {
- IJavaElement key = (IJavaElement) e.nextElement();
- Object value = newElements.get(key);
- fgJavaModelManager.putInfo(key, value);
- }
- // add the info for this at the end, to ensure that a getInfo cannot reply null in case the LRU cache needs
- // to be flushed. Might lead to performance issues.
- // see PR 1G2K5S7: ITPJCORE:ALL - NPE when accessing source for a binary type
- fgJavaModelManager.putInfo(this, info);
}
-
- /**
- * Close the buffer associated with this element, if any.
- */
- protected void closeBuffer(OpenableElementInfo info) {
- IBuffer buffer = null;
- buffer = getBufferManager().getBuffer(this);
- if (buffer != null) {
- buffer.removeBufferChangedListener(this);
- buffer.close();
- fgJavaModelManager.getElementsOutOfSynchWithBuffers().remove(this);
- }
+}
+/**
+ * This element is being closed. Do any necessary cleanup.
+ */
+protected void closing(Object info) throws JavaModelException {
+ OpenableElementInfo openableInfo = (OpenableElementInfo) info;
+ closeBuffer(openableInfo);
+ super.closing(info);
+}
+/**
+ * @see ICodeAssist
+ */
+protected void codeComplete(org.eclipse.jdt.internal.compiler.env.ICompilationUnit cu, org.eclipse.jdt.internal.compiler.env.ICompilationUnit unitToSkip, int position, ICodeCompletionRequestor requestor) throws JavaModelException {
+ if (requestor == null) {
+ throw new IllegalArgumentException(Util.bind("codeAssist.nullRequestor"/*nonNLS*/));
}
-
- /**
- * This element is being closed. Do any necessary cleanup.
- */
- protected void closing(Object info) throws JavaModelException {
- OpenableElementInfo openableInfo = (OpenableElementInfo) info;
- closeBuffer(openableInfo);
- super.closing(info);
+ if (position < -1 || position > getBuffer().getLength()) {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS));
}
+ SearchableEnvironment environment = (SearchableEnvironment) ((JavaProject) getJavaProject()).getSearchableNameEnvironment();
+ environment.unitToSkip = unitToSkip;
- /**
- * @see ICodeAssist
- */
- protected void codeComplete(
- org.eclipse.jdt.internal.compiler.env.ICompilationUnit cu,
- org.eclipse.jdt.internal.compiler.env.ICompilationUnit unitToSkip,
- int position,
- ICodeCompletionRequestor requestor)
- throws JavaModelException {
- if (requestor == null) {
- throw new IllegalArgumentException("requestor cannot be null");
- }
- if (position < -1 || position > getBuffer().getLength()) {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS));
- }
- SearchableEnvironment environment =
- (SearchableEnvironment) ((JavaProject) getJavaProject())
- .getSearchableNameEnvironment();
- environment.unitToSkip = unitToSkip;
+ CompletionEngine engine = new CompletionEngine(environment, new CompletionRequestorWrapper(requestor), JavaModelManager.convertConfigurableOptions(JavaCore.getOptions()));
+ engine.complete(cu, position);
+ environment.unitToSkip = null;
+}
+/**
+ * @see ICodeAssist
+ */
+protected IJavaElement[] codeSelect(org.eclipse.jdt.internal.compiler.env.ICompilationUnit cu, int offset, int length) throws JavaModelException {
+ SelectionRequestor requestor= new SelectionRequestor(((JavaProject)getJavaProject()).getNameLookup(), this);
+ this.codeSelect(cu, offset, length, requestor);
+ return requestor.getElements();
+}
+/**
+ * @see ICodeAssist
+ */
+protected void codeSelect(org.eclipse.jdt.internal.compiler.env.ICompilationUnit cu, int offset, int length, ISelectionRequestor requestor) throws JavaModelException {
- CompletionEngine engine =
- new CompletionEngine(
- environment,
- new CompletionRequestorWrapper(requestor),
- JavaModelManager.convertConfigurableOptions(JavaCore.getOptions()));
- engine.complete(cu, position);
- environment.unitToSkip = null;
+ // fix for 1FWNMHH, part (1)
+ if (length == 0) {
+ return;
}
-
- /**
- * @see ICodeAssist
- */
- protected IJavaElement[] codeSelect(
- org.eclipse.jdt.internal.compiler.env.ICompilationUnit cu,
- int offset,
- int length)
- throws JavaModelException {
- SelectionRequestor requestor =
- new SelectionRequestor(((JavaProject) getJavaProject()).getNameLookup(), this);
- this.codeSelect(cu, offset, length, requestor);
- return requestor.getElements();
+
+ int end= getBuffer().getLength();
+ if (offset < 0 || length < 0 || offset + length > end ) {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS));
}
- /**
- * @see ICodeAssist
- */
- protected void codeSelect(
- org.eclipse.jdt.internal.compiler.env.ICompilationUnit cu,
- int offset,
- int length,
- ISelectionRequestor requestor)
- throws JavaModelException {
-
- // fix for 1FWNMHH, part (1)
- if (length == 0) {
- return;
- }
-
- int end = getBuffer().getLength();
- if (offset < 0 || length < 0 || offset + length > end) {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS));
+ // fix for 1FVGGKF
+ ISearchableNameEnvironment environment = ((JavaProject)getJavaProject()).getSearchableNameEnvironment();
+
+ // fix for 1FVXGDK
+ SelectionEngine engine = new SelectionEngine(environment, requestor, JavaModelManager.convertConfigurableOptions(JavaCore.getOptions()));
+ engine.select(cu, offset, offset + length - 1);
+}
+/**
+ * Returns a new element info for this element.
+ */
+protected OpenableElementInfo createElementInfo() {
+ return new OpenableElementInfo();
+}
+/**
+ * Builds this element's structure and properties in the given
+ * info object, based on this element's current contents (i.e. buffer
+ * contents if this element has an open buffer, or resource contents
+ * if this element does not have an open buffer). Children
+ * are placed in the given newElements table (note, this element
+ * has already been placed in the newElements table). Returns true
+ * if successful, or false if an error is encountered while determining
+ * the structure of this element.
+ */
+protected abstract boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Hashtable newElements, IResource underlyingResource) throws JavaModelException;
+/**
+ * Note: a buffer with no unsaved changes can be closed by the Java Model
+ * since it has a finite number of buffers allowed open at one time. If this
+ * is the first time a request is being made for the buffer, an attempt is
+ * made to create and fill this element's buffer. If the buffer has been
+ * closed since it was first opened, the buffer is re-created.
+ *
+ * @see IOpenable
+ */
+public IBuffer getBuffer() throws JavaModelException {
+ if (hasBuffer()) {
+ // ensure element is open
+ if (!isOpen()) {
+ getElementInfo();
}
-
- // fix for 1FVGGKF
- ISearchableNameEnvironment environment =
- ((JavaProject) getJavaProject()).getSearchableNameEnvironment();
-
- // fix for 1FVXGDK
- SelectionEngine engine =
- new SelectionEngine(
- environment,
- requestor,
- JavaModelManager.convertConfigurableOptions(JavaCore.getOptions()));
- engine.select(cu, offset, offset + length - 1);
- }
-
- /**
- * Returns a new element info for this element.
- */
- protected OpenableElementInfo createElementInfo() {
- return new OpenableElementInfo();
- }
-
- /**
- * Builds this element's structure and properties in the given
- * info object, based on this element's current contents (i.e. buffer
- * contents if this element has an open buffer, or resource contents
- * if this element does not have an open buffer). Children
- * are placed in the given newElements table (note, this element
- * has already been placed in the newElements table). Returns true
- * if successful, or false if an error is encountered while determining
- * the structure of this element.
- */
- protected abstract boolean generateInfos(
- OpenableElementInfo info,
- IProgressMonitor pm,
- Hashtable newElements,
- IResource underlyingResource)
- throws JavaModelException;
- /**
- * Note: a buffer with no unsaved changes can be closed by the Java Model
- * since it has a finite number of buffers allowed open at one time. If this
- * is the first time a request is being made for the buffer, an attempt is
- * made to create and fill this element's buffer. If the buffer has been
- * closed since it was first opened, the buffer is re-created.
- *
- * @see IOpenable
- */
- public IBuffer getBuffer() throws JavaModelException {
- if (hasBuffer()) {
- // ensure element is open
- if (!isOpen()) {
- getElementInfo();
- }
- IBuffer buffer = getBufferManager().getBuffer(this);
- if (buffer == null) {
- // try to (re)open a buffer
- buffer = openBuffer(null);
- }
- return buffer;
- } else {
- return null;
+ IBuffer buffer = getBufferManager().getBuffer(this);
+ if (buffer == null) {
+ // try to (re)open a buffer
+ buffer = openBuffer(null);
}
+ return buffer;
+ } else {
+ return null;
}
-
- /**
- * Returns the buffer manager for this element.
- */
- protected IBufferManager getBufferManager() {
- return BufferManager.getDefaultBufferManager();
- }
-
- /**
- * Return my underlying resource. Elements that may not have a
- * corresponding resource must override this method.
- *
- * @see IJavaElement
- */
- public IResource getCorrespondingResource() throws JavaModelException {
- return getUnderlyingResource();
+}
+/**
+ * Returns the buffer manager for this element.
+ */
+protected IBufferManager getBufferManager() {
+ return BufferManager.getDefaultBufferManager();
+}
+/**
+ * Return my underlying resource. Elements that may not have a
+ * corresponding resource must override this method.
+ *
+ * @see IJavaElement
+ */
+public IResource getCorrespondingResource() throws JavaModelException {
+ return getUnderlyingResource();
+}
+/**
+ * @see IJavaElement
+ */
+public IResource getUnderlyingResource() throws JavaModelException {
+ IResource parentResource = fParent.getUnderlyingResource();
+ if (parentResource == null) {
+ return null;
}
-
- /**
- * @see IJavaElement
- */
- public IResource getUnderlyingResource() throws JavaModelException {
- IResource parentResource = fParent.getUnderlyingResource();
- if (parentResource == null) {
- return null;
- }
- int type = parentResource.getType();
- if (type == IResource.FOLDER || type == IResource.PROJECT) {
- IContainer folder = (IContainer) parentResource;
- IResource resource = folder.findMember(fName);
- if (resource == null) {
- throw newNotPresentException();
- } else {
- return resource;
- }
+ int type = parentResource.getType();
+ if (type == IResource.FOLDER || type == IResource.PROJECT) {
+ IContainer folder = (IContainer) parentResource;
+ IResource resource = folder.findMember(fName);
+ if (resource == null) {
+ throw newNotPresentException();
} else {
- return parentResource;
+ return resource;
}
+ } else {
+ return parentResource;
}
-
- /**
- * Returns true if this element may have an associated source buffer,
- * otherwise false. Subclasses must override as required.
- */
- protected boolean hasBuffer() {
+}
+/**
+ * Returns true if this element may have an associated source buffer,
+ * otherwise false. Subclasses must override as required.
+ */
+protected boolean hasBuffer() {
+ return false;
+}
+/**
+ * @see IParent
+ */
+public boolean hasChildren() throws JavaModelException {
+ return getChildren().length > 0;
+}
+/**
+ * @see IOpenable
+ */
+public boolean hasUnsavedChanges() throws JavaModelException{
+
+ if (isReadOnly() || !isOpen()) {
return false;
}
-
- /**
- * @see IParent
- */
- public boolean hasChildren() throws JavaModelException {
- return getChildren().length > 0;
+ if (getBuffer() != null && getBuffer().hasUnsavedChanges()) {
+ return true;
}
-
- /**
- * @see IOpenable
- */
- public boolean hasUnsavedChanges() throws JavaModelException {
-
- if (isReadOnly() || !isOpen()) {
- return false;
- }
- if (getBuffer() != null && getBuffer().hasUnsavedChanges()) {
- return true;
- }
- // for package fragments, package fragment roots, and projects must check open buffers
- // to see if they have an child with unsaved changes
- if (fLEType == PACKAGE_FRAGMENT
- || fLEType == PACKAGE_FRAGMENT_ROOT
- || fLEType == JAVA_PROJECT
- || fLEType == JAVA_MODEL) { // fix for 1FWNMHH, part (2)
- Enumeration openBuffers = getBufferManager().getOpenBuffers();
- while (openBuffers.hasMoreElements()) {
- IBuffer buffer = (IBuffer) openBuffers.nextElement();
- if (buffer.hasUnsavedChanges()) {
- IJavaElement owner = (IJavaElement) buffer.getOwner();
- if (isAncestorOf(owner)) {
- return true;
- }
+ // for package fragments, package fragment roots, and projects must check open buffers
+ // to see if they have an child with unsaved changes
+ if (fLEType == PACKAGE_FRAGMENT ||
+ fLEType == PACKAGE_FRAGMENT_ROOT ||
+ fLEType == JAVA_PROJECT ||
+ fLEType == JAVA_MODEL) { // fix for 1FWNMHH, part (2)
+ Enumeration openBuffers= getBufferManager().getOpenBuffers();
+ while (openBuffers.hasMoreElements()) {
+ IBuffer buffer= (IBuffer)openBuffers.nextElement();
+ if (buffer.hasUnsavedChanges()) {
+ IJavaElement owner= (IJavaElement)buffer.getOwner();
+ if (isAncestorOf(owner)) {
+ return true;
}
}
}
-
- return false;
}
-
- /**
- * Subclasses must override as required.
- *
- * @see IOpenable
- */
- public boolean isConsistent() throws JavaModelException {
- return true;
- }
-
- /**
- *
- * @see IOpenable
- */
- public boolean isOpen() {
- return fgJavaModelManager.getInfo(this) != null;
- }
-
- /**
- * Returns true if this represents a source element.
- * Openable source elements have an associated buffer created
- * when they are opened.
- */
- protected boolean isSourceElement() {
- return false;
- }
-
- /**
- * @see IOpenable
- */
- public void makeConsistent(IProgressMonitor pm) throws JavaModelException {
- if (!isConsistent()) {
- buildStructure((OpenableElementInfo) getElementInfo(), pm);
- }
- }
-
- /**
- * @see IOpenable
- */
- public void open(IProgressMonitor pm) throws JavaModelException {
- if (!isOpen()) {
- openWhenClosed(pm);
- }
+
+ return false;
+}
+/**
+ * Subclasses must override as required.
+ *
+ * @see IOpenable
+ */
+public boolean isConsistent() throws JavaModelException {
+ return true;
+}
+/**
+ *
+ * @see IOpenable
+ */
+public boolean isOpen() {
+ return fgJavaModelManager.getInfo(this) != null;
+}
+/**
+ * Returns true if this represents a source element.
+ * Openable source elements have an associated buffer created
+ * when they are opened.
+ */
+protected boolean isSourceElement() {
+ return false;
+}
+/**
+ * @see IOpenable
+ */
+public void makeConsistent(IProgressMonitor pm) throws JavaModelException {
+ if (!isConsistent()) {
+ buildStructure((OpenableElementInfo)getElementInfo(), pm);
}
-
- /**
- * Opens a buffer on the contents of this element, and returns
- * the buffer, or returns <code>null</code> if opening fails.
- * By default, do nothing - subclasses that have buffers
- * must override as required.
- */
- protected IBuffer openBuffer(IProgressMonitor pm) throws JavaModelException {
- return null;
+}
+/**
+ * @see IOpenable
+ */
+public void open(IProgressMonitor pm) throws JavaModelException {
+ if (!isOpen()) {
+ openWhenClosed(pm);
}
-
- /**
- * Open an <code>Openable</code> that is known to be closed (no check for <code>isOpen()</code>).
- */
- protected void openWhenClosed(IProgressMonitor pm) throws JavaModelException {
- try {
- // 1) Parent must be open - open the parent if necessary
- Openable openableParent = (Openable) getOpenableParent();
- if (openableParent != null) {
- OpenableElementInfo openableParentInfo =
- (OpenableElementInfo) fgJavaModelManager.getInfo((IJavaElement) openableParent);
- if (openableParentInfo == null) {
- openableParent.openWhenClosed(pm);
- }
- // Parent is open.
+}
+/**
+ * Opens a buffer on the contents of this element, and returns
+ * the buffer, or returns <code>null</code> if opening fails.
+ * By default, do nothing - subclasses that have buffers
+ * must override as required.
+ */
+protected IBuffer openBuffer(IProgressMonitor pm) throws JavaModelException {
+ return null;
+}
+/**
+ * Open an <code>Openable</code> that is known to be closed (no check for <code>isOpen()</code>).
+ */
+protected void openWhenClosed(IProgressMonitor pm) throws JavaModelException {
+ try {
+ // 1) Parent must be open - open the parent if necessary
+ Openable openableParent = (Openable)getOpenableParent();
+ if (openableParent != null) {
+ OpenableElementInfo openableParentInfo = (OpenableElementInfo) fgJavaModelManager.getInfo((IJavaElement) openableParent);
+ if (openableParentInfo == null) {
+ openableParent.openWhenClosed(pm);
}
+ // Parent is open.
+ }
- // 1.5) Ensure my resource is local
- IResource resource = getCorrespondingResource();
- if (resource != null) {
- try {
- JavaModelManager.getJavaModelManager().ensureLocal(resource);
- } catch (CoreException e) {
- throw new JavaModelException(e);
- }
+ // 1.5) Ensure my resource is local
+ IResource resource = getCorrespondingResource();
+ if (resource != null) {
+ try {
+ JavaModelManager.getJavaModelManager().ensureLocal(resource);
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
+ }
- // 2) create the new element info and open a buffer
- OpenableElementInfo info = createElementInfo();
- if (resource != null && isSourceElement()) {
- openBuffer(pm);
- }
+ // 2) create the new element info and open a buffer
+ OpenableElementInfo info = createElementInfo();
+ if (resource != null && isSourceElement()) {
+ openBuffer(pm);
+ }
- // 3) build the structure of the openable
- buildStructure(info, pm);
+ // 3) build the structure of the openable
+ buildStructure(info, pm);
- // 4) anything special
- opening(info);
+ // 4) anything special
+ opening(info);
- // if any problems occuring openning the element, ensure that it's info
- // does not remain in the cache (some elements, pre-cache their info
- // as they are being opened).
- } catch (JavaModelException e) {
- fgJavaModelManager.removeInfo(this);
- throw e;
- }
+ // if any problems occuring openning the element, ensure that it's info
+ // does not remain in the cache (some elements, pre-cache their info
+ // as they are being opened).
+ } catch (JavaModelException e) {
+ fgJavaModelManager.removeInfo(this);
+ throw e;
}
-
- /**
- * @see IOpenable
- */
- public void save(IProgressMonitor pm, boolean force)
- throws JavaModelException {
- if (isReadOnly()) {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
- }
- IBuffer buf = getBuffer();
- if (buf != null) { // some Openables (like a JavaProject) don't have a buffer
- buf.save(pm, force);
- this.makeConsistent(pm); // update the element info of this element
- }
+}
+/**
+ * @see IOpenable
+ */
+public void save(IProgressMonitor pm, boolean force) throws JavaModelException {
+ if (isReadOnly()) {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.READ_ONLY, this));
}
-
- /**
- * Find enclosing package fragment root if any
- */
- public IPackageFragmentRoot getPackageFragmentRoot() {
- IJavaElement current = this;
- do {
- if (current instanceof IPackageFragmentRoot)
- return (IPackageFragmentRoot) current;
- current = current.getParent();
- } while (current != null);
- return null;
+ IBuffer buf = getBuffer();
+ if (buf != null) { // some Openables (like a JavaProject) don't have a buffer
+ buf.save(pm, force);
+ this.makeConsistent(pm); // update the element info of this element
}
+}
+/**
+ * Find enclosing package fragment root if any
+ */
+public PackageFragmentRoot getPackageFragmentRoot() {
+ IJavaElement current = this;
+ do {
+ if (current instanceof PackageFragmentRoot) return (PackageFragmentRoot)current;
+ current = current.getParent();
+ } while(current != null);
+ return null;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/OpenableElementInfo.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/OpenableElementInfo.java
index a95e05c06a..5283c7396a 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/OpenableElementInfo.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/OpenableElementInfo.java
@@ -7,7 +7,7 @@ package org.eclipse.jdt.internal.core;
import org.eclipse.core.resources.*;
/** Element info for IOpenable elements. */
-/* package */
-class OpenableElementInfo extends JavaElementInfo {
+/* package */ class OpenableElementInfo extends JavaElementInfo {
+
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/OverflowingLRUCache.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/OverflowingLRUCache.java
index e4af524a0b..2d49198720 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/OverflowingLRUCache.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/OverflowingLRUCache.java
@@ -54,53 +54,49 @@ public abstract class OverflowingLRUCache extends LRUCache {
* Inital load factor of one half.
*/
protected double fLoadFactor = 0.667;
- /**
- * Creates a OverflowingLRUCache.
- * @param size Size limit of cache.
- */
- public OverflowingLRUCache(int size) {
- this(size, 0);
- }
-
- /**
- * Creates a OverflowingLRUCache.
- * @param size Size limit of cache.
- * @param overflow Size of the overflow.
- */
- public OverflowingLRUCache(int size, int overflow) {
- super(size);
- fOverflow = overflow;
- }
-
+/**
+ * Creates a OverflowingLRUCache.
+ * @param size Size limit of cache.
+ */
+public OverflowingLRUCache(int size) {
+ this(size, 0);
+}
+/**
+ * Creates a OverflowingLRUCache.
+ * @param size Size limit of cache.
+ * @param overflow Size of the overflow.
+ */
+public OverflowingLRUCache(int size, int overflow) {
+ super(size);
+ fOverflow = overflow;
+}
/**
* Returns a new cache containing the same contents.
*
* @return New copy of this object.
*/
public Object clone() {
-
- OverflowingLRUCache newCache =
- (OverflowingLRUCache) newInstance(fSpaceLimit, fOverflow);
+
+ OverflowingLRUCache newCache = (OverflowingLRUCache)newInstance(fSpaceLimit, fOverflow);
LRUCacheEntry qEntry;
-
+
/* Preserve order of entries by copying from oldest to newest */
qEntry = this.fEntryQueueTail;
while (qEntry != null) {
- newCache.privateAdd(qEntry._fKey, qEntry._fValue, qEntry._fSpace);
+ newCache.privateAdd (qEntry._fKey, qEntry._fValue, qEntry._fSpace);
qEntry = qEntry._fPrevious;
}
return newCache;
}
-
- /**
- * Returns true if the element is successfully closed and
- * removed from the cache, otherwise false.
- *
- * <p>NOTE: this triggers an external remove from the cache
- * by closing the obejct.
- *
- */
- protected abstract boolean close(LRUCacheEntry entry);
+/**
+ * Returns true if the element is successfully closed and
+ * removed from the cache, otherwise false.
+ *
+ * <p>NOTE: this triggers an external remove from the cache
+ * by closing the obejct.
+ *
+ */
+protected abstract boolean close(LRUCacheEntry entry);
/**
* Returns an enumerator of the values in the cache with the most
* recently used first.
@@ -108,20 +104,18 @@ public abstract class OverflowingLRUCache extends LRUCache {
public Enumeration elements() {
if (fEntryQueue == null)
return new LRUCacheEnumerator(null);
- LRUCacheEnumerator.LRUEnumeratorElement head =
+ LRUCacheEnumerator.LRUEnumeratorElement head =
new LRUCacheEnumerator.LRUEnumeratorElement(fEntryQueue._fValue);
LRUCacheEntry currentEntry = fEntryQueue._fNext;
LRUCacheEnumerator.LRUEnumeratorElement currentElement = head;
- while (currentEntry != null) {
- currentElement.fNext =
- new LRUCacheEnumerator.LRUEnumeratorElement(currentEntry._fValue);
+ while(currentEntry != null) {
+ currentElement.fNext = new LRUCacheEnumerator.LRUEnumeratorElement(currentEntry._fValue);
currentElement = currentElement.fNext;
-
+
currentEntry = currentEntry._fNext;
}
return new LRUCacheEnumerator(head);
}
-
/**
* This method exposed only for testing purposes!
*
@@ -131,69 +125,65 @@ public abstract class OverflowingLRUCache extends LRUCache {
public java.util.Hashtable getEntryTable() {
return fEntryTable;
}
-
- /**
- * Returns the load factor for the cache. The load factor determines how
- * much space is reclaimed when the cache exceeds its space limit.
- * @return double
- */
- public double getLoadFactor() {
- return fLoadFactor;
- }
-
+/**
+ * Returns the load factor for the cache. The load factor determines how
+ * much space is reclaimed when the cache exceeds its space limit.
+ * @return double
+ */
+public double getLoadFactor() {
+ return fLoadFactor;
+}
/**
* @return The space by which the cache has overflown.
*/
public int getOverflow() {
return fOverflow;
}
-
- /**
- * Ensures there is the specified amount of free space in the receiver,
- * by removing old entries if necessary. Returns true if the requested space was
- * made available, false otherwise. May not be able to free enough space
- * since some elements cannot be removed until they are saved.
- *
- * @param space Amount of space to free up
- */
- protected boolean makeSpace(int space) {
- int limit = fSpaceLimit;
- if (fOverflow == 0) {
- /* if space is already available */
- if (fCurrentSpace + space <= limit) {
- return true;
- }
- }
-
- // System.out.println("Cache Reached Max!");
- // printStats();
-
- /* Free up space by removing oldest entries */
- int spaceNeeded = (int) (fLoadFactor * fSpaceLimit);
- spaceNeeded = (spaceNeeded > space) ? spaceNeeded : space;
- LRUCacheEntry entry = fEntryQueueTail;
- // int i = 0;
- while (fCurrentSpace + spaceNeeded > limit && entry != null) {
- this.privateRemoveEntry(entry, false, false);
- entry = entry._fPrevious;
- // i++;
- }
-
- // System.out.println("Checked " + i + " entries.");
- // System.out.println("Current Space at " + fCurrentSpace);
- // printStats();
-
- /* check again, since we may have aquired enough space */
+/**
+ * Ensures there is the specified amount of free space in the receiver,
+ * by removing old entries if necessary. Returns true if the requested space was
+ * made available, false otherwise. May not be able to free enough space
+ * since some elements cannot be removed until they are saved.
+ *
+ * @param space Amount of space to free up
+ */
+protected boolean makeSpace(int space) {
+ int limit = fSpaceLimit;
+ if (fOverflow == 0) {
+ /* if space is already available */
if (fCurrentSpace + space <= limit) {
- fOverflow = 0;
return true;
}
+ }
+
+// System.out.println("Cache Reached Max!");
+// printStats();
+
+ /* Free up space by removing oldest entries */
+ int spaceNeeded = (int)(fLoadFactor * fSpaceLimit);
+ spaceNeeded = (spaceNeeded > space) ? spaceNeeded : space;
+ LRUCacheEntry entry = fEntryQueueTail;
+// int i = 0;
+ while (fCurrentSpace + spaceNeeded > limit && entry != null) {
+ this.privateRemoveEntry(entry, false, false);
+ entry = entry._fPrevious;
+// i++;
+ }
- /* update fOverflow */
- fOverflow = fCurrentSpace + space - limit;
- return false;
+// System.out.println("Checked " + i + " entries.");
+// System.out.println("Current Space at " + fCurrentSpace);
+// printStats();
+
+ /* check again, since we may have aquired enough space */
+ if (fCurrentSpace + space <= limit) {
+ fOverflow = 0;
+ return true;
}
+ /* update fOverflow */
+ fOverflow = fCurrentSpace + space - limit;
+ return false;
+}
/**
* Returns a new instance of the reciever.
*/
@@ -205,65 +195,63 @@ public abstract class OverflowingLRUCache extends LRUCache {
* This function does not modify timestamps.
*/
public Object peek(Object key) {
-
+
LRUCacheEntry entry = (LRUCacheEntry) fEntryTable.get(key);
if (entry == null) {
return null;
}
return entry._fValue;
}
-
- /**
- * @private For testing purposes only
- */
- public void printStats() {
- int forwardListLength = 0;
- LRUCacheEntry entry = fEntryQueue;
- while (entry != null) {
- forwardListLength++;
- entry = entry._fNext;
- }
- System.out.println("Forward length: " + forwardListLength);
-
- int backwardListLength = 0;
- entry = fEntryQueueTail;
- while (entry != null) {
- backwardListLength++;
- entry = entry._fPrevious;
- }
- System.out.println("Backward length: " + backwardListLength);
-
- Enumeration keys = fEntryTable.keys();
- java.util.Vector v = new java.util.Vector();
- class Temp {
- public Class fClass;
- public int fCount;
- public Temp(Class aClass) {
- fClass = aClass;
- fCount = 1;
- }
- public String toString() {
- return "Class: " + fClass + " has " + fCount + " entries.";
- }
+/**
+ * @private For testing purposes only
+ */
+public void printStats() {
+ int forwardListLength = 0;
+ LRUCacheEntry entry = fEntryQueue;
+ while(entry != null) {
+ forwardListLength++;
+ entry = entry._fNext;
+ }
+ System.out.println("Forward length: "/*nonNLS*/ + forwardListLength);
+
+ int backwardListLength = 0;
+ entry = fEntryQueueTail;
+ while(entry != null) {
+ backwardListLength++;
+ entry = entry._fPrevious;
+ }
+ System.out.println("Backward length: "/*nonNLS*/ + backwardListLength);
+
+ Enumeration keys = fEntryTable.keys();
+ java.util.Vector v = new java.util.Vector();
+ class Temp {
+ public Class fClass;
+ public int fCount;
+ public Temp(Class aClass) {
+ fClass = aClass;
+ fCount = 1;
}
- java.util.Hashtable h = new java.util.Hashtable();
- while (keys.hasMoreElements()) {
- entry = (LRUCacheEntry) fEntryTable.get(keys.nextElement());
- Class key = entry._fValue.getClass();
- Temp t = (Temp) h.get(key);
- if (t == null) {
- h.put(key, new Temp(key));
- } else {
- t.fCount++;
- }
+ public String toString() {
+ return "Class: "/*nonNLS*/ + fClass + " has "/*nonNLS*/ + fCount + " entries."/*nonNLS*/;
}
-
- keys = h.keys();
- while (keys.hasMoreElements()) {
- System.out.println(h.get(keys.nextElement()));
+ }
+ java.util.Hashtable h = new java.util.Hashtable();
+ while(keys.hasMoreElements()) {
+ entry = (LRUCacheEntry)fEntryTable.get(keys.nextElement());
+ Class key = entry._fValue.getClass();
+ Temp t = (Temp)h.get(key);
+ if (t == null) {
+ h.put(key, new Temp(key));
+ } else {
+ t.fCount++;
}
}
+ keys = h.keys();
+ while(keys.hasMoreElements()) {
+ System.out.println(h.get(keys.nextElement()));
+ }
+}
/**
* Removes the entry from the entry queue.
* Calls <code>privateRemoveEntry</code> with the external functionality enabled.
@@ -271,55 +259,50 @@ public abstract class OverflowingLRUCache extends LRUCache {
* @param shuffle indicates whether we are just shuffling the queue
* (i.e., the entry table is left alone).
*/
- protected void privateRemoveEntry(LRUCacheEntry entry, boolean shuffle) {
+ protected void privateRemoveEntry (LRUCacheEntry entry, boolean shuffle) {
privateRemoveEntry(entry, shuffle, true);
}
-
- /**
- * Removes the entry from the entry queue. If <i>external</i> is true, the entry is removed
- * without checking if it can be removed. It is assumed that the client has already closed
- * the element it is trying to remove (or will close it promptly).
- *
- * If <i>external</i> is false, and the entry is not closed, it is not removed and the
- * pointers are not changed.
- *
- * @param shuffle indicates whether we are just shuffling the queue
- * (i.e., the entry table is left alone).
- */
- protected void privateRemoveEntry(
- LRUCacheEntry entry,
- boolean shuffle,
- boolean external) {
- if (!shuffle) {
- if (external) {
- fEntryTable.remove(entry._fKey);
- fCurrentSpace -= entry._fSpace;
- privateNotifyDeletionFromCache(entry);
- } else {
- if (!close(entry)) {
- return;
- }
- }
- }
-
- LRUCacheEntry previous = entry._fPrevious;
- LRUCacheEntry next = entry._fNext;
-
- /* if this was the first entry */
- if (previous == null) {
- fEntryQueue = next;
+/**
+ * Removes the entry from the entry queue. If <i>external</i> is true, the entry is removed
+ * without checking if it can be removed. It is assumed that the client has already closed
+ * the element it is trying to remove (or will close it promptly).
+ *
+ * If <i>external</i> is false, and the entry is not closed, it is not removed and the
+ * pointers are not changed.
+ *
+ * @param shuffle indicates whether we are just shuffling the queue
+ * (i.e., the entry table is left alone).
+ */
+protected void privateRemoveEntry(LRUCacheEntry entry, boolean shuffle, boolean external) {
+ if (!shuffle) {
+ if (external) {
+ fEntryTable.remove(entry._fKey);
+ fCurrentSpace -= entry._fSpace;
+ privateNotifyDeletionFromCache(entry);
} else {
- previous._fNext = next;
+ if (!close(entry)) {
+ return;
+ }
}
+ }
- /* if this was the last entry */
- if (next == null) {
- fEntryQueueTail = previous;
- } else {
- next._fPrevious = previous;
- }
+ LRUCacheEntry previous = entry._fPrevious;
+ LRUCacheEntry next = entry._fNext;
+
+ /* if this was the first entry */
+ if (previous == null) {
+ fEntryQueue = next;
+ } else {
+ previous._fNext = next;
}
+ /* if this was the last entry */
+ if (next == null) {
+ fEntryQueueTail = previous;
+ } else {
+ next._fPrevious = previous;
+ }
+}
/**
* Sets the value in the cache at the given key. Returns the value.
*
@@ -331,13 +314,13 @@ public abstract class OverflowingLRUCache extends LRUCache {
/* attempt to rid ourselves of the overflow, if there is any */
if (fOverflow > 0)
shrink();
-
+
/* Check whether there's an entry in the cache */
- int newSpace = spaceFor(key, value);
- LRUCacheEntry entry = (LRUCacheEntry) fEntryTable.get(key);
-
+ int newSpace = spaceFor (key, value);
+ LRUCacheEntry entry = (LRUCacheEntry) fEntryTable.get (key);
+
if (entry != null) {
-
+
/**
* Replace the entry in the cache if it would not overflow
* the cache. Otherwise flush the entry and re-add it so as
@@ -346,27 +329,26 @@ public abstract class OverflowingLRUCache extends LRUCache {
int oldSpace = entry._fSpace;
int newTotal = fCurrentSpace - oldSpace + newSpace;
if (newTotal <= fSpaceLimit) {
- updateTimestamp(entry);
+ updateTimestamp (entry);
entry._fValue = value;
entry._fSpace = newSpace;
fCurrentSpace = newTotal;
fOverflow = 0;
return value;
} else {
- privateRemoveEntry(entry, false, false);
+ privateRemoveEntry (entry, false, false);
}
}
-
+
// attempt to make new space
makeSpace(newSpace);
-
+
// add without worring about space, it will
// be handled later in a makeSpace call
- privateAdd(key, value, newSpace);
-
+ privateAdd (key, value, newSpace);
+
return value;
}
-
/**
* Removes and returns the value in the cache for the given key.
* If the key is not in the cache, returns null.
@@ -377,21 +359,18 @@ public abstract class OverflowingLRUCache extends LRUCache {
public Object remove(Object key) {
return removeKey(key);
}
-
- /**
- * Sets the load factor for the cache. The load factor determines how
- * much space is reclaimed when the cache exceeds its space limit.
- * @param newLoadFactor double
- * @throws IllegalArgumentException when the new load factor is not in (0.0, 1.0]
- */
- public void setLoadFactor(double newLoadFactor)
- throws IllegalArgumentException {
- if (newLoadFactor <= 1.0 && newLoadFactor > 0.0)
- fLoadFactor = newLoadFactor;
- else
- throw new IllegalArgumentException("incorrect load factor");
- }
-
+/**
+ * Sets the load factor for the cache. The load factor determines how
+ * much space is reclaimed when the cache exceeds its space limit.
+ * @param newLoadFactor double
+ * @throws IllegalArgumentException when the new load factor is not in (0.0, 1.0]
+ */
+public void setLoadFactor(double newLoadFactor) throws IllegalArgumentException {
+ if(newLoadFactor <= 1.0 && newLoadFactor > 0.0)
+ fLoadFactor = newLoadFactor;
+ else
+ throw new IllegalArgumentException(Util.bind("cache.invalidLoadFactor"/*nonNLS*/));
+}
/**
* Sets the maximum amount of space that the cache can store
*
@@ -403,7 +382,6 @@ public abstract class OverflowingLRUCache extends LRUCache {
}
fSpaceLimit = limit;
}
-
/**
* Attempts to shrink the cache if it has overflown.
* Returns true if the cache shrinks to less than or equal to <code>fSpaceLimit</code>.
@@ -413,32 +391,28 @@ public abstract class OverflowingLRUCache extends LRUCache {
return makeSpace(0);
return true;
}
-
- /**
- * Returns a String that represents the value of this object. This method
- * is for debugging purposes only.
- */
- public String toString() {
- return "OverflowingLRUCache "
- + ((fCurrentSpace + fOverflow) * 100.0 / fSpaceLimit)
- + "% full\n"
- + this.toStringContents();
- }
-
- /**
- * Updates the timestamp for the given entry, ensuring that the queue is
- * kept in correct order. The entry must exist.
- *
- * <p>This method will do nothing if timestamps have been disabled.
- */
- protected void updateTimestamp(LRUCacheEntry entry) {
- if (fTimestampsOn) {
- entry._fTimestamp = fTimestampCounter++;
- if (fEntryQueue != entry) {
- this.privateRemoveEntry(entry, true);
- this.privateAddEntry(entry, true);
- }
+/**
+ * Returns a String that represents the value of this object. This method
+ * is for debugging purposes only.
+ */
+public String toString() {
+ return
+ "OverflowingLRUCache "/*nonNLS*/ + ((fCurrentSpace + fOverflow) * 100.0 / fSpaceLimit) + "% full\n"/*nonNLS*/ +
+ this.toStringContents();
+}
+/**
+ * Updates the timestamp for the given entry, ensuring that the queue is
+ * kept in correct order. The entry must exist.
+ *
+ * <p>This method will do nothing if timestamps have been disabled.
+ */
+protected void updateTimestamp(LRUCacheEntry entry) {
+ if (fTimestampsOn) {
+ entry._fTimestamp = fTimestampCounter++;
+ if (fEntryQueue != entry) {
+ this.privateRemoveEntry(entry, true);
+ this.privateAddEntry(entry, true);
}
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageDeclaration.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageDeclaration.java
index 338f330f7c..c774187aab 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageDeclaration.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageDeclaration.java
@@ -13,38 +13,30 @@ import org.eclipse.jdt.core.jdom.IDOMNode;
* @see IPackageDeclaration
*/
-/* package */
-class PackageDeclaration
- extends SourceRefElement
- implements IPackageDeclaration {
- protected PackageDeclaration(ICompilationUnit parent, String name) {
- super(PACKAGE_DECLARATION, parent, name);
- }
-
- /**
- * @see JavaElement#equalsDOMNode
- */
- protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
- return (node.getNodeType() == IDOMNode.PACKAGE)
- && getElementName().equals(node.getName());
- }
-
- /**
- * @see JavaElement#getHandleMemento()
- */
- protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_PACKAGEDECLARATION;
- }
-
- /**
- * @private Debugging purposes
- */
- protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
- buffer.append("package ");
- buffer.append(getElementName());
- if (info == null) {
- buffer.append(" (not open)");
- }
+/* package */ class PackageDeclaration extends SourceRefElement implements IPackageDeclaration {
+protected PackageDeclaration(ICompilationUnit parent, String name) {
+ super(PACKAGE_DECLARATION, parent, name);
+}
+/**
+ * @see JavaElement#equalsDOMNode
+ */
+protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
+ return (node.getNodeType() == IDOMNode.PACKAGE) && getElementName().equals(node.getName());
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+protected char getHandleMementoDelimiter() {
+ return JavaElement.JEM_PACKAGEDECLARATION;
+}
+/**
+ * @private Debugging purposes
+ */
+protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
+ buffer.append("package "/*nonNLS*/);
+ buffer.append(getElementName());
+ if (info == null) {
+ buffer.append(" (not open)"/*nonNLS*/);
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragment.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragment.java
index 4b58ce7b39..9ab3bb1c45 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragment.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragment.java
@@ -19,353 +19,297 @@ public class PackageFragment extends Openable implements IPackageFragment {
/**
* Constant empty list of class files
*/
- protected static IClassFile[] fgEmptyClassFileList = new IClassFile[] {
- };
-
+ protected static IClassFile[] fgEmptyClassFileList= new IClassFile[] {};
/**
* Constant empty list of compilation units
*/
- protected static ICompilationUnit[] fgEmptyCompilationUnitList =
- new ICompilationUnit[] {
- };
-
- /**
- * Constructs a handle for a package fragment
- *
- * @see IPackageFragment
- */
- protected PackageFragment(IPackageFragmentRoot root, String name) {
- super(PACKAGE_FRAGMENT, root, name);
+ protected static ICompilationUnit[] fgEmptyCompilationUnitList= new ICompilationUnit[] {};
+/**
+ * Constructs a handle for a package fragment
+ *
+ * @see IPackageFragment
+ */
+protected PackageFragment(IPackageFragmentRoot root, String name) {
+ super(PACKAGE_FRAGMENT, root, name);
+}
+/**
+ * Compute the children of this package fragment.
+ *
+ * <p>Package fragments which are folders recognize files based on the
+ * type of the fragment
+ * <p>Package fragments which are in a jar only recognize .class files (
+ * @see JarPackageFragment).
+ */
+protected boolean computeChildren(OpenableElementInfo info, IResource resource) throws JavaModelException {
+ Vector vChildren = new Vector();
+ int kind = getKind();
+ String extType;
+ if (kind == IPackageFragmentRoot.K_SOURCE) {
+ extType = "java"/*nonNLS*/;
+ } else {
+ extType = "class"/*nonNLS*/;
}
-
- /**
- * Compute the children of this package fragment.
- *
- * <p>Package fragments which are folders recognize files based on the
- * type of the fragment
- * <p>Package fragments which are in a jar only recognize .class files (
- * @see JarPackageFragment).
- */
- protected boolean computeChildren(OpenableElementInfo info, IResource resource)
- throws JavaModelException {
- Vector vChildren = new Vector();
- int kind = getKind();
- String extType;
- if (kind == IPackageFragmentRoot.K_SOURCE) {
- extType = "java";
- } else {
- extType = "class";
- }
- try {
- IResource[] members = ((IContainer) resource).members();
- for (int i = 0, max = members.length; i < max; i++) {
- IResource child = members[i];
- if (child.getType() != IResource.FOLDER) {
- String extension = child.getProjectRelativePath().getFileExtension();
- if (extension != null) {
- if (extension.equalsIgnoreCase(extType)) {
- IJavaElement childElement;
- if (kind == IPackageFragmentRoot.K_SOURCE) {
- childElement = getCompilationUnit(child.getName());
- } else {
- childElement = getClassFile(child.getName());
- }
- vChildren.addElement(childElement);
+ try {
+ IResource[] members = ((IContainer) resource).members();
+ for (int i = 0, max = members.length; i < max; i++) {
+ IResource child = members[i];
+ if (child.getType() != IResource.FOLDER) {
+ String extension = child.getProjectRelativePath().getFileExtension();
+ if (extension != null) {
+ if (extension.equalsIgnoreCase(extType)) {
+ IJavaElement childElement;
+ if (kind == IPackageFragmentRoot.K_SOURCE) {
+ childElement = getCompilationUnit(child.getName());
+ } else {
+ childElement = getClassFile(child.getName());
}
+ vChildren.addElement(childElement);
}
}
}
- } catch (CoreException e) {
- throw new JavaModelException(e);
- }
- vChildren.trimToSize();
- IJavaElement[] children = new IJavaElement[vChildren.size()];
- vChildren.copyInto(children);
- info.setChildren(children);
- return true;
- }
-
- /**
- * Returns true if this fragment contains at least one java resource.
- * Returns false otherwise.
- */
- public boolean containsJavaResources() throws JavaModelException {
- return ((PackageFragmentInfo) getElementInfo()).containsJavaResources();
- }
-
- /**
- * @see ISourceManipulation
- */
- public void copy(
- IJavaElement container,
- IJavaElement sibling,
- String rename,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- if (container == null) {
- throw new IllegalArgumentException("container cannot be null");
- }
- IJavaElement[] elements = new IJavaElement[] { this };
- IJavaElement[] containers = new IJavaElement[] { container };
- IJavaElement[] siblings = null;
- if (sibling != null) {
- siblings = new IJavaElement[] { sibling };
- }
- String[] renamings = null;
- if (rename != null) {
- renamings = new String[] { rename };
}
- getJavaModel().copy(elements, containers, siblings, renamings, force, monitor);
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
-
- /**
- * @see IPackageFragment
- */
- public ICompilationUnit createCompilationUnit(
- String name,
- String contents,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- CreateCompilationUnitOperation op =
- new CreateCompilationUnitOperation(this, name, contents, force);
- runOperation(op, monitor);
- return getCompilationUnit(name);
+ vChildren.trimToSize();
+ IJavaElement[] children = new IJavaElement[vChildren.size()];
+ vChildren.copyInto(children);
+ info.setChildren(children);
+ return true;
+}
+/**
+ * Returns true if this fragment contains at least one java resource.
+ * Returns false otherwise.
+ */
+public boolean containsJavaResources() throws JavaModelException {
+ return ((PackageFragmentInfo) getElementInfo()).containsJavaResources();
+}
+/**
+ * @see ISourceManipulation
+ */
+public void copy(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ if (container == null) {
+ throw new IllegalArgumentException(Util.bind("operation.nullContainer"/*nonNLS*/));
}
-
- /**
- * @see JavaElement
- */
- protected OpenableElementInfo createElementInfo() {
- return new PackageFragmentInfo();
+ IJavaElement[] elements= new IJavaElement[] {this};
+ IJavaElement[] containers= new IJavaElement[] {container};
+ IJavaElement[] siblings= null;
+ if (sibling != null) {
+ siblings= new IJavaElement[] {sibling};
}
-
- /**
- * @see ISourceManipulation
- */
- public void delete(boolean force, IProgressMonitor monitor)
- throws JavaModelException {
- IJavaElement[] elements = new IJavaElement[] { this };
- getJavaModel().delete(elements, force, monitor);
+ String[] renamings= null;
+ if (rename != null) {
+ renamings= new String[] {rename};
}
-
- /**
- * @see Openable
- */
- protected boolean generateInfos(
- OpenableElementInfo info,
- IProgressMonitor pm,
- Hashtable newElements,
- IResource underlyingResource)
- throws JavaModelException {
- return computeChildren(info, underlyingResource);
+ getJavaModel().copy(elements, containers, siblings, renamings, force, monitor);
+}
+/**
+ * @see IPackageFragment
+ */
+public ICompilationUnit createCompilationUnit(String name, String contents, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ CreateCompilationUnitOperation op= new CreateCompilationUnitOperation(this, name, contents, force);
+ runOperation(op, monitor);
+ return getCompilationUnit(name);
+}
+/**
+ * @see JavaElement
+ */
+protected OpenableElementInfo createElementInfo() {
+ return new PackageFragmentInfo();
+}
+/**
+ * @see ISourceManipulation
+ */
+public void delete(boolean force, IProgressMonitor monitor) throws JavaModelException {
+ IJavaElement[] elements = new IJavaElement[] {this};
+ getJavaModel().delete(elements, force, monitor);
+}
+/**
+ * @see Openable
+ */
+protected boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Hashtable newElements, IResource underlyingResource) throws JavaModelException {
+ return computeChildren(info, underlyingResource);
+}
+/**
+ * @see IPackageFragment
+ */
+public IClassFile getClassFile(String name) {
+ return new ClassFile(this, name);
+}
+/**
+ * Returns a the collection of class files in this - a folder package fragment which has a root
+ * that has its kind set to <code>IPackageFragmentRoot.K_Source</code> does not
+ * recognize class files.
+ *
+ * @see IPackageFragment
+ * @see JarPackageFragment
+ */
+public IClassFile[] getClassFiles() throws JavaModelException {
+ if (getKind() == IPackageFragmentRoot.K_SOURCE) {
+ return fgEmptyClassFileList;
}
-
- /**
- * @see IPackageFragment
- */
- public IClassFile getClassFile(String name) {
- return new ClassFile(this, name);
+
+ Vector v= getChildrenOfType(CLASS_FILE);
+ IClassFile[] array= new IClassFile[v.size()];
+ v.copyInto(array);
+ return array;
+}
+/**
+ * @see IPackageFragment
+ */
+public ICompilationUnit getCompilationUnit(String name) {
+ return new CompilationUnit(this, name);
+}
+/**
+ * @see IPackageFragment
+ */
+public ICompilationUnit[] getCompilationUnits() throws JavaModelException {
+ if (getKind() == IPackageFragmentRoot.K_BINARY) {
+ return fgEmptyCompilationUnitList;
}
-
- /**
- * Returns a the collection of class files in this - a folder package fragment which has a root
- * that has its kind set to <code>IPackageFragmentRoot.K_Source</code> does not
- * recognize class files.
- *
- * @see IPackageFragment
- * @see JarPackageFragment
- */
- public IClassFile[] getClassFiles() throws JavaModelException {
- if (getKind() == IPackageFragmentRoot.K_SOURCE) {
- return fgEmptyClassFileList;
- }
-
- Vector v = getChildrenOfType(CLASS_FILE);
- IClassFile[] array = new IClassFile[v.size()];
- v.copyInto(array);
- return array;
+
+ Vector v= getChildrenOfType(COMPILATION_UNIT);
+ ICompilationUnit[] array= new ICompilationUnit[v.size()];
+ v.copyInto(array);
+ return array;
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+protected char getHandleMementoDelimiter() {
+ return JavaElement.JEM_PACKAGEFRAGMENT;
+}
+/**
+ * @see IPackageFragment
+ */
+public int getKind() throws JavaModelException {
+ return ((IPackageFragmentRoot)getParent()).getKind();
+}
+/**
+ * Returns an array of non-java resources contained in the receiver.
+ */
+public Object[] getNonJavaResources() throws JavaModelException {
+ if (this.isDefaultPackage()) {
+ // We don't want to show non java resources of the default package (see PR #1G58NB8)
+ return JavaElementInfo.NO_NON_JAVA_RESOURCES;
+ } else {
+ return ((PackageFragmentInfo) getElementInfo()).getNonJavaResources(getUnderlyingResource());
}
-
- /**
- * @see IPackageFragment
- */
- public ICompilationUnit getCompilationUnit(String name) {
- return new CompilationUnit(this, name);
+}
+/**
+ * @see IJavaElement
+ */
+public IResource getUnderlyingResource() throws JavaModelException {
+ IResource rootResource = fParent.getUnderlyingResource();
+ if (rootResource == null) {
+ //jar package fragment root that has no associated resource
+ return null;
}
-
- /**
- * @see IPackageFragment
- */
- public ICompilationUnit[] getCompilationUnits() throws JavaModelException {
- if (getKind() == IPackageFragmentRoot.K_BINARY) {
- return fgEmptyCompilationUnitList;
+ // the underlying resource may be a folder or a project (in the case that the project folder
+ // is atually the package fragment root)
+ if (rootResource.getType() == IResource.FOLDER || rootResource.getType() == IResource.PROJECT) {
+ IContainer folder = (IContainer) rootResource;
+ String[] segs = Signature.getSimpleNames(fName);
+ for (int i = 0; i < segs.length; ++i) {
+ IResource child = folder.findMember(segs[i]);
+ if (child == null || child.getType() != IResource.FOLDER) {
+ throw newNotPresentException();
+ }
+ folder = (IFolder) child;
}
-
- Vector v = getChildrenOfType(COMPILATION_UNIT);
- ICompilationUnit[] array = new ICompilationUnit[v.size()];
- v.copyInto(array);
- return array;
- }
-
- /**
- * @see JavaElement#getHandleMemento()
- */
- protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_PACKAGEFRAGMENT;
+ return folder;
+ } else {
+ return rootResource;
}
-
- /**
- * @see IPackageFragment
- */
- public int getKind() throws JavaModelException {
- return ((IPackageFragmentRoot) getParent()).getKind();
- }
-
- /**
- * Returns an array of non-java resources contained in the receiver.
- */
- public Object[] getNonJavaResources() throws JavaModelException {
- if (this.isDefaultPackage()) {
- // We don't want to show non java resources of the default package (see PR #1G58NB8)
- return JavaElementInfo.NO_NON_JAVA_RESOURCES;
- } else {
- return ((PackageFragmentInfo) getElementInfo()).getNonJavaResources(
- getUnderlyingResource());
+}
+/**
+ * @see IPackageFragment
+ */
+public boolean hasSubpackages() throws JavaModelException {
+ IJavaElement[] packages= ((IPackageFragmentRoot)getParent()).getChildren();
+ String name = getElementName();
+ int nameLength = name.length();
+ String packageName = isDefaultPackage() ? name : name+"."/*nonNLS*/;
+ for (int i= 0; i < packages.length; i++) {
+ String otherName = packages[i].getElementName();
+ if (otherName.length() > nameLength && otherName.startsWith(packageName)) {
+ return true;
}
}
-
- /**
- * @see IJavaElement
- */
- public IResource getUnderlyingResource() throws JavaModelException {
- IResource rootResource = fParent.getUnderlyingResource();
- if (rootResource == null) {
- //jar package fragment root that has no associated resource
- return null;
- }
- // the underlying resource may be a folder or a project (in the case that the project folder
- // is atually the package fragment root)
- if (rootResource.getType() == IResource.FOLDER
- || rootResource.getType() == IResource.PROJECT) {
- IContainer folder = (IContainer) rootResource;
- String[] segs = Signature.getSimpleNames(fName);
- for (int i = 0; i < segs.length; ++i) {
- IResource child = folder.findMember(segs[i]);
- if (child == null || child.getType() != IResource.FOLDER) {
- throw newNotPresentException();
- }
- folder = (IFolder) child;
- }
- return folder;
- } else {
- return rootResource;
- }
+ return false;
+}
+/**
+ * @see IPackageFragment
+ */
+public boolean isDefaultPackage() {
+ return this.getElementName().length() == 0;
+}
+/**
+ * @see ISourceManipulation
+ */
+public void move(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ if (container == null) {
+ throw new IllegalArgumentException(Util.bind("operation.nullContainer"/*nonNLS*/));
}
-
- /**
- * @see IPackageFragment
- */
- public boolean hasSubpackages() throws JavaModelException {
- IJavaElement[] packages = ((IPackageFragmentRoot) getParent()).getChildren();
- String name = getElementName();
- int nameLength = name.length();
- String packageName = isDefaultPackage() ? name : name + ".";
- for (int i = 0; i < packages.length; i++) {
- String otherName = packages[i].getElementName();
- if (otherName.length() > nameLength && otherName.startsWith(packageName)) {
- return true;
- }
- }
- return false;
+ IJavaElement[] elements= new IJavaElement[] {this};
+ IJavaElement[] containers= new IJavaElement[] {container};
+ IJavaElement[] siblings= null;
+ if (sibling != null) {
+ siblings= new IJavaElement[] {sibling};
}
-
- /**
- * @see IPackageFragment
- */
- public boolean isDefaultPackage() {
- return this.getElementName().length() == 0;
+ String[] renamings= null;
+ if (rename != null) {
+ renamings= new String[] {rename};
}
-
- /**
- * @see ISourceManipulation
- */
- public void move(
- IJavaElement container,
- IJavaElement sibling,
- String rename,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- if (container == null) {
- throw new IllegalArgumentException("conatiner cannot be null");
- }
- IJavaElement[] elements = new IJavaElement[] { this };
- IJavaElement[] containers = new IJavaElement[] { container };
- IJavaElement[] siblings = null;
- if (sibling != null) {
- siblings = new IJavaElement[] { sibling };
- }
- String[] renamings = null;
- if (rename != null) {
- renamings = new String[] { rename };
- }
- getJavaModel().move(elements, containers, siblings, renamings, force, monitor);
+ getJavaModel().move(elements, containers, siblings, renamings, force, monitor);
+}
+/**
+ * Recomputes the children of this element, based on the current state
+ * of the workbench.
+ */
+public void refreshChildren() {
+ try {
+ OpenableElementInfo info= (OpenableElementInfo)getElementInfo();
+ computeChildren(info, getUnderlyingResource());
+ } catch (JavaModelException e) {
+ // do nothing.
}
-
- /**
- * Recomputes the children of this element, based on the current state
- * of the workbench.
- */
- public void refreshChildren() {
- try {
- OpenableElementInfo info = (OpenableElementInfo) getElementInfo();
- computeChildren(info, getUnderlyingResource());
- } catch (JavaModelException e) {
- // do nothing.
- }
+}
+/**
+ * @see ISourceManipulation
+ */
+public void rename(String name, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ if (name == null) {
+ throw new IllegalArgumentException(Util.bind("element.nullName"/*nonNLS*/));
}
-
- /**
- * @see ISourceManipulation
- */
- public void rename(String name, boolean force, IProgressMonitor monitor)
- throws JavaModelException {
- if (name == null) {
- throw new IllegalArgumentException("name cannot be null");
- }
- IJavaElement[] elements = new IJavaElement[] { this };
- IJavaElement[] dests = new IJavaElement[] { this.getParent()};
- String[] renamings = new String[] { name };
- getJavaModel().rename(elements, dests, renamings, force, monitor);
+ IJavaElement[] elements= new IJavaElement[] {this};
+ IJavaElement[] dests= new IJavaElement[] {this.getParent()};
+ String[] renamings= new String[] {name};
+ getJavaModel().rename(elements, dests, renamings, force, monitor);
+}
+/**
+ * @private Debugging purposes
+ */
+protected void toStringChildren(int tab, StringBuffer buffer, Object info) {
+ if (tab == 0) {
+ super.toStringChildren(tab, buffer, info);
}
-
- /**
- * @private Debugging purposes
- */
- protected void toStringChildren(int tab, StringBuffer buffer, Object info) {
- if (tab == 0) {
- super.toStringChildren(tab, buffer, info);
- }
+}
+/**
+ * @private Debugging purposes
+ */
+protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
+ if (getElementName().length() == 0) {
+ buffer.append("[default]"/*nonNLS*/);
+ } else {
+ buffer.append(getElementName());
}
-
- /**
- * @private Debugging purposes
- */
- protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
- if (getElementName().length() == 0) {
- buffer.append("[default]");
- } else {
- buffer.append(getElementName());
- }
- if (info == null) {
- buffer.append(" (not open)");
- } else {
- if (tab > 0) {
- buffer.append(" (...)");
- }
+ if (info == null) {
+ buffer.append(" (not open)"/*nonNLS*/);
+ } else {
+ if (tab > 0) {
+ buffer.append(" (...)"/*nonNLS*/);
}
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragmentInfo.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragmentInfo.java
index 22e1ea7e65..6dc504d686 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragmentInfo.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragmentInfo.java
@@ -20,87 +20,76 @@ class PackageFragmentInfo extends OpenableElementInfo {
*/
protected Object[] fNonJavaResources;
- /**
- * Create and initialize a new instance of the receiver
- */
- public PackageFragmentInfo() {
- fNonJavaResources = null;
- }
-
- /**
- * Compute the non-java resources of this package fragment.
- *
- * <p>Package fragments which are folders recognize files based on the
- * type of the fragment
- * <p>Package fragments which are in a jar only recognize .class files (
- * @see JarPackageFragment).
- */
- private Object[] computeNonJavaResources(IResource resource) {
- Object[] nonJavaResources = new IResource[5];
- int nonJavaResourcesCounter = 0;
- try {
- IResource[] members = ((IContainer) resource).members();
- for (int i = 0, max = members.length; i < max; i++) {
- IResource child = members[i];
- if (child.getType() != IResource.FOLDER) {
- String extension = child.getProjectRelativePath().getFileExtension();
- if (!"java".equalsIgnoreCase(extension)
- && !"class".equalsIgnoreCase(extension)) {
- if (nonJavaResources.length == nonJavaResourcesCounter) {
- // resize
- System.arraycopy(
- nonJavaResources,
- 0,
- (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]),
- 0,
- nonJavaResourcesCounter);
- }
- nonJavaResources[nonJavaResourcesCounter++] = child;
+/**
+ * Create and initialize a new instance of the receiver
+ */
+public PackageFragmentInfo() {
+ fNonJavaResources = null;
+}
+/**
+ * Compute the non-java resources of this package fragment.
+ *
+ * <p>Package fragments which are folders recognize files based on the
+ * type of the fragment
+ * <p>Package fragments which are in a jar only recognize .class files (
+ * @see JarPackageFragment).
+ */
+private Object[] computeNonJavaResources(IResource resource) {
+ Object[] nonJavaResources = new IResource[5];
+ int nonJavaResourcesCounter = 0;
+ try{
+ IResource[] members = ((IContainer) resource).members();
+ for (int i = 0, max = members.length; i < max; i++) {
+ IResource child = members[i];
+ if (child.getType() != IResource.FOLDER) {
+ String extension = child.getProjectRelativePath().getFileExtension();
+ if (!"java"/*nonNLS*/.equalsIgnoreCase(extension) && !"class"/*nonNLS*/.equalsIgnoreCase(extension)) {
+ if (nonJavaResources.length == nonJavaResourcesCounter) {
+ // resize
+ System.arraycopy(
+ nonJavaResources,
+ 0,
+ (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]),
+ 0,
+ nonJavaResourcesCounter);
}
+ nonJavaResources[nonJavaResourcesCounter++] = child;
}
}
- if (nonJavaResourcesCounter == 0) {
- nonJavaResources = NO_NON_JAVA_RESOURCES;
- } else {
- if (nonJavaResources.length != nonJavaResourcesCounter) {
- System.arraycopy(
- nonJavaResources,
- 0,
- (nonJavaResources = new IResource[nonJavaResourcesCounter]),
- 0,
- nonJavaResourcesCounter);
- }
- }
- } catch (CoreException e) {
- nonJavaResources = NO_NON_JAVA_RESOURCES;
- nonJavaResourcesCounter = 0;
}
- return nonJavaResources;
- }
-
- /**
- */
- boolean containsJavaResources() {
- return fChildren.length != 0;
- }
-
- /**
- * Returns an array of non-java resources contained in the receiver.
- */
- Object[] getNonJavaResources(IResource underlyingResource) {
- Object[] nonJavaResources = fNonJavaResources;
- if (nonJavaResources == null) {
- nonJavaResources = computeNonJavaResources(underlyingResource);
- fNonJavaResources = nonJavaResources;
- }
- return nonJavaResources;
+ if (nonJavaResourcesCounter == 0) {
+ nonJavaResources = NO_NON_JAVA_RESOURCES;
+ } else {
+ if (nonJavaResources.length != nonJavaResourcesCounter) {
+ System.arraycopy(nonJavaResources, 0, (nonJavaResources = new IResource[nonJavaResourcesCounter]), 0, nonJavaResourcesCounter);
+ }
+ }
+ } catch(CoreException e) {
+ nonJavaResources = NO_NON_JAVA_RESOURCES;
+ nonJavaResourcesCounter = 0;
}
-
- /**
- * Set the fNonJavaResources to res value
- */
- synchronized void setNonJavaResources(Object[] resources) {
- fNonJavaResources = resources;
+ return nonJavaResources;
+}
+/**
+ */
+boolean containsJavaResources() {
+ return fChildren.length != 0;
+}
+/**
+ * Returns an array of non-java resources contained in the receiver.
+ */
+Object[] getNonJavaResources(IResource underlyingResource) {
+ Object[] nonJavaResources = fNonJavaResources;
+ if (nonJavaResources == null) {
+ nonJavaResources = computeNonJavaResources(underlyingResource);
+ fNonJavaResources = nonJavaResources;
}
-
+ return nonJavaResources;
+}
+/**
+ * Set the fNonJavaResources to res value
+ */
+synchronized void setNonJavaResources(Object[] resources) {
+ fNonJavaResources = resources;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
index be9bbc77ff..5de8071e79 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragmentRoot.java
@@ -15,355 +15,293 @@ import org.eclipse.core.runtime.CoreException;
/**
* @see IPackageFragmentRoot
*/
-public class PackageFragmentRoot
- extends Openable
- implements IPackageFragmentRoot {
+public class PackageFragmentRoot extends Openable implements IPackageFragmentRoot {
/**
* The resource associated with this root.
* @see IResource
*/
protected IResource fResource;
- /**
- * Constructs a package fragment root which is the root of the java package
- * directory hierarchy.
- */
- protected PackageFragmentRoot(IResource resource, IJavaProject project) {
- this(resource, project, resource.getProjectRelativePath().toString());
- fResource = resource;
- }
-
- /**
- * Constructs a package fragment root which is the root of the java package
- * directory hierarchy.
- */
- protected PackageFragmentRoot(
- IResource resource,
- IJavaProject project,
- String path) {
- super(PACKAGE_FRAGMENT_ROOT, project, path);
- fResource = resource;
- }
-
- /**
- * @see IPackageFragmentRoot
- */
- public void attachSource(
- IPath zipPath,
- IPath rootPath,
- IProgressMonitor monitor)
- throws JavaModelException {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this));
- }
-
- /**
- * Compute the package fragment children of this package fragment root.
- *
- * @exception JavaModelException The resource associated with this package fragment root does not exist
- */
- protected boolean computeChildren(OpenableElementInfo info)
- throws JavaModelException {
- try {
- // the underlying resource may be a folder or a project (in the case that the project folder
- // is actually the package fragment root)
- if (fResource.getType() == IResource.FOLDER
- || fResource.getType() == IResource.PROJECT) {
- Vector vChildren = new Vector(5);
- computeFolderChildren((IContainer) fResource, "", vChildren);
- IJavaElement[] children = new IJavaElement[vChildren.size()];
- vChildren.copyInto(children);
- info.setChildren(children);
- }
- } catch (JavaModelException e) {
- //problem resolving children; structure remains unknown
- info.setChildren(new IJavaElement[] {
- });
- throw e;
+/**
+ * Constructs a package fragment root which is the root of the java package
+ * directory hierarchy.
+ */
+protected PackageFragmentRoot(IResource resource, IJavaProject project) {
+ this(resource, project, resource.getProjectRelativePath().toString());
+ fResource = resource;
+}
+/**
+ * Constructs a package fragment root which is the root of the java package
+ * directory hierarchy.
+ */
+protected PackageFragmentRoot(IResource resource, IJavaProject project, String path) {
+ super(PACKAGE_FRAGMENT_ROOT, project, path);
+ fResource = resource;
+}
+/**
+ * @see IPackageFragmentRoot
+ */
+public void attachSource(IPath zipPath, IPath rootPath, IProgressMonitor monitor) throws JavaModelException {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this));
+}
+/**
+ * Compute the package fragment children of this package fragment root.
+ *
+ * @exception JavaModelException The resource associated with this package fragment root does not exist
+ */
+protected boolean computeChildren(OpenableElementInfo info) throws JavaModelException {
+ try {
+ // the underlying resource may be a folder or a project (in the case that the project folder
+ // is actually the package fragment root)
+ if (fResource.getType() == IResource.FOLDER || fResource.getType() == IResource.PROJECT) {
+ Vector vChildren = new Vector(5);
+ computeFolderChildren((IContainer) fResource, ""/*nonNLS*/, vChildren);
+ IJavaElement[] children = new IJavaElement[vChildren.size()];
+ vChildren.copyInto(children);
+ info.setChildren(children);
}
- return true;
+ } catch (JavaModelException e) {
+ //problem resolving children; structure remains unknown
+ info.setChildren(new IJavaElement[]{});
+ throw e;
}
-
- /**
- * Starting at this folder, create package fragments and add the fragments to the collection
- * of children.
- *
- * @exception JavaModelException The resource associated with this package fragment does not exist
- */
- protected void computeFolderChildren(
- IContainer folder,
- String prefix,
- Vector vChildren)
- throws JavaModelException {
- IPackageFragment pkg = getPackageFragment(prefix);
- vChildren.addElement(pkg);
- try {
- IPath outputLocationPath = getJavaProject().getOutputLocation();
- IResource[] members = folder.members();
- for (int i = 0, max = members.length; i < max; i++) {
- IResource member = members[i];
- if (member.getType() == IResource.FOLDER
- && member.getName().indexOf('.') < 0) {
- String newPrefix;
- if (prefix.length() == 0) {
- newPrefix = member.getName();
- } else {
- newPrefix = prefix + "." + member.getName();
- }
- // eliminate binary output only if nested inside direct subfolders
- if (!member.getFullPath().equals(outputLocationPath)) {
- computeFolderChildren((IFolder) member, newPrefix, vChildren);
- }
+ return true;
+}
+/**
+ * Starting at this folder, create package fragments and add the fragments to the collection
+ * of children.
+ *
+ * @exception JavaModelException The resource associated with this package fragment does not exist
+ */
+protected void computeFolderChildren(IContainer folder, String prefix, Vector vChildren) throws JavaModelException {
+ IPackageFragment pkg = getPackageFragment(prefix);
+ vChildren.addElement(pkg);
+ try {
+ IPath outputLocationPath = getJavaProject().getOutputLocation();
+ IResource[] members = folder.members();
+ for (int i = 0, max = members.length; i < max; i++) {
+ IResource member = members[i];
+ if (member.getType() == IResource.FOLDER && member.getName().indexOf('.') < 0) {
+ String newPrefix;
+ if (prefix.length() == 0) {
+ newPrefix = member.getName();
+ } else {
+ newPrefix = prefix + "."/*nonNLS*/ + member.getName();
+ }
+ // eliminate binary output only if nested inside direct subfolders
+ if (!member.getFullPath().equals(outputLocationPath)) {
+ computeFolderChildren((IFolder) member, newPrefix, vChildren);
}
- }
- } catch (IllegalArgumentException e) {
- throw new JavaModelException(
- e,
- IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST);
- // could be thrown by ElementTree when path is not found
- } catch (CoreException e) {
- throw new JavaModelException(e);
- }
- }
-
- /**
- * Returns a new element info for this element.
- */
- protected OpenableElementInfo createElementInfo() {
- return new PackageFragmentRootInfo();
- }
-
- /**
- * @see IPackageFragmentRoot
- */
- public IPackageFragment createPackageFragment(
- String name,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- CreatePackageFragmentOperation op =
- new CreatePackageFragmentOperation(this, name, force);
- runOperation(op, monitor);
- return getPackageFragment(name);
- }
-
- /**
- * Returns the root's kind - K_SOURCE or K_BINARY, defaults
- * to K_SOURCE if it is not on the classpath.
- *
- * @exception NotPresentException if the project and root do
- * not exist.
- */
- protected int determineKind(IResource underlyingResource)
- throws JavaModelException {
- IClasspathEntry[] entries = getJavaProject().getResolvedClasspath(true);
- for (int i = 0; i < entries.length; i++) {
- IClasspathEntry entry = entries[i];
- if (entry.getPath().equals(underlyingResource.getFullPath())) {
- return entry.getContentKind();
}
}
- return IPackageFragmentRoot.K_SOURCE;
+ } catch(IllegalArgumentException e){
+ throw new JavaModelException(e, IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST); // could be thrown by ElementTree when path is not found
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
-
- /**
- * Compares two objects for equality;
- * for <code>PackageFragmentRoot</code>s, equality is having the
- * same <code>JavaModel</code>, same resources, and occurrence count.
- *
- */
- public boolean equals(Object o) {
- if (this == o)
- return true;
- if (!(o instanceof PackageFragmentRoot))
- return false;
- PackageFragmentRoot other = (PackageFragmentRoot) o;
- return getJavaModel().equals(other.getJavaModel())
- && fResource.equals(other.fResource)
- && fOccurrenceCount == other.fOccurrenceCount;
- }
-
- /**
- * @see IJavaElement
- */
- public boolean exists() {
- if (!this.exists0())
- return false;
-
- // Make the root path a workspace relative path (case of a jar external to its project but internal to the workspace)
- IPath path = this.getPath();
- IJavaProject project = this.getJavaProject();
-
- // Check that the package fragment root is in its parent's classpath
- try {
- IPackageFragmentRoot[] roots = project.getPackageFragmentRoots();
- for (int i = 0, length = roots.length; i < length; i++) {
- if (this.equals(roots[i]))
- return true;
- }
- if (project.getOutputLocation().equals(path)) {
- // special permission granted to project binary output (when building)
- return true;
- }
- return false;
- } catch (JavaModelException e) {
- return false;
+}
+/**
+ * Returns a new element info for this element.
+ */
+protected OpenableElementInfo createElementInfo() {
+ return new PackageFragmentRootInfo();
+}
+/**
+ * @see IPackageFragmentRoot
+ */
+public IPackageFragment createPackageFragment(String name, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ CreatePackageFragmentOperation op = new CreatePackageFragmentOperation(this, name, force);
+ runOperation(op, monitor);
+ return getPackageFragment(name);
+}
+/**
+ * Returns the root's kind - K_SOURCE or K_BINARY, defaults
+ * to K_SOURCE if it is not on the classpath.
+ *
+ * @exception NotPresentException if the project and root do
+ * not exist.
+ */
+protected int determineKind(IResource underlyingResource) throws JavaModelException {
+ IClasspathEntry[] entries= getJavaProject().getResolvedClasspath(true);
+ for (int i= 0; i < entries.length; i++) {
+ IClasspathEntry entry= entries[i];
+ if (entry.getPath().equals(underlyingResource.getFullPath())) {
+ return entry.getContentKind();
}
}
-
- public boolean exists0() {
- return super.exists();
- }
-
- /**
- * @see Openable
- */
- protected boolean generateInfos(
- OpenableElementInfo info,
- IProgressMonitor pm,
- Hashtable newElements,
- IResource underlyingResource)
- throws JavaModelException {
- ((PackageFragmentRootInfo) info).setRootKind(determineKind(underlyingResource));
- return computeChildren(info);
- }
-
- /**
- * @see JavaElement#getHandleMemento()
- */
- protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_PACKAGEFRAGMENTROOT;
- }
-
- /**
- * @see IPackageFragmentRoot
- */
- public int getKind() throws JavaModelException {
- return ((PackageFragmentRootInfo) getElementInfo()).getRootKind();
- }
-
- /**
- * Returns an array of non-java resources contained in the receiver.
- */
- public Object[] getNonJavaResources() throws JavaModelException {
- return ((PackageFragmentRootInfo) getElementInfo()).getNonJavaResources(
- getJavaProject(),
- getUnderlyingResource());
- }
-
- /**
- * @see IPackageFragmentRoot
- */
- public IPackageFragment getPackageFragment(String packageName) {
- return new PackageFragment(this, packageName);
- }
-
- /**
- * Returns the package name for the given folder
- * (which is a decendent of this root).
- */
- protected String getPackageName(IFolder folder) throws JavaModelException {
- IPath myPath = getPath();
- IPath pkgPath = folder.getFullPath();
- int mySegmentCount = myPath.segmentCount();
- int pkgSegmentCount = pkgPath.segmentCount();
- StringBuffer name = new StringBuffer(IPackageFragment.DEFAULT_PACKAGE_NAME);
- for (int i = mySegmentCount; i < pkgSegmentCount; i++) {
- if (i > mySegmentCount) {
- name.append(".");
- }
- name.append(pkgPath.segment(i));
+ return IPackageFragmentRoot.K_SOURCE;
+}
+/**
+ * Compares two objects for equality;
+ * for <code>PackageFragmentRoot</code>s, equality is having the
+ * same <code>JavaModel</code>, same resources, and occurrence count.
+ *
+ */
+public boolean equals(Object o) {
+ if (this == o)
+ return true;
+ if (!(o instanceof PackageFragmentRoot))
+ return false;
+ PackageFragmentRoot other = (PackageFragmentRoot) o;
+ return getJavaModel().equals(other.getJavaModel()) &&
+ fResource.equals(other.fResource) &&
+ fOccurrenceCount == other.fOccurrenceCount;
+}
+/**
+ * @see IJavaElement
+ */
+public boolean exists() {
+ if (!this.exists0()) return false;
+
+ // Make the root path a workspace relative path (case of a jar external to its project but internal to the workspace)
+ IPath path = this.getPath();
+ IJavaProject project = this.getJavaProject();
+
+ // Check that the package fragment root is in its parent's classpath
+ try {
+ IPackageFragmentRoot[] roots = project.getPackageFragmentRoots();
+ for (int i = 0, length = roots.length; i < length; i++) {
+ if (this.equals(roots[i])) return true;
}
- return name.toString();
- }
-
- /**
- * @see IPackageFragmentRoot
- */
- public IPath getPath() {
- return fResource.getFullPath();
- }
-
- /**
- * Cannot attach source to a folder.
- *
- * @see IPackageFragmentRoot
- */
- public IPath getSourceAttachmentPath() throws JavaModelException {
- return null;
- }
-
- /**
- * Cannot attach source to a folder.
- *
- * @see IPackageFragmentRoot
- */
- public IPath getSourceAttachmentRootPath() throws JavaModelException {
- return null;
- }
-
- /**
- * @see IJavaElement
- */
- public IResource getUnderlyingResource() throws JavaModelException {
- if (fResource.exists()) {
- return fResource;
- } else {
- throw newNotPresentException();
+ if (project.getOutputLocation().equals(path)){ // special permission granted to project binary output (when building)
+ return true;
}
-
- }
-
- public int hashCode() {
- return fResource.hashCode();
- }
-
- /**
- * @see IPackageFragmentRoot
- */
- public boolean isArchive() {
return false;
- }
-
- /**
- * @see IPackageFragmentRoot
- */
- public boolean isExternal() {
+ } catch (JavaModelException e) {
return false;
}
-
- /**
- * Recomputes the children of this element, based on the current state
- * of the workbench.
- */
- public void refreshChildren() {
- try {
- OpenableElementInfo info = (OpenableElementInfo) getElementInfo();
- computeChildren(info);
- } catch (JavaModelException e) {
- // do nothing.
+}
+
+public boolean exists0() {
+ return super.exists();
+}
+
+/**
+ * @see Openable
+ */
+protected boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Hashtable newElements, IResource underlyingResource) throws JavaModelException {
+ ((PackageFragmentRootInfo) info).setRootKind(determineKind(underlyingResource));
+ return computeChildren(info);
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+protected char getHandleMementoDelimiter() {
+ return JavaElement.JEM_PACKAGEFRAGMENTROOT;
+}
+/**
+ * @see IPackageFragmentRoot
+ */
+public int getKind() throws JavaModelException {
+ return ((PackageFragmentRootInfo)getElementInfo()).getRootKind();
+}
+/**
+ * Returns an array of non-java resources contained in the receiver.
+ */
+public Object[] getNonJavaResources() throws JavaModelException {
+ return ((PackageFragmentRootInfo) getElementInfo()).getNonJavaResources(getJavaProject(), getUnderlyingResource());
+}
+/**
+ * @see IPackageFragmentRoot
+ */
+public IPackageFragment getPackageFragment(String packageName) {
+ return new PackageFragment(this, packageName);
+}
+/**
+ * Returns the package name for the given folder
+ * (which is a decendent of this root).
+ */
+protected String getPackageName(IFolder folder) throws JavaModelException {
+ IPath myPath= getPath();
+ IPath pkgPath= folder.getFullPath();
+ int mySegmentCount= myPath.segmentCount();
+ int pkgSegmentCount= pkgPath.segmentCount();
+ StringBuffer name = new StringBuffer(IPackageFragment.DEFAULT_PACKAGE_NAME);
+ for (int i= mySegmentCount; i < pkgSegmentCount; i++) {
+ if (i > mySegmentCount) {
+ name.append('.');
}
+ name.append(pkgPath.segment(i));
}
-
+ return name.toString();
+}
+/**
+ * @see IPackageFragmentRoot
+ */
+public IPath getPath() {
+ return fResource.getFullPath();
+}
+/**
+ * Cannot attach source to a folder.
+ *
+ * @see IPackageFragmentRoot
+ */
+public IPath getSourceAttachmentPath() throws JavaModelException {
+ return null;
+}
+/**
+ * Cannot attach source to a folder.
+ *
+ * @see IPackageFragmentRoot
+ */
+public IPath getSourceAttachmentRootPath() throws JavaModelException {
+ return null;
+}
+/**
+ * @see IJavaElement
+ */
+public IResource getUnderlyingResource() throws JavaModelException {
+ if (fResource.exists()) {
+ return fResource;
+ } else {
+ throw newNotPresentException();
+ }
+
+}
+public int hashCode() {
+ return fResource.hashCode();
+}
+/**
+ * @see IPackageFragmentRoot
+ */
+public boolean isArchive() {
+ return false;
+}
+/**
+ * @see IPackageFragmentRoot
+ */
+public boolean isExternal() {
+ return false;
+}
+/**
+ * Recomputes the children of this element, based on the current state
+ * of the workbench.
+ */
+public void refreshChildren() {
+ try {
+ OpenableElementInfo info= (OpenableElementInfo)getElementInfo();
+ computeChildren(info);
+ } catch (JavaModelException e) {
+ // do nothing.
+ }
+}
/**
* Reset the array of non-java resources contained in the receiver to null.
*/
public void resetNonJavaResources() throws JavaModelException {
((PackageFragmentRootInfo) getElementInfo()).setNonJavaResources(null);
}
-
- /**
- * @private Debugging purposes
- */
- protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
- if (getElementName().length() == 0) {
- buffer.append("[project root]");
- } else {
- buffer.append(getElementName());
- }
- if (info == null) {
- buffer.append(" (not open)");
- }
+/**
+ * @private Debugging purposes
+ */
+protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
+ if (getElementName().length() == 0) {
+ buffer.append("[project root]"/*nonNLS*/);
+ } else {
+ buffer.append(getElementName());
}
-
+ if (info == null) {
+ buffer.append(" (not open)"/*nonNLS*/);
+ }
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragmentRootInfo.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragmentRootInfo.java
index 11b815cc28..ff1c197991 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragmentRootInfo.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/PackageFragmentRootInfo.java
@@ -25,123 +25,96 @@ class PackageFragmentRootInfo extends OpenableElementInfo {
* <li><code>IPackageFragmentRoot.K_SOURCE</code>
* <li><code>IPackageFragmentRoot.K_BINARY</code></ul>
*/
- protected int fRootKind = IPackageFragmentRoot.K_SOURCE;
+ protected int fRootKind= IPackageFragmentRoot.K_SOURCE;
/**
* A array with all the non-java resources contained by this PackageFragment
*/
protected Object[] fNonJavaResources;
- /**
- * Create and initialize a new instance of the receiver
- */
- public PackageFragmentRootInfo() {
- fNonJavaResources = null;
- }
-
- /**
- * Starting at this folder, create non-java resources for this package fragment root
- * and add them to the non-java resources collection.
- *
- * @exception JavaModelException The resource associated with this package fragment does not exist
- */
- private Object[] computeFolderNonJavaResources(
- IJavaProject project,
- IContainer folder)
- throws JavaModelException {
- Object[] nonJavaResources = new IResource[5];
- int nonJavaResourcesCounter = 0;
- try {
- IResource[] members = folder.members();
- for (int i = 0, max = members.length; i < max; i++) {
- IResource member = members[i];
- if (member.getType() == IResource.FILE) {
- String extension = member.getProjectRelativePath().getFileExtension();
- if (!"java".equalsIgnoreCase(extension)
- && !"class".equalsIgnoreCase(extension)) {
- if (project.findPackageFragmentRoot(member.getFullPath()) == null) {
- if (nonJavaResources.length == nonJavaResourcesCounter) {
- // resize
- System.arraycopy(
- nonJavaResources,
- 0,
- (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]),
- 0,
- nonJavaResourcesCounter);
- }
- nonJavaResources[nonJavaResourcesCounter++] = member;
+/**
+ * Create and initialize a new instance of the receiver
+ */
+public PackageFragmentRootInfo() {
+ fNonJavaResources = null;
+}
+/**
+ * Starting at this folder, create non-java resources for this package fragment root
+ * and add them to the non-java resources collection.
+ *
+ * @exception JavaModelException The resource associated with this package fragment does not exist
+ */
+private Object[] computeFolderNonJavaResources(IJavaProject project, IContainer folder) throws JavaModelException {
+ Object[] nonJavaResources = new IResource[5];
+ int nonJavaResourcesCounter = 0;
+ try {
+ IResource[] members = folder.members();
+ for (int i = 0, max = members.length; i < max; i++) {
+ IResource member = members[i];
+ if (member.getType() == IResource.FILE) {
+ String extension = member.getProjectRelativePath().getFileExtension();
+ if (!"java"/*nonNLS*/.equalsIgnoreCase(extension) && !"class"/*nonNLS*/.equalsIgnoreCase(extension)) {
+ if (project.findPackageFragmentRoot(member.getFullPath()) == null) {
+ if (nonJavaResources.length == nonJavaResourcesCounter) {
+ // resize
+ System.arraycopy(nonJavaResources, 0, (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]), 0, nonJavaResourcesCounter);
}
+ nonJavaResources[nonJavaResourcesCounter++] = member;
}
}
}
- if (nonJavaResources.length != nonJavaResourcesCounter) {
- System.arraycopy(
- nonJavaResources,
- 0,
- (nonJavaResources = new IResource[nonJavaResourcesCounter]),
- 0,
- nonJavaResourcesCounter);
- }
- return nonJavaResources;
- } catch (CoreException e) {
- throw new JavaModelException(e);
}
- }
-
- /**
- * Compute the non-package resources of this package fragment root.
- *
- * @exception JavaModelException The resource associated with this package fragment root does not exist
- */
- private Object[] computeNonJavaResources(
- IJavaProject project,
- IResource underlyingResource) {
- Object[] nonJavaResources = NO_NON_JAVA_RESOURCES;
- try {
- // the underlying resource may be a folder or a project (in the case that the project folder
- // is actually the package fragment root)
- if (underlyingResource.getType() == IResource.FOLDER
- || underlyingResource.getType() == IResource.PROJECT) {
- nonJavaResources =
- computeFolderNonJavaResources(project, (IContainer) underlyingResource);
- }
- } catch (JavaModelException e) {
+ if (nonJavaResources.length != nonJavaResourcesCounter) {
+ System.arraycopy(nonJavaResources, 0, (nonJavaResources = new IResource[nonJavaResourcesCounter]), 0, nonJavaResourcesCounter);
}
return nonJavaResources;
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
-
- /**
- * Returns an array of non-java resources contained in the receiver.
- */
- synchronized Object[] getNonJavaResources(
- IJavaProject project,
- IResource underlyingResource) {
- Object[] nonJavaResources = fNonJavaResources;
- if (nonJavaResources == null) {
- nonJavaResources = this.computeNonJavaResources(project, underlyingResource);
- fNonJavaResources = nonJavaResources;
+}
+/**
+ * Compute the non-package resources of this package fragment root.
+ *
+ * @exception JavaModelException The resource associated with this package fragment root does not exist
+ */
+private Object[] computeNonJavaResources(IJavaProject project, IResource underlyingResource) {
+ Object[] nonJavaResources = NO_NON_JAVA_RESOURCES;
+ try {
+ // the underlying resource may be a folder or a project (in the case that the project folder
+ // is actually the package fragment root)
+ if (underlyingResource.getType() == IResource.FOLDER || underlyingResource.getType() == IResource.PROJECT) {
+ nonJavaResources = computeFolderNonJavaResources(project, (IContainer) underlyingResource);
}
- return nonJavaResources;
+ } catch (JavaModelException e) {
}
-
- /**
- * Returns the kind of this root.
- */
- public int getRootKind() {
- return fRootKind;
- }
-
- /**
- * Set the fNonJavaResources to res value
- */
- synchronized void setNonJavaResources(Object[] resources) {
- fNonJavaResources = resources;
- }
-
- /**
- * Sets the kind of this root.
- */
- protected void setRootKind(int newRootKind) {
- fRootKind = newRootKind;
+ return nonJavaResources;
+}
+/**
+ * Returns an array of non-java resources contained in the receiver.
+ */
+synchronized Object[] getNonJavaResources(IJavaProject project, IResource underlyingResource) {
+ Object[] nonJavaResources = fNonJavaResources;
+ if (nonJavaResources == null) {
+ nonJavaResources = this.computeNonJavaResources(project, underlyingResource);
+ fNonJavaResources = nonJavaResources;
}
-
+ return nonJavaResources;
+}
+/**
+ * Returns the kind of this root.
+ */
+public int getRootKind() {
+ return fRootKind;
+}
+/**
+ * Set the fNonJavaResources to res value
+ */
+synchronized void setNonJavaResources(Object[] resources) {
+ fNonJavaResources = resources;
+}
+/**
+ * Sets the kind of this root.
+ */
+protected void setRootKind(int newRootKind) {
+ fRootKind = newRootKind;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Problem.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Problem.java
index 28e6812e77..67880d2fb8 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Problem.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Problem.java
@@ -1,5 +1,5 @@
package org.eclipse.jdt.internal.core;
-
+
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
@@ -9,235 +9,139 @@ import org.eclipse.jdt.internal.compiler.env.*;
import org.eclipse.jdt.internal.compiler.ast.*;
import org.eclipse.jdt.internal.compiler.problem.*;
import org.eclipse.jdt.internal.compiler.impl.*;
-
+
public class Problem implements IProblem, ProblemSeverities, ProblemIrritants {
private char[] fileName;
private int id;
- private int startPosition, endPosition, line;
+ private int startPosition, endPosition,line;
private int severity;
- private String[] arguments;
+ private String[] arguments;
private String message;
- public Problem(
- char[] originatingFileName,
- String message,
- int id,
- String[] stringArguments,
- int severity,
- int startPosition,
- int endPosition,
- int line) {
-
- this.fileName = originatingFileName;
- this.message = message;
- this.id = id;
- this.arguments = stringArguments;
- this.severity = severity;
- this.startPosition = startPosition;
- this.endPosition = endPosition;
- this.line = line;
- }
-
- public String errorReportSource(ICompilationUnit compilationUnit) {
- //extra from the source the innacurate token
- //and "highlight" it using some underneath ^^^^^
- //put some context around too.
-
- //this code assumes that the font used in the console is fixed size
-
- //sanity .....
- if ((startPosition > endPosition)
- || ((startPosition <= 0) && (endPosition <= 0)))
- return "\n!! no source information available !!";
-
- //regular behavior....(slow code)
-
- final int AROUND = 60; //increase this value to see more ....
- final char SPACE = '\u0020';
- final char MARK = '^';
- final char TAB = '\t';
- char[] source = compilationUnit.getContents();
- //the next code tries to underline the token.....
- //it assumes (for a good display) that token source does not
- //contain any \r \n. This is false on statements !
- //(the code still works but the display is not optimal !)
-
- //compute the how-much-char we are displaying around the inaccurate token
- int begin = startPosition >= source.length ? source.length - 1 : startPosition;
- int relativeStart = 0;
- int end = endPosition >= source.length ? source.length - 1 : endPosition;
- int relativeEnd = 0;
- label : for (relativeStart = 0;; relativeStart++) {
- if (begin == 0)
- break label;
- if ((source[begin - 1] == '\n') || (source[begin - 1] == '\r'))
- break label;
- begin--;
- }
- label : for (relativeEnd = 0;; relativeEnd++) {
- if ((end + 1) >= source.length)
- break label;
- if ((source[end + 1] == '\r') || (source[end + 1] == '\n')) {
- break label;
- }
- end++;
- }
- //extract the message form the source
- char[] extract = new char[end - begin + 1];
- System.arraycopy(source, begin, extract, 0, extract.length);
- char c;
- //remove all SPACE and TAB that begin the error message...
- int trimLeftIndex = 0;
- while (((c = extract[trimLeftIndex++]) == TAB) || (c == SPACE)) {
- };
- System.arraycopy(
- extract,
- trimLeftIndex - 1,
- extract = new char[extract.length - trimLeftIndex + 1],
- 0,
- extract.length);
- relativeStart -= trimLeftIndex;
- //buffer spaces and tabs in order to reach the error position
- int pos = 0;
- char[] underneath = new char[extract.length]; // can't be bigger
- for (int i = 0; i <= relativeStart; i++) {
- if (extract[i] == TAB) {
- underneath[pos++] = TAB;
- } else {
- underneath[pos++] = SPACE;
- }
- }
- //mark the error position
- for (int i = startPosition;
- i <= (endPosition >= source.length ? source.length - 1 : endPosition);
- i++)
- underneath[pos++] = MARK;
- //resize underneathto remove 'null' chars
- System.arraycopy(underneath, 0, underneath = new char[pos], 0, pos);
-
- return " (at line " + String.valueOf(line) + ")" + //NON NLS
- "\n\t" + new String(extract) + "\n\t" + new String(underneath);
- }
-
- /**
- * Answer back the original arguments recorded into the problem.
- * @return java.lang.String[]
- */
- public String[] getArguments() {
- return arguments;
- }
-
- /**
- * Answer the type of problem.
- * @see com.ibm.compiler.java.problem.ProblemIrritants
- * @return int
- */
- public int getID() {
- return id;
- }
-
- /**
- * Answer a localized, human-readable message string which describes the problem.
- * @return java.lang.String
- */
- public String getMessage() {
- return message;
- }
-
- /**
- * Answer the file name in which the problem was found.
- * @return char[]
- */
- public char[] getOriginatingFileName() {
- return fileName;
- }
-
- /**
- * Answer the severity of the problem.
- * @return int
- */
- public int getSeverity() {
- return severity;
- }
-
- /**
- * Answer the end position of the problem (inclusive), or -1 if unknown.
- * @return int
- */
- public int getSourceEnd() {
- return endPosition;
- }
-
- /**
- * Answer the line number in source where the problem begins.
- * @return int
- */
- public int getSourceLineNumber() {
- return line;
- }
-
- /**
- * Answer the start position of the problem (inclusive), or -1 if unknown.
- * @return int
- */
- public int getSourceStart() {
- return startPosition;
- }
-
- /*
- * Helper method: checks the severity to see if the Error bit is set.
- * @return boolean
- */
- public boolean isError() {
- return (severity & ProblemSeverities.Error) != 0;
- }
-
- /*
- * Helper method: checks the severity to see if the Error bit is not set.
- * @return boolean
- */
- public boolean isWarning() {
- return (severity & ProblemSeverities.Error) == 0;
- }
-
- /**
- * Set the end position of the problem (inclusive), or -1 if unknown.
- *
- * Used for shifting problem positions.
- * @param sourceEnd the new value of the sourceEnd of the receiver
- */
- public void setSourceEnd(int sourceEnd) {
- endPosition = sourceEnd;
- }
-
- /**
- * Set the line number in source where the problem begins.
- * @param lineNumber the new value of the line number of the receiver
- */
- public void setSourceLineNumber(int lineNumber) {
- line = lineNumber;
- }
-
- /**
- * Set the start position of the problem (inclusive), or -1 if unknown.
- *
- * Used for shifting problem positions.
- * @param sourceStart the new value of the source start position of the receiver
- */
- public void setSourceStart(int sourceStart) {
- startPosition = sourceStart;
- }
-
- public String toString() {
-
- String s = "Pb(" + (id & IgnoreCategoriesMask) + ") ";
- if (message != null) {
- s += message;
- } else {
- if (arguments != null)
- for (int i = 0; i < arguments.length; i++)
- s += " " + arguments[i];
- }
- return s;
- }
-
+public Problem(
+ char[] originatingFileName,
+ String message,
+ int id,
+ String[] stringArguments,
+ int severity,
+ int startPosition,
+ int endPosition,
+ int line) {
+
+ this.fileName = originatingFileName;
+ this.message = message;
+ this.id = id;
+ this.arguments = stringArguments;
+ this.severity = severity;
+ this.startPosition = startPosition;
+ this.endPosition = endPosition;
+ this.line = line;
+}
+/**
+ * Answer back the original arguments recorded into the problem.
+ * @return java.lang.String[]
+ */
+public String[] getArguments() {
+ return arguments;
+}
+/**
+ * Answer the type of problem.
+ * @see com.ibm.compiler.java.problem.ProblemIrritants
+ * @return int
+ */
+public int getID() {
+ return id;
+}
+/**
+ * Answer a localized, human-readable message string which describes the problem.
+ * @return java.lang.String
+ */
+public String getMessage() {
+ return message;
+}
+/**
+ * Answer the file name in which the problem was found.
+ * @return char[]
+ */
+public char[] getOriginatingFileName() {
+ return fileName;
+}
+/**
+ * Answer the severity of the problem.
+ * @return int
+ */
+public int getSeverity() {
+ return severity;
+}
+/**
+ * Answer the end position of the problem (inclusive), or -1 if unknown.
+ * @return int
+ */
+public int getSourceEnd() {
+ return endPosition;
+}
+/**
+ * Answer the line number in source where the problem begins.
+ * @return int
+ */
+public int getSourceLineNumber() {
+ return line;
+}
+/**
+ * Answer the start position of the problem (inclusive), or -1 if unknown.
+ * @return int
+ */
+public int getSourceStart() {
+ return startPosition;
+}
+/*
+ * Helper method: checks the severity to see if the Error bit is set.
+ * @return boolean
+ */
+public boolean isError() {
+ return (severity & ProblemSeverities.Error) != 0;
+}
+/*
+ * Helper method: checks the severity to see if the Error bit is not set.
+ * @return boolean
+ */
+public boolean isWarning() {
+ return (severity & ProblemSeverities.Error) == 0;
+}
+/**
+ * Set the end position of the problem (inclusive), or -1 if unknown.
+ *
+ * Used for shifting problem positions.
+ * @param sourceEnd the new value of the sourceEnd of the receiver
+ */
+public void setSourceEnd(int sourceEnd) {
+ endPosition = sourceEnd;
+}
+/**
+ * Set the line number in source where the problem begins.
+ * @param lineNumber the new value of the line number of the receiver
+ */
+public void setSourceLineNumber(int lineNumber) {
+ line = lineNumber;
+}
+/**
+ * Set the start position of the problem (inclusive), or -1 if unknown.
+ *
+ * Used for shifting problem positions.
+ * @param sourceStart the new value of the source start position of the receiver
+ */
+public void setSourceStart(int sourceStart) {
+ startPosition = sourceStart;
+}
+public String toString() {
+
+ String s = "Pb("/*nonNLS*/ + (id & IgnoreCategoriesMask) + ") "/*nonNLS*/;
+ if (message != null) {
+ s += message;
+ } else {
+ if (arguments != null)
+ for (int i = 0; i < arguments.length; i++)
+ s += " "/*nonNLS*/ + arguments[i];
+ }
+ return s;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Region.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Region.java
index b6b319e276..15b66de75b 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Region.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Region.java
@@ -15,7 +15,7 @@ import java.util.Vector;
/**
* @see IRegion
*/
-
+
public class Region implements IRegion {
/**
@@ -23,132 +23,124 @@ public class Region implements IRegion {
* that have been added to the region
*/
protected Vector fRootElements;
- /**
- * Creates an empty region.
- *
- * @see IRegion
- */
- public Region() {
- fRootElements = new Vector(1);
+/**
+ * Creates an empty region.
+ *
+ * @see IRegion
+ */
+public Region() {
+ fRootElements = new Vector(1);
+}
+/**
+ * @see IRegion#add(IJavaElement)
+ */
+public void add(IJavaElement element) {
+ if (!contains(element)) {
+ //"new" element added to region
+ removeAllChildren(element);
+ fRootElements.addElement(element);
+ fRootElements.trimToSize();
}
-
- /**
- * @see IRegion#add(IJavaElement)
- */
- public void add(IJavaElement element) {
- if (!contains(element)) {
- //"new" element added to region
- removeAllChildren(element);
- fRootElements.addElement(element);
- fRootElements.trimToSize();
+}
+/**
+ * @see IRegion
+ */
+public boolean contains(IJavaElement element) {
+
+ int size = fRootElements.size();
+ Vector parents = getAncestors(element);
+
+ for (int i = 0; i < size; i++) {
+ IJavaElement aTop = (IJavaElement) fRootElements.elementAt(i);
+ if (aTop.equals(element)) {
+ return true;
}
- }
-
- /**
- * @see IRegion
- */
- public boolean contains(IJavaElement element) {
-
- int size = fRootElements.size();
- Vector parents = getAncestors(element);
-
- for (int i = 0; i < size; i++) {
- IJavaElement aTop = (IJavaElement) fRootElements.elementAt(i);
- if (aTop.equals(element)) {
+ for (int j = 0, pSize = parents.size(); j < pSize; j++) {
+ if (aTop.equals(parents.elementAt(j))) {
+ //an ancestor is already included
return true;
}
- for (int j = 0, pSize = parents.size(); j < pSize; j++) {
- if (aTop.equals(parents.elementAt(j))) {
- //an ancestor is already included
- return true;
- }
- }
}
- return false;
}
-
- /**
- * Returns a collection of all the parents of this element
- * in bottom-up order.
- *
- */
- private Vector getAncestors(IJavaElement element) {
- Vector parents = new Vector();
- IJavaElement parent = element.getParent();
- while (parent != null) {
- parents.addElement(parent);
- parent = parent.getParent();
- }
- parents.trimToSize();
- return parents;
+ return false;
+}
+/**
+ * Returns a collection of all the parents of this element
+ * in bottom-up order.
+ *
+ */
+private Vector getAncestors(IJavaElement element) {
+ Vector parents = new Vector();
+ IJavaElement parent = element.getParent();
+ while (parent != null) {
+ parents.addElement(parent);
+ parent = parent.getParent();
}
-
- /**
- * @see IRegion
- */
- public IJavaElement[] getElements() {
- int size = fRootElements.size();
- IJavaElement[] roots = new IJavaElement[size];
- for (int i = 0; i < size; i++) {
- roots[i] = (IJavaElement) fRootElements.elementAt(i);
- }
-
- return roots;
+ parents.trimToSize();
+ return parents;
+}
+/**
+ * @see IRegion
+ */
+public IJavaElement[] getElements() {
+ int size= fRootElements.size();
+ IJavaElement[] roots= new IJavaElement[size];
+ for (int i = 0; i < size; i++) {
+ roots[i]= (IJavaElement) fRootElements.elementAt(i);
}
- /**
- * @see IRegion#remove(IJavaElement)
- */
- public boolean remove(IJavaElement element) {
-
- removeAllChildren(element);
- return fRootElements.removeElement(element);
- }
+ return roots;
+}
+/**
+ * @see IRegion#remove(IJavaElement)
+ */
+public boolean remove(IJavaElement element) {
- /**
- * Removes any children of this element that are contained within this
- * region as this parent is about to be added to the region.
- *
- * <p>Children are all children, not just direct children.
- */
- private void removeAllChildren(IJavaElement element) {
- if (element instanceof IParent) {
- Vector newRootElements = new Vector();
- for (int i = 0, size = fRootElements.size(); i < size; i++) {
- IJavaElement currentRoot = (IJavaElement) fRootElements.elementAt(i);
- //walk the current root hierarchy
- IJavaElement parent = currentRoot.getParent();
- boolean isChild = false;
- while (parent != null) {
- if (parent.equals(element)) {
- isChild = true;
- break;
- }
- parent = parent.getParent();
- }
- if (!isChild) {
- newRootElements.addElement(currentRoot);
+ removeAllChildren(element);
+ return fRootElements.removeElement(element);
+}
+/**
+ * Removes any children of this element that are contained within this
+ * region as this parent is about to be added to the region.
+ *
+ * <p>Children are all children, not just direct children.
+ */
+private void removeAllChildren(IJavaElement element) {
+ if (element instanceof IParent) {
+ Vector newRootElements = new Vector();
+ for (int i = 0, size = fRootElements.size(); i < size; i++) {
+ IJavaElement currentRoot = (IJavaElement)fRootElements.elementAt(i);
+ //walk the current root hierarchy
+ IJavaElement parent = currentRoot.getParent();
+ boolean isChild= false;
+ while (parent != null) {
+ if (parent.equals(element)) {
+ isChild= true;
+ break;
}
+ parent = parent.getParent();
+ }
+ if (!isChild) {
+ newRootElements.addElement(currentRoot);
}
- fRootElements = newRootElements;
}
+ fRootElements= newRootElements;
}
-
- /**
- * Returns a printable representation of this region.
- */
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- IJavaElement[] roots = getElements();
- buffer.append('[');
- for (int i = 0; i < roots.length; i++) {
- buffer.append(roots[i].getElementName());
- if (i < (roots.length - 1)) {
- buffer.append(", ");
- }
+}
+/**
+ * Returns a printable representation of this region.
+ */
+public String toString() {
+ StringBuffer buffer= new StringBuffer();
+ IJavaElement[] roots= getElements();
+ buffer.append('[');
+ for (int i= 0; i < roots.length; i++) {
+ buffer.append(roots[i].getElementName());
+ if (i < (roots.length - 1)) {
+ buffer.append(", "/*nonNLS*/);
}
- buffer.append(']');
- return buffer.toString();
}
-
+ buffer.append(']');
+ return buffer.toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/RenameElementsOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/RenameElementsOperation.java
index 0c4a6d580a..50a35bf09e 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/RenameElementsOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/RenameElementsOperation.java
@@ -24,66 +24,57 @@ import org.eclipse.jdt.core.JavaModelException;
* </ul>
*/
public class RenameElementsOperation extends MoveElementsOperation {
- /**
- * When executed, this operation will rename the specified elements with the given names in the
- * corresponding destinations.
- */
- public RenameElementsOperation(
- IJavaElement[] elements,
- IJavaElement[] destinations,
- String[] newNames,
- boolean force) {
- //a rename is a move to the same parent with a new name specified
- //these elements are from different parents
- super(elements, destinations, force);
- setRenamings(newNames);
- }
-
- /**
- * @see MultiOperation
- */
- protected String getMainTaskName() {
- return "Renaming elements...";
- }
-
- /**
- * @see CopyElementsOperation#isRename()
- */
- protected boolean isRename() {
- return true;
- }
-
- /**
- * @see MultiOperation
- */
- protected IJavaModelStatus verify() {
- IJavaModelStatus status = super.verify();
- if (!status.isOK())
- return status;
- if (fRenamingsList == null || fRenamingsList.length == 0)
- return new JavaModelStatus(IJavaModelStatusConstants.NULL_NAME);
- return JavaModelStatus.VERIFIED_OK;
- }
-
- /**
- * @see MultiOperation
- */
- protected void verify(IJavaElement element) throws JavaModelException {
- int elementType = element.getElementType();
-
- if (element == null || !element.exists())
- error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element);
-
- if (element.isReadOnly())
- error(IJavaModelStatusConstants.READ_ONLY, element);
-
- if (!(element instanceof ISourceReference))
- error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
-
- if (elementType < IJavaElement.TYPE || elementType == IJavaElement.INITIALIZER)
- error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
-
- verifyRenaming(element);
- }
-
+/**
+ * When executed, this operation will rename the specified elements with the given names in the
+ * corresponding destinations.
+ */
+public RenameElementsOperation(IJavaElement[] elements, IJavaElement[] destinations, String[] newNames, boolean force) {
+ //a rename is a move to the same parent with a new name specified
+ //these elements are from different parents
+ super(elements, destinations, force);
+ setRenamings(newNames);
+}
+/**
+ * @see MultiOperation
+ */
+protected String getMainTaskName() {
+ return Util.bind("operation.renameElementProgress"/*nonNLS*/);
+}
+/**
+ * @see CopyElementsOperation#isRename()
+ */
+protected boolean isRename() {
+ return true;
+}
+/**
+ * @see MultiOperation
+ */
+protected IJavaModelStatus verify() {
+ IJavaModelStatus status = super.verify();
+ if (! status.isOK())
+ return status;
+ if (fRenamingsList == null || fRenamingsList.length == 0)
+ return new JavaModelStatus(IJavaModelStatusConstants.NULL_NAME);
+ return JavaModelStatus.VERIFIED_OK;
+}
+/**
+ * @see MultiOperation
+ */
+protected void verify(IJavaElement element) throws JavaModelException {
+ int elementType = element.getElementType();
+
+ if (element == null || !element.exists())
+ error(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, element);
+
+ if (element.isReadOnly())
+ error(IJavaModelStatusConstants.READ_ONLY, element);
+
+ if (!(element instanceof ISourceReference))
+ error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
+
+ if (elementType < IJavaElement.TYPE || elementType == IJavaElement.INITIALIZER)
+ error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
+
+ verifyRenaming(element);
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/RenameResourceElementsOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/RenameResourceElementsOperation.java
index c5a9371033..f26666bfec 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/RenameResourceElementsOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/RenameResourceElementsOperation.java
@@ -19,56 +19,46 @@ import org.eclipse.jdt.core.JavaModelException;
* main type are renamed.
* </ul>
*/
-public class RenameResourceElementsOperation
- extends MoveResourceElementsOperation {
- /**
- * When executed, this operation will rename the specified elements with the given names in the
- * corresponding destinations.
- */
- public RenameResourceElementsOperation(
- IJavaElement[] elements,
- IJavaElement[] destinations,
- String[] newNames,
- boolean force) {
- //a rename is a move to the same parent with a new name specified
- //these elements are from different parents
- super(elements, destinations, force);
- setRenamings(newNames);
- }
-
- /**
- * @see MultiOperation
- */
- protected String getMainTaskName() {
- return "Renaming resources...";
- }
+public class RenameResourceElementsOperation extends MoveResourceElementsOperation {
+/**
+ * When executed, this operation will rename the specified elements with the given names in the
+ * corresponding destinations.
+ */
+public RenameResourceElementsOperation(IJavaElement[] elements, IJavaElement[] destinations, String[] newNames, boolean force) {
+ //a rename is a move to the same parent with a new name specified
+ //these elements are from different parents
+ super(elements, destinations, force);
+ setRenamings(newNames);
+}
+/**
+ * @see MultiOperation
+ */
+protected String getMainTaskName() {
+ return Util.bind("operation.renameResourceProgress"/*nonNLS*/);
+}
+/**
+ * @see CopyResourceElementsOperation#isRename()
+ */
+protected boolean isRename() {
+ return true;
+}
+/**
+ * @see MultiOperation
+ */
+protected void verify(IJavaElement element) throws JavaModelException {
+ super.verify(element);
- /**
- * @see CopyResourceElementsOperation#isRename()
- */
- protected boolean isRename() {
- return true;
+ String newName = getNewNameFor(element);
+ int elementType = element.getElementType();
+
+ if (!(elementType == IJavaElement.COMPILATION_UNIT || elementType == IJavaElement.PACKAGE_FRAGMENT)) {
+ error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
}
-
- /**
- * @see MultiOperation
- */
- protected void verify(IJavaElement element) throws JavaModelException {
- super.verify(element);
-
- String newName = getNewNameFor(element);
- int elementType = element.getElementType();
-
- if (!(elementType == IJavaElement.COMPILATION_UNIT
- || elementType == IJavaElement.PACKAGE_FRAGMENT)) {
+ if (elementType == IJavaElement.COMPILATION_UNIT) {
+ if (((ICompilationUnit) element).isWorkingCopy()) {
error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
}
- if (elementType == IJavaElement.COMPILATION_UNIT) {
- if (((ICompilationUnit) element).isWorkingCopy()) {
- error(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, element);
- }
- }
- verifyRenaming(element);
}
-
+ verifyRenaming(element);
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SearchableEnvironment.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
index 0a74f4e827..745ff1af97 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SearchableEnvironment.java
@@ -18,343 +18,270 @@ import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
* uses the Java model as a search tool.
*/
-public class SearchableEnvironment
- implements ISearchableNameEnvironment, IJavaSearchConstants {
+public class SearchableEnvironment implements ISearchableNameEnvironment, IJavaSearchConstants {
protected NameLookup nameLookup;
protected ICompilationUnit unitToSkip;
public CompilationUnit unitToLookInside;
protected IJavaProject project;
- /**
- * Creates a SearchableEnvironment on the given project
- */
- public SearchableEnvironment(IJavaProject project) throws JavaModelException {
- this.project = project;
- this.nameLookup = (NameLookup) ((JavaProject) project).getNameLookup();
- }
-
- /**
- * Returns the given type in the the given package if it exists,
- * otherwise <code>null</code>.
- */
- protected NameEnvironmentAnswer find(String typeName, String packageName) {
- if (packageName == null)
- packageName = IPackageFragment.DEFAULT_PACKAGE_NAME;
- IType type =
- this.nameLookup.findType(
- typeName,
- packageName,
- false,
- INameLookup.ACCEPT_CLASSES | INameLookup.ACCEPT_INTERFACES);
- if (type == null) {
- // look inside the compilation unit that is being searched currently
- //for a non-public or inner type.
- if (this.unitToLookInside != null) {
- if (this.unitToLookInside.getParent().getElementName().equals(packageName)) {
- try {
- IType[] allTypes = this.unitToLookInside.getTypes();
- for (int i = 0; i < allTypes.length; i++) {
- if (allTypes[i].getElementName().equals(typeName)) {
- type = allTypes[i];
- break;
- }
+/**
+ * Creates a SearchableEnvironment on the given project
+ */
+public SearchableEnvironment(IJavaProject project) throws JavaModelException {
+ this.project = project;
+ this.nameLookup = (NameLookup)((JavaProject)project).getNameLookup();
+}
+/**
+ * Returns the given type in the the given package if it exists,
+ * otherwise <code>null</code>.
+ */
+protected NameEnvironmentAnswer find(String typeName, String packageName) {
+ if (packageName == null)
+ packageName = IPackageFragment.DEFAULT_PACKAGE_NAME;
+ IType type = this.nameLookup.findType(typeName, packageName, false, INameLookup.ACCEPT_CLASSES | INameLookup.ACCEPT_INTERFACES);
+ if (type == null) {
+ // look inside the compilation unit that is being searched currently
+ //for a non-public or inner type.
+ if (this.unitToLookInside != null) {
+ if (this.unitToLookInside.getParent().getElementName().equals(packageName)) {
+ try {
+ IType[] allTypes = this.unitToLookInside.getTypes();
+ for (int i= 0; i < allTypes.length; i++) {
+ if (allTypes[i].getElementName().equals(typeName)) {
+ type = allTypes[i];
+ break;
}
- } catch (JavaModelException e) {
}
+ } catch (JavaModelException e) {
}
}
}
- if (type != null) {
- if (type instanceof BinaryType) {
- try {
- return new NameEnvironmentAnswer(
- (IBinaryType) ((BinaryType) type).getRawInfo());
- } catch (JavaModelException npe) {
- return null;
- }
- } else { //SourceType
- try {
- return new NameEnvironmentAnswer(
- (ISourceType) ((SourceType) type).getRawInfo());
- } catch (JavaModelException npe) {
- return null;
- }
+ }
+ if (type != null) {
+ if (type instanceof BinaryType) {
+ try {
+ return new NameEnvironmentAnswer((IBinaryType) ((BinaryType) type).getRawInfo());
+ } catch (JavaModelException npe) {
+ return null;
+ }
+ } else { //SourceType
+ try {
+ return new NameEnvironmentAnswer((ISourceType)((SourceType)type).getRawInfo());
+ } catch (JavaModelException npe) {
+ return null;
}
}
- return null;
}
-
- /**
- * @see SearchableBuilderEnvironment
- */
- public void findPackages(char[] prefix, ISearchRequestor requestor) {
- this.nameLookup.seekPackageFragments(
- new String(prefix),
- true,
- new SearchableEnvironmentRequestor(requestor));
+ return null;
+}
+/**
+ * @see SearchableBuilderEnvironment
+ */
+public void findPackages(char[] prefix, ISearchRequestor requestor) {
+ this.nameLookup.seekPackageFragments(new String(prefix), true, new SearchableEnvironmentRequestor(requestor));
+}
+/**
+ * @see INameEnvironment
+ */
+public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
+ if (compoundTypeName == null)
+ return null;
+ int length = compoundTypeName.length;
+ if (length == 1)
+ return find(new String(compoundTypeName[0]), null);
+ StringBuffer buffer = new StringBuffer(length * 6);
+ int lengthM1 = length - 1;
+ for(int i = 0; i < lengthM1; i++) {
+ buffer.append(compoundTypeName[i]);
+ if (i + 1 != lengthM1)
+ buffer.append('.');
}
+ String className = new String(compoundTypeName[lengthM1]);
+ return find(className, buffer.toString());
+}
+/**
+ * @see INameEnvironment
+ */
+public NameEnvironmentAnswer findType(char[] name, char[][] packages) {
+ if (name == null)
+ return null;
- /**
- * @see INameEnvironment
- */
- public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
- if (compoundTypeName == null)
- return null;
- int length = compoundTypeName.length;
- if (length == 1)
- return find(new String(compoundTypeName[0]), null);
- StringBuffer buffer = new StringBuffer(length * 6);
- int lengthM1 = length - 1;
- for (int i = 0; i < lengthM1; i++) {
- buffer.append(compoundTypeName[i]);
- if (i + 1 != lengthM1)
- buffer.append(".");
- }
- String className = new String(compoundTypeName[lengthM1]);
- return find(className, buffer.toString());
+ if (packages == null || packages.length == 0)
+ return find(new String(name), null);
+
+ int length = packages.length;
+ StringBuffer buffer = new StringBuffer(length * 6);
+ for(int i = 0; i < length; i++) {
+ buffer.append(packages[i]);
+ if (i + 1 != length)
+ buffer.append('.');
}
+ String className = new String(name);
+ return find(className, buffer.toString());
+}
+/**
+ * @see ISearchableNameEnvironment
+ */
+public void findTypes(char[] prefix, final ISearchRequestor storage) {
- /**
- * @see INameEnvironment
- */
- public NameEnvironmentAnswer findType(char[] name, char[][] packages) {
- if (name == null)
- return null;
-
- if (packages == null || packages.length == 0)
- return find(new String(name), null);
-
- int length = packages.length;
- StringBuffer buffer = new StringBuffer(length * 6);
- for (int i = 0; i < length; i++) {
- buffer.append(packages[i]);
- if (i + 1 != length)
- buffer.append(".");
- }
- String className = new String(name);
- return find(className, buffer.toString());
+/*
+ if (true){
+ findTypes(new String(prefix), storage, INameLookup.ACCEPT_CLASSES | INameLookup.ACCEPT_INTERFACES);
+ return;
}
-
- /**
- * @see ISearchableNameEnvironment
- */
- public void findTypes(char[] prefix, final ISearchRequestor storage) {
-
- /*
- if (true){
+*/
+ try {
+ final String excludePath;
+ if (this.unitToSkip != null){
+ if (!(this.unitToSkip instanceof IJavaElement)){ // revert to model investigation
findTypes(new String(prefix), storage, INameLookup.ACCEPT_CLASSES | INameLookup.ACCEPT_INTERFACES);
return;
}
- */
- try {
- final String excludePath;
- if (this.unitToSkip != null) {
- if (!(this.unitToSkip instanceof IJavaElement)) {
- // revert to model investigation
- findTypes(
- new String(prefix),
- storage,
- INameLookup.ACCEPT_CLASSES | INameLookup.ACCEPT_INTERFACES);
- return;
- }
- excludePath =
- ((IJavaElement) this.unitToSkip)
- .getUnderlyingResource()
- .getFullPath()
- .toString();
- } else {
- excludePath = null;
- }
- int lastDotIndex = CharOperation.lastIndexOf('.', prefix);
- char[] qualification, simpleName;
- if (lastDotIndex < 0) {
- qualification = null;
- simpleName = CharOperation.toLowerCase(prefix);
- } else {
- qualification = CharOperation.subarray(prefix, 0, lastDotIndex);
- simpleName =
- CharOperation.toLowerCase(
- CharOperation.subarray(prefix, lastDotIndex + 1, prefix.length));
- }
-
- SearchEngine searchEngine = new SearchEngine();
+ excludePath = ((IJavaElement)this.unitToSkip).getUnderlyingResource().getFullPath().toString();
+ } else {
+ excludePath = null;
+ }
+ int lastDotIndex = CharOperation.lastIndexOf('.', prefix);
+ char[] qualification, simpleName;
+ if (lastDotIndex < 0){
+ qualification = null;
+ simpleName = CharOperation.toLowerCase(prefix);
+ } else {
+ qualification = CharOperation.subarray(prefix, 0, lastDotIndex);
+ simpleName = CharOperation.toLowerCase(CharOperation.subarray(prefix, lastDotIndex+1, prefix.length));
+ }
+
+ SearchEngine searchEngine = new SearchEngine();
- IProject projectRsc = (IProject) this.project.getUnderlyingResource();
- IJavaSearchScope scope =
- searchEngine.createJavaSearchScope(new IResource[] { projectRsc });
+ IProject projectRsc = (IProject) this.project.getUnderlyingResource();
+ IJavaSearchScope scope = searchEngine.createJavaSearchScope(new IResource[]{ projectRsc});
- IProgressMonitor progressMonitor = new IProgressMonitor() {
- boolean isCanceled = false;
- public void beginTask(String name, int totalWork) {
- }
- public void done() {
- }
- public void internalWorked(double work) {
- }
- public boolean isCanceled() {
- return isCanceled;
- }
- public void setCanceled(boolean value) {
- isCanceled = value;
- }
- public void setTaskName(String name) {
- }
- public void subTask(String name) {
- }
- public void worked(int work) {
- }
- };
- ITypeNameRequestor nameRequestor = new ITypeNameRequestor() {
- public void acceptClass(
- char[] packageName,
- char[] simpleTypeName,
- char[][] enclosingTypeNames,
- String path) {
- if (excludePath != null && excludePath.equals(path))
- return;
- if (enclosingTypeNames != null && enclosingTypeNames.length > 0)
- return; // accept only top level types
- storage.acceptClass(packageName, simpleTypeName, 0);
- }
- public void acceptInterface(
- char[] packageName,
- char[] simpleTypeName,
- char[][] enclosingTypeNames,
- String path) {
- if (excludePath != null && excludePath.equals(path))
- return;
- if (enclosingTypeNames != null && enclosingTypeNames.length > 0)
- return; // accept only top level types
- storage.acceptInterface(packageName, simpleTypeName, 0);
- }
- };
- try {
- searchEngine.searchAllTypeNames(
- projectRsc.getWorkspace(),
- qualification,
- simpleName,
- PREFIX_MATCH,
- CASE_INSENSITIVE,
- IJavaSearchConstants.TYPE,
- scope,
- nameRequestor,
- CANCEL_IF_NOT_READY_TO_SEARCH,
- progressMonitor);
- } catch (OperationCanceledException e) {
- findTypes(
- new String(prefix),
- storage,
- INameLookup.ACCEPT_CLASSES | INameLookup.ACCEPT_INTERFACES);
+ IProgressMonitor progressMonitor = new IProgressMonitor(){
+ boolean isCanceled = false;
+ public void beginTask(String name, int totalWork){}
+ public void done(){}
+ public void internalWorked(double work){}
+ public boolean isCanceled(){ return isCanceled; }
+ public void setCanceled(boolean value){ isCanceled = value; }
+ public void setTaskName(String name){}
+ public void subTask(String name){}
+ public void worked(int work){}
+ };
+ ITypeNameRequestor nameRequestor = new ITypeNameRequestor(){
+ public void acceptClass(char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path){
+ if (excludePath != null && excludePath.equals(path)) return;
+ if (enclosingTypeNames != null && enclosingTypeNames.length > 0) return; // accept only top level types
+ storage.acceptClass(packageName, simpleTypeName, 0);
}
- } catch (JavaModelException e) {
- findTypes(
- new String(prefix),
- storage,
- INameLookup.ACCEPT_CLASSES | INameLookup.ACCEPT_INTERFACES);
- }
- }
-
- /**
- * Returns all types whose name starts with the given (qualified) <code>prefix</code>.
- *
- * If the <code>prefix</code> is unqualified, all types whose simple name matches
- * the <code>prefix</code> are returned.
- */
- private void findTypes(String prefix, ISearchRequestor storage, int type) {
- SearchableEnvironmentRequestor requestor =
- new SearchableEnvironmentRequestor(storage, this.unitToSkip);
- int index = prefix.lastIndexOf('.');
- if (index == -1) {
- this.nameLookup.seekTypes(prefix, null, true, type, requestor);
- } else {
- String packageName = prefix.substring(0, index);
- String className = prefix.substring(index + 1);
- JavaElementRequestor javaElementRequestor = new JavaElementRequestor();
- this.nameLookup.seekPackageFragments(packageName, false, javaElementRequestor);
- IPackageFragment[] packageFragments =
- javaElementRequestor.getPackageFragments();
- if (packageFragments == null)
- return;
- for (int i = 0, packagesLength = packageFragments.length;
- i < packagesLength;
- i++) {
- if (packageFragments[i] == null)
- continue;
- this.nameLookup.seekTypes(
- className,
- packageFragments[i],
- true,
- type,
- requestor);
+ public void acceptInterface(char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path){
+ if (excludePath != null && excludePath.equals(path)) return;
+ if (enclosingTypeNames != null && enclosingTypeNames.length > 0) return; // accept only top level types
+ storage.acceptInterface(packageName, simpleTypeName, 0);
}
+ };
+ try {
+ searchEngine.searchAllTypeNames(
+ projectRsc.getWorkspace(),
+ qualification,
+ simpleName,
+ PREFIX_MATCH,
+ CASE_INSENSITIVE,
+ IJavaSearchConstants.TYPE,
+ scope,
+ nameRequestor,
+ CANCEL_IF_NOT_READY_TO_SEARCH,
+ progressMonitor);
+ } catch (OperationCanceledException e) {
+ findTypes(new String(prefix), storage, INameLookup.ACCEPT_CLASSES | INameLookup.ACCEPT_INTERFACES);
}
+ } catch(JavaModelException e){
+ findTypes(new String(prefix), storage, INameLookup.ACCEPT_CLASSES | INameLookup.ACCEPT_INTERFACES);
}
-
- /**
- * @see SearchableBuilderEnvironment
- */
- public boolean isPackage(char[][] parentPackageName, char[] subPackageName) {
- if (parentPackageName == null || parentPackageName.length == 0)
- return isTopLevelPackage(subPackageName);
- if (subPackageName == null)
- return false;
- int length = parentPackageName.length;
- StringBuffer buffer = new StringBuffer((length + 1) * 6);
- for (int i = 0; i < length; i++) {
- if (parentPackageName[i] == null || isQualified(parentPackageName[i]))
- return false;
- buffer.append(parentPackageName[i]);
- buffer.append(".");
- }
- if (isQualified(subPackageName)) {
- return false;
+}
+/**
+ * Returns all types whose name starts with the given (qualified) <code>prefix</code>.
+ *
+ * If the <code>prefix</code> is unqualified, all types whose simple name matches
+ * the <code>prefix</code> are returned.
+ */
+private void findTypes(String prefix, ISearchRequestor storage, int type) {
+ SearchableEnvironmentRequestor requestor = new SearchableEnvironmentRequestor(storage, this.unitToSkip);
+ int index = prefix.lastIndexOf('.');
+ if (index == -1) {
+ this.nameLookup.seekTypes(prefix, null, true, type, requestor);
+ } else {
+ String packageName = prefix.substring(0, index);
+ String className = prefix.substring(index + 1);
+ JavaElementRequestor javaElementRequestor = new JavaElementRequestor();
+ this.nameLookup.seekPackageFragments(packageName, false, javaElementRequestor);
+ IPackageFragment[] packageFragments = javaElementRequestor.getPackageFragments();
+ if (packageFragments == null)
+ return;
+ for (int i = 0, packagesLength = packageFragments.length; i < packagesLength; i++) {
+ if (packageFragments[i] == null)
+ continue;
+ this.nameLookup.seekTypes(className, packageFragments[i], true, type, requestor);
}
- buffer.append(subPackageName);
- boolean result =
- this.nameLookup.findPackageFragments(buffer.toString(), false) != null;
- return result;
-
}
-
- /**
- * Returns true if there are no '.' characters in the given name.
- */
- protected boolean isQualified(char[] name) {
- if (name != null) {
- return CharOperation.indexOf('.', name) > -1;
- }
+}
+/**
+ * @see SearchableBuilderEnvironment
+ */
+public boolean isPackage(char[][] parentPackageName, char[] subPackageName) {
+ if (parentPackageName == null || parentPackageName.length == 0)
+ return isTopLevelPackage(subPackageName);
+ if (subPackageName == null)
return false;
- }
-
- /**
- * @see SearchableBuilderEnvironment
- */
- public boolean isTopLevelPackage(char[] packageName) {
- if (packageName == null)
+ int length = parentPackageName.length;
+ StringBuffer buffer = new StringBuffer((length + 1) * 6);
+ for(int i = 0; i < length; i++) {
+ if (parentPackageName[i] == null || isQualified(parentPackageName[i]))
return false;
- boolean result =
- !isQualified(packageName)
- && this.nameLookup.findPackageFragments(new String(packageName), false) != null;
- return result;
-
+ buffer.append(parentPackageName[i]);
+ buffer.append('.');
}
-
- /**
- * Returns a printable string for the array.
- */
- protected String toStringChar(char[] name) {
- return "[" + new String(name) + "]";
+ if (isQualified(subPackageName)) {
+ return false;
}
-
- /**
- * Returns a printable string for the array.
- */
- protected String toStringCharChar(char[][] names) {
- StringBuffer result = new StringBuffer();
- for (int i = 0; i < names.length; i++) {
- result.append(toStringChar(names[i]));
- }
- return result.toString();
+ buffer.append(subPackageName);
+ boolean result= this.nameLookup.findPackageFragments(buffer.toString(), false) != null;
+ return result;
+
+}
+/**
+ * Returns true if there are no '.' characters in the given name.
+ */
+protected boolean isQualified(char[] name) {
+ if (name != null) {
+ return CharOperation.indexOf('.', name) > -1;
}
+ return false;
+}
+/**
+ * @see SearchableBuilderEnvironment
+ */
+public boolean isTopLevelPackage(char[] packageName) {
+ if (packageName == null)
+ return false;
+ boolean result= !isQualified(packageName)
+ && this.nameLookup.findPackageFragments(new String(packageName), false) != null;
+ return result;
}
+/**
+ * Returns a printable string for the array.
+ */
+protected String toStringChar(char[] name) {
+ return "["/*nonNLS*/ + new String(name) + "]"/*nonNLS*/;
+}
+/**
+ * Returns a printable string for the array.
+ */
+protected String toStringCharChar(char[][] names) {
+ StringBuffer result= new StringBuffer();
+ for (int i= 0; i < names.length; i++) {
+ result.append(toStringChar(names[i]));
+ }
+ return result.toString();
+}
+}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SearchableEnvironmentRequestor.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SearchableEnvironmentRequestor.java
index b979876025..87445d6c47 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SearchableEnvironmentRequestor.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SearchableEnvironmentRequestor.java
@@ -15,9 +15,7 @@ import org.eclipse.jdt.core.JavaModelException;
* Implements <code>IJavaElementRequestor</code>, wrappering and forwarding
* results onto a <code>org.eclipse.jdt.internal.codeassist.api.ISearchRequestor</code>.
*/
-class SearchableEnvironmentRequestor
- extends JavaElementRequestor
- implements IJavaElementRequestor {
+class SearchableEnvironmentRequestor extends JavaElementRequestor implements IJavaElementRequestor {
/**
* The <code>ISearchRequestor</code> this JavaElementRequestor wraps
* and forwards results to.
@@ -28,65 +26,52 @@ class SearchableEnvironmentRequestor
* accept types within.
*/
protected ICompilationUnit fUnitToSkip;
- /**
- * Constructs a SearchableEnvironmentRequestor that wraps the
- * given SearchRequestor.
- */
- public SearchableEnvironmentRequestor(ISearchRequestor requestor) {
- fRequestor = requestor;
- fUnitToSkip = null;
- }
-
- /**
- * Constructs a SearchableEnvironmentRequestor that wraps the
- * given SearchRequestor. The requestor will not accept types in
- * the <code>unitToSkip</code>.
- */
- public SearchableEnvironmentRequestor(
- ISearchRequestor requestor,
- ICompilationUnit unitToSkip) {
- fRequestor = requestor;
- fUnitToSkip = unitToSkip;
- }
-
- /**
- * Do nothing, a SearchRequestor does not accept initializers
- * so there is no need to forward this results.
- *
- * @see IJavaElementRequestor
- */
- public void acceptInitializer(IInitializer initializer) {
-
- }
-
- /**
- * @see IJavaElementRequestor
- */
- public void acceptPackageFragment(IPackageFragment packageFragment) {
- fRequestor.acceptPackage(packageFragment.getElementName().toCharArray());
- }
+/**
+ * Constructs a SearchableEnvironmentRequestor that wraps the
+ * given SearchRequestor.
+ */
+public SearchableEnvironmentRequestor(ISearchRequestor requestor) {
+ fRequestor = requestor;
+ fUnitToSkip= null;
+}
+/**
+ * Constructs a SearchableEnvironmentRequestor that wraps the
+ * given SearchRequestor. The requestor will not accept types in
+ * the <code>unitToSkip</code>.
+ */
+public SearchableEnvironmentRequestor(ISearchRequestor requestor, ICompilationUnit unitToSkip) {
+ fRequestor = requestor;
+ fUnitToSkip= unitToSkip;
+}
+/**
+ * Do nothing, a SearchRequestor does not accept initializers
+ * so there is no need to forward this results.
+ *
+ * @see IJavaElementRequestor
+ */
+public void acceptInitializer(IInitializer initializer) {
- /**
- * @see IJavaElementRequestor
- */
- public void acceptType(IType type) {
- try {
- if (fUnitToSkip != null && fUnitToSkip.equals(type.getCompilationUnit())) {
- return;
- }
- if (type.isClass()) {
- fRequestor.acceptClass(
- type.getPackageFragment().getElementName().toCharArray(),
- type.getElementName().toCharArray(),
- type.getFlags());
- } else {
- fRequestor.acceptInterface(
- type.getPackageFragment().getElementName().toCharArray(),
- type.getElementName().toCharArray(),
- type.getFlags());
- }
- } catch (JavaModelException npe) {
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptPackageFragment(IPackageFragment packageFragment) {
+ fRequestor.acceptPackage(packageFragment.getElementName().toCharArray());
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptType(IType type) {
+ try {
+ if (fUnitToSkip != null && fUnitToSkip.equals(type.getCompilationUnit())){
+ return;
+ }
+ if (type.isClass()) {
+ fRequestor.acceptClass(type.getPackageFragment().getElementName().toCharArray(), type.getElementName().toCharArray(), type.getFlags());
+ } else {
+ fRequestor.acceptInterface(type.getPackageFragment().getElementName().toCharArray(), type.getElementName().toCharArray(), type.getFlags());
}
+ } catch (JavaModelException npe) {
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SelectionRequestor.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SelectionRequestor.java
index 3a48ffc6a4..bc94fbc0b3 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SelectionRequestor.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SelectionRequestor.java
@@ -19,7 +19,7 @@ public class SelectionRequestor implements ISelectionRequestor {
/**
* The name lookup facility used to resolve packages
*/
- protected INameLookup fNameLookup = null;
+ protected INameLookup fNameLookup= null;
/**
* Fix for 1FVXGDK
@@ -31,287 +31,219 @@ public class SelectionRequestor implements ISelectionRequestor {
/**
* The collection of resolved elements.
*/
- protected IJavaElement[] fElements = fgEmptyElements;
+ protected IJavaElement[] fElements= fgEmptyElements;
/**
* Empty collection used for efficiency.
*/
- protected static IJavaElement[] fgEmptyElements = new IJavaElement[] {
- };
-
- /**
- * Creates a selection requestor that uses that given
- * name lookup facility to resolve names.
- *
- * Fix for 1FVXGDK
- */
- public SelectionRequestor(INameLookup nameLookup, IJavaElement codeResolve) {
- super();
- fNameLookup = nameLookup;
- fCodeResolve = codeResolve;
- }
-
- /**
- * Resolve the binary method
- *
- * fix for 1FWFT6Q
- */
- protected void acceptBinaryMethod(
- IType type,
- char[] selector,
- char[][] parameterPackageNames,
- char[][] parameterTypeNames) {
- String[] parameterTypes = null;
- if (parameterTypeNames != null) {
- parameterTypes = new String[parameterTypeNames.length];
- for (int i = 0, max = parameterTypeNames.length; i < max; i++) {
- String pkg = IPackageFragment.DEFAULT_PACKAGE_NAME;
- if (parameterPackageNames[i] != null && parameterPackageNames[i].length > 0) {
- pkg = new String(parameterPackageNames[i]) + ".";
- }
- parameterTypes[i] =
- Signature.createTypeSignature(pkg + new String(parameterTypeNames[i]), true);
+ protected static IJavaElement[] fgEmptyElements = new IJavaElement[]{};
+/**
+ * Creates a selection requestor that uses that given
+ * name lookup facility to resolve names.
+ *
+ * Fix for 1FVXGDK
+ */
+public SelectionRequestor(INameLookup nameLookup, IJavaElement codeResolve) {
+ super();
+ fNameLookup = nameLookup;
+ fCodeResolve = codeResolve;
+}
+/**
+ * Resolve the binary method
+ *
+ * fix for 1FWFT6Q
+ */
+protected void acceptBinaryMethod(IType type, char[] selector, char[][] parameterPackageNames, char[][] parameterTypeNames) {
+ String[] parameterTypes= null;
+ if (parameterTypeNames != null) {
+ parameterTypes= new String[parameterTypeNames.length];
+ for (int i= 0, max = parameterTypeNames.length; i < max; i++) {
+ String pkg = IPackageFragment.DEFAULT_PACKAGE_NAME;
+ if (parameterPackageNames[i] != null && parameterPackageNames[i].length > 0) {
+ pkg = new String(parameterPackageNames[i]) + "."/*nonNLS*/;
}
+ parameterTypes[i]= Signature.createTypeSignature(
+ pkg + new String(parameterTypeNames[i]), true);
}
- IMethod method = type.getMethod(new String(selector), parameterTypes);
- if (method.exists()) {
- fElements = growAndAddToArray(fElements, method);
- }
- }
-
- /**
- * Resolve the class.
- */
- public void acceptClass(
- char[] packageName,
- char[] className,
- boolean needQualification) {
- acceptType(
- packageName,
- className,
- INameLookup.ACCEPT_CLASSES,
- needQualification);
}
-
- /**
- * Do nothing.
- */
- public void acceptError(IProblem error) {
+ IMethod method= type.getMethod(new String(selector), parameterTypes);
+ if (method.exists()) {
+ fElements = growAndAddToArray(fElements, method);
}
-
- /**
- * Resolve the field.
- */
- public void acceptField(
- char[] declaringTypePackageName,
- char[] declaringTypeName,
- char[] name) {
- IType type =
- resolveType(
- declaringTypePackageName,
- declaringTypeName,
- INameLookup.ACCEPT_CLASSES | INameLookup.ACCEPT_INTERFACES);
- if (type != null) {
- IField field = type.getField(new String(name));
- if (field.exists()) {
- fElements = growAndAddToArray(fElements, field);
- }
+}
+/**
+ * Resolve the class.
+ */
+public void acceptClass(char[] packageName, char[] className, boolean needQualification) {
+ acceptType(packageName, className, INameLookup.ACCEPT_CLASSES, needQualification);
+}
+/**
+ * Do nothing.
+ */
+public void acceptError(IProblem error) {}
+/**
+ * Resolve the field.
+ */
+public void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, char[] name) {
+ IType type= resolveType(declaringTypePackageName, declaringTypeName,
+ INameLookup.ACCEPT_CLASSES | INameLookup.ACCEPT_INTERFACES);
+ if (type != null) {
+ IField field= type.getField(new String(name));
+ if (field.exists()) {
+ fElements= growAndAddToArray(fElements, field);
}
}
-
- /**
- * Resolve the interface
- */
- public void acceptInterface(
- char[] packageName,
- char[] interfaceName,
- boolean needQualification) {
- acceptType(
- packageName,
- interfaceName,
- INameLookup.ACCEPT_INTERFACES,
- needQualification);
- }
-
- /**
- * Resolve the method
- */
- public void acceptMethod(
- char[] declaringTypePackageName,
- char[] declaringTypeName,
- char[] selector,
- char[][] parameterPackageNames,
- char[][] parameterTypeNames) {
- IType type =
- resolveType(
- declaringTypePackageName,
- declaringTypeName,
- INameLookup.ACCEPT_CLASSES | INameLookup.ACCEPT_INTERFACES);
- // fix for 1FWFT6Q
- if (type != null) {
- if (type.isBinary()) {
- acceptBinaryMethod(type, selector, parameterPackageNames, parameterTypeNames);
- } else {
- acceptSourceMethod(type, selector, parameterPackageNames, parameterTypeNames);
- }
+}
+/**
+ * Resolve the interface
+ */
+public void acceptInterface(char[] packageName, char[] interfaceName, boolean needQualification) {
+ acceptType(packageName, interfaceName, INameLookup.ACCEPT_INTERFACES, needQualification);
+}
+/**
+ * Resolve the method
+ */
+public void acceptMethod(char[] declaringTypePackageName, char[] declaringTypeName, char[] selector, char[][] parameterPackageNames, char[][] parameterTypeNames) {
+ IType type= resolveType(declaringTypePackageName, declaringTypeName,
+ INameLookup.ACCEPT_CLASSES | INameLookup.ACCEPT_INTERFACES);
+ // fix for 1FWFT6Q
+ if (type != null) {
+ if (type.isBinary()) {
+ acceptBinaryMethod(type, selector, parameterPackageNames, parameterTypeNames);
+ } else {
+ acceptSourceMethod(type, selector, parameterPackageNames, parameterTypeNames);
}
}
-
- /**
- * Resolve the package
- */
- public void acceptPackage(char[] packageName) {
- IPackageFragment[] pkgs =
- fNameLookup.findPackageFragments(new String(packageName), false);
- if (pkgs != null) {
- for (int i = 0, length = pkgs.length; i < length; i++) {
- fElements = growAndAddToArray(fElements, pkgs[i]);
- }
+}
+/**
+ * Resolve the package
+ */
+public void acceptPackage(char[] packageName) {
+ IPackageFragment[] pkgs = fNameLookup.findPackageFragments(new String(packageName), false);
+ if (pkgs != null) {
+ for (int i = 0, length = pkgs.length; i < length; i++) {
+ fElements = growAndAddToArray(fElements, pkgs[i]);
}
}
-
- /**
- * Resolve the source method
- *
- * fix for 1FWFT6Q
- */
- protected void acceptSourceMethod(
- IType type,
- char[] selector,
- char[][] parameterPackageNames,
- char[][] parameterTypeNames) {
- String name = new String(selector);
- IMethod[] methods = null;
- try {
- methods = type.getMethods();
- } catch (JavaModelException e) {
- return;
- }
- IJavaElement[] matches = new IJavaElement[] {
- };
- for (int i = 0; i < methods.length; i++) {
- if (methods[i].getElementName().equals(name)
- && methods[i].getParameterTypes().length == parameterTypeNames.length) {
- matches = growAndAddToArray(matches, methods[i]);
- }
+}
+/**
+ * Resolve the source method
+ *
+ * fix for 1FWFT6Q
+ */
+protected void acceptSourceMethod(IType type, char[] selector, char[][] parameterPackageNames, char[][] parameterTypeNames) {
+ String name = new String(selector);
+ IMethod[] methods = null;
+ try {
+ methods = type.getMethods();
+ } catch (JavaModelException e) {
+ return;
+ }
+ IJavaElement[] matches = new IJavaElement[] {};
+ for (int i = 0; i < methods.length; i++) {
+ if (methods[i].getElementName().equals(name) && methods[i].getParameterTypes().length == parameterTypeNames.length) {
+ matches = growAndAddToArray(matches, methods[i]);
}
+ }
- // if no matches, nothing to report
- if (matches.length == 0) {
- return;
- }
+ // if no matches, nothing to report
+ if (matches.length == 0) {
+ return;
+ }
- // if there is only one match, we've got it
- if (matches.length == 1) {
- fElements = growAndAddToArray(fElements, matches[0]);
- return;
- }
+ // if there is only one match, we've got it
+ if (matches.length == 1) {
+ fElements = growAndAddToArray(fElements, matches[0]);
+ return;
+ }
- // more than one match - must match simple parameter types
- for (int i = 0; i < matches.length; i++) {
- IMethod method = (IMethod) matches[i];
- String[] signatures = method.getParameterTypes();
- boolean match = true;
- for (int p = 0; p < signatures.length; p++) {
- String simpleName = Signature.getSimpleName(Signature.toString(signatures[p]));
- if (!simpleName.equals(new String(parameterTypeNames[p]))) {
- match = false;
- break;
- }
- }
- if (match) {
- fElements = growAndAddToArray(fElements, method);
+ // more than one match - must match simple parameter types
+ for (int i = 0; i < matches.length; i++) {
+ IMethod method= (IMethod)matches[i];
+ String[] signatures = method.getParameterTypes();
+ boolean match= true;
+ for (int p = 0; p < signatures.length; p++) {
+ String simpleName= Signature.getSimpleName(Signature.toString(signatures[p]));
+ if (!simpleName.equals(new String(parameterTypeNames[p]))) {
+ match = false;
+ break;
}
}
-
- }
-
- /**
- * Resolve the type, adding to the resolved elements.
- */
- protected void acceptType(
- char[] packageName,
- char[] typeName,
- int acceptFlags,
- boolean needQualification) {
- IType type = resolveType(packageName, typeName, acceptFlags);
- if (type != null) {
- fElements = growAndAddToArray(fElements, type);
+ if (match) {
+ fElements = growAndAddToArray(fElements, method);
}
-
- }
-
- /**
- * Returns the resolved elements.
- */
- public IJavaElement[] getElements() {
- return fElements;
}
-
- /**
- * Adds the new element to a new array that contains all of the elements of the old array.
- * Returns the new array.
- */
- protected IJavaElement[] growAndAddToArray(
- IJavaElement[] array,
- IJavaElement addition) {
- IJavaElement[] old = array;
- array = new IJavaElement[old.length + 1];
- System.arraycopy(old, 0, array, 0, old.length);
- array[old.length] = addition;
- return array;
+
+}
+/**
+ * Resolve the type, adding to the resolved elements.
+ */
+protected void acceptType(char[] packageName, char[] typeName, int acceptFlags, boolean needQualification) {
+ IType type= resolveType(packageName, typeName, acceptFlags);
+ if (type != null) {
+ fElements= growAndAddToArray(fElements, type);
}
-
- /**
- * Resolve the type
- */
- protected IType resolveType(
- char[] packageName,
- char[] typeName,
- int acceptFlags) {
- //fix for 1FVXGDK
- IType type = null;
- if (packageName == null || packageName.length == 0) {
- // default package
- type = fNameLookup.findType(new String(typeName), false, acceptFlags);
- } else {
- IPackageFragment[] pkgs =
- fNameLookup.findPackageFragments(new String(packageName), false);
- if (pkgs != null) {
- for (int i = 0, length = pkgs.length; i < length; i++) {
- type = fNameLookup.findType(new String(typeName), pkgs[i], false, acceptFlags);
- if (type != null)
- break;
- }
+
+}
+/**
+ * Returns the resolved elements.
+ */
+public IJavaElement[] getElements() {
+ return fElements;
+}
+/**
+ * Adds the new element to a new array that contains all of the elements of the old array.
+ * Returns the new array.
+ */
+protected IJavaElement[] growAndAddToArray(IJavaElement[] array, IJavaElement addition) {
+ IJavaElement[] old = array;
+ array = new IJavaElement[old.length + 1];
+ System.arraycopy(old, 0, array, 0, old.length);
+ array[old.length] = addition;
+ return array;
+}
+/**
+ * Resolve the type
+ */
+protected IType resolveType(char[] packageName, char[] typeName, int acceptFlags) {
+ //fix for 1FVXGDK
+ IType type= null;
+ if (packageName == null || packageName.length == 0) {
+ // default package
+ type= fNameLookup.findType(new String(typeName), false, acceptFlags);
+ } else {
+ IPackageFragment[] pkgs = fNameLookup.findPackageFragments(new String(packageName), false);
+ if (pkgs != null) {
+ for (int i = 0, length = pkgs.length; i < length; i++) {
+ type= fNameLookup.findType(new String(typeName), pkgs[i], false, acceptFlags);
+ if (type != null) break;
}
}
- if (type == null) {
- String pName = IPackageFragment.DEFAULT_PACKAGE_NAME;
- if (packageName != null) {
- pName = new String(packageName);
+ }
+ if (type == null) {
+ String pName= IPackageFragment.DEFAULT_PACKAGE_NAME;
+ if (packageName != null) {
+ pName = new String(packageName);
+ }
+ if (fCodeResolve != null && fCodeResolve.getParent().getElementName().equals(pName)) {
+ // look inside the type in which we are resolving in
+ String tName= new String(typeName);
+ tName = tName.replace('.','$');
+ IType[] allTypes= null;
+ try {
+ java.util.Vector v = ((JavaElement)fCodeResolve).getChildrenOfType(IJavaElement.TYPE);
+ allTypes = new IType[v.size()];
+ v.copyInto(allTypes);
+ } catch (JavaModelException e) {
+ return null;
}
- if (fCodeResolve != null
- && fCodeResolve.getParent().getElementName().equals(pName)) {
- // look inside the type in which we are resolving in
- String tName = new String(typeName);
- tName = tName.replace('.', '$');
- IType[] allTypes = null;
- try {
- java.util.Vector v =
- ((JavaElement) fCodeResolve).getChildrenOfType(IJavaElement.TYPE);
- allTypes = new IType[v.size()];
- v.copyInto(allTypes);
- } catch (JavaModelException e) {
- return null;
- }
- for (int i = 0; i < allTypes.length; i++) {
- if (allTypes[i].getTypeQualifiedName().equals(tName)) {
- return allTypes[i];
- }
+ for (int i= 0; i < allTypes.length; i++) {
+ if (allTypes[i].getTypeQualifiedName().equals(tName)) {
+ return allTypes[i];
}
}
}
- return type;
}
-
+ return type;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SetClasspathOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SetClasspathOperation.java
index 323fc06bbd..8e622e34dd 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SetClasspathOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SetClasspathOperation.java
@@ -14,33 +14,25 @@ import org.eclipse.jdt.core.*;
* @see IJavaProject
*/
public class SetClasspathOperation extends JavaModelOperation {
- IClasspathEntry[] oldResolvedPath;
+ IClasspathEntry[] oldResolvedPath;
IClasspathEntry[] newRawPath;
boolean saveClasspath;
- /**
- * When executed, this operation sets the classpath of the given project.
- */
- public SetClasspathOperation(
- IJavaProject project,
- IClasspathEntry[] oldResolvedPath,
- IClasspathEntry[] newRawPath,
- boolean saveClasspath) {
- super(new IJavaElement[] { project });
- this.oldResolvedPath = oldResolvedPath;
- this.newRawPath = newRawPath;
- this.saveClasspath = saveClasspath;
- }
-
+/**
+ * When executed, this operation sets the classpath of the given project.
+ */
+public SetClasspathOperation(IJavaProject project, IClasspathEntry[] oldResolvedPath, IClasspathEntry[] newRawPath, boolean saveClasspath) {
+ super(new IJavaElement[] {project});
+ this.oldResolvedPath = oldResolvedPath;
+ this.newRawPath = newRawPath;
+ this.saveClasspath = saveClasspath;
+}
/**
* Adds deltas for the given roots, with the specified change flag,
* and closes the root. Helper method for #setClasspath
*/
- protected void addDeltas(
- IPackageFragmentRoot[] roots,
- int flag,
- JavaElementDelta delta) {
- for (int i = 0; i < roots.length; i++) {
- IPackageFragmentRoot root = roots[i];
+ protected void addDeltas(IPackageFragmentRoot[] roots, int flag, JavaElementDelta delta) {
+ for (int i= 0; i < roots.length; i++) {
+ IPackageFragmentRoot root= roots[i];
delta.changed(root, flag);
try {
root.close();
@@ -48,209 +40,168 @@ public class SetClasspathOperation extends JavaModelOperation {
}
}
}
-
/**
* Returns the index of the item in the list if the given list contains the specified entry. If the list does
* not contain the entry, -1 is returned.
* A helper method for #setClasspath
*/
- protected int classpathContains(
- IClasspathEntry[] list,
- IClasspathEntry entry) {
- for (int i = 0; i < list.length; i++) {
+ protected int classpathContains(IClasspathEntry[] list, IClasspathEntry entry) {
+ for (int i= 0; i < list.length; i++) {
if (list[i].equals(entry)) {
return i;
}
}
return -1;
}
-
- /**
- * Sets the classpath of the pre-specified project.
- */
- protected void executeOperation() throws JavaModelException {
- beginTask("Setting classpath...", 2);
- JavaProject project = ((JavaProject) getElementsToProcess()[0]);
-
- project.setRawClasspath0(this.newRawPath);
-
- // change builder specs to build in the order given by the new classpath
- JavaModelManager manager = project.getJavaModelManager();
- manager.setBuildOrder(
- ((JavaModel) project.getJavaModel()).computeBuildOrder(true));
-
- if (this.oldResolvedPath != null) {
- generateClasspathChangeDeltas(
- this.oldResolvedPath,
- project.getResolvedClasspath(true),
- manager,
- project);
- } else {
- project.saveClasspath(this.saveClasspath);
- }
-
- done();
+/**
+ * Sets the classpath of the pre-specified project.
+ */
+protected void executeOperation() throws JavaModelException {
+ beginTask(Util.bind("classpath.settingProgress"/*nonNLS*/), 2);
+ JavaProject project= ((JavaProject) getElementsToProcess()[0]);
+
+ project.setRawClasspath0(this.newRawPath);
+
+ // change builder specs to build in the order given by the new classpath
+ JavaModelManager manager = project.getJavaModelManager();
+ manager.setBuildOrder(((JavaModel) project.getJavaModel()).computeBuildOrder(true));
+
+ // flush markers
+ project.flushClasspathProblemMarkers();
+
+ // resolve new path (asking for marker creation if problems)
+ IClasspathEntry[] newResolvedPath = project.getResolvedClasspath(true, true);
+
+ if (this.oldResolvedPath != null) {
+ generateClasspathChangeDeltas(this.oldResolvedPath, newResolvedPath, manager, project);
+ } else {
+ project.saveClasspath(this.saveClasspath);
}
+ done();
+}
/**
* Generates the delta of removed/added/reordered roots.
* Use three deltas in case the same root is removed/added/reordered (i.e. changed from
* K_SOURCE to K_BINARY or visa versa)
*/
- protected void generateClasspathChangeDeltas(
- IClasspathEntry[] oldResolvedPath,
- IClasspathEntry[] newResolvedPath,
- JavaModelManager manager,
- JavaProject project) {
+ protected void generateClasspathChangeDeltas(IClasspathEntry[] oldResolvedPath, IClasspathEntry[] newResolvedPath, JavaModelManager manager, JavaProject project) {
boolean hasChangedSourceEntries = false;
-
- JavaElementDelta delta = new JavaElementDelta(getJavaModel());
+
+ JavaElementDelta delta= new JavaElementDelta(getJavaModel());
boolean hasDelta = false;
- boolean oldResolvedPathLongest =
- oldResolvedPath.length >= newResolvedPath.length;
- for (int i = 0; i < oldResolvedPath.length; i++) {
- int index = classpathContains(newResolvedPath, oldResolvedPath[i]);
+ boolean oldResolvedPathLongest= oldResolvedPath.length >= newResolvedPath.length;
+ for (int i= 0; i < oldResolvedPath.length; i++) {
+ int index= classpathContains(newResolvedPath, oldResolvedPath[i]);
if (index == -1) {
- IPackageFragmentRoot[] pkgFragmentRoots =
- project.getPackageFragmentRoots(oldResolvedPath[i]);
+ IPackageFragmentRoot[] pkgFragmentRoots = project.getPackageFragmentRoots(oldResolvedPath[i]);
addDeltas(pkgFragmentRoots, IJavaElementDelta.F_REMOVED_FROM_CLASSPATH, delta);
- hasChangedSourceEntries |= oldResolvedPath[i].getEntryKind()
- == IClasspathEntry.CPE_SOURCE;
+ hasChangedSourceEntries |= oldResolvedPath[i].getEntryKind() == IClasspathEntry.CPE_SOURCE;
// force detach source on jar package fragment roots (source will be lazily computed when needed)
for (int j = 0, length = pkgFragmentRoots.length; j < length; j++) {
IPackageFragmentRoot root = pkgFragmentRoots[j];
if (root instanceof JarPackageFragmentRoot) {
- JarPackageFragmentRoot jarRoot = (JarPackageFragmentRoot) root;
+ JarPackageFragmentRoot jarRoot = (JarPackageFragmentRoot)root;
try {
- jarRoot.getWorkspace().getRoot().setPersistentProperty(
- jarRoot.getSourceAttachmentPropertyName(),
- null);
- // loose info - will be recomputed
- } catch (CoreException ce) {
+ jarRoot.getWorkspace().getRoot().setPersistentProperty(jarRoot.getSourceAttachmentPropertyName(), null); // loose info - will be recomputed
+ } catch(CoreException ce){
}
}
}
-
+
hasDelta = true;
- } else
- if (oldResolvedPathLongest && index != i) { //reordering of the classpath
- addDeltas(
- project.getPackageFragmentRoots(oldResolvedPath[i]),
- IJavaElementDelta.F_CLASSPATH_REORDER,
- delta);
- hasChangedSourceEntries |= oldResolvedPath[i].getEntryKind()
- == IClasspathEntry.CPE_SOURCE;
- hasDelta = true;
- }
+ } else if (oldResolvedPathLongest && index != i) { //reordering of the classpath
+ addDeltas(project.getPackageFragmentRoots(oldResolvedPath[i]), IJavaElementDelta.F_CLASSPATH_REORDER, delta);
+ hasChangedSourceEntries |= oldResolvedPath[i].getEntryKind() == IClasspathEntry.CPE_SOURCE;
+ hasDelta = true;
+ }
}
- for (int i = 0; i < newResolvedPath.length; i++) {
- int index = classpathContains(oldResolvedPath, newResolvedPath[i]);
+ for (int i= 0; i < newResolvedPath.length; i++) {
+ int index= classpathContains(oldResolvedPath, newResolvedPath[i]);
if (index == -1) {
- addDeltas(
- project.getPackageFragmentRoots(newResolvedPath[i]),
- IJavaElementDelta.F_ADDED_TO_CLASSPATH,
- delta);
- hasChangedSourceEntries |= newResolvedPath[i].getEntryKind()
- == IClasspathEntry.CPE_SOURCE;
+ addDeltas(project.getPackageFragmentRoots(newResolvedPath[i]), IJavaElementDelta.F_ADDED_TO_CLASSPATH, delta);
+ hasChangedSourceEntries |= newResolvedPath[i].getEntryKind() == IClasspathEntry.CPE_SOURCE;
hasDelta = true;
- } else
- if (!oldResolvedPathLongest && index != i) { //reordering of the classpath
- addDeltas(
- project.getPackageFragmentRoots(newResolvedPath[i]),
- IJavaElementDelta.F_CLASSPATH_REORDER,
- delta);
- hasChangedSourceEntries |= newResolvedPath[i].getEntryKind()
- == IClasspathEntry.CPE_SOURCE;
- hasDelta = true;
- }
+ } else if (!oldResolvedPathLongest && index != i) { //reordering of the classpath
+ addDeltas(project.getPackageFragmentRoots(newResolvedPath[i]), IJavaElementDelta.F_CLASSPATH_REORDER, delta);
+ hasChangedSourceEntries |= newResolvedPath[i].getEntryKind() == IClasspathEntry.CPE_SOURCE;
+ hasDelta = true;
+ }
}
if (hasDelta) {
try {
project.saveClasspath(this.saveClasspath);
- } catch (JavaModelException e) {
+ } catch(JavaModelException e){
}
this.addDelta(delta);
// loose all built state - next build will be a full one
manager.setLastBuiltState(project.getProject(), null);
- if (hasChangedSourceEntries)
- updateAffectedProjects(project.getProject().getFullPath());
+ if (hasChangedSourceEntries) updateAffectedProjects(project.getProject().getFullPath());
}
}
-
- /**
- * Possible failures: <ul>
- * <li>NO_ELEMENTS_TO_PROCESS - the project supplied to the operation is
- * <code>null</code>.
- * <li>NULL_PATH - the output location path supplied to the operation
- * is <code>null</code>.
- * <li>PATH_OUTSIDE_PROJECT - the output location path supplied to the operation
- * is outside of the project supplied to this operation.
- * <li>DEVICE_PATH - the path supplied to this operation must not specify a
- * device
- * <li>RELATIVE_PATH - the path supplied to this operation must be
- * an absolute path
- * <li>INVALID_PATH - the output location cannot overlap any package fragment
- * root, except the project folder.
- * <li>ELEMENT_DOES_NOT_EXIST - the Java project does not exist
- * </ul>
- */
- public IJavaModelStatus verify() {
- IJavaModelStatus status = super.verify();
- if (!status.isOK()) {
- return status;
- }
- IClasspathEntry[] cp = this.newRawPath;
- IJavaProject javaProject = (IJavaProject) getElementToProcess();
- IPath projectPath = javaProject.getProject().getFullPath();
-
- IPath outputLocation;
- try {
- outputLocation = javaProject.getOutputLocation();
- } catch (JavaModelException e) {
- return e.getJavaModelStatus();
- }
- for (int i = 0; i < cp.length; i++) {
- if (cp[i].getEntryKind() == IClasspathEntry.CPE_SOURCE) {
- IPath entry = cp[i].getPath();
- if (!entry.equals(projectPath)
- && !entry.equals(outputLocation)
- && (outputLocation.isPrefixOf(entry) || entry.isPrefixOf(outputLocation))) {
- return new JavaModelStatus(IJavaModelStatusConstants.INVALID_PATH, entry);
- }
- }
- }
- return JavaModelStatus.VERIFIED_OK;
+/**
+ * Possible failures: <ul>
+ * <li>NO_ELEMENTS_TO_PROCESS - the project supplied to the operation is
+ * <code>null</code>.
+ * <li>NULL_PATH - the output location path supplied to the operation
+ * is <code>null</code>.
+ * <li>PATH_OUTSIDE_PROJECT - the output location path supplied to the operation
+ * is outside of the project supplied to this operation.
+ * <li>DEVICE_PATH - the path supplied to this operation must not specify a
+ * device
+ * <li>RELATIVE_PATH - the path supplied to this operation must be
+ * an absolute path
+ * <li>INVALID_PATH - the output location cannot overlap any package fragment
+ * root, except the project folder.
+ * <li>ELEMENT_DOES_NOT_EXIST - the Java project does not exist
+ * </ul>
+ */
+public IJavaModelStatus verify() {
+ IJavaModelStatus status = super.verify();
+ if (!status.isOK()) {
+ return status;
+ }
+ IJavaProject javaProject = (IJavaProject)getElementToProcess();
+
+ // retrieve output location
+ IPath outputLocation;
+ try {
+ outputLocation = javaProject.getOutputLocation();
+ } catch(JavaModelException e){
+ return e.getJavaModelStatus();
}
- /**
- * Update projects which are affected by this classpath change:
- * those which refers to the current project as source
- */
- protected void updateAffectedProjects(IPath prerequisiteProjectPath) {
+ return JavaConventions.validateClasspath(javaProject, this.newRawPath, outputLocation);
+}
+
+/**
+ * Update projects which are affected by this classpath change:
+ * those which refers to the current project as source
+ */
+protected void updateAffectedProjects(IPath prerequisiteProjectPath){
- try {
- IJavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
- IJavaProject[] projects = model.getJavaProjects();
- for (int i = 0, projectCount = projects.length; i < projectCount; i++) {
- try {
- JavaProject project = (JavaProject) projects[i];
- IClasspathEntry[] classpath = project.getRawClasspath();
- for (int j = 0, entryCount = classpath.length; j < entryCount; j++) {
- IClasspathEntry entry = classpath[j];
- if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT
- && entry.getPath().equals(prerequisiteProjectPath)) {
+ try {
+ IJavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
+ IJavaProject[] projects = model.getJavaProjects();
+ for (int i = 0, projectCount = projects.length; i < projectCount; i++){
+ try {
+ JavaProject project = (JavaProject)projects[i];
+ IClasspathEntry[] classpath = project.getRawClasspath();
+ for (int j =0, entryCount = classpath.length; j < entryCount; j++){
+ IClasspathEntry entry = classpath[j];
+ if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT
+ && entry.getPath().equals(prerequisiteProjectPath)){
project.updateClassPath();
break;
}
- }
- } catch (JavaModelException e) {
}
+ } catch(JavaModelException e){
}
- } catch (JavaModelException e) {
}
+ } catch(JavaModelException e){
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SetOutputLocationOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SetOutputLocationOperation.java
index dc2c0f6896..a21411e8ef 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SetOutputLocationOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SetOutputLocationOperation.java
@@ -23,206 +23,158 @@ public class SetOutputLocationOperation extends JavaModelOperation {
* The new output location for the Java project
*/
protected IPath fOutputLocation;
- /**
- * When executed, this operation sets the output location of the given project.
- * The output location is where the builder writes <code>.class</code> files.
- */
- public SetOutputLocationOperation(IJavaProject project, IPath outputLocation) {
- super(new IJavaElement[] { project });
- fOutputLocation = outputLocation;
- }
-
- /**
- * Recursively adds all subfolders of <code>folder</code> to the given collection.
- */
- protected void collectAllSubfolders(IFolder folder, Vector collection)
- throws JavaModelException {
- try {
- IResource[] members = folder.members();
- for (int i = 0, max = members.length; i < max; i++) {
- IResource r = members[i];
- if (r.getType() == IResource.FOLDER) {
- collection.addElement(r);
- collectAllSubfolders((IFolder) r, collection);
- }
+/**
+ * When executed, this operation sets the output location of the given project.
+ * The output location is where the builder writes <code>.class</code> files.
+ */
+public SetOutputLocationOperation(IJavaProject project, IPath outputLocation) {
+ super(new IJavaElement[] {project});
+ fOutputLocation = outputLocation;
+}
+/**
+ * Recursively adds all subfolders of <code>folder</code> to the given collection.
+ */
+protected void collectAllSubfolders(IFolder folder, Vector collection) throws JavaModelException {
+ try {
+ IResource[] members= folder.members();
+ for (int i = 0, max = members.length; i < max; i++) {
+ IResource r= members[i];
+ if (r.getType() == IResource.FOLDER) {
+ collection.addElement(r);
+ collectAllSubfolders((IFolder)r, collection);
}
- } catch (CoreException e) {
- throw new JavaModelException(e);
- }
+ }
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
-
- /**
- * Returns a collection of package fragments that have been added/removed
- * as the result of changing the output location to/from the given
- * location. The collection is empty if no package fragments are
- * affected.
- */
- protected Vector determineAffectedPackageFragments(IPath location)
- throws JavaModelException {
- Vector fragments = new Vector();
- JavaProject project = ((JavaProject) getElementsToProcess()[0]);
-
- // see if this will cause any package fragments to be affected
- IWorkspace workspace = getWorkspace();
- IResource resource = null;
- if (location != null) {
- resource = workspace.getRoot().findMember(location);
- }
- if (resource != null && resource.getType() == IResource.FOLDER) {
- IFolder folder = (IFolder) resource;
- // only changes if it actually existed
- IClasspathEntry[] classpath = project.getResolvedClasspath(true);
- for (int i = 0; i < classpath.length; i++) {
- IClasspathEntry entry = classpath[i];
- IPath path = classpath[i].getPath();
- if (entry.getEntryKind() != IClasspathEntry.CPE_PROJECT
- && path.isPrefixOf(location)
- && !path.equals(location)) {
- IPackageFragmentRoot[] roots = project.getPackageFragmentRoots(classpath[i]);
- IPackageFragmentRoot root = roots[0];
- // now the output location becomes a package fragment - along with any subfolders
- Vector folders = new Vector();
- folders.addElement(folder);
- collectAllSubfolders(folder, folders);
- Enumeration elements = folders.elements();
- int segments = path.segmentCount();
- while (elements.hasMoreElements()) {
- IFolder f = (IFolder) elements.nextElement();
- IPath relativePath = f.getFullPath().removeFirstSegments(segments);
- String name = relativePath.toOSString();
- name = name.replace(File.pathSeparatorChar, '.');
- if (name.endsWith(".")) {
- name = name.substring(0, name.length() - 1);
- }
- IPackageFragment pkg = root.getPackageFragment(name);
- fragments.addElement(pkg);
+}
+/**
+ * Returns a collection of package fragments that have been added/removed
+ * as the result of changing the output location to/from the given
+ * location. The collection is empty if no package fragments are
+ * affected.
+ */
+protected Vector determineAffectedPackageFragments(IPath location) throws JavaModelException {
+ Vector fragments = new Vector();
+ JavaProject project = ((JavaProject) getElementsToProcess()[0]);
+
+ // see if this will cause any package fragments to be affected
+ IWorkspace workspace = getWorkspace();
+ IResource resource = null;
+ if (location != null) {
+ resource = workspace.getRoot().findMember(location);
+ }
+ if (resource != null && resource.getType() == IResource.FOLDER) {
+ IFolder folder = (IFolder) resource;
+ // only changes if it actually existed
+ IClasspathEntry[] classpath = project.getResolvedClasspath(true);
+ for (int i = 0; i < classpath.length; i++) {
+ IClasspathEntry entry = classpath[i];
+ IPath path = classpath[i].getPath();
+ if (entry.getEntryKind() != IClasspathEntry.CPE_PROJECT && path.isPrefixOf(location) && !path.equals(location)) {
+ IPackageFragmentRoot[] roots = project.getPackageFragmentRoots(classpath[i]);
+ IPackageFragmentRoot root = roots[0];
+ // now the output location becomes a package fragment - along with any subfolders
+ Vector folders = new Vector();
+ folders.addElement(folder);
+ collectAllSubfolders(folder, folders);
+ Enumeration elements = folders.elements();
+ int segments = path.segmentCount();
+ while (elements.hasMoreElements()) {
+ IFolder f = (IFolder) elements.nextElement();
+ IPath relativePath = f.getFullPath().removeFirstSegments(segments);
+ String name = relativePath.toOSString();
+ name = name.replace(File.pathSeparatorChar, '.');
+ if (name.endsWith("."/*nonNLS*/)) {
+ name = name.substring(0, name.length() - 1);
}
+ IPackageFragment pkg = root.getPackageFragment(name);
+ fragments.addElement(pkg);
}
}
}
- return fragments;
}
-
- /**
- * Sets the output location of the pre-specified project.
- *
- * <p>This can cause changes in package fragments - i.e. if the
- * old and new output location folder could be considered as
- * a package fragment.
- */
- protected void executeOperation() throws JavaModelException {
- beginTask("Setting output location...", 2);
- JavaProject project = ((JavaProject) getElementsToProcess()[0]);
-
- IPath oldLocation = project.getOutputLocation();
- IPath newLocation = fOutputLocation;
-
- // see if this will cause any package fragments to be added
- boolean deltaToFire = false;
- JavaElementDelta delta = newJavaElementDelta();
- Vector added = determineAffectedPackageFragments(oldLocation);
- Enumeration pkgs = added.elements();
- while (pkgs.hasMoreElements()) {
- IPackageFragment frag = (IPackageFragment) pkgs.nextElement();
- ((IPackageFragmentRoot) frag.getParent()).close();
- delta.added(frag);
- deltaToFire = true;
- }
-
- // see if this will cause any package fragments to be removed
- Vector removed = determineAffectedPackageFragments(newLocation);
- pkgs = removed.elements();
- while (pkgs.hasMoreElements()) {
- IPackageFragment frag = (IPackageFragment) pkgs.nextElement();
- ((IPackageFragmentRoot) frag.getParent()).close();
- delta.removed(frag);
- deltaToFire = true;
- }
-
- project.setOutputLocation0(fOutputLocation);
- if (deltaToFire) {
- addDelta(delta);
- }
- worked(1);
- project.saveClasspath();
- worked(1);
-
- // loose all built state - next build will be a full one
- JavaModelManager.getJavaModelManager().setLastBuiltState(
- project.getProject(),
- null);
- done();
+ return fragments;
+}
+/**
+ * Sets the output location of the pre-specified project.
+ *
+ * <p>This can cause changes in package fragments - i.e. if the
+ * old and new output location folder could be considered as
+ * a package fragment.
+ */
+protected void executeOperation() throws JavaModelException {
+ beginTask(Util.bind("classpath.settingOutputLocationProgress"/*nonNLS*/), 2);
+ JavaProject project= ((JavaProject) getElementsToProcess()[0]);
+
+ IPath oldLocation= project.getOutputLocation();
+ IPath newLocation= fOutputLocation;
+
+ // see if this will cause any package fragments to be added
+ boolean deltaToFire= false;
+ JavaElementDelta delta = newJavaElementDelta();
+ Vector added= determineAffectedPackageFragments(oldLocation);
+ Enumeration pkgs= added.elements();
+ while (pkgs.hasMoreElements()) {
+ IPackageFragment frag= (IPackageFragment)pkgs.nextElement();
+ ((IPackageFragmentRoot)frag.getParent()).close();
+ delta.added(frag);
+ deltaToFire = true;
}
- /**
- * Possible failures: <ul>
- * <li>NO_ELEMENTS_TO_PROCESS - the project supplied to the operation is
- * <code>null</code>.
- * <li>NULL_PATH - the output location path supplied to the operation
- * is <code>null</code>.
- * <li>PATH_OUTSIDE_PROJECT - the output location path supplied to the operation
- * is outside of the project supplied to this operation.
- * <li>DEVICE_PATH - the path supplied to this operation must not specify a
- * device
- * <li>RELATIVE_PATH - the path supplied to this operation must be
- * an absolute path
- * <li>INVALID_PATH - the output location cannot overlap any package fragment
- * root, except the project folder.
- * <li>ELEMENT_DOES_NOT_EXIST - the Java project does not exist
- * </ul>
- */
- public IJavaModelStatus verify() {
- IJavaModelStatus status = super.verify();
- if (!status.isOK()) {
- return status;
- }
- if (fOutputLocation == null) {
- return new JavaModelStatus(IJavaModelStatusConstants.NULL_PATH);
- }
-
- if (fOutputLocation.isAbsolute()) {
- IProject project = ((IJavaProject) fElementsToProcess[0]).getProject();
-
- if (project.getFullPath().isPrefixOf(fOutputLocation)) {
- //project relative path
- String projectName = fOutputLocation.segment(0);
- if (!projectName.equals(fElementsToProcess[0].getElementName())) {
- //a workspace relative path outside of this project
- return new JavaModelStatus(
- IJavaModelStatusConstants.PATH_OUTSIDE_PROJECT,
- fOutputLocation);
- }
- } else {
- return new JavaModelStatus(
- IJavaModelStatusConstants.DEVICE_PATH,
- fOutputLocation);
- }
- } else {
- return new JavaModelStatus(
- IJavaModelStatusConstants.RELATIVE_PATH,
- fOutputLocation);
- }
-
- IClasspathEntry[] cp = null;
- IJavaProject javaProject = (IJavaProject) getElementToProcess();
- try {
- cp = javaProject.getResolvedClasspath(true);
- } catch (JavaModelException e) {
- return e.getJavaModelStatus();
- }
- IPath projectPath = javaProject.getProject().getFullPath();
- for (int i = 0; i < cp.length; i++) {
- IPath entry = cp[i].getPath();
- if (!entry.equals(projectPath)
- && !entry.equals(fOutputLocation)
- && (fOutputLocation.isPrefixOf(entry) || entry.isPrefixOf(fOutputLocation))) {
- return new JavaModelStatus(
- IJavaModelStatusConstants.INVALID_PATH,
- fOutputLocation);
- }
- }
-
- return JavaModelStatus.VERIFIED_OK;
+ // see if this will cause any package fragments to be removed
+ Vector removed= determineAffectedPackageFragments(newLocation);
+ pkgs= removed.elements();
+ while (pkgs.hasMoreElements()) {
+ IPackageFragment frag= (IPackageFragment)pkgs.nextElement();
+ ((IPackageFragmentRoot)frag.getParent()).close();
+ delta.removed(frag);
+ deltaToFire = true;
}
+
+ project.setOutputLocation0(fOutputLocation);
+ if (deltaToFire) {
+ addDelta(delta);
+ }
+ worked(1);
+ project.saveClasspath();
+ worked(1);
+ // loose all built state - next build will be a full one
+ JavaModelManager.getJavaModelManager().setLastBuiltState(project.getProject(), null);
+ done();
+}
+/**
+ * Possible failures: <ul>
+ * <li>NO_ELEMENTS_TO_PROCESS - the project supplied to the operation is
+ * <code>null</code>.
+ * <li>NULL_PATH - the output location path supplied to the operation
+ * is <code>null</code>.
+ * <li>PATH_OUTSIDE_PROJECT - the output location path supplied to the operation
+ * is outside of the project supplied to this operation.
+ * <li>DEVICE_PATH - the path supplied to this operation must not specify a
+ * device
+ * <li>RELATIVE_PATH - the path supplied to this operation must be
+ * an absolute path
+ * <li>INVALID_PATH - the output location cannot overlap any package fragment
+ * root, except the project folder.
+ * <li>ELEMENT_DOES_NOT_EXIST - the Java project does not exist
+ * </ul>
+ */
+public IJavaModelStatus verify() {
+ IJavaModelStatus status = super.verify();
+ if (!status.isOK()) {
+ return status;
+ }
+ // retrieve classpath
+ IClasspathEntry[] classpath = null;
+ IJavaProject javaProject= (IJavaProject)getElementToProcess();
+ IPath projectPath= javaProject.getProject().getFullPath();
+ try {
+ classpath = javaProject.getResolvedClasspath(true);
+ } catch (JavaModelException e) {
+ return e.getJavaModelStatus();
+ }
+ return JavaConventions.validateClasspath((IJavaProject) fElementsToProcess[0], classpath, fOutputLocation);
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SingleTypeRequestor.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SingleTypeRequestor.java
index 5218023cdc..828f723acc 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SingleTypeRequestor.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SingleTypeRequestor.java
@@ -12,70 +12,60 @@ import org.eclipse.jdt.core.*;
* The SingleTypeRequestor is an IJavaElementRequestor that
* only accepts one result element and then cancels.
*/
-/* package */
-class SingleTypeRequestor implements IJavaElementRequestor {
+/* package */ class SingleTypeRequestor implements IJavaElementRequestor {
/**
* The single accepted element
*/
- protected IType fElement = null;
- /**
- * @see IJavaElementRequestor
- */
- public void acceptField(IField field) {
- }
-
- /**
- * @see IJavaElementRequestor
- */
- public void acceptInitializer(IInitializer initializer) {
- }
-
- /**
- * @see IJavaElementRequestor
- */
- public void acceptMemberType(IType type) {
- fElement = type;
- }
-
- /**
- * @see IJavaElementRequestor
- */
- public void acceptMethod(IMethod method) {
- }
-
- /**
- * @see IJavaElementRequestor
- */
- public void acceptPackageFragment(IPackageFragment packageFragment) {
- }
-
- /**
- * @see IJavaElementRequestor
- */
- public void acceptType(IType type) {
- fElement = type;
- }
-
- /**
- * Returns the type accepted by this requestor, or <code>null</code>
- * if no type has been accepted.
- */
- public IType getType() {
- return fElement;
- }
-
- /**
- * @see IJavaElementRequestor
- */
- public boolean isCanceled() {
- return fElement != null;
- }
-
- /**
- * Reset the state of this requestor
- */
- public void reset() {
- fElement = null;
- }
-
+ protected IType fElement= null;
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptField(IField field) {
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptInitializer(IInitializer initializer) {
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptMemberType(IType type) {
+ fElement= type;
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptMethod(IMethod method) {
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptPackageFragment(IPackageFragment packageFragment) {
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public void acceptType(IType type) {
+ fElement= type;
+}
+/**
+ * Returns the type accepted by this requestor, or <code>null</code>
+ * if no type has been accepted.
+ */
+public IType getType() {
+ return fElement;
+}
+/**
+ * @see IJavaElementRequestor
+ */
+public boolean isCanceled() {
+ return fElement != null;
+}
+/**
+ * Reset the state of this requestor
+ */
+public void reset() {
+ fElement= null;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceField.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceField.java
index ae6a731e4c..00d5b06bd1 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceField.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceField.java
@@ -13,62 +13,55 @@ import org.eclipse.jdt.core.jdom.IDOMNode;
* @see IField
*/
-/* package */
-class SourceField extends Member implements IField {
+/* package */ class SourceField extends Member implements IField {
- /**
- * Constructs a handle to the field with the given name in the specified type.
- */
- protected SourceField(IType parent, String name) {
- super(FIELD, parent, name);
- }
-
- /**
- * @see JavaElement#equalsDOMNode
- */
- protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
- return (node.getNodeType() == IDOMNode.FIELD) && super.equalsDOMNode(node);
- }
-
- /**
- * @see IField
- */
- public Object getConstant() throws JavaModelException {
- SourceFieldElementInfo info = (SourceFieldElementInfo) getElementInfo();
- return convertConstant(info.getConstant());
- }
-
- /**
- * @see JavaElement#getHandleMemento()
- */
- protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_FIELD;
- }
-
- /**
- * @see IField
- */
- public String getTypeSignature() throws JavaModelException {
- SourceFieldElementInfo info = (SourceFieldElementInfo) getElementInfo();
- return info.getTypeSignature();
- }
-
- /**
- * @private Debugging purposes
- */
- protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
- if (info == null) {
- buffer.append(getElementName());
- buffer.append(" (not open)");
- } else {
- try {
- buffer.append(Signature.toString(this.getTypeSignature()));
- buffer.append(" ");
- buffer.append(this.getElementName());
- } catch (JavaModelException e) {
- buffer.append("<JavaModelException in toString of " + getElementName());
- }
+/**
+ * Constructs a handle to the field with the given name in the specified type.
+ */
+protected SourceField(IType parent, String name) {
+ super(FIELD, parent, name);
+}
+/**
+ * @see JavaElement#equalsDOMNode
+ */
+protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
+ return (node.getNodeType() == IDOMNode.FIELD) && super.equalsDOMNode(node);
+}
+/**
+ * @see IField
+ */
+public Object getConstant() throws JavaModelException {
+ SourceFieldElementInfo info = (SourceFieldElementInfo) getElementInfo();
+ return convertConstant(info.getConstant());
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+protected char getHandleMementoDelimiter() {
+ return JavaElement.JEM_FIELD;
+}
+/**
+ * @see IField
+ */
+public String getTypeSignature() throws JavaModelException {
+ SourceFieldElementInfo info = (SourceFieldElementInfo) getElementInfo();
+ return info.getTypeSignature();
+}
+/**
+ * @private Debugging purposes
+ */
+protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
+ if (info == null) {
+ buffer.append(getElementName());
+ buffer.append(" (not open)"/*nonNLS*/);
+ } else {
+ try {
+ buffer.append(Signature.toString(this.getTypeSignature()));
+ buffer.append(" "/*nonNLS*/);
+ buffer.append(this.getElementName());
+ } catch (JavaModelException e) {
+ buffer.append("<JavaModelException in toString of "/*nonNLS*/ + getElementName());
}
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceFieldElementInfo.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceFieldElementInfo.java
index 71bf433509..3fada33f53 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceFieldElementInfo.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceFieldElementInfo.java
@@ -14,64 +14,55 @@ import org.eclipse.jdt.core.Signature;
* Element info for IField elements.
*/
-/* package */
-class SourceFieldElementInfo
- extends MemberElementInfo
- implements ISourceField {
+/* package */ class SourceFieldElementInfo extends MemberElementInfo implements ISourceField {
/**
* The type name of this field.
*/
protected char[] fTypeName;
-
+
/**
* The field's constant value
*/
protected Constant fConstant;
- /**
- * Constructs an info object for the given field.
- */
- protected SourceFieldElementInfo() {
- fConstant = Constant.NotAConstant;
- }
-
- /**
- * Returns the constant associated with this field or
- * Constant.NotAConstant if the field is not constant.
- */
- public Constant getConstant() {
- return fConstant;
- }
-
- /**
- * Returns the type name of the field.
- */
- public char[] getTypeName() {
- return fTypeName;
- }
-
- /**
- * Returns the type signature of the field.
- *
- * @see Signature
- */
- protected String getTypeSignature() {
- return Signature.createTypeSignature(fTypeName, false);
- }
-
- /**
- * Returns the constant associated with this field or
- * Constant.NotAConstant if the field is not constant.
- */
- public void setConstant(Constant constant) {
- fConstant = constant;
- }
-
- /**
- * Sets the type name of the field.
- */
- protected void setTypeName(char[] typeName) {
- fTypeName = typeName;
- }
-
+/**
+ * Constructs an info object for the given field.
+ */
+protected SourceFieldElementInfo() {
+ fConstant = Constant.NotAConstant;
+}
+/**
+ * Returns the constant associated with this field or
+ * Constant.NotAConstant if the field is not constant.
+ */
+public Constant getConstant() {
+ return fConstant;
+}
+/**
+ * Returns the type name of the field.
+ */
+public char[] getTypeName() {
+ return fTypeName;
+}
+/**
+ * Returns the type signature of the field.
+ *
+ * @see Signature
+ */
+protected String getTypeSignature() {
+ return Signature.createTypeSignature(fTypeName, false);
+}
+/**
+ * Returns the constant associated with this field or
+ * Constant.NotAConstant if the field is not constant.
+ */
+public void setConstant(Constant constant) {
+ fConstant = constant;
+}
+/**
+ * Sets the type name of the field.
+ */
+protected void setTypeName(char[] typeName) {
+ fTypeName= typeName;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMapper.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMapper.java
index 9ab52b83f9..b38372f52a 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMapper.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMapper.java
@@ -19,6 +19,8 @@ import org.eclipse.jdt.core.*;
import org.eclipse.jdt.internal.compiler.*;
import org.eclipse.jdt.internal.core.util.ReferenceInfoAdapter;
+import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
+
/**
* A SourceMapper maps source code in a ZIP file to binary types in
* a JAR. The SourceMapper uses the fuzzy parser to identify source
@@ -29,9 +31,7 @@ import org.eclipse.jdt.internal.core.util.ReferenceInfoAdapter;
* @see AttachSourceOperation
* @see JarPackageFragment
*/
-public class SourceMapper
- extends ReferenceInfoAdapter
- implements ISourceElementRequestor {
+public class SourceMapper extends ReferenceInfoAdapter implements ISourceElementRequestor {
/**
* The binary type source is being mapped for
@@ -70,7 +70,7 @@ public class SourceMapper
/**
* The unknown source range {-1, 0}
*/
- protected static SourceRange fgUnknownRange = new SourceRange(-1, 0);
+ protected static SourceRange fgUnknownRange= new SourceRange(-1, 0);
/**
* The position within the source of the start of the
@@ -98,559 +98,411 @@ public class SourceMapper
/**
* Enclosing type information
*/
- IType[] types;
- int[] typeDeclarationStarts;
- SourceRange[] typeNameRanges;
- int typeDepth;
- /**
- * Creates a <code>SourceMapper</code> that locates source in the zip file
- * at the given location in the specified package fragment root.
- */
- public SourceMapper(IPath zipPath, String rootPath, JavaModel model) {
- fZipPath = zipPath;
- fRootPath = rootPath.replace('\\', '/');
- if (fRootPath.endsWith("/")) {
- fRootPath = fRootPath.substring(0, fRootPath.lastIndexOf('/'));
- }
- fJavaModel = model;
- fSourceRanges = new Hashtable();
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void acceptImport(
- int declarationStart,
- int declarationEnd,
- char[] name,
- boolean onDemand) {
- //do nothing
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void acceptInitializer(
- int modifiers,
- int declarationSourceStart,
- int declarationSourceEnd) {
- //do nothing
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void acceptLineSeparatorPositions(int[] positions) {
- //do nothing
+ IType[] types;
+ int[] typeDeclarationStarts;
+ SourceRange[] typeNameRanges;
+ int typeDepth;
+/**
+ * Creates a <code>SourceMapper</code> that locates source in the zip file
+ * at the given location in the specified package fragment root.
+ */
+public SourceMapper(IPath zipPath, String rootPath, JavaModel model) {
+ fZipPath= zipPath;
+ fRootPath= rootPath.replace('\\', '/');
+ if (fRootPath.endsWith("/"/*nonNLS*/)) {
+ fRootPath = fRootPath.substring(0, fRootPath.lastIndexOf('/'));
}
-
- /**
- * @see ISourceElementRequestor
- */
- public void acceptPackage(
- int declarationStart,
- int declarationEnd,
- char[] name) {
- //do nothing
+ fJavaModel= model;
+ fSourceRanges= new Hashtable();
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void acceptImport(int declarationStart, int declarationEnd, char[] name, boolean onDemand) {
+ //do nothing
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void acceptInitializer(int modifiers, int declarationSourceStart, int declarationSourceEnd) {
+ //do nothing
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void acceptLineSeparatorPositions(int[] positions) {
+ //do nothing
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void acceptPackage(int declarationStart, int declarationEnd, char[] name) {
+ //do nothing
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void acceptProblem(IProblem problem) {
+ //do nothing
+}
+/**
+ * Closes this <code>SourceMapper</code>'s zip file. Once this is done, this
+ * <code>SourceMapper</code> cannot be used again.
+ */
+public void close() throws JavaModelException {
+ fSourceRanges= null;
+}
+/**
+ * Converts these type names to signatures.
+ * @see Signature.
+ */
+public String[] convertTypeNamesToSigs(char[][] typeNames) {
+ if (typeNames == null)
+ return fgEmptyStringArray;
+ int n = typeNames.length;
+ if (n == 0)
+ return fgEmptyStringArray;
+ String[] typeSigs = new String[n];
+ for (int i = 0; i < n; ++i) {
+ typeSigs[i] = Signature.createTypeSignature(typeNames[i], false);
}
+ return typeSigs;
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void enterClass(int declarationStart, int modifiers, char[] name, int nameSourceStart, int nameSourceEnd, char[] superclass, char[][] superinterfaces) {
- /**
- * @see ISourceElementRequestor
- */
- public void acceptProblem(IProblem problem) {
- //do nothing
+ this.typeDepth++;
+ if (this.typeDepth == this.types.length){ // need to grow
+ System.arraycopy(this.types, 0, this.types = new IType[this.typeDepth*2], 0, this.typeDepth);
+ System.arraycopy(this.typeNameRanges, 0, this.typeNameRanges = new SourceRange[this.typeDepth*2], 0, this.typeDepth);
+ System.arraycopy(this.typeDeclarationStarts, 0, this.typeDeclarationStarts = new int[this.typeDepth*2], 0, this.typeDepth);
}
-
- /**
- * Closes this <code>SourceMapper</code>'s zip file. Once this is done, this
- * <code>SourceMapper</code> cannot be used again.
- */
- public void close() throws JavaModelException {
- fSourceRanges = null;
+ this.types[typeDepth] = this.getType(new String(name));
+ this.typeNameRanges[typeDepth] = new SourceRange(nameSourceStart, nameSourceEnd - nameSourceStart + 1);
+ this.typeDeclarationStarts[typeDepth] = declarationStart;
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void enterCompilationUnit() {
+ // do nothing
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void enterConstructor(int declarationStart, int modifiers, char[] name, int nameSourceStart, int nameSourceEnd, char[][] parameterTypes, char[][] parameterNames, char[][] exceptionTypes) {
+ enterMethod(declarationStart, modifiers, null, name, nameSourceStart, nameSourceEnd, parameterTypes, parameterNames, exceptionTypes);
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void enterField(int declarationStart, int modifiers, char[] type, char[] name, int nameSourceStart, int nameSourceEnd) {
+ if (typeDepth >= 0 && fMemberDeclarationStart == -1) { // don't allow nested member (can only happen with anonymous inner classes)
+ fMemberDeclarationStart= declarationStart;
+ fMemberNameRange= new SourceRange(nameSourceStart, nameSourceEnd - nameSourceStart + 1);
+ fMemberName= new String(name);
+ }
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void enterInterface(int declarationStart, int modifiers, char[] name, int nameSourceStart, int nameSourceEnd, char[][] superinterfaces) {
+ enterClass(declarationStart, modifiers, name, nameSourceStart, nameSourceEnd, null, superinterfaces);
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void enterMethod(int declarationStart, int modifiers, char[] returnType, char[] name, int nameSourceStart, int nameSourceEnd, char[][] parameterTypes, char[][] parameterNames, char[][] exceptionTypes) {
+ if (typeDepth >= 0 && fMemberDeclarationStart == -1) { // don't allow nested member (can only happen with anonymous inner classes)
+ fMemberName= new String(name);
+ fMemberNameRange= new SourceRange(nameSourceStart, nameSourceEnd - nameSourceStart + 1);
+ fMemberDeclarationStart= declarationStart;
+ fMethodParameterTypes= parameterTypes;
+ }
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void exitClass(int declarationEnd) {
+ if (typeDepth >= 0) {
+ IType currentType = this.types[typeDepth];
+ setSourceRange(
+ currentType,
+ new SourceRange(
+ this.typeDeclarationStarts[typeDepth] ,
+ declarationEnd - this.typeDeclarationStarts[typeDepth] + 1),
+ this.typeNameRanges[typeDepth]);
+ this.typeDepth--;
}
-
- /**
- * Converts these type names to signatures.
- * @see Signature.
- */
- public String[] convertTypeNamesToSigs(char[][] typeNames) {
- if (typeNames == null)
- return fgEmptyStringArray;
- int n = typeNames.length;
- if (n == 0)
- return fgEmptyStringArray;
- String[] typeSigs = new String[n];
- for (int i = 0; i < n; ++i) {
- typeSigs[i] = Signature.createTypeSignature(typeNames[i], false);
- }
- return typeSigs;
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void exitCompilationUnit(int declarationEnd) {
+ //do nothing
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void exitConstructor(int declarationEnd) {
+ exitMethod(declarationEnd);
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void exitField(int declarationEnd) {
+ if (typeDepth >= 0 && fMemberDeclarationStart != -1) {
+ IType currentType = this.types[typeDepth];
+ setSourceRange(currentType.getField(fMemberName), new SourceRange(fMemberDeclarationStart, declarationEnd - fMemberDeclarationStart + 1), fMemberNameRange);
+ fMemberDeclarationStart = -1;
}
-
- /**
- * @see ISourceElementRequestor
- */
- public void enterClass(
- int declarationStart,
- int modifiers,
- char[] name,
- int nameSourceStart,
- int nameSourceEnd,
- char[] superclass,
- char[][] superinterfaces) {
-
- this.typeDepth++;
- if (this.typeDepth == this.types.length) { // need to grow
- System.arraycopy(
- this.types,
- 0,
- this.types = new IType[this.typeDepth * 2],
- 0,
- this.typeDepth);
- System.arraycopy(
- this.typeNameRanges,
- 0,
- this.typeNameRanges = new SourceRange[this.typeDepth * 2],
- 0,
- this.typeDepth);
- System.arraycopy(
- this.typeDeclarationStarts,
- 0,
- this.typeDeclarationStarts = new int[this.typeDepth * 2],
- 0,
- this.typeDepth);
- }
- this.types[typeDepth] = this.getType(new String(name));
- this.typeNameRanges[typeDepth] =
- new SourceRange(nameSourceStart, nameSourceEnd - nameSourceStart + 1);
- this.typeDeclarationStarts[typeDepth] = declarationStart;
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void exitInterface(int declarationEnd) {
+ exitClass(declarationEnd);
+}
+/**
+ * @see ISourceElementRequestor
+ */
+public void exitMethod(int declarationEnd) {
+ if (typeDepth >= 0 && fMemberDeclarationStart != -1) {
+ IType currentType = this.types[typeDepth];
+ SourceRange sourceRange= new SourceRange(fMemberDeclarationStart, declarationEnd - fMemberDeclarationStart + 1);
+ setSourceRange(currentType.getMethod(fMemberName, convertTypeNamesToSigs(fMethodParameterTypes)), sourceRange, fMemberNameRange);
+ fMemberDeclarationStart = -1;
}
-
- /**
- * @see ISourceElementRequestor
- */
- public void enterCompilationUnit() {
- // do nothing
+}
+/**
+ * Locates and returns source code for the given (binary) type, in this
+ * SourceMapper's ZIP file, or returns <code>null</code> if source
+ * code cannot be found.
+ */
+public char[] findSource(IType type) {
+ if (!type.isBinary()) {
+ return null;
}
-
- /**
- * @see ISourceElementRequestor
- */
- public void enterConstructor(
- int declarationStart,
- int modifiers,
- char[] name,
- int nameSourceStart,
- int nameSourceEnd,
- char[][] parameterTypes,
- char[][] parameterNames,
- char[][] exceptionTypes) {
- enterMethod(
- declarationStart,
- modifiers,
- null,
- name,
- nameSourceStart,
- nameSourceEnd,
- parameterTypes,
- parameterNames,
- exceptionTypes);
+ BinaryType parent= (BinaryType)type.getDeclaringType();
+ BinaryType declType= (BinaryType)type;
+ while (parent != null) {
+ declType= parent;
+ parent= (BinaryType)declType.getDeclaringType();
}
-
- /**
- * @see ISourceElementRequestor
- */
- public void enterField(
- int declarationStart,
- int modifiers,
- char[] type,
- char[] name,
- int nameSourceStart,
- int nameSourceEnd) {
- if (typeDepth >= 0
- && fMemberDeclarationStart == -1) {
- // don't allow nested member (can only happen with anonymous inner classes)
- fMemberDeclarationStart = declarationStart;
- fMemberNameRange =
- new SourceRange(nameSourceStart, nameSourceEnd - nameSourceStart + 1);
- fMemberName = new String(name);
- }
+ IBinaryType info= null;
+ try {
+ info= (IBinaryType)declType.getRawInfo();
+ } catch (JavaModelException e) {
+ return null;
}
-
- /**
- * @see ISourceElementRequestor
- */
- public void enterInterface(
- int declarationStart,
- int modifiers,
- char[] name,
- int nameSourceStart,
- int nameSourceEnd,
- char[][] superinterfaces) {
- enterClass(
- declarationStart,
- modifiers,
- name,
- nameSourceStart,
- nameSourceEnd,
- null,
- superinterfaces);
+ return this.findSource(type, info);
+}
+/**
+ * Locates and returns source code for the given (binary) type, in this
+ * SourceMapper's ZIP file, or returns <code>null</code> if source
+ * code cannot be found.
+ */
+public char[] findSource(IType type, IBinaryType info) {
+ char[] sourceFileName = info.sourceFileName();
+ if (sourceFileName == null) return null; // no source file attribute
+ String name = new String(sourceFileName);
+
+ IPackageFragment pkgFrag = type.getPackageFragment();
+ if (!pkgFrag.isDefaultPackage()) {
+ String pkg= type.getPackageFragment().getElementName().replace('.', '/');
+ name= pkg + '/' + name;
}
-
- /**
- * @see ISourceElementRequestor
- */
- public void enterMethod(
- int declarationStart,
- int modifiers,
- char[] returnType,
- char[] name,
- int nameSourceStart,
- int nameSourceEnd,
- char[][] parameterTypes,
- char[][] parameterNames,
- char[][] exceptionTypes) {
- if (typeDepth >= 0
- && fMemberDeclarationStart == -1) {
- // don't allow nested member (can only happen with anonymous inner classes)
- fMemberName = new String(name);
- fMemberNameRange =
- new SourceRange(nameSourceStart, nameSourceEnd - nameSourceStart + 1);
- fMemberDeclarationStart = declarationStart;
- fMethodParameterTypes = parameterTypes;
+ // try to get the entry
+ ZipEntry entry= null;
+ ZipFile zip = null;
+ char[] source= null;
+ try {
+ String fullName;
+ //add the root path if specified
+ if (!fRootPath.equals(IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH)) {
+ fullName= fRootPath + '/' + name;
+ } else {
+ fullName= name;
}
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void exitClass(int declarationEnd) {
- if (typeDepth >= 0) {
- IType currentType = this.types[typeDepth];
- setSourceRange(
- currentType,
- new SourceRange(
- this.typeDeclarationStarts[typeDepth],
- declarationEnd - this.typeDeclarationStarts[typeDepth] + 1),
- this.typeNameRanges[typeDepth]);
- this.typeDepth--;
+ zip = getZip();
+ entry= zip.getEntry(fullName);
+ if (entry != null) {
+ // now read the source code
+ byte[] bytes= readEntry(zip, entry);
+ if (bytes != null) {
+ try {
+ source= BufferManager.bytesToChar(bytes);
+ } catch (JavaModelException e) {
+ source= null;
+ }
+ }
}
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void exitCompilationUnit(int declarationEnd) {
- //do nothing
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void exitConstructor(int declarationEnd) {
- exitMethod(declarationEnd);
- }
-
- /**
- * @see ISourceElementRequestor
- */
- public void exitField(int declarationEnd) {
- if (typeDepth >= 0 && fMemberDeclarationStart != -1) {
- IType currentType = this.types[typeDepth];
- setSourceRange(
- currentType.getField(fMemberName),
- new SourceRange(
- fMemberDeclarationStart,
- declarationEnd - fMemberDeclarationStart + 1),
- fMemberNameRange);
- fMemberDeclarationStart = -1;
+ } catch (CoreException e) {
+ return null;
+ } finally {
+ if (zip != null) {
+ try {
+ zip.close();
+ } catch(IOException e) {}
}
}
-
- /**
- * @see ISourceElementRequestor
- */
- public void exitInterface(int declarationEnd) {
- exitClass(declarationEnd);
+ return source;
+}
+/**
+ * Returns the SourceRange for the name of the given element, or
+ * {-1, -1} if no source range is known for the name of the element.
+ */
+public SourceRange getNameRange(IJavaElement element) {
+ if (element.getElementType() == IJavaElement.METHOD && ((IMember)element).isBinary()) {
+ element= getUnqualifiedMethodHandle((IMethod)element);
}
-
- /**
- * @see ISourceElementRequestor
- */
- public void exitMethod(int declarationEnd) {
- if (typeDepth >= 0 && fMemberDeclarationStart != -1) {
- IType currentType = this.types[typeDepth];
- SourceRange sourceRange =
- new SourceRange(
- fMemberDeclarationStart,
- declarationEnd - fMemberDeclarationStart + 1);
- setSourceRange(
- currentType.getMethod(
- fMemberName,
- convertTypeNamesToSigs(fMethodParameterTypes)),
- sourceRange,
- fMemberNameRange);
- fMemberDeclarationStart = -1;
- }
+ SourceRange[] ranges= (SourceRange[])fSourceRanges.get(element);
+ if (ranges == null) {
+ return fgUnknownRange;
+ } else {
+ return ranges[1];
}
-
- /**
- * Locates and returns source code for the given (binary) type, in this
- * SourceMapper's ZIP file, or returns <code>null</code> if source
- * code cannot be found.
- */
- public char[] findSource(IType type) {
- if (!type.isBinary()) {
- return null;
- }
- BinaryType parent = (BinaryType) type.getDeclaringType();
- BinaryType declType = (BinaryType) type;
- while (parent != null) {
- declType = parent;
- parent = (BinaryType) declType.getDeclaringType();
- }
- IBinaryType info = null;
- try {
- info = (IBinaryType) declType.getRawInfo();
- } catch (JavaModelException e) {
- return null;
- }
- return this.findSource(type, info);
+}
+/**
+ * Returns the <code>SourceRange</code> for the given element, or
+ * {-1, -1} if no source range is known for the element.
+ */
+public SourceRange getSourceRange(IJavaElement element) {
+ if (element.getElementType() == IJavaElement.METHOD && ((IMember)element).isBinary()) {
+ element= getUnqualifiedMethodHandle((IMethod)element);
}
-
- /**
- * Locates and returns source code for the given (binary) type, in this
- * SourceMapper's ZIP file, or returns <code>null</code> if source
- * code cannot be found.
- */
- public char[] findSource(IType type, IBinaryType info) {
- String name = null;
- // see 1FVVWZT
- if (info instanceof ClassFileReader) {
- char[] sourceFileName = ((ClassFileReader) info).sourceFileName();
- if (sourceFileName == null)
- return null; // no source file attribute
- name = new String(sourceFileName);
- } else {
- return null;
- }
-
- IPackageFragment pkgFrag = type.getPackageFragment();
- if (!pkgFrag.isDefaultPackage()) {
- String pkg = type.getPackageFragment().getElementName().replace('.', '/');
- name = pkg + '/' + name;
- }
- // try to get the entry
- ZipEntry entry = null;
- ZipFile zip = null;
- char[] source = null;
- try {
- String fullName;
- //add the root path if specified
- if (!fRootPath.equals(IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH)) {
- fullName = fRootPath + '/' + name;
- } else {
- fullName = name;
- }
- zip = getZip();
- entry = zip.getEntry(fullName);
- if (entry != null) {
- // now read the source code
- byte[] bytes = readEntry(zip, entry);
- if (bytes != null) {
- try {
- source = BufferManager.bytesToChar(bytes);
- } catch (JavaModelException e) {
- source = null;
- }
- }
- }
- } catch (CoreException e) {
- return null;
- } finally {
- if (zip != null) {
- try {
- zip.close();
- } catch (IOException e) {
- }
- }
- }
- return source;
+ SourceRange[] ranges= (SourceRange[])fSourceRanges.get(element);
+ if (ranges == null) {
+ return fgUnknownRange;
+ } else {
+ return ranges[0];
}
-
- /**
- * Returns the SourceRange for the name of the given element, or
- * {-1, -1} if no source range is known for the name of the element.
- */
- public SourceRange getNameRange(IJavaElement element) {
- if (element.getElementType() == IJavaElement.METHOD
- && ((IMember) element).isBinary()) {
- element = getUnqualifiedMethodHandle((IMethod) element);
+}
+/**
+ * Returns the type with the given <code>typeName</code>. Returns inner classes
+ * as well.
+ */
+protected IType getType(String typeName) {
+ if (fType.getElementName().equals(typeName))
+ return fType;
+ else
+ return fType.getType(typeName);
+}
+/**
+ * Creates a handle that has parameter types that are not
+ * fully qualified so that the correct source is found.
+ */
+protected IJavaElement getUnqualifiedMethodHandle(IMethod method) {
+
+ String[] qualifiedParameterTypes = method.getParameterTypes();
+ String[] unqualifiedParameterTypes = new String[qualifiedParameterTypes.length];
+ for (int i = 0; i < qualifiedParameterTypes.length; i++) {
+ StringBuffer unqualifiedName= new StringBuffer();
+ String qualifiedName= qualifiedParameterTypes[i];
+ int count = 0;
+ while (qualifiedName.charAt(count) == Signature.C_ARRAY) {
+ unqualifiedName.append(Signature.C_ARRAY);
+ ++count;
}
- SourceRange[] ranges = (SourceRange[]) fSourceRanges.get(element);
- if (ranges == null) {
- return fgUnknownRange;
+ if (qualifiedName.charAt(count) == Signature.C_RESOLVED) {
+ unqualifiedName.append(Signature.C_UNRESOLVED);
+ unqualifiedName.append(Signature.getSimpleName(qualifiedName));
} else {
- return ranges[1];
+ unqualifiedName.append(qualifiedName.substring(count, qualifiedName.length()));
}
+ unqualifiedParameterTypes[i]= unqualifiedName.toString();
}
-
- /**
- * Returns the <code>SourceRange</code> for the given element, or
- * {-1, -1} if no source range is known for the element.
- */
- public SourceRange getSourceRange(IJavaElement element) {
- if (element.getElementType() == IJavaElement.METHOD
- && ((IMember) element).isBinary()) {
- element = getUnqualifiedMethodHandle((IMethod) element);
- }
- SourceRange[] ranges = (SourceRange[]) fSourceRanges.get(element);
- if (ranges == null) {
- return fgUnknownRange;
+ return ((IType) method.getParent()).getMethod(method.getElementName(), unqualifiedParameterTypes);
+}
+/**
+ * Returns the <code>ZipFile</code> that source is located in.
+ */
+public ZipFile getZip() throws CoreException {
+ return fJavaModel.fgJavaModelManager.getZipFile(fZipPath);
+}
+/**
+ * Maps the given source code to the given binary type and its children.
+ */
+public void mapSource(IType type, char[] contents) {
+ this.mapSource(type, contents, null);
+}
+/**
+ * Maps the given source code to the given binary type and its children.
+ * If a non-null java element is passed, finds the name range for the
+ * given java element without storing it.
+ */
+public ISourceRange mapSource(IType type, char[] contents, IJavaElement searchedElement) {
+ fType= (BinaryType)type;
+
+ this.searchedElement = searchedElement;
+ this.types = new IType[1];
+ this.typeDeclarationStarts = new int[1];
+ this.typeNameRanges = new SourceRange[1];
+ this.typeDepth = -1;
+
+ Hashtable oldSourceRanges = (Hashtable)fSourceRanges.clone();
+ try {
+ IProblemFactory factory= new DefaultProblemFactory();
+ SourceElementParser parser = new SourceElementParser(this, factory);
+ parser.parseCompilationUnit(new BasicCompilationUnit(contents, type.getElementName() + ".java"/*nonNLS*/), false);
+ if (searchedElement != null) {
+ ISourceRange range = this.getNameRange(searchedElement);
+ return range;
} else {
- return ranges[0];
+ return null;
}
- }
-
- /**
- * Returns the type with the given <code>typeName</code>. Returns inner classes
- * as well.
- */
- protected IType getType(String typeName) {
- if (fType.getElementName().equals(typeName))
- return fType;
- else
- return fType.getType(typeName);
- }
-
- /**
- * Creates a handle that has parameter types that are not
- * fully qualified so that the correct source is found.
- */
- protected IJavaElement getUnqualifiedMethodHandle(IMethod method) {
-
- String[] qualifiedParameterTypes = method.getParameterTypes();
- String[] unqualifiedParameterTypes = new String[qualifiedParameterTypes.length];
- for (int i = 0; i < qualifiedParameterTypes.length; i++) {
- StringBuffer unqualifiedName = new StringBuffer();
- String qualifiedName = qualifiedParameterTypes[i];
- int count = 0;
- while (qualifiedName.charAt(count) == Signature.C_ARRAY) {
- unqualifiedName.append(Signature.C_ARRAY);
- ++count;
- }
- if (qualifiedName.charAt(count) == Signature.C_RESOLVED) {
- unqualifiedName.append(Signature.C_UNRESOLVED);
- unqualifiedName.append(Signature.getSimpleName(qualifiedName));
- } else {
- unqualifiedName.append(qualifiedName.substring(count, qualifiedName.length()));
- }
- unqualifiedParameterTypes[i] = unqualifiedName.toString();
+ } finally {
+ if (searchedElement != null) {
+ fSourceRanges = oldSourceRanges;
}
- return ((IType) method.getParent()).getMethod(
- method.getElementName(),
- unqualifiedParameterTypes);
- }
-
- /**
- * Returns the <code>ZipFile</code> that source is located in.
- */
- public ZipFile getZip() throws CoreException {
- return fJavaModel.fgJavaModelManager.getZipFile(fZipPath);
- }
-
- /**
- * Maps the given source code to the given binary type and its children.
- */
- public void mapSource(IType type, char[] contents) {
- this.mapSource(type, contents, null);
- }
-
- /**
- * Maps the given source code to the given binary type and its children.
- * If a non-null java element is passed, finds the name range for the
- * given java element without storing it.
- */
- public ISourceRange mapSource(
- IType type,
- char[] contents,
- IJavaElement searchedElement) {
- fType = (BinaryType) type;
-
- this.searchedElement = searchedElement;
- this.types = new IType[1];
- this.typeDeclarationStarts = new int[1];
- this.typeNameRanges = new SourceRange[1];
+ fType= null;
+ this.searchedElement = null;
+ this.types = null;
+ this.typeDeclarationStarts = null;
+ this.typeNameRanges = null;
this.typeDepth = -1;
-
- Hashtable oldSourceRanges = (Hashtable) fSourceRanges.clone();
- try {
- IProblemFactory factory = new ProblemFactory();
- SourceElementParser parser = new SourceElementParser(this, factory);
- parser.parseCompilationUnit(
- new BasicCompilationUnit(contents, type.getElementName() + ".java"),
- false);
- if (searchedElement != null) {
- ISourceRange range = this.getNameRange(searchedElement);
- return range;
- } else {
- return null;
- }
- } finally {
- if (searchedElement != null) {
- fSourceRanges = oldSourceRanges;
- }
- fType = null;
- this.searchedElement = null;
- this.types = null;
- this.typeDeclarationStarts = null;
- this.typeNameRanges = null;
- this.typeDepth = -1;
- }
}
-
- /**
- * Returns the contents of the specified zip entry
- */
- protected byte[] readEntry(ZipFile zip, ZipEntry entry) {
- InputStream stream = null;
- try {
- stream = zip.getInputStream(entry);
- int remaining = (int) entry.getSize();
- byte[] bytes = new byte[remaining];
- int offset = 0;
- while (remaining > 0) {
- int read = stream.read(bytes, offset, remaining);
- if (read == -1)
- break;
- remaining -= read;
- offset += read;
- }
- return bytes;
- } catch (IOException e) {
- return null;
- } catch (ArrayIndexOutOfBoundsException e) {
- return null;
- } finally {
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException ioe) {
- }
+}
+/**
+ * Returns the contents of the specified zip entry
+ */
+protected byte[] readEntry(ZipFile zip, ZipEntry entry) {
+ InputStream stream = null;
+ try {
+ stream = zip.getInputStream(entry);
+ int remaining = (int) entry.getSize();
+ byte[] bytes = new byte[remaining];
+ int offset = 0;
+ while (remaining > 0) {
+ int read = stream.read(bytes, offset, remaining);
+ if (read == -1)
+ break;
+ remaining -= read;
+ offset += read;
+ }
+ return bytes;
+ } catch (IOException e) {
+ return null;
+ } catch (ArrayIndexOutOfBoundsException e) {
+ return null;
+ } finally {
+ if (stream != null) {
+ try {
+ stream.close();
+ } catch (IOException ioe) {
}
}
}
-
- /**
- * Sets the mapping for this element to its source ranges for its source range
- * and name range.
- *
- * @see fSourceRanges
- */
- protected void setSourceRange(
- IJavaElement element,
- SourceRange sourceRange,
- SourceRange nameRange) {
- fSourceRanges.put(element, new SourceRange[] { sourceRange, nameRange });
- }
-
+}
+/**
+ * Sets the mapping for this element to its source ranges for its source range
+ * and name range.
+ *
+ * @see fSourceRanges
+ */
+protected void setSourceRange(IJavaElement element, SourceRange sourceRange, SourceRange nameRange) {
+ fSourceRanges.put(element, new SourceRange[] {sourceRange, nameRange});
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMethod.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMethod.java
index 2d2c31d8b8..e522c94da0 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMethod.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMethod.java
@@ -15,8 +15,7 @@ import org.eclipse.jdt.core.jdom.IDOMNode;
* @see IMethod
*/
-/* package */
-class SourceMethod extends Member implements IMethod {
+/* package */ class SourceMethod extends Member implements IMethod {
/**
* The parameter type signatures of the method - stored locally
@@ -28,221 +27,197 @@ class SourceMethod extends Member implements IMethod {
/**
* An empty list of Strings
*/
- protected static final String[] fgEmptyList = new String[] {
- };
-
- protected SourceMethod(IType parent, String name, String[] parameterTypes) {
- super(METHOD, parent, name);
- Assert.isTrue(name.indexOf('.') == -1);
- if (parameterTypes == null) {
- fParameterTypes = fgEmptyList;
- } else {
- fParameterTypes = parameterTypes;
- }
+ protected static final String[] fgEmptyList= new String[] {};
+protected SourceMethod(IType parent, String name, String[] parameterTypes) {
+ super(METHOD, parent, name);
+ Assert.isTrue(name.indexOf('.') == -1);
+ if (parameterTypes == null) {
+ fParameterTypes= fgEmptyList;
+ } else {
+ fParameterTypes= parameterTypes;
}
-
- public boolean equals(Object o) {
- return super.equals(o)
- && Util.equalArraysOrNull(fParameterTypes, ((SourceMethod) o).fParameterTypes);
- }
-
- /**
- * @see JavaElement#equalsDOMNode
- */
- protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
- if (node.getNodeType() == IDOMNode.METHOD) {
- IDOMMethod m = (IDOMMethod) node;
- if (isConstructor()) {
- return (
- m.isConstructor()
- || m.getName().equals(
- this.getElementName()) /* case of a constructor that is being renamed */)
+}
+public boolean equals(Object o) {
+ return super.equals(o) && Util.equalArraysOrNull(fParameterTypes, ((SourceMethod)o).fParameterTypes);
+}
+/**
+ * @see JavaElement#equalsDOMNode
+ */
+protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
+ if (node.getNodeType() == IDOMNode.METHOD) {
+ IDOMMethod m = (IDOMMethod)node;
+ if (isConstructor()) {
+ return
+ (m.isConstructor() || m.getName().equals(this.getElementName()) /* case of a constructor that is being renamed */)
&& signatureEquals(m);
- } else {
- return super.equalsDOMNode(node) && signatureEquals(m);
- }
} else {
- return false;
+ return super.equalsDOMNode(node) && signatureEquals(m);
}
-
+ } else {
+ return false;
}
- /**
- * @see IMethod
- */
- public String[] getExceptionTypes() throws JavaModelException {
- SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo();
- char[][] exs = info.getExceptionTypeNames();
- return CompilationUnitStructureRequestor.convertTypeNamesToSigs(exs);
- }
-
- /**
- * @see JavaElement#getHandleMemento()
- */
- public String getHandleMemento() {
- StringBuffer buff =
- new StringBuffer(((JavaElement) getParent()).getHandleMemento());
+}
+/**
+ * @see IMethod
+ */
+public String[] getExceptionTypes() throws JavaModelException {
+ SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo();
+ char[][] exs= info.getExceptionTypeNames();
+ return CompilationUnitStructureRequestor.convertTypeNamesToSigs(exs);
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+public String getHandleMemento() {
+ StringBuffer buff = new StringBuffer(((JavaElement) getParent()).getHandleMemento());
+ buff.append(getHandleMementoDelimiter());
+ buff.append(getElementName());
+ for (int i = 0; i < fParameterTypes.length; i++) {
buff.append(getHandleMementoDelimiter());
- buff.append(getElementName());
- for (int i = 0; i < fParameterTypes.length; i++) {
- buff.append(getHandleMementoDelimiter());
- buff.append(fParameterTypes[i]);
- }
- return buff.toString();
+ buff.append(fParameterTypes[i]);
}
-
- /**
- * @see JavaElement#getHandleMemento()
- */
- protected char getHandleMementoDelimiter() {
- return JavaElement.JEM_METHOD;
+ return buff.toString();
+}
+/**
+ * @see JavaElement#getHandleMemento()
+ */
+protected char getHandleMementoDelimiter() {
+ return JavaElement.JEM_METHOD;
+}
+/**
+ * @see IMethod
+ */
+public int getNumberOfParameters() {
+ return fParameterTypes == null ? 0 : fParameterTypes.length;
+}
+/**
+ * @see IMethod
+ */
+public String[] getParameterNames() throws JavaModelException {
+ SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo();
+ char[][] names= info.getArgumentNames();
+ if (names == null || names.length == 0) {
+ return fgEmptyList;
}
-
- /**
- * @see IMethod
- */
- public int getNumberOfParameters() {
- return fParameterTypes == null ? 0 : fParameterTypes.length;
+ String[] strings= new String[names.length];
+ for (int i= 0; i < names.length; i++) {
+ strings[i]= new String(names[i]);
}
-
- /**
- * @see IMethod
- */
- public String[] getParameterNames() throws JavaModelException {
- SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo();
- char[][] names = info.getArgumentNames();
- if (names == null || names.length == 0) {
- return fgEmptyList;
- }
- String[] strings = new String[names.length];
- for (int i = 0; i < names.length; i++) {
- strings[i] = new String(names[i]);
+ return strings;
+}
+/**
+ * @see IMethod
+ */
+public String[] getParameterTypes() {
+ return fParameterTypes;
+}
+/**
+ * @see IMethod
+ */
+public String getReturnType() throws JavaModelException {
+ SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo();
+ return Signature.createTypeSignature(info.getReturnTypeName(), false);
+}
+/**
+ * @see IMethod
+ */
+public String getSignature() throws JavaModelException {
+ SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo();
+ return info.getSignature();
+}
+/**
+ * @see IMethod
+ */
+public boolean isConstructor() throws JavaModelException {
+ SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo();
+ return info.isConstructor();
+}
+/**
+ */
+public String readableName() {
+
+ StringBuffer buffer = new StringBuffer(super.readableName());
+ buffer.append('(');
+ String[] parameterTypes = this.getParameterTypes();
+ int length;
+ if (parameterTypes != null && (length = parameterTypes.length) > 0) {
+ for (int i = 0; i < length; i++) {
+ buffer.append(Signature.toString(parameterTypes[i]));
+ if (i < length - 1) {
+ buffer.append(", "/*nonNLS*/);
+ }
}
- return strings;
}
-
- /**
- * @see IMethod
- */
- public String[] getParameterTypes() {
- return fParameterTypes;
- }
-
- /**
- * @see IMethod
- */
- public String getReturnType() throws JavaModelException {
- SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo();
- return Signature.createTypeSignature(info.getReturnTypeName(), false);
- }
-
- /**
- * @see IMethod
- */
- public String getSignature() throws JavaModelException {
- SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo();
- return info.getSignature();
- }
-
- /**
- * @see IMethod
- */
- public boolean isConstructor() throws JavaModelException {
- SourceMethodElementInfo info = (SourceMethodElementInfo) getElementInfo();
- return info.isConstructor();
+ buffer.append(')');
+ return buffer.toString();
+}
+/**
+ * Returns <code>true</code> if the signature of this <code>SourceMethod</code> matches that of the given
+ * <code>IDOMMethod</code>, otherwise <code>false</code>.
+ */
+protected boolean signatureEquals(IDOMMethod method) throws JavaModelException {
+ String[] otherTypes= method.getParameterTypes();
+ String[] types= getParameterTypes();
+ boolean ok= true;
+
+ // ensure the number of parameters match
+ if (otherTypes == null || otherTypes.length == 0) {
+ ok= (types == null || types.length == 0);
+ } else if (types != null) {
+ ok= (otherTypes.length == types.length);
+ } else {
+ return false;
}
- /**
- */
- public String readableName() {
-
- StringBuffer buffer = new StringBuffer(super.readableName());
- buffer.append("(");
- String[] parameterTypes = this.getParameterTypes();
- int length;
- if (parameterTypes != null && (length = parameterTypes.length) > 0) {
- for (int i = 0; i < length; i++) {
- buffer.append(Signature.toString(parameterTypes[i]));
- if (i < length - 1) {
- buffer.append(", ");
+ // ensure the parameter type signatures match
+ if (ok) {
+ if (types != null) {
+ int i;
+ for (i= 0; i < types.length; i++) {
+ String otherType= Signature.createTypeSignature(otherTypes[i].toCharArray(), false);
+ if (!types[i].equals(otherType)) {
+ ok= false;
+ break;
}
}
}
- buffer.append(")");
- return buffer.toString();
}
- /**
- * Returns <code>true</code> if the signature of this <code>SourceMethod</code> matches that of the given
- * <code>IDOMMethod</code>, otherwise <code>false</code>.
- */
- protected boolean signatureEquals(IDOMMethod method)
- throws JavaModelException {
- String[] otherTypes = method.getParameterTypes();
- String[] types = getParameterTypes();
- boolean ok = true;
-
- // ensure the number of parameters match
- if (otherTypes == null || otherTypes.length == 0) {
- ok = (types == null || types.length == 0);
- } else
- if (types != null) {
- ok = (otherTypes.length == types.length);
- } else {
- return false;
+ return ok;
+}
+/**
+ * @private Debugging purposes
+ */
+protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
+ if (info == null) {
+ buffer.append(getElementName());
+ buffer.append(" (not open)"/*nonNLS*/);
+ } else {
+ try {
+ if (Flags.isStatic(this.getFlags())) {
+ buffer.append("static "/*nonNLS*/);
}
-
- // ensure the parameter type signatures match
- if (ok) {
- if (types != null) {
- int i;
- for (i = 0; i < types.length; i++) {
- String otherType =
- Signature.createTypeSignature(otherTypes[i].toCharArray(), false);
- if (!types[i].equals(otherType)) {
- ok = false;
- break;
- }
- }
+ if (!this.isConstructor()) {
+ buffer.append(Signature.toString(this.getReturnType()));
+ buffer.append(' ');
}
- }
-
- return ok;
- }
-
- /**
- * @private Debugging purposes
- */
- protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
- if (info == null) {
- buffer.append(getElementName());
- buffer.append(" (not open)");
- } else {
- try {
- if (Flags.isStatic(this.getFlags())) {
- buffer.append("static ");
- }
- if (!this.isConstructor()) {
- buffer.append(Signature.toString(this.getReturnType()));
- buffer.append(" ");
- }
- buffer.append(this.getElementName());
- buffer.append("(");
- String[] parameterTypes = this.getParameterTypes();
- int length;
- if (parameterTypes != null && (length = parameterTypes.length) > 0) {
- for (int i = 0; i < length; i++) {
- buffer.append(Signature.toString(parameterTypes[i]));
- if (i < length - 1) {
- buffer.append(", ");
- }
+ buffer.append(this.getElementName());
+ buffer.append('(');
+ String[] parameterTypes = this.getParameterTypes();
+ int length;
+ if (parameterTypes != null && (length = parameterTypes.length) > 0) {
+ for (int i = 0; i < length; i++) {
+ buffer.append(Signature.toString(parameterTypes[i]));
+ if (i < length - 1) {
+ buffer.append(", "/*nonNLS*/);
}
}
- buffer.append(")");
- } catch (JavaModelException e) {
- buffer.append("<JavaModelException in toString of " + getElementName());
}
+ buffer.append(')');
+ } catch (JavaModelException e) {
+ buffer.append("<JavaModelException in toString of "/*nonNLS*/ + getElementName());
}
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMethodElementInfo.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMethodElementInfo.java
index b6dffd43a1..509e11dab3 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMethodElementInfo.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMethodElementInfo.java
@@ -12,10 +12,7 @@ import org.eclipse.jdt.core.Signature;
/**
* Element info for IMethod elements.
*/
-/* package */
-class SourceMethodElementInfo
- extends MemberElementInfo
- implements ISourceMethod {
+/* package */ class SourceMethodElementInfo extends MemberElementInfo implements ISourceMethod {
/**
* For a source method (i.e. method contained in a comilation unit)
@@ -54,61 +51,46 @@ class SourceMethodElementInfo
/**
* Constructor flag.
*/
- protected boolean isConstructor = false;
- public char[][] getArgumentNames() {
- return this.argumentNames;
- }
-
- public char[][] getArgumentTypeNames() {
- return this.argumentTypeNames;
- }
-
- public char[][] getExceptionTypeNames() {
- return this.exceptionTypes;
- }
-
- public char[] getReturnTypeName() {
- return this.returnType;
- }
-
- public char[] getSelector() {
- return this.name;
- }
-
- protected String getSignature() {
-
- String[] paramSignatures = new String[this.argumentTypeNames.length];
- for (int i = 0; i < this.argumentTypeNames.length; ++i) {
- paramSignatures[i] =
- Signature.createTypeSignature(this.argumentTypeNames[i], false);
- }
- return Signature.createMethodSignature(
- paramSignatures,
- Signature.createTypeSignature(this.returnType, false));
- }
-
- public boolean isConstructor() {
- return this.isConstructor;
- }
-
- protected void setArgumentNames(char[][] names) {
- this.argumentNames = names;
- }
-
- protected void setArgumentTypeNames(char[][] types) {
- this.argumentTypeNames = types;
- }
-
- protected void setConstructor(boolean isConstructor) {
- this.isConstructor = isConstructor;
- }
-
- protected void setExceptionTypeNames(char[][] types) {
- this.exceptionTypes = types;
- }
+ protected boolean isConstructor= false;
+public char[][] getArgumentNames() {
+ return this.argumentNames;
+}
+public char[][] getArgumentTypeNames() {
+ return this.argumentTypeNames;
+}
+public char[][] getExceptionTypeNames() {
+ return this.exceptionTypes;
+}
+public char[] getReturnTypeName() {
+ return this.returnType;
+}
+public char[] getSelector() {
+ return this.name;
+}
+protected String getSignature() {
- protected void setReturnType(char[] type) {
- this.returnType = type;
+ String[] paramSignatures = new String[this.argumentTypeNames.length];
+ for (int i = 0; i < this.argumentTypeNames.length; ++i) {
+ paramSignatures[i] = Signature.createTypeSignature(this.argumentTypeNames[i], false);
}
-
+ return Signature.createMethodSignature(paramSignatures, Signature.createTypeSignature(this.returnType, false));
+}
+public boolean isConstructor() {
+ return this.isConstructor;
+}
+protected void setArgumentNames(char[][] names) {
+ this.argumentNames = names;
+}
+protected void setArgumentTypeNames(char[][] types) {
+ this.argumentTypeNames = types;
+}
+protected void setConstructor(boolean isConstructor) {
+ this.isConstructor = isConstructor;
+}
+protected void setExceptionTypeNames(char[][] types) {
+ this.exceptionTypes = types;
+}
+protected void setReturnType(char[] type) {
+ this.returnType = type;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceRange.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceRange.java
index e1e20ee13f..e0aa4054a3 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceRange.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceRange.java
@@ -11,38 +11,33 @@ import org.eclipse.jdt.core.*;
/**
* @see ISourceRange
*/
-/* package */
-class SourceRange implements ISourceRange {
+/* package */ class SourceRange implements ISourceRange {
- protected int offset, length;
-
- protected SourceRange(int offset, int length) {
- this.offset = offset;
- this.length = length;
- }
-
- /**
- * @see ISourceRange
- */
- public int getLength() {
- return this.length;
- }
-
- /**
- * @see ISourceRange
- */
- public int getOffset() {
- return this.offset;
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append("[offset=");
- buffer.append(this.offset);
- buffer.append(", length=");
- buffer.append(this.length);
- buffer.append("]");
- return buffer.toString();
- }
+protected int offset, length;
+protected SourceRange(int offset, int length) {
+ this.offset = offset;
+ this.length = length;
+}
+/**
+ * @see ISourceRange
+ */
+public int getLength() {
+ return this.length;
+}
+/**
+ * @see ISourceRange
+ */
+public int getOffset() {
+ return this.offset;
+}
+public String toString() {
+ StringBuffer buffer = new StringBuffer();
+ buffer.append("[offset="/*nonNLS*/);
+ buffer.append(this.offset);
+ buffer.append(", length="/*nonNLS*/);
+ buffer.append(this.length);
+ buffer.append("]"/*nonNLS*/);
+ return buffer.toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceRefElement.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceRefElement.java
index dfca0a9c18..c0f0f428ab 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceRefElement.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceRefElement.java
@@ -13,218 +13,186 @@ import org.eclipse.jdt.core.*;
* Abstract class for Java elements which implement ISourceReference.
*/
-/* package */
-abstract class SourceRefElement
- extends JavaElement
- implements ISourceReference {
+/* package */ abstract class SourceRefElement extends JavaElement implements ISourceReference {
- protected SourceRefElement(int type, IJavaElement parent, String name) {
- super(type, parent, name);
- }
-
- /**
- * @see ISourceManipulation
- */
- public void copy(
- IJavaElement container,
- IJavaElement sibling,
- String rename,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- if (container == null) {
- throw new IllegalArgumentException("conatiner cannot be null");
- }
- IJavaElement[] elements = new IJavaElement[] { this };
- IJavaElement[] containers = new IJavaElement[] { container };
- IJavaElement[] siblings = null;
- if (sibling != null) {
- siblings = new IJavaElement[] { sibling };
- }
- String[] renamings = null;
- if (rename != null) {
- renamings = new String[] { rename };
- }
- getJavaModel().copy(elements, containers, siblings, renamings, force, monitor);
+protected SourceRefElement(int type, IJavaElement parent, String name) {
+ super(type, parent, name);
+}
+/**
+ * @see ISourceManipulation
+ */
+public void copy(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ if (container == null) {
+ throw new IllegalArgumentException(Util.bind("operation.nullContainer"/*nonNLS*/));
}
-
- /**
- * @see ISourceManipulation
- */
- public void delete(boolean force, IProgressMonitor monitor)
- throws JavaModelException {
- IJavaElement[] elements = new IJavaElement[] { this };
- getJavaModel().delete(elements, force, monitor);
+ IJavaElement[] elements= new IJavaElement[] {this};
+ IJavaElement[] containers= new IJavaElement[] {container};
+ IJavaElement[] siblings= null;
+ if (sibling != null) {
+ siblings= new IJavaElement[] {sibling};
}
-
- /**
- * @see IMember
- */
- public ICompilationUnit getCompilationUnit() {
- return ((JavaElement) getParent()).getCompilationUnit();
+ String[] renamings= null;
+ if (rename != null) {
+ renamings= new String[] {rename};
}
-
- /**
- * Elements within compilation units and class files have no
- * corresponding resource.
- *
- * @see IJavaElement
- */
- public IResource getCorrespondingResource() throws JavaModelException {
+ getJavaModel().copy(elements, containers, siblings, renamings, force, monitor);
+}
+/**
+ * @see ISourceManipulation
+ */
+public void delete(boolean force, IProgressMonitor monitor) throws JavaModelException {
+ IJavaElement[] elements = new IJavaElement[] {this};
+ getJavaModel().delete(elements, force, monitor);
+}
+/**
+ * @see IMember
+ */
+public ICompilationUnit getCompilationUnit() {
+ return ((JavaElement)getParent()).getCompilationUnit();
+}
+/**
+ * Elements within compilation units and class files have no
+ * corresponding resource.
+ *
+ * @see IJavaElement
+ */
+public IResource getCorrespondingResource() throws JavaModelException {
+ return null;
+}
+/**
+ * Return the first instance of IOpenable in the hierarchy of this
+ * type (going up the hierarchy from this type);
+ */
+public IOpenable getOpenableParent() {
+ IJavaElement parent = getParent();
+ if (parent instanceof IOpenable)
+ return (IOpenable) parent;
+ return ((JavaElement) parent).getOpenableParent();
+}
+/**
+ * @see ISourceReference
+ */
+public String getSource() throws JavaModelException {
+ IOpenable openable = getOpenableParent();
+ IBuffer buffer = openable.getBuffer();
+ if (buffer == null) {
return null;
}
-
- /**
- * Return the first instance of IOpenable in the hierarchy of this
- * type (going up the hierarchy from this type);
- */
- public IOpenable getOpenableParent() {
- IJavaElement parent = getParent();
- if (parent instanceof IOpenable)
- return (IOpenable) parent;
- return ((JavaElement) parent).getOpenableParent();
- }
-
- /**
- * @see ISourceReference
- */
- public String getSource() throws JavaModelException {
- IOpenable openable = getOpenableParent();
- IBuffer buffer = openable.getBuffer();
- if (buffer == null) {
- return null;
- }
- ISourceRange range = getSourceRange();
- int offset = range.getOffset();
- int length = range.getLength();
- if (offset == -1 || length == 0) {
- return null;
- }
- return buffer.getText(offset, length);
- }
-
- /**
- * @see ISourceReference
- */
- public ISourceRange getSourceRange() throws JavaModelException {
- SourceRefElementInfo info = (SourceRefElementInfo) getElementInfo();
- return info.getSourceRange();
+ ISourceRange range = getSourceRange();
+ int offset = range.getOffset();
+ int length = range.getLength();
+ if (offset == -1 || length == 0 ) {
+ return null;
}
-
- /**
- * @see IJavaElement
- */
- public IResource getUnderlyingResource() throws JavaModelException {
- return getParent().getUnderlyingResource();
+ return buffer.getText(offset, length);
+}
+/**
+ * @see ISourceReference
+ */
+public ISourceRange getSourceRange() throws JavaModelException {
+ SourceRefElementInfo info = (SourceRefElementInfo) getElementInfo();
+ return info.getSourceRange();
+}
+/**
+ * @see IJavaElement
+ */
+public IResource getUnderlyingResource() throws JavaModelException {
+ return getParent().getUnderlyingResource();
+}
+/**
+ * @see ISourceManipulation
+ */
+public void move(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ if (container == null) {
+ throw new IllegalArgumentException(Util.bind("operation.nullContainer"/*nonNLS*/));
}
-
- /**
- * @see ISourceManipulation
- */
- public void move(
- IJavaElement container,
- IJavaElement sibling,
- String rename,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- if (container == null) {
- throw new IllegalArgumentException("conatiner cannot be null");
- }
- IJavaElement[] elements = new IJavaElement[] { this };
- IJavaElement[] containers = new IJavaElement[] { container };
- IJavaElement[] siblings = null;
- if (sibling != null) {
- siblings = new IJavaElement[] { sibling };
- }
- String[] renamings = null;
- if (rename != null) {
- renamings = new String[] { rename };
- }
- getJavaModel().move(elements, containers, siblings, renamings, force, monitor);
+ IJavaElement[] elements= new IJavaElement[] {this};
+ IJavaElement[] containers= new IJavaElement[] {container};
+ IJavaElement[] siblings= null;
+ if (sibling != null) {
+ siblings= new IJavaElement[] {sibling};
}
-
- /**
- * Changes the source end index of this element, all children (following
- * <code>child</code>), and all following elements.
- */
- public void offsetSourceEndAndChildren(int amount, IJavaElement child) {
- try {
- SourceRefElementInfo info = (SourceRefElementInfo) getRawInfo();
- info.setSourceRangeEnd(info.getDeclarationSourceEnd() + amount);
- IJavaElement[] children = getChildren();
- boolean afterChild = false;
- for (int i = 0; i < children.length; i++) {
- IJavaElement aChild = children[i];
- if (afterChild) {
- ((JavaElement) aChild).offsetSourceRange(amount);
- } else {
- afterChild = aChild.equals(child);
- }
- }
- ((JavaElement) getParent()).offsetSourceEndAndChildren(amount, this);
- } catch (JavaModelException npe) {
- return;
- }
+ String[] renamings= null;
+ if (rename != null) {
+ renamings= new String[] {rename};
}
-
- /**
- * Changes the source indexes of this element and all children elements.
- */
- public void offsetSourceRange(int amount) {
- try {
- SourceRefElementInfo info = (SourceRefElementInfo) getRawInfo();
- info.setSourceRangeStart(info.getDeclarationSourceStart() + amount);
- info.setSourceRangeEnd(info.getDeclarationSourceEnd() + amount);
- IJavaElement[] children = getChildren();
- for (int i = 0; i < children.length; i++) {
- IJavaElement aChild = children[i];
+ getJavaModel().move(elements, containers, siblings, renamings, force, monitor);
+}
+/**
+ * Changes the source end index of this element, all children (following
+ * <code>child</code>), and all following elements.
+ */
+public void offsetSourceEndAndChildren(int amount, IJavaElement child) {
+ try {
+ SourceRefElementInfo info = (SourceRefElementInfo) getRawInfo();
+ info.setSourceRangeEnd(info.getDeclarationSourceEnd() + amount);
+ IJavaElement[] children = getChildren();
+ boolean afterChild = false;
+ for (int i = 0; i < children.length; i++) {
+ IJavaElement aChild = children[i];
+ if (afterChild) {
((JavaElement) aChild).offsetSourceRange(amount);
+ } else {
+ afterChild = aChild.equals(child);
}
- } catch (JavaModelException npe) {
- return;
}
+ ((JavaElement) getParent()).offsetSourceEndAndChildren(amount, this);
+ } catch (JavaModelException npe) {
+ return;
}
-
- /**
- * @see ISourceManipulation
- */
- public void rename(String name, boolean force, IProgressMonitor monitor)
- throws JavaModelException {
- if (name == null) {
- throw new IllegalArgumentException("name cannot be null");
+}
+/**
+ * Changes the source indexes of this element and all children elements.
+ */
+public void offsetSourceRange(int amount) {
+ try {
+ SourceRefElementInfo info = (SourceRefElementInfo) getRawInfo();
+ info.setSourceRangeStart(info.getDeclarationSourceStart() + amount);
+ info.setSourceRangeEnd(info.getDeclarationSourceEnd() + amount);
+ IJavaElement[] children = getChildren();
+ for (int i = 0; i < children.length; i++) {
+ IJavaElement aChild = children[i];
+ ((JavaElement) aChild).offsetSourceRange(amount);
}
- IJavaElement[] elements = new IJavaElement[] { this };
- IJavaElement[] dests = new IJavaElement[] { this.getParent()};
- String[] renamings = new String[] { name };
- getJavaModel().rename(elements, dests, renamings, force, monitor);
+ } catch (JavaModelException npe) {
+ return;
}
-
- /**
- * Updates the end source index for this element, and all following elements.
- */
- public void triggerSourceEndOffset(int amount, int nameStart, int nameEnd) {
- try {
- SourceRefElementInfo info = (SourceRefElementInfo) getRawInfo();
- info.setSourceRangeEnd(info.getDeclarationSourceEnd() + amount);
- ((JavaElement) getParent()).offsetSourceEndAndChildren(amount, this);
- } catch (JavaModelException npe) {
- return;
- }
+}
+/**
+ * @see ISourceManipulation
+ */
+public void rename(String name, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ if (name == null) {
+ throw new IllegalArgumentException(Util.bind("element.nullName"/*nonNLS*/));
}
-
- /**
- * Updates the source indexes of this element and all following elements.
- */
- public void triggerSourceRangeOffset(int amount, int nameStart, int nameEnd) {
- try {
- SourceRefElementInfo info = (SourceRefElementInfo) getRawInfo();
- info.setSourceRangeStart(info.getDeclarationSourceStart() + amount);
- info.setSourceRangeEnd(info.getDeclarationSourceEnd() + amount);
- ((JavaElement) getParent()).offsetSourceEndAndChildren(amount, this);
- } catch (JavaModelException npe) {
- return;
- }
+ IJavaElement[] elements= new IJavaElement[] {this};
+ IJavaElement[] dests= new IJavaElement[] {this.getParent()};
+ String[] renamings= new String[] {name};
+ getJavaModel().rename(elements, dests, renamings, force, monitor);
+}
+/**
+ * Updates the end source index for this element, and all following elements.
+ */
+public void triggerSourceEndOffset(int amount, int nameStart, int nameEnd) {
+ try {
+ SourceRefElementInfo info = (SourceRefElementInfo) getRawInfo();
+ info.setSourceRangeEnd(info.getDeclarationSourceEnd() + amount);
+ ((JavaElement) getParent()).offsetSourceEndAndChildren(amount, this);
+ } catch (JavaModelException npe) {
+ return;
}
-
+}
+/**
+ * Updates the source indexes of this element and all following elements.
+ */
+public void triggerSourceRangeOffset(int amount, int nameStart, int nameEnd) {
+ try {
+ SourceRefElementInfo info = (SourceRefElementInfo) getRawInfo();
+ info.setSourceRangeStart(info.getDeclarationSourceStart() + amount);
+ info.setSourceRangeEnd(info.getDeclarationSourceEnd() + amount);
+ ((JavaElement) getParent()).offsetSourceEndAndChildren(amount, this);
+ } catch (JavaModelException npe) {
+ return;
+ }
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceRefElementInfo.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceRefElementInfo.java
index 4a8e8af785..83d7fdf3a5 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceRefElementInfo.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceRefElementInfo.java
@@ -11,43 +11,34 @@ import org.eclipse.jdt.core.*;
/**
* Element info for ISourceReference elements.
*/
-/* package */
-class SourceRefElementInfo extends JavaElementInfo {
+/* package */ class SourceRefElementInfo extends JavaElementInfo {
protected int fSourceRangeStart, fSourceRangeEnd;
- protected SourceRefElementInfo() {
- setIsStructureKnown(true);
- }
-
- /**
- * @see ISourceType
- * @see ISourceMethod
- * @see ISourceField
- */
- public int getDeclarationSourceEnd() {
- return fSourceRangeEnd;
- }
-
- /**
- * @see ISourceType
- * @see ISourceMethod
- * @see ISourceField
- */
- public int getDeclarationSourceStart() {
- return fSourceRangeStart;
- }
-
- protected ISourceRange getSourceRange() {
- return new SourceRange(
- fSourceRangeStart,
- fSourceRangeEnd - fSourceRangeStart + 1);
- }
-
- protected void setSourceRangeEnd(int end) {
- fSourceRangeEnd = end;
- }
-
- protected void setSourceRangeStart(int start) {
- fSourceRangeStart = start;
- }
-
+protected SourceRefElementInfo() {
+ setIsStructureKnown(true);
+}
+/**
+ * @see ISourceType
+ * @see ISourceMethod
+ * @see ISourceField
+ */
+public int getDeclarationSourceEnd() {
+ return fSourceRangeEnd;
+}
+/**
+ * @see ISourceType
+ * @see ISourceMethod
+ * @see ISourceField
+ */
+public int getDeclarationSourceStart() {
+ return fSourceRangeStart;
+}
+protected ISourceRange getSourceRange() {
+ return new SourceRange(fSourceRangeStart, fSourceRangeEnd - fSourceRangeStart + 1);
+}
+protected void setSourceRangeEnd(int end) {
+ fSourceRangeEnd = end;
+}
+protected void setSourceRangeStart(int start) {
+ fSourceRangeStart = start;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceType.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceType.java
index aa9a3fccac..3fffc3fa6f 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceType.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceType.java
@@ -29,391 +29,306 @@ public class SourceType extends Member implements IType {
/**
* An empty list of Strings
*/
- protected static final String[] fgEmptyList = new String[] {
- };
-
- protected SourceType(IJavaElement parent, String name) {
- super(TYPE, parent, name);
- Assert.isTrue(name.indexOf('.') == -1);
+ protected static final String[] fgEmptyList= new String[] {};
+protected SourceType(IJavaElement parent, String name) {
+ super(TYPE, parent, name);
+ Assert.isTrue(name.indexOf('.') == -1);
+}
+/**
+ * @see IType
+ */
+public IField createField(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ CreateFieldOperation op = new CreateFieldOperation(this, contents, force);
+ if (sibling != null) {
+ op.createBefore(sibling);
}
-
- /**
- * @see IType
- */
- public IField createField(
- String contents,
- IJavaElement sibling,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- CreateFieldOperation op = new CreateFieldOperation(this, contents, force);
- if (sibling != null) {
- op.createBefore(sibling);
- }
- runOperation(op, monitor);
- return (IField) op.getResultElements()[0];
+ runOperation(op, monitor);
+ return (IField) op.getResultElements()[0];
+}
+/**
+ * @see IType
+ */
+public IInitializer createInitializer(String contents, IJavaElement sibling, IProgressMonitor monitor) throws JavaModelException {
+ CreateInitializerOperation op = new CreateInitializerOperation(this, contents);
+ if (sibling != null) {
+ op.createBefore(sibling);
}
-
- /**
- * @see IType
- */
- public IInitializer createInitializer(
- String contents,
- IJavaElement sibling,
- IProgressMonitor monitor)
- throws JavaModelException {
- CreateInitializerOperation op = new CreateInitializerOperation(this, contents);
- if (sibling != null) {
- op.createBefore(sibling);
- }
- runOperation(op, monitor);
- return (IInitializer) op.getResultElements()[0];
+ runOperation(op, monitor);
+ return (IInitializer) op.getResultElements()[0];
+}
+/**
+ * @see IType
+ */
+public IMethod createMethod(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ CreateMethodOperation op = new CreateMethodOperation(this, contents, force);
+ if (sibling != null) {
+ op.createBefore(sibling);
}
-
- /**
- * @see IType
- */
- public IMethod createMethod(
- String contents,
- IJavaElement sibling,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- CreateMethodOperation op = new CreateMethodOperation(this, contents, force);
- if (sibling != null) {
- op.createBefore(sibling);
- }
- runOperation(op, monitor);
- return (IMethod) op.getResultElements()[0];
+ runOperation(op, monitor);
+ return (IMethod) op.getResultElements()[0];
+}
+/**
+ * @see IType
+ */
+public IType createType(String contents, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException {
+ CreateTypeOperation op = new CreateTypeOperation(this, contents, force);
+ if (sibling != null) {
+ op.createBefore(sibling);
}
-
- /**
- * @see IType
- */
- public IType createType(
- String contents,
- IJavaElement sibling,
- boolean force,
- IProgressMonitor monitor)
- throws JavaModelException {
- CreateTypeOperation op = new CreateTypeOperation(this, contents, force);
- if (sibling != null) {
- op.createBefore(sibling);
- }
- runOperation(op, monitor);
- return (IType) op.getResultElements()[0];
+ runOperation(op, monitor);
+ return (IType) op.getResultElements()[0];
+}
+/**
+ * @see JavaElement#equalsDOMNode
+ */
+protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
+ return (node.getNodeType() == IDOMNode.TYPE) && super.equalsDOMNode(node);
+}
+/**
+ * @see IMember
+ */
+public IType getDeclaringType() {
+ IJavaElement parent = getParent();
+ while (parent != null) {
+ if (parent.getElementType() == IJavaElement.TYPE) {
+ return (IType) parent;
+ } else
+ if (parent instanceof IMember) {
+ parent = parent.getParent();
+ } else {
+ return null;
+ }
}
-
- /**
- * @see JavaElement#equalsDOMNode
- */
- protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
- return (node.getNodeType() == IDOMNode.TYPE) && super.equalsDOMNode(node);
+ return null;
+}
+/**
+ * @see IType#getField
+ */
+public IField getField(String name) {
+ return new SourceField(this, name);
+}
+/**
+ * @see IType
+ */
+public IField[] getFields() throws JavaModelException {
+ Vector v= getChildrenOfType(FIELD);
+ IField[] array= new IField[v.size()];
+ v.copyInto(array);
+ return array;
+}
+/**
+ * @see IType
+ */
+public String getFullyQualifiedName() {
+ String packageName = getPackageFragment().getElementName();
+ if (packageName.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) {
+ return getTypeQualifiedName();
}
-
- /**
- * @see IMember
- */
- public IType getDeclaringType() {
- IJavaElement parent = getParent();
- while (parent != null) {
- if (parent.getElementType() == IJavaElement.TYPE) {
- return (IType) parent;
- } else
- if (parent instanceof IMember) {
- parent = parent.getParent();
- } else {
- return null;
- }
+ return packageName + '.' + getTypeQualifiedName();
+}
+/**
+ * @see IType
+ */
+public IInitializer getInitializer(int occurrenceCount) {
+ return new Initializer(this, occurrenceCount);
+}
+/**
+ * @see IType
+ */
+public IInitializer[] getInitializers() throws JavaModelException {
+ Vector v= getChildrenOfType(INITIALIZER);
+ IInitializer[] array= new IInitializer[v.size()];
+ v.copyInto(array);
+ return array;
+}
+/**
+ * @see IType#getMethod
+ */
+public IMethod getMethod(String name, String[] parameterTypeSignatures) {
+ return new SourceMethod(this, name, parameterTypeSignatures);
+}
+/**
+ * @see IType
+ */
+public IMethod[] getMethods() throws JavaModelException {
+ Vector v= getChildrenOfType(METHOD);
+ IMethod[] array= new IMethod[v.size()];
+ v.copyInto(array);
+ return array;
+}
+/**
+ * @see IType
+ */
+public IPackageFragment getPackageFragment() {
+ IJavaElement parent = fParent;
+ while (parent != null) {
+ if (parent.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
+ return (IPackageFragment) parent;
}
- return null;
- }
-
- /**
- * @see IType#getField
- */
- public IField getField(String name) {
- return new SourceField(this, name);
- }
-
- /**
- * @see IType
- */
- public IField[] getFields() throws JavaModelException {
- Vector v = getChildrenOfType(FIELD);
- IField[] array = new IField[v.size()];
- v.copyInto(array);
- return array;
- }
-
- /**
- * @see IType
- */
- public String getFullyQualifiedName() {
- String packageName = getPackageFragment().getElementName();
- if (packageName.equals(IPackageFragment.DEFAULT_PACKAGE_NAME)) {
- return getTypeQualifiedName();
+ else {
+ parent = parent.getParent();
}
- return packageName + '.' + getTypeQualifiedName();
- }
-
- /**
- * @see IType
- */
- public IInitializer getInitializer(int occurrenceCount) {
- return new Initializer(this, occurrenceCount);
}
-
- /**
- * @see IType
- */
- public IInitializer[] getInitializers() throws JavaModelException {
- Vector v = getChildrenOfType(INITIALIZER);
- IInitializer[] array = new IInitializer[v.size()];
- v.copyInto(array);
- return array;
+ Assert.isTrue(false); // should not happen
+ return null;
+}
+/**
+ * @see IType
+ */
+public String getSuperclassName() throws JavaModelException {
+ SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo();
+ char[] superclassName= info.getSuperclassName();
+ if (superclassName == null) {
+ return null;
}
-
- /**
- * @see IType#getMethod
- */
- public IMethod getMethod(String name, String[] parameterTypeSignatures) {
- return new SourceMethod(this, name, parameterTypeSignatures);
+ return new String(superclassName);
+}
+/**
+ * @see IType
+ */
+public String[] getSuperInterfaceNames() throws JavaModelException {
+ SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo();
+ char[][] names= info.getInterfaceNames();
+ if (names == null) {
+ return fgEmptyList;
}
-
- /**
- * @see IType
- */
- public IMethod[] getMethods() throws JavaModelException {
- Vector v = getChildrenOfType(METHOD);
- IMethod[] array = new IMethod[v.size()];
- v.copyInto(array);
- return array;
+ String[] strings= new String[names.length];
+ for (int i= 0; i < names.length; i++) {
+ strings[i]= new String(names[i]);
}
-
- /**
- * @see IType
- */
- public IPackageFragment getPackageFragment() {
- IJavaElement parent = fParent;
- while (parent != null) {
- if (parent.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
- return (IPackageFragment) parent;
- } else {
- parent = parent.getParent();
- }
- }
- Assert.isTrue(false); // should not happen
- return null;
+ return strings;
+}
+/**
+ * @see IType
+ */
+public IType getType(String name) {
+ return new SourceType(this, name);
+}
+/**
+ * @see IType
+ */
+public String getTypeQualifiedName() {
+ if (fParent.getElementType() == IJavaElement.COMPILATION_UNIT) {
+ return fName;
+ } else {
+ return ((IType) fParent).getTypeQualifiedName() + '$' + fName;
}
-
- /**
- * @see IType
- */
- public String getSuperclassName() throws JavaModelException {
- SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo();
- char[] superclassName = info.getSuperclassName();
- if (superclassName == null) {
- return null;
- }
- return new String(superclassName);
+}
+/**
+ * @see IType
+ */
+public IType[] getTypes() throws JavaModelException {
+ Vector v= getChildrenOfType(TYPE);
+ IType[] array= new IType[v.size()];
+ v.copyInto(array);
+ return array;
+}
+/**
+ * @see IParent
+ */
+public boolean hasChildren() throws JavaModelException {
+ return getChildren().length > 0;
+}
+/**
+ * @see IType
+ */
+public boolean isClass() throws JavaModelException {
+ return !isInterface();
+}
+/**
+ * @see IType
+ */
+public boolean isInterface() throws JavaModelException {
+ SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo();
+ return info.isInterface();
+}
+/**
+ * @see IType
+ */
+public ITypeHierarchy newSupertypeHierarchy(IProgressMonitor monitor) throws JavaModelException {
+ CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, SearchEngine.createWorkspaceScope(), false);
+ runOperation(op, monitor);
+ return op.getResult();
+}
+/**
+ * @see IType
+ */
+public ITypeHierarchy newTypeHierarchy(IProgressMonitor monitor) throws JavaModelException {
+ CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(this, SearchEngine.createWorkspaceScope(), true);
+ runOperation(op, monitor);
+ return op.getResult();
+}
+/**
+ * @see IType
+ */
+public ITypeHierarchy newTypeHierarchy(IJavaProject project, IProgressMonitor monitor) throws JavaModelException {
+ if (project == null) {
+ throw new IllegalArgumentException(Util.bind("hierarchy.nullProject"/*nonNLS*/));
}
+
+ CreateTypeHierarchyOperation op= new CreateTypeHierarchyOperation(
+ this,
+ SearchEngine.createJavaSearchScope(new IResource[]{ project.getProject() }),
+ true);
+ runOperation(op, monitor);
+ return op.getResult();
+}
+/**
+ * See ISourceType.resolveType(...)
+ */
- /**
- * @see IType
- */
- public String[] getSuperInterfaceNames() throws JavaModelException {
- SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo();
- char[][] names = info.getInterfaceNames();
- if (names == null) {
- return fgEmptyList;
+ public String[][] resolveType(String typeName) throws JavaModelException {
+ ISourceType info = (ISourceType) this.getElementInfo();
+ ISearchableNameEnvironment environment = ((JavaProject)getJavaProject()).getSearchableNameEnvironment();
+
+ class TypeResolveRequestor implements ISelectionRequestor {
+ String[][] answers = null;
+ void acceptType(String[] answer){
+ if (answers == null) answers = new String[][]{ answer };
+ // grow
+ int length = answers.length;
+ System.arraycopy(answers, 0, answers = new String[length+1][], 0, length);
+ answers[length] = answer;
}
- String[] strings = new String[names.length];
- for (int i = 0; i < names.length; i++) {
- strings[i] = new String(names[i]);
+ public void acceptClass(char[] packageName, char[] className, boolean needQualification) {
+ acceptType(new String[] { new String(packageName), new String(className) });
}
- return strings;
- }
-
- /**
- * @see IType
- */
- public IType getType(String name) {
- return new SourceType(this, name);
- }
-
- /**
- * @see IType
- */
- public String getTypeQualifiedName() {
- if (fParent.getElementType() == IJavaElement.COMPILATION_UNIT) {
- return fName;
- } else {
- return ((IType) fParent).getTypeQualifiedName() + '$' + fName;
+
+ public void acceptInterface(char[] packageName, char[] interfaceName, boolean needQualification) {
+ acceptType(new String[] { new String(packageName), new String(interfaceName) });
}
- }
- /**
- * @see IType
- */
- public IType[] getTypes() throws JavaModelException {
- Vector v = getChildrenOfType(TYPE);
- IType[] array = new IType[v.size()];
- v.copyInto(array);
- return array;
- }
+ public void acceptError(IProblem error) {}
+ public void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, char[] name) {}
+ public void acceptMethod(char[] declaringTypePackageName, char[] declaringTypeName, char[] selector, char[][] parameterPackageNames, char[][] parameterTypeNames) {}
+ public void acceptPackage(char[] packageName){}
- /**
- * @see IParent
- */
- public boolean hasChildren() throws JavaModelException {
- return getChildren().length > 0;
}
-
- /**
- * @see IType
- */
- public boolean isClass() throws JavaModelException {
- return !isInterface();
- }
-
- /**
- * @see IType
- */
- public boolean isInterface() throws JavaModelException {
- SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo();
- return info.isInterface();
- }
-
- /**
- * @see IType
- */
- public ITypeHierarchy newSupertypeHierarchy(IProgressMonitor monitor)
- throws JavaModelException {
- CreateTypeHierarchyOperation op =
- new CreateTypeHierarchyOperation(
- this,
- SearchEngine.createWorkspaceScope(),
- false);
- runOperation(op, monitor);
- return op.getResult();
- }
-
- /**
- * @see IType
- */
- public ITypeHierarchy newTypeHierarchy(IProgressMonitor monitor)
- throws JavaModelException {
- CreateTypeHierarchyOperation op =
- new CreateTypeHierarchyOperation(
- this,
- SearchEngine.createWorkspaceScope(),
- true);
- runOperation(op, monitor);
- return op.getResult();
- }
-
- /**
- * @see IType
- */
- public ITypeHierarchy newTypeHierarchy(
- IJavaProject project,
- IProgressMonitor monitor)
- throws JavaModelException {
- if (project == null) {
- throw new IllegalArgumentException("project argument cannot be null");
- }
-
- CreateTypeHierarchyOperation op =
- new CreateTypeHierarchyOperation(
- this,
- SearchEngine.createJavaSearchScope(new IResource[] { project.getProject()}),
- true);
- runOperation(op, monitor);
- return op.getResult();
- }
-
- /**
- * See ISourceType.resolveType(...)
- */
-
- public String[][] resolveType(String typeName) throws JavaModelException {
- ISourceType info = (ISourceType) this.getElementInfo();
- ISearchableNameEnvironment environment =
- ((JavaProject) getJavaProject()).getSearchableNameEnvironment();
-
- class TypeResolveRequestor implements ISelectionRequestor {
- String[][] answers = null;
- void acceptType(String[] answer) {
- if (answers == null)
- answers = new String[][] { answer };
- // grow
- int length = answers.length;
- System.arraycopy(answers, 0, answers = new String[length + 1][], 0, length);
- answers[length] = answer;
- }
- public void acceptClass(
- char[] packageName,
- char[] className,
- boolean needQualification) {
- acceptType(new String[] { new String(packageName), new String(className)});
- }
-
- public void acceptInterface(
- char[] packageName,
- char[] interfaceName,
- boolean needQualification) {
- acceptType(new String[] { new String(packageName), new String(interfaceName)});
- }
-
- public void acceptError(IProblem error) {
- }
- public void acceptField(
- char[] declaringTypePackageName,
- char[] declaringTypeName,
- char[] name) {
- }
- public void acceptMethod(
- char[] declaringTypePackageName,
- char[] declaringTypeName,
- char[] selector,
- char[][] parameterPackageNames,
- char[][] parameterTypeNames) {
- }
- public void acceptPackage(char[] packageName) {
+ TypeResolveRequestor requestor = new TypeResolveRequestor();
+ SelectionEngine engine =
+ new SelectionEngine(environment, requestor, JavaModelManager.convertConfigurableOptions(JavaCore.getOptions()));
+
+ engine.selectType(info, typeName.toCharArray());
+ return requestor.answers;
+}
+/**
+ * @private Debugging purposes
+ */
+protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
+ if (info == null) {
+ buffer.append(this.getElementName());
+ buffer.append(" (not open)"/*nonNLS*/);
+ } else {
+ try {
+ if (this.isInterface()) {
+ buffer.append("interface "/*nonNLS*/);
+ } else {
+ buffer.append("class "/*nonNLS*/);
}
-
- }
- TypeResolveRequestor requestor = new TypeResolveRequestor();
- SelectionEngine engine =
- new SelectionEngine(
- environment,
- requestor,
- JavaModelManager.convertConfigurableOptions(JavaCore.getOptions()));
-
- engine.selectType(info, typeName.toCharArray());
- return requestor.answers;
- }
-
- /**
- * @private Debugging purposes
- */
- protected void toStringInfo(int tab, StringBuffer buffer, Object info) {
- if (info == null) {
buffer.append(this.getElementName());
- buffer.append(" (not open)");
- } else {
- try {
- if (this.isInterface()) {
- buffer.append("interface ");
- } else {
- buffer.append("class ");
- }
- buffer.append(this.getElementName());
- } catch (JavaModelException e) {
- buffer.append("<JavaModelException in toString of " + getElementName());
- }
+ } catch (JavaModelException e) {
+ buffer.append("<JavaModelException in toString of "/*nonNLS*/ + getElementName());
}
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceTypeElementInfo.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceTypeElementInfo.java
index e38ef83eb7..0202868e1f 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceTypeElementInfo.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceTypeElementInfo.java
@@ -12,16 +12,14 @@ import org.eclipse.jdt.core.*;
/**
* Element info for an IType element that originated from source.
*/
-public class SourceTypeElementInfo
- extends MemberElementInfo
- implements ISourceType {
+public class SourceTypeElementInfo extends MemberElementInfo implements ISourceType {
/**
* The name of the superclass for this type. This name
* is fully qualified for binary types and is NOT
* fully qualified for source types.
*/
protected char[] fSuperclassName;
-
+
/**
* The names of the interfaces this type implements or
* extends. These names are fully qualified in the case
@@ -29,7 +27,7 @@ public class SourceTypeElementInfo
* case of a source type
*/
protected char[][] fSuperInterfaceNames;
-
+
/**
* The enclosing type name for this type.
*
@@ -40,282 +38,251 @@ public class SourceTypeElementInfo
/**
* The name of the source file this type is declared in.
*/
- protected char[] fSourceFileName = null;
+ protected char[] fSourceFileName= null;
/**
* The name of the package this type is contained in.
*/
- protected char[] fPackageName = null;
+ protected char[] fPackageName= null;
/**
* The qualified name of this type.
*/
- protected char[] fQualifiedName = null;
+ protected char[] fQualifiedName= null;
/**
* The fields declared in this type
*/
- protected ISourceField[] fFields = null;
+ protected ISourceField[] fFields= null;
/**
* The methods declared in this type
*/
- protected ISourceMethod[] fMethods = null;
+ protected ISourceMethod[] fMethods= null;
/**
* The types declared in this type
*/
- protected ISourceType[] fMemberTypes = null;
+ protected ISourceType[] fMemberTypes= null;
/**
* The imports in this type's compilation unit
*/
- protected char[][] fImports = null;
+ protected char[][] fImports= null;
/**
* Backpointer to my type handle - useful for translation
* from info to handle.
*/
- protected IType fHandle = null;
-
+ protected IType fHandle= null;
+
/**
* Empty list of methods
*/
- protected static ISourceMethod[] fgEmptyMethods = new ISourceMethod[] {
- };
+ protected static ISourceMethod[] fgEmptyMethods= new ISourceMethod[]{};
/**
* Empty list of types
*/
- protected static ISourceType[] fgEmptyTypes = new ISourceType[] {
- };
+ protected static ISourceType[] fgEmptyTypes= new ISourceType[]{};
/**
* Empty list of fields
*/
- protected static ISourceField[] fgEmptyFields = new ISourceField[] {
- };
+ protected static ISourceField[] fgEmptyFields= new ISourceField[]{};
/**
* Empty list of imports
*/
- protected static char[][] fgEmptyImports = new char[][] {
- };
-
- /**
- * Adds the given field to this type's collection of fields
- */
- protected void addField(ISourceField field) {
- if (fFields == null) {
- fFields = fgEmptyFields;
- }
- ISourceField[] copy = new ISourceField[fFields.length + 1];
- System.arraycopy(fFields, 0, copy, 0, fFields.length);
- copy[fFields.length] = field;
- fFields = copy;
+ protected static char[][] fgEmptyImports= new char[][]{};
+/**
+ * Adds the given field to this type's collection of fields
+ */
+protected void addField(ISourceField field) {
+ if (fFields == null) {
+ fFields= fgEmptyFields;
}
-
- /**
- * Adds the given field to this type's collection of fields
- */
- protected void addImport(char[] i) {
- if (fImports == null) {
- fImports = fgEmptyImports;
- }
- char[][] copy = new char[fImports.length + 1][];
- System.arraycopy(fImports, 0, copy, 0, fImports.length);
- copy[fImports.length] = i;
- fImports = copy;
+ ISourceField[] copy= new ISourceField[fFields.length + 1];
+ System.arraycopy(fFields, 0, copy, 0, fFields.length);
+ copy[fFields.length]= field;
+ fFields= copy;
+}
+/**
+ * Adds the given field to this type's collection of fields
+ */
+protected void addImport(char[] i) {
+ if (fImports== null) {
+ fImports= fgEmptyImports;
}
-
- /**
- * Adds the given type to this type's collection of member types
- */
- protected void addMemberType(ISourceType type) {
- if (fMemberTypes == null) {
- fMemberTypes = fgEmptyTypes;
- }
- ISourceType[] copy = new ISourceType[fMemberTypes.length + 1];
- System.arraycopy(fMemberTypes, 0, copy, 0, fMemberTypes.length);
- copy[fMemberTypes.length] = type;
- fMemberTypes = copy;
+ char[][] copy= new char[fImports.length + 1][];
+ System.arraycopy(fImports, 0, copy, 0, fImports.length);
+ copy[fImports.length]= i;
+ fImports= copy;
+}
+/**
+ * Adds the given type to this type's collection of member types
+ */
+protected void addMemberType(ISourceType type) {
+ if (fMemberTypes == null) {
+ fMemberTypes= fgEmptyTypes;
}
-
- /**
- * Adds the given method to this type's collection of methods
- */
- protected void addMethod(ISourceMethod method) {
- if (fMethods == null) {
- fMethods = fgEmptyMethods;
- }
- ISourceMethod[] copy = new ISourceMethod[fMethods.length + 1];
- System.arraycopy(fMethods, 0, copy, 0, fMethods.length);
- copy[fMethods.length] = method;
- fMethods = copy;
+ ISourceType[] copy= new ISourceType[fMemberTypes.length + 1];
+ System.arraycopy(fMemberTypes, 0, copy, 0, fMemberTypes.length);
+ copy[fMemberTypes.length]= type;
+ fMemberTypes= copy;
+}
+/**
+ * Adds the given method to this type's collection of methods
+ */
+protected void addMethod(ISourceMethod method) {
+ if (fMethods== null) {
+ fMethods= fgEmptyMethods;
}
-
- /**
- * Returns the ISourceType that is the enclosing type for this
- * type, or <code>null</code> if this type is a top level type.
- */
- public ISourceType getEnclosingType() {
- IJavaElement parent = fHandle.getParent();
- if (parent != null && parent.getElementType() == IJavaElement.TYPE) {
- try {
- return (ISourceType) ((JavaElement) parent).getElementInfo();
- } catch (JavaModelException e) {
- return null;
- }
- } else {
+ ISourceMethod[] copy= new ISourceMethod[fMethods.length + 1];
+ System.arraycopy(fMethods, 0, copy, 0, fMethods.length);
+ copy[fMethods.length]= method;
+ fMethods= copy;
+}
+/**
+ * Returns the ISourceType that is the enclosing type for this
+ * type, or <code>null</code> if this type is a top level type.
+ */
+public ISourceType getEnclosingType() {
+ IJavaElement parent= fHandle.getParent();
+ if (parent != null && parent.getElementType() == IJavaElement.TYPE) {
+ try {
+ return (ISourceType)((JavaElement)parent).getElementInfo();
+ } catch (JavaModelException e) {
return null;
}
+ } else {
+ return null;
}
-
- /**
- * @see ISourceType
- */
- public char[] getEnclosingTypeName() {
- return fEnclosingTypeName;
- }
-
- /**
- * @see ISourceType
- */
- public ISourceField[] getFields() {
- return fFields;
- }
-
- /**
- * @see ISourceType
- */
- public char[] getFileName() {
- return fSourceFileName;
- }
-
- /**
- * Returns the handle for this type info
- */
- public IType getHandle() {
- return fHandle;
- }
-
- /**
- * @see ISourceType
- */
- public char[][] getImports() {
- return fImports;
- }
-
- /**
- * @see ISourceType
- */
- public char[][] getInterfaceNames() {
- return fSuperInterfaceNames;
- }
-
- /**
- * @see ISourceType
- */
- public ISourceType[] getMemberTypes() {
- return fMemberTypes;
- }
-
- /**
- * @see ISourceType
- */
- public ISourceMethod[] getMethods() {
- return fMethods;
- }
-
- /**
- * @see ISourceType
- */
- public char[] getPackageName() {
- return fPackageName;
- }
-
- /**
- * @see ISourceType
- */
- public char[] getQualifiedName() {
- return fQualifiedName;
- }
-
- /**
- * @see ISourceType
- */
- public char[] getSuperclassName() {
- return fSuperclassName;
- }
-
- /**
- * @see ISourceType
- */
- public boolean isBinaryType() {
- return false;
- }
-
- /**
- * @see ISourceType
- */
- public boolean isClass() {
- return (this.flags & IConstants.AccInterface) == 0;
- }
-
- /**
- * @see ISourceType
- */
- public boolean isInterface() {
- return (this.flags & IConstants.AccInterface) != 0;
- }
-
- /**
- * Sets the (unqualified) name of the type that encloses this type.
- */
- protected void setEnclosingTypeName(char[] enclosingTypeName) {
- fEnclosingTypeName = enclosingTypeName;
- }
-
- /**
- * Sets the handle for this type info
- */
- protected void setHandle(IType handle) {
- fHandle = handle;
- }
-
- /**
- * Sets the name of the package this type is declared in.
- */
- protected void setPackageName(char[] name) {
- fPackageName = name;
- }
-
- /**
- * Sets this type's qualified name.
- */
- protected void setQualifiedName(char[] name) {
- fQualifiedName = name;
- }
-
- /**
- * Sets the name of the source file this type is declared in.
- */
- protected void setSourceFileName(char[] name) {
- fSourceFileName = name;
- }
-
- /**
- * Sets the (unqualified) name of this type's superclass
- */
- protected void setSuperclassName(char[] superclassName) {
- fSuperclassName = superclassName;
- }
-
- /**
- * Sets the (unqualified) names of the interfaces this type implements or extends
- */
- protected void setSuperInterfaceNames(char[][] superInterfaceNames) {
- fSuperInterfaceNames = superInterfaceNames;
- }
-
+}
+/**
+ * @see ISourceType
+ */
+public char[] getEnclosingTypeName() {
+ return fEnclosingTypeName;
+}
+/**
+ * @see ISourceType
+ */
+public ISourceField[] getFields() {
+ return fFields;
+}
+/**
+ * @see ISourceType
+ */
+public char[] getFileName() {
+ return fSourceFileName;
+}
+/**
+ * Returns the handle for this type info
+ */
+public IType getHandle() {
+ return fHandle;
+}
+/**
+ * @see ISourceType
+ */
+public char[][] getImports() {
+ return fImports;
+}
+/**
+ * @see ISourceType
+ */
+public char[][] getInterfaceNames() {
+ return fSuperInterfaceNames;
+}
+/**
+ * @see ISourceType
+ */
+public ISourceType[] getMemberTypes() {
+ return fMemberTypes;
+}
+/**
+ * @see ISourceType
+ */
+public ISourceMethod[] getMethods() {
+ return fMethods;
+}
+/**
+ * @see ISourceType
+ */
+public char[] getPackageName() {
+ return fPackageName;
+}
+/**
+ * @see ISourceType
+ */
+public char[] getQualifiedName() {
+ return fQualifiedName;
+}
+/**
+ * @see ISourceType
+ */
+public char[] getSuperclassName() {
+ return fSuperclassName;
+}
+/**
+ * @see ISourceType
+ */
+public boolean isBinaryType() {
+ return false;
+}
+/**
+ * @see ISourceType
+ */
+public boolean isClass() {
+ return (this.flags & IConstants.AccInterface) == 0;
+}
+/**
+ * @see ISourceType
+ */
+public boolean isInterface() {
+ return (this.flags & IConstants.AccInterface) != 0;
+}
+/**
+ * Sets the (unqualified) name of the type that encloses this type.
+ */
+protected void setEnclosingTypeName(char[] enclosingTypeName) {
+ fEnclosingTypeName = enclosingTypeName;
+}
+/**
+ * Sets the handle for this type info
+ */
+protected void setHandle(IType handle) {
+ fHandle= handle;
+}
+/**
+ * Sets the name of the package this type is declared in.
+ */
+protected void setPackageName(char[] name) {
+ fPackageName= name;
+}
+/**
+ * Sets this type's qualified name.
+ */
+protected void setQualifiedName(char[] name) {
+ fQualifiedName= name;
+}
+/**
+ * Sets the name of the source file this type is declared in.
+ */
+protected void setSourceFileName(char[] name) {
+ fSourceFileName= name;
+}
+/**
+ * Sets the (unqualified) name of this type's superclass
+ */
+protected void setSuperclassName(char[] superclassName) {
+ fSuperclassName = superclassName;
+}
+/**
+ * Sets the (unqualified) names of the interfaces this type implements or extends
+ */
+protected void setSuperInterfaceNames(char[][] superInterfaceNames) {
+ fSuperInterfaceNames = superInterfaceNames;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/TypeVector.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/TypeVector.java
index 9d45479fff..11c365754f 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/TypeVector.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/TypeVector.java
@@ -8,117 +8,93 @@ import org.eclipse.jdt.core.IType;
public final class TypeVector {
static int INITIAL_SIZE = 10;
-
+
public int size;
int maxSize;
IType[] elements;
- public TypeVector() {
- maxSize = INITIAL_SIZE;
- size = 0;
- elements = new IType[maxSize];
- }
-
- public TypeVector(IType[] types) {
- this.size = types.length;
- this.maxSize = this.size + 1;
- // when an element is added, it assumes that the length is > 0
- elements = new IType[this.maxSize];
- System.arraycopy(types, 0, elements, 0, this.size);
- }
-
- public TypeVector(IType type) {
- this.maxSize = INITIAL_SIZE;
- this.size = 1;
- elements = new IType[this.maxSize];
- elements[0] = type;
- }
-
- public void add(IType newElement) {
- if (size == maxSize) // knows that size starts <= maxSize
- System.arraycopy(elements, 0, (elements = new IType[maxSize *= 2]), 0, size);
- elements[size++] = newElement;
- }
-
- public void addAll(IType[] newElements) {
- if (size + newElements.length >= maxSize) {
- maxSize = size + newElements.length; // assume no more elements will be added
- System.arraycopy(elements, 0, (elements = new IType[maxSize]), 0, size);
- }
- System.arraycopy(newElements, 0, elements, size, newElements.length);
- size += newElements.length;
- }
-
- public boolean contains(IType element) {
- for (int i = size; --i >= 0;)
- if (element.equals(elements[i]))
- return true;
- return false;
- }
-
- public TypeVector copy() {
- TypeVector clone = new TypeVector();
- int length = this.elements.length;
- System.arraycopy(
- this.elements,
- 0,
- clone.elements = new IType[length],
- 0,
- length);
- clone.size = this.size;
- clone.maxSize = this.maxSize;
- return clone;
- }
-
- public IType elementAt(int index) {
- return elements[index];
- }
-
- public IType[] elements() {
- if (this.size < this.maxSize) {
- maxSize = size;
- System.arraycopy(
- this.elements,
- 0,
- (this.elements = new IType[maxSize]),
- 0,
- size);
- }
- return this.elements;
- }
-
- public IType find(IType element) {
- for (int i = size; --i >= 0;)
- if (element == elements[i])
- return elements[i];
- return null;
- }
-
- public IType remove(IType element) {
- // assumes only one occurrence of the element exists
- for (int i = size; --i >= 0;)
- if (element == elements[i]) {
- // shift the remaining elements down one spot
- System.arraycopy(elements, i + 1, elements, i, --size - i);
- elements[size] = null;
- return element;
- }
- return null;
+public TypeVector() {
+ maxSize = INITIAL_SIZE;
+ size = 0;
+ elements = new IType[maxSize];
+}
+public TypeVector(IType[] types) {
+ this.size = types.length;
+ this.maxSize = this.size + 1; // when an element is added, it assumes that the length is > 0
+ elements = new IType[this.maxSize];
+ System.arraycopy(types, 0, elements, 0, this.size);
+}
+public TypeVector(IType type) {
+ this.maxSize = INITIAL_SIZE;
+ this.size = 1;
+ elements = new IType[this.maxSize];
+ elements[0] = type;
+}
+public void add(IType newElement) {
+ if (size == maxSize) // knows that size starts <= maxSize
+ System.arraycopy(elements, 0, (elements = new IType[maxSize *= 2]), 0, size);
+ elements[size++] = newElement;
+}
+public void addAll(IType[] newElements) {
+ if (size + newElements.length >= maxSize) {
+ maxSize = size + newElements.length; // assume no more elements will be added
+ System.arraycopy(elements, 0, (elements = new IType[maxSize]), 0, size);
}
-
- public void removeAll() {
- for (int i = size; --i >= 0;)
- elements[i] = null;
- size = 0;
+ System.arraycopy(newElements, 0, elements, size, newElements.length);
+ size += newElements.length;
+}
+public boolean contains(IType element) {
+ for (int i = size; --i >= 0;)
+ if (element.equals(elements[i]))
+ return true;
+ return false;
+}
+public TypeVector copy() {
+ TypeVector clone = new TypeVector();
+ int length = this.elements.length;
+ System.arraycopy(this.elements, 0, clone.elements = new IType[length], 0, length);
+ clone.size = this.size;
+ clone.maxSize = this.maxSize;
+ return clone;
+}
+public IType elementAt(int index) {
+ return elements[index];
+}
+public IType[] elements() {
+ if (this.size < this.maxSize) {
+ maxSize = size;
+ System.arraycopy(this.elements, 0, (this.elements = new IType[maxSize]), 0, size);
}
-
- public String toString() {
- StringBuffer buffer = new StringBuffer("[");
- for (int i = 0; i < size; i++) {
- buffer.append("\n");
- buffer.append(elements[i]);
+ return this.elements;
+}
+public IType find(IType element) {
+ for (int i = size; --i >= 0;)
+ if (element == elements[i])
+ return elements[i];
+ return null;
+}
+public IType remove(IType element) {
+ // assumes only one occurrence of the element exists
+ for (int i = size; --i >= 0;)
+ if (element == elements[i]) {
+ // shift the remaining elements down one spot
+ System.arraycopy(elements, i + 1, elements, i, --size - i);
+ elements[size] = null;
+ return element;
}
- buffer.append("\n]");
- return buffer.toString();
+ return null;
+}
+public void removeAll() {
+ for (int i = size; --i >= 0;)
+ elements[i] = null;
+ size = 0;
+}
+public String toString() {
+ StringBuffer buffer = new StringBuffer("["/*nonNLS*/);
+ for (int i = 0; i < size; i++) {
+ buffer.append("\n"/*nonNLS*/);
+ buffer.append(elements[i]);
}
-
+ buffer.append("\n]"/*nonNLS*/);
+ return buffer.toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Util.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Util.java
index e7ab522a32..4c39fff104 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Util.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/Util.java
@@ -8,6 +8,10 @@ import org.eclipse.jdt.internal.compiler.util.CharOperation;
import java.io.*;
+import java.util.MissingResourceException;
+import java.util.Locale;
+import java.util.ResourceBundle;
+
/**
* Provides convenient utility methods to other types in this package.
*/
@@ -28,7 +32,7 @@ public class Util {
*/
int compare(Object a, Object b);
}
-
+
public static final String[] fgEmptyStringArray = new String[0];
/**
@@ -36,129 +40,123 @@ public class Util {
*/
private static boolean JDK1_1 = false;
- static {
- String ver = System.getProperty("java.version");
- JDK1_1 = ((ver != null) && ver.startsWith("1.1"));
- }
+ /* Bundle containing messages */
+ protected static ResourceBundle bundle;
+ private final static String bundleName = "org.eclipse.jdt.internal.core.Messages"/*nonNLS*/;
+
+ public final static char[] SUFFIX_class = ".class"/*nonNLS*/.toCharArray();
+ public final static char[] SUFFIX_CLASS = ".CLASS"/*nonNLS*/.toCharArray();
+ public final static char[] SUFFIX_java = ".java"/*nonNLS*/.toCharArray();
+ public final static char[] SUFFIX_JAVA = ".JAVA"/*nonNLS*/.toCharArray();
+ static {
+ String ver = System.getProperty("java.version"/*nonNLS*/);
+ JDK1_1 = ((ver != null) && ver.startsWith("1.1"/*nonNLS*/));
+ relocalize();
+ }
/**
* Checks the type signature in String sig,
* starting at start and ending before end (end is not included).
* Returns the index of the character immediately after the signature if valid,
* or -1 if not valid.
*/
- private static int checkTypeSignature(
- String sig,
- int start,
- int end,
- boolean allowVoid) {
- if (start >= end)
- return -1;
+ private static int checkTypeSignature(String sig, int start, int end, boolean allowVoid) {
+ if (start >= end) return -1;
int i = start;
char c = sig.charAt(i++);
int nestingDepth = 0;
while (c == '[') {
++nestingDepth;
- if (i >= end)
- return -1;
+ if (i >= end) return -1;
c = sig.charAt(i++);
}
switch (c) {
- case 'B' :
- case 'C' :
- case 'D' :
- case 'F' :
- case 'I' :
- case 'J' :
- case 'S' :
- case 'Z' :
+ case 'B':
+ case 'C':
+ case 'D':
+ case 'F':
+ case 'I':
+ case 'J':
+ case 'S':
+ case 'Z':
break;
- case 'V' :
- if (!allowVoid)
- return -1;
+ case 'V':
+ if (!allowVoid) return -1;
// array of void is not allowed
- if (nestingDepth != 0)
- return -1;
+ if (nestingDepth != 0) return -1;
break;
- case 'L' :
+ case 'L':
int semicolon = sig.indexOf(';', i);
// Must have at least one character between L and ;
- if (semicolon <= i || semicolon >= end)
- return -1;
+ if (semicolon <= i || semicolon >= end) return -1;
i = semicolon + 1;
break;
- default :
+ default:
return -1;
}
return i;
}
-
- /**
- * Combines two hash codes to make a new one.
- */
- public static int combineHashCodes(int hashCode1, int hashCode2) {
- return hashCode1 * 17 + hashCode2;
- }
-
- /**
- * Compares two byte arrays.
- * Returns <0 if a byte in a is less than the corresponding byte in b, or if a is shorter, or if a is null.
- * Returns >0 if a byte in a is greater than the corresponding byte in b, or if a is longer, or if b is null.
- * Returns 0 if they are equal or both null.
- */
- public static int compare(byte[] a, byte[] b) {
- if (a == b)
- return 0;
- if (a == null)
- return -1;
- if (b == null)
- return 1;
- int len = Math.min(a.length, b.length);
- for (int i = 0; i < len; ++i) {
- int diff = a[i] - b[i];
- if (diff != 0)
- return diff;
- }
- if (a.length > len)
- return 1;
- if (b.length > len)
- return -1;
+/**
+ * Combines two hash codes to make a new one.
+ */
+public static int combineHashCodes(int hashCode1, int hashCode2) {
+ return hashCode1 * 17 + hashCode2;
+}
+/**
+ * Compares two byte arrays.
+ * Returns <0 if a byte in a is less than the corresponding byte in b, or if a is shorter, or if a is null.
+ * Returns >0 if a byte in a is greater than the corresponding byte in b, or if a is longer, or if b is null.
+ * Returns 0 if they are equal or both null.
+ */
+public static int compare(byte[] a, byte[] b) {
+ if (a == b)
return 0;
- }
-
- /**
- * Compares two char arrays lexicographically.
- * The comparison is based on the Unicode value of each character in
- * the char arrays.
- * @return the value <code>0</code> if a is equal to
- * b; a value less than <code>0</code> if a
- * is lexicographically less than b; and a
- * value greater than <code>0</code> if a is
- * lexicographically greater than b.
- */
- public static int compare(char[] v1, char[] v2) {
- int len1 = v1.length;
- int len2 = v2.length;
- int n = Math.min(len1, len2);
- int i = 0;
- while (n-- != 0) {
- if (v1[i] != v2[i]) {
- return v1[i] - v2[i];
- }
- ++i;
+ if (a == null)
+ return -1;
+ if (b == null)
+ return 1;
+ int len = Math.min(a.length, b.length);
+ for (int i = 0; i < len; ++i) {
+ int diff = a[i] - b[i];
+ if (diff != 0)
+ return diff;
+ }
+ if (a.length > len)
+ return 1;
+ if (b.length > len)
+ return -1;
+ return 0;
+}
+/**
+ * Compares two char arrays lexicographically.
+ * The comparison is based on the Unicode value of each character in
+ * the char arrays.
+ * @return the value <code>0</code> if a is equal to
+ * b; a value less than <code>0</code> if a
+ * is lexicographically less than b; and a
+ * value greater than <code>0</code> if a is
+ * lexicographically greater than b.
+ */
+public static int compare(char[] v1, char[] v2) {
+ int len1 = v1.length;
+ int len2 = v2.length;
+ int n = Math.min(len1, len2);
+ int i = 0;
+ while (n-- != 0) {
+ if (v1[i] != v2[i]) {
+ return v1[i] - v2[i];
}
- return len1 - len2;
+ ++i;
}
-
+ return len1 - len2;
+}
/**
* Concatenate two strings with a char in between.
* @see concat(String, String)
*/
public static String concat(String s1, char c, String s2) {
- if (s1 == null)
- s1 = "null";
- if (s2 == null)
- s2 = "null";
+ if (s1 == null) s1 = "null"/*nonNLS*/;
+ if (s2 == null) s2 = "null"/*nonNLS*/;
int l1 = s1.length();
int l2 = s2.length();
char[] buf = new char[l1 + 1 + l2];
@@ -167,7 +165,6 @@ public class Util {
s2.getChars(0, l2, buf, l1 + 1);
return new String(buf);
}
-
/**
* Concatenate two strings.
* Much faster than using +, which:
@@ -179,10 +176,8 @@ public class Util {
* String constructor copies its argument, but there's no way around this.
*/
public static String concat(String s1, String s2) {
- if (s1 == null)
- s1 = "null";
- if (s2 == null)
- s2 = "null";
+ if (s1 == null) s1 = "null"/*nonNLS*/;
+ if (s2 == null) s2 = "null"/*nonNLS*/;
int l1 = s1.length();
int l2 = s2.length();
char[] buf = new char[l1 + l2];
@@ -190,18 +185,14 @@ public class Util {
s2.getChars(0, l2, buf, l1);
return new String(buf);
}
-
/**
* Concatenate three strings.
* @see concat(String, String)
*/
public static String concat(String s1, String s2, String s3) {
- if (s1 == null)
- s1 = "null";
- if (s2 == null)
- s2 = "null";
- if (s3 == null)
- s3 = "null";
+ if (s1 == null) s1 = "null"/*nonNLS*/;
+ if (s2 == null) s2 = "null"/*nonNLS*/;
+ if (s3 == null) s3 = "null"/*nonNLS*/;
int l1 = s1.length();
int l2 = s2.length();
int l3 = s3.length();
@@ -211,37 +202,34 @@ public class Util {
s3.getChars(0, l3, buf, l1 + l2);
return new String(buf);
}
-
- /**
- * Converts a type signature from the IBinaryType representation to the DC representation.
- */
- public static String convertTypeSignature(char[] sig) {
- return new String(sig).replace('/', '.');
- }
-
- /**
- * Compares two arrays using equals() on the elements.
- * Either or both arrays may be null.
- * Returns true if both are null.
- * Returns false if only one is null.
- * If both are arrays, returns true iff they have the same length and
- * all elements are equal.
- */
- public static boolean equalArraysOrNull(int[] a, int[] b) {
- if (a == b)
- return true;
- if (a == null || b == null)
- return false;
- int len = a.length;
- if (len != b.length)
- return false;
- for (int i = 0; i < len; ++i) {
- if (a[i] != b[i])
- return false;
- }
+/**
+ * Converts a type signature from the IBinaryType representation to the DC representation.
+ */
+public static String convertTypeSignature(char[] sig) {
+ return new String(sig).replace('/', '.');
+}
+/**
+ * Compares two arrays using equals() on the elements.
+ * Either or both arrays may be null.
+ * Returns true if both are null.
+ * Returns false if only one is null.
+ * If both are arrays, returns true iff they have the same length and
+ * all elements are equal.
+ */
+public static boolean equalArraysOrNull(int[] a, int[] b) {
+ if (a == b)
return true;
+ if (a == null || b == null)
+ return false;
+ int len = a.length;
+ if (len != b.length)
+ return false;
+ for (int i = 0; i < len; ++i) {
+ if (a[i] != b[i])
+ return false;
}
-
+ return true;
+}
/**
* Compares two arrays using equals() on the elements.
* Either or both arrays may be null.
@@ -251,21 +239,16 @@ public class Util {
* all elements compare true with equals.
*/
public static boolean equalArraysOrNull(Object[] a, Object[] b) {
- if (a == b)
- return true;
- if (a == null || b == null)
- return false;
+ if (a == b) return true;
+ if (a == null || b == null) return false;
int len = a.length;
- if (len != b.length)
- return false;
+ if (len != b.length) return false;
for (int i = 0; i < len; ++i) {
- if (!a[i].equals(b[i]))
- return false;
+ if (!a[i].equals(b[i])) return false;
}
return true;
}
-
/**
* Compares two String arrays using equals() on the elements.
* The arrays are first sorted.
@@ -277,24 +260,19 @@ public class Util {
* The original arrays are left untouched.
*/
public static boolean equalArraysOrNullSortFirst(String[] a, String[] b) {
- if (a == b)
- return true;
- if (a == null || b == null)
- return false;
+ if (a == b) return true;
+ if (a == null || b == null) return false;
int len = a.length;
- if (len != b.length)
- return false;
- if (len >= 2) { // only need to sort if more than two items
+ if (len != b.length) return false;
+ if (len >= 2) { // only need to sort if more than two items
a = sortCopy(a);
b = sortCopy(b);
}
for (int i = 0; i < len; ++i) {
- if (!a[i].equals(b[i]))
- return false;
+ if (!a[i].equals(b[i])) return false;
}
return true;
}
-
/**
* Compares two arrays using equals() on the elements.
* The arrays are first sorted.
@@ -305,27 +283,20 @@ public class Util {
* iff, after sorting both arrays, all elements compare true with equals.
* The original arrays are left untouched.
*/
- public static boolean equalArraysOrNullSortFirst(
- Comparable[] a,
- Comparable[] b) {
- if (a == b)
- return true;
- if (a == null || b == null)
- return false;
+ public static boolean equalArraysOrNullSortFirst(Comparable[] a, Comparable[] b) {
+ if (a == b) return true;
+ if (a == null || b == null) return false;
int len = a.length;
- if (len != b.length)
- return false;
- if (len >= 2) { // only need to sort if more than two items
+ if (len != b.length) return false;
+ if (len >= 2) { // only need to sort if more than two items
a = sortCopy(a);
b = sortCopy(b);
}
for (int i = 0; i < len; ++i) {
- if (!a[i].equals(b[i]))
- return false;
+ if (!a[i].equals(b[i])) return false;
}
return true;
}
-
/**
* Compares two objects using equals().
* Either or both array may be null.
@@ -342,118 +313,106 @@ public class Util {
}
return a.equals(b);
}
-
/**
* Given a qualified name, extract the last component.
* If the input is not qualified, the same string is answered.
*/
public static String extractLastName(String qualifiedName) {
int i = qualifiedName.lastIndexOf('.');
- if (i == -1)
- return qualifiedName;
- return qualifiedName.substring(i + 1);
+ if (i == -1) return qualifiedName;
+ return qualifiedName.substring(i+1);
}
-
- /**
- * Extracts the parameter types from a method signature.
- */
- public static String[] extractParameterTypes(char[] sig) {
- int count = getParameterCount(sig);
- String[] result = new String[count];
- if (count == 0)
- return result;
- int i = CharOperation.indexOf('(', sig) + 1;
- count = 0;
- int len = sig.length;
- int start = i;
- for (;;) {
- if (i == len)
- break;
- char c = sig[i];
- if (c == ')')
- break;
- if (c == '[') {
- ++i;
- } else
- if (c == 'L') {
- i = CharOperation.indexOf(';', sig, i + 1) + 1;
- Assert.isTrue(i != 0);
- result[count++] = convertTypeSignature(CharOperation.subarray(sig, start, i));
- start = i;
- } else {
- ++i;
- result[count++] = convertTypeSignature(CharOperation.subarray(sig, start, i));
- start = i;
- }
- }
+/**
+ * Extracts the parameter types from a method signature.
+ */
+public static String[] extractParameterTypes(char[] sig) {
+ int count = getParameterCount(sig);
+ String[] result = new String[count];
+ if (count == 0)
return result;
+ int i = CharOperation.indexOf('(', sig) + 1;
+ count = 0;
+ int len = sig.length;
+ int start = i;
+ for (;;) {
+ if (i == len)
+ break;
+ char c = sig[i];
+ if (c == ')')
+ break;
+ if (c == '[') {
+ ++i;
+ } else
+ if (c == 'L') {
+ i = CharOperation.indexOf(';', sig, i + 1) + 1;
+ Assert.isTrue(i != 0);
+ result[count++] = convertTypeSignature(CharOperation.subarray(sig, start, i));
+ start = i;
+ } else {
+ ++i;
+ result[count++] = convertTypeSignature(CharOperation.subarray(sig, start, i));
+ start = i;
+ }
}
-
+ return result;
+}
/**
* Extracts the return type from a method signature.
*/
public static String extractReturnType(String sig) {
int i = sig.lastIndexOf(')');
Assert.isTrue(i != -1);
- return sig.substring(i + 1);
+ return sig.substring(i+1);
}
-
- /**
- * Returns the number of parameter types in a method signature.
- */
- public static int getParameterCount(char[] sig) {
- int i = CharOperation.indexOf('(', sig) + 1;
- Assert.isTrue(i != 0);
- int count = 0;
- int len = sig.length;
- for (;;) {
- if (i == len)
- break;
- char c = sig[i];
- if (c == ')')
- break;
- if (c == '[') {
+/**
+ * Returns the number of parameter types in a method signature.
+ */
+public static int getParameterCount(char[] sig) {
+ int i = CharOperation.indexOf('(', sig) + 1;
+ Assert.isTrue(i != 0);
+ int count = 0;
+ int len = sig.length;
+ for (;;) {
+ if (i == len)
+ break;
+ char c = sig[i];
+ if (c == ')')
+ break;
+ if (c == '[') {
+ ++i;
+ } else
+ if (c == 'L') {
+ ++count;
+ i = CharOperation.indexOf(';', sig, i + 1) + 1;
+ Assert.isTrue(i != 0);
+ } else {
+ ++count;
++i;
- } else
- if (c == 'L') {
- ++count;
- i = CharOperation.indexOf(';', sig, i + 1) + 1;
- Assert.isTrue(i != 0);
- } else {
- ++count;
- ++i;
- }
- }
- return count;
+ }
}
-
+ return count;
+}
/**
* Returns true if the given method signature is valid,
* false if it is not.
*/
public static boolean isValidMethodSignature(String sig) {
int len = sig.length();
- if (len == 0)
- return false;
+ if (len == 0) return false;
int i = 0;
char c = sig.charAt(i++);
- if (c != '(')
- return false;
- if (i >= len)
- return false;
+ if (c != '(') return false;
+ if (i >= len) return false;
while (sig.charAt(i) != ')') {
// Void is not allowed as a parameter type.
i = checkTypeSignature(sig, i, len, false);
- if (i == -1)
- return false;
- if (i >= len)
- return false;
+ if (i == -1) return false;
+ if (i >= len) return false;
}
++i;
i = checkTypeSignature(sig, i, len, true);
return i == len;
}
-
/**
* Returns true if the given type signature is valid,
* false if it is not.
@@ -462,248 +421,217 @@ public class Util {
int len = sig.length();
return checkTypeSignature(sig, 0, len, allowVoid) == len;
}
-
- /**
- * Sort the objects in the given collection using the given sort order.
- */
- private static void quickSort(
- Object[] sortedCollection,
- int left,
- int right,
- int[] sortOrder) {
- int original_left = left;
- int original_right = right;
- int mid = sortOrder[(left + right) / 2];
- do {
- while (sortOrder[left] < mid) {
- left++;
- }
- while (mid < sortOrder[right]) {
- right--;
- }
- if (left <= right) {
- Object tmp = sortedCollection[left];
- sortedCollection[left] = sortedCollection[right];
- sortedCollection[right] = tmp;
- int tmp2 = sortOrder[left];
- sortOrder[left] = sortOrder[right];
- sortOrder[right] = tmp2;
- left++;
- right--;
- }
- }
- while (left <= right);
- if (original_left < right) {
- quickSort(sortedCollection, original_left, right, sortOrder);
- }
- if (left < original_right) {
- quickSort(sortedCollection, left, original_right, sortOrder);
- }
+/**
+ * Sort the objects in the given collection using the given sort order.
+ */
+private static void quickSort(Object[] sortedCollection, int left, int right, int[] sortOrder) {
+ int original_left = left;
+ int original_right = right;
+ int mid = sortOrder[ (left + right) / 2];
+ do {
+ while (sortOrder[left] < mid) {
+ left++;
+ }
+ while (mid < sortOrder[right]) {
+ right--;
+ }
+ if (left <= right) {
+ Object tmp = sortedCollection[left];
+ sortedCollection[left] = sortedCollection[right];
+ sortedCollection[right] = tmp;
+ int tmp2 = sortOrder[left];
+ sortOrder[left] = sortOrder[right];
+ sortOrder[right] = tmp2;
+ left++;
+ right--;
+ }
+ } while (left <= right);
+ if (original_left < right) {
+ quickSort(sortedCollection, original_left, right, sortOrder);
+ }
+ if (left < original_right) {
+ quickSort(sortedCollection, left, original_right, sortOrder);
}
-
- /**
- * Sort the objects in the given collection using the given comparer.
- */
- private static void quickSort(
- Object[] sortedCollection,
- int left,
- int right,
- Comparer comparer) {
- int original_left = left;
- int original_right = right;
- Object mid = sortedCollection[(left + right) / 2];
- do {
- while (comparer.compare(sortedCollection[left], mid) < 0) {
- left++;
- }
- while (comparer.compare(mid, sortedCollection[right]) < 0) {
- right--;
- }
- if (left <= right) {
- Object tmp = sortedCollection[left];
- sortedCollection[left] = sortedCollection[right];
- sortedCollection[right] = tmp;
- left++;
- right--;
- }
- }
- while (left <= right);
- if (original_left < right) {
- quickSort(sortedCollection, original_left, right, comparer);
- }
- if (left < original_right) {
- quickSort(sortedCollection, left, original_right, comparer);
- }
+}
+/**
+ * Sort the objects in the given collection using the given comparer.
+ */
+private static void quickSort(Object[] sortedCollection, int left, int right, Comparer comparer) {
+ int original_left = left;
+ int original_right = right;
+ Object mid = sortedCollection[ (left + right) / 2];
+ do {
+ while (comparer.compare(sortedCollection[left], mid) < 0) {
+ left++;
+ }
+ while (comparer.compare(mid, sortedCollection[right]) < 0) {
+ right--;
+ }
+ if (left <= right) {
+ Object tmp = sortedCollection[left];
+ sortedCollection[left] = sortedCollection[right];
+ sortedCollection[right] = tmp;
+ left++;
+ right--;
+ }
+ } while (left <= right);
+ if (original_left < right) {
+ quickSort(sortedCollection, original_left, right, comparer);
+ }
+ if (left < original_right) {
+ quickSort(sortedCollection, left, original_right, comparer);
}
-
- /**
- * Sort the strings in the given collection.
- */
- private static void quickSort(String[] sortedCollection, int left, int right) {
- int original_left = left;
- int original_right = right;
- String mid = sortedCollection[(left + right) / 2];
- do {
- while (sortedCollection[left].compareTo(mid) < 0) {
- left++;
- }
- while (mid.compareTo(sortedCollection[right]) < 0) {
- right--;
- }
- if (left <= right) {
- String tmp = sortedCollection[left];
- sortedCollection[left] = sortedCollection[right];
- sortedCollection[right] = tmp;
- left++;
- right--;
- }
- }
- while (left <= right);
- if (original_left < right) {
- quickSort(sortedCollection, original_left, right);
- }
- if (left < original_right) {
- quickSort(sortedCollection, left, original_right);
- }
+}
+/**
+ * Sort the strings in the given collection.
+ */
+private static void quickSort(String[] sortedCollection, int left, int right) {
+ int original_left = left;
+ int original_right = right;
+ String mid = sortedCollection[ (left + right) / 2];
+ do {
+ while (sortedCollection[left].compareTo(mid) < 0) {
+ left++;
+ }
+ while (mid.compareTo(sortedCollection[right]) < 0) {
+ right--;
+ }
+ if (left <= right) {
+ String tmp = sortedCollection[left];
+ sortedCollection[left] = sortedCollection[right];
+ sortedCollection[right] = tmp;
+ left++;
+ right--;
+ }
+ } while (left <= right);
+ if (original_left < right) {
+ quickSort(sortedCollection, original_left, right);
+ }
+ if (left < original_right) {
+ quickSort(sortedCollection, left, original_right);
}
-
- /**
- * Sort the comparable objects in the given collection.
- */
- private static void quickSort(
- Comparable[] sortedCollection,
- int left,
- int right) {
- int original_left = left;
- int original_right = right;
- Comparable mid = sortedCollection[(left + right) / 2];
- do {
- while (sortedCollection[left].compareTo(mid) < 0) {
- left++;
- }
- while (mid.compareTo(sortedCollection[right]) < 0) {
- right--;
- }
- if (left <= right) {
- Comparable tmp = sortedCollection[left];
- sortedCollection[left] = sortedCollection[right];
- sortedCollection[right] = tmp;
- left++;
- right--;
- }
- }
- while (left <= right);
- if (original_left < right) {
- quickSort(sortedCollection, original_left, right);
- }
- if (left < original_right) {
- quickSort(sortedCollection, left, original_right);
- }
+}
+/**
+ * Sort the comparable objects in the given collection.
+ */
+private static void quickSort(Comparable[] sortedCollection, int left, int right) {
+ int original_left = left;
+ int original_right = right;
+ Comparable mid = sortedCollection[ (left + right) / 2];
+ do {
+ while (sortedCollection[left].compareTo(mid) < 0) {
+ left++;
+ }
+ while (mid.compareTo(sortedCollection[right]) < 0) {
+ right--;
+ }
+ if (left <= right) {
+ Comparable tmp = sortedCollection[left];
+ sortedCollection[left] = sortedCollection[right];
+ sortedCollection[right] = tmp;
+ left++;
+ right--;
+ }
+ } while (left <= right);
+ if (original_left < right) {
+ quickSort(sortedCollection, original_left, right);
+ }
+ if (left < original_right) {
+ quickSort(sortedCollection, left, original_right);
}
-
- /**
- * Sort the strings in the given collection in reverse alphabetical order.
- */
- private static void quickSortReverse(
- String[] sortedCollection,
- int left,
- int right) {
- int original_left = left;
- int original_right = right;
- String mid = sortedCollection[(left + right) / 2];
- do {
- while (sortedCollection[left].compareTo(mid) > 0) {
- left++;
- }
- while (mid.compareTo(sortedCollection[right]) > 0) {
- right--;
- }
- if (left <= right) {
- String tmp = sortedCollection[left];
- sortedCollection[left] = sortedCollection[right];
- sortedCollection[right] = tmp;
- left++;
- right--;
- }
- }
- while (left <= right);
- if (original_left < right) {
- quickSortReverse(sortedCollection, original_left, right);
+}
+/**
+ * Sort the strings in the given collection in reverse alphabetical order.
+ */
+private static void quickSortReverse(String[] sortedCollection, int left, int right) {
+ int original_left = left;
+ int original_right = right;
+ String mid = sortedCollection[ (left + right) / 2];
+ do {
+ while (sortedCollection[left].compareTo(mid) > 0) {
+ left++;
+ }
+ while (mid.compareTo(sortedCollection[right]) > 0) {
+ right--;
+ }
+ if (left <= right) {
+ String tmp = sortedCollection[left];
+ sortedCollection[left] = sortedCollection[right];
+ sortedCollection[right] = tmp;
+ left++;
+ right--;
+ }
+ } while (left <= right);
+ if (original_left < right) {
+ quickSortReverse(sortedCollection, original_left, right);
+ }
+ if (left < original_right) {
+ quickSortReverse(sortedCollection, left, original_right);
+ }
+}
+public static byte[] readContentsAsBytes(InputStream input) throws IOException {
+ BufferedInputStream bufferedInputStream = null;
+ try {
+ final int BUF_SIZE = 8192;
+ byte[] buf = new byte[BUF_SIZE];
+ int read;
+ int totalRead = 0;
+ bufferedInputStream = new BufferedInputStream(input);
+ while (totalRead < BUF_SIZE && (read = bufferedInputStream.read(buf, totalRead, BUF_SIZE - totalRead)) != -1) {
+ totalRead += read;
+ }
+ if (totalRead < BUF_SIZE) {
+ byte[] result = new byte[totalRead];
+ System.arraycopy(buf, 0, result, 0, totalRead);
+ return result;
}
- if (left < original_right) {
- quickSortReverse(sortedCollection, left, original_right);
+ ByteArrayOutputStream out = new ByteArrayOutputStream(BUF_SIZE*2);
+ out.write(buf);
+ while ((read = bufferedInputStream.read(buf, 0, BUF_SIZE)) != -1) {
+ out.write(buf, 0, read);
}
+ return out.toByteArray();
}
-
- public static byte[] readContentsAsBytes(InputStream input)
- throws IOException {
- BufferedInputStream bufferedInputStream = null;
+ finally {
try {
- final int BUF_SIZE = 8192;
- byte[] buf = new byte[BUF_SIZE];
- int read;
- int totalRead = 0;
- bufferedInputStream = new BufferedInputStream(input);
- while (totalRead < BUF_SIZE
- && (read = bufferedInputStream.read(buf, totalRead, BUF_SIZE - totalRead))
- != -1) {
- totalRead += read;
- }
- if (totalRead < BUF_SIZE) {
- byte[] result = new byte[totalRead];
- System.arraycopy(buf, 0, result, 0, totalRead);
- return result;
- }
- ByteArrayOutputStream out = new ByteArrayOutputStream(BUF_SIZE * 2);
- out.write(buf);
- while ((read = bufferedInputStream.read(buf, 0, BUF_SIZE)) != -1) {
- out.write(buf, 0, read);
- }
- return out.toByteArray();
- } finally {
- try {
- if (bufferedInputStream != null) {
- bufferedInputStream.close();
- }
- } catch (IOException e) {
- // Ignore
+ if (bufferedInputStream != null) {
+ bufferedInputStream.close();
}
}
+ catch (IOException e) {
+ // Ignore
+ }
}
-
- /**
- * Sorts an array of objects in place, using the sort order given for each item.
- */
- public static void sort(Object[] objects, int[] sortOrder) {
- if (objects.length > 1)
- quickSort(objects, 0, objects.length - 1, sortOrder);
- }
-
- /**
- * Sorts an array of objects in place.
- * The given comparer compares pairs of items.
- */
- public static void sort(Object[] objects, Comparer comparer) {
- if (objects.length > 1)
- quickSort(objects, 0, objects.length - 1, comparer);
- }
-
- /**
- * Sorts an array of strings in place using quicksort.
- */
- public static void sort(String[] strings) {
- if (strings.length > 1)
- quickSort(strings, 0, strings.length - 1);
- }
-
- /**
- * Sorts an array of Comparable objects in place.
- */
- public static void sort(Comparable[] objects) {
- if (objects.length > 1)
- quickSort(objects, 0, objects.length - 1);
- }
-
+}
+/**
+ * Sorts an array of objects in place, using the sort order given for each item.
+ */
+public static void sort(Object[] objects, int[] sortOrder) {
+ if (objects.length > 1)
+ quickSort(objects, 0, objects.length - 1, sortOrder);
+}
+/**
+ * Sorts an array of objects in place.
+ * The given comparer compares pairs of items.
+ */
+public static void sort(Object[] objects, Comparer comparer) {
+ if (objects.length > 1)
+ quickSort(objects, 0, objects.length - 1, comparer);
+}
+/**
+ * Sorts an array of strings in place using quicksort.
+ */
+public static void sort(String[] strings) {
+ if (strings.length > 1)
+ quickSort(strings, 0, strings.length - 1);
+}
+/**
+ * Sorts an array of Comparable objects in place.
+ */
+public static void sort(Comparable[] objects) {
+ if (objects.length > 1)
+ quickSort(objects, 0, objects.length - 1);
+}
/**
* Sorts an array of Strings, returning a new array
* with the sorted items. The original array is left untouched.
@@ -715,7 +643,6 @@ public class Util {
sort(copy, comparer);
return copy;
}
-
/**
* Sorts an array of Strings, returning a new array
* with the sorted items. The original array is left untouched.
@@ -727,7 +654,6 @@ public class Util {
sort(copy);
return copy;
}
-
/**
* Sorts an array of Comparable objects, returning a new array
* with the sorted items. The original array is left untouched.
@@ -739,16 +665,14 @@ public class Util {
sort(copy);
return copy;
}
-
- /**
- * Sorts an array of strings in place using quicksort
- * in reverse alphabetical order.
- */
- public static void sortReverseOrder(String[] strings) {
- if (strings.length > 1)
- quickSortReverse(strings, 0, strings.length - 1);
- }
-
+/**
+ * Sorts an array of strings in place using quicksort
+ * in reverse alphabetical order.
+ */
+public static void sortReverseOrder(String[] strings) {
+ if (strings.length > 1)
+ quickSortReverse(strings, 0, strings.length - 1);
+}
/**
* Converts a String[] to char[][].
*/
@@ -760,7 +684,6 @@ public class Util {
}
return result;
}
-
/**
* Converts a String to char[].
*/
@@ -770,7 +693,6 @@ public class Util {
s.getChars(0, len, chars, 0);
return chars;
}
-
/**
* Converts a String to char[][], where segments are separate by '.'.
*/
@@ -794,26 +716,22 @@ public class Util {
}
return segs;
}
-
/**
* Converts a char[][] to String, where segments are separated by '.'.
*/
public static String toString(char[][] c) {
StringBuffer sb = new StringBuffer();
for (int i = 0, max = c.length; i < max; ++i) {
- if (i != 0)
- sb.append('.');
+ if (i != 0) sb.append('.');
sb.append(c[i]);
}
return sb.toString();
}
-
/**
* Converts a char[][] and a char[] to String, where segments are separated by '.'.
*/
public static String toString(char[][] c, char[] d) {
- if (c == null)
- return new String(d);
+ if (c == null) return new String(d);
StringBuffer sb = new StringBuffer();
for (int i = 0, max = c.length; i < max; ++i) {
sb.append(c[i]);
@@ -822,21 +740,18 @@ public class Util {
sb.append(d);
return sb.toString();
}
-
/**
* Converts a char[] to String.
*/
public static String toString(char[] c) {
return new String(c);
}
-
/**
* Asserts that the given method signature is valid.
*/
public static void validateMethodSignature(String sig) {
Assert.isTrue(isValidMethodSignature(sig));
}
-
/**
* Asserts that the given type signature is valid.
*/
@@ -844,4 +759,136 @@ public class Util {
Assert.isTrue(isValidTypeSignature(sig, allowVoid));
}
+/**
+ * Lookup the message with the given ID in this catalog
+ */
+public static String bind(String id) {
+ return bind(id, (String[])null);
+}
+
+/**
+ * Lookup the message with the given ID in this catalog and bind its
+ * substitution locations with the given string values.
+ */
+public static String bind(String id, String[] bindings) {
+ if (id == null)
+ return "No message available"/*nonNLS*/;
+ String message = null;
+ try {
+ message = bundle.getString(id);
+ } catch (MissingResourceException e) {
+ // If we got an exception looking for the message, fail gracefully by just returning
+ // the id we were looking for. In most cases this is semi-informative so is not too bad.
+ return "Missing message: "/*nonNLS*/ + id + " in: "/*nonNLS*/ + bundleName;
+ }
+ if (bindings == null)
+ return message;
+ int length = message.length();
+ int start = -1;
+ int end = length;
+ StringBuffer output = new StringBuffer(80);
+ while (true) {
+ if ((end = message.indexOf('{', start)) > -1) {
+ output.append(message.substring(start + 1, end));
+ if ((start = message.indexOf('}', end)) > -1) {
+ int index = -1;
+ try {
+ index = Integer.parseInt(message.substring(end + 1, start));
+ output.append(bindings[index]);
+ } catch (NumberFormatException nfe) {
+ output.append(message.substring(end + 1, start + 1));
+ } catch (ArrayIndexOutOfBoundsException e) {
+ output.append("{missing "/*nonNLS*/ + Integer.toString(index) + "}"/*nonNLS*/);
+ }
+ } else {
+ output.append(message.substring(end, length));
+ break;
+ }
+ } else {
+ output.append(message.substring(start + 1, length));
+ break;
+ }
+ }
+ return output.toString();
+}
+
+/**
+ * Lookup the message with the given ID in this catalog and bind its
+ * substitution locations with the given string.
+ */
+public static String bind(String id, String binding) {
+ return bind(id, new String[] {binding});
+}
+
+/**
+ * Lookup the message with the given ID in this catalog and bind its
+ * substitution locations with the given strings.
+ */
+public static String bind(String id, String binding1, String binding2) {
+ return bind(id, new String[] {binding1, binding2});
+}
+
+ /**
+ * Returns true iff str.toLowerCase().endsWith(end.toLowerCase())
+ * implementation is not creating extra strings.
+ */
+ public final static boolean endsWithIgnoreCase(String str, String end) {
+
+ int strLength = str == null ? 0 : str.length();
+ int endLength = end == null ? 0 : end.length();
+
+ // return false if the string is smaller than the end.
+ if(endLength > strLength)
+ return false;
+
+ // return false if any character of the end are
+ // not the same in lower case.
+ for(int i = 1 ; i <= endLength; i++){
+ if(Character.toLowerCase(end.charAt(endLength - i)) != Character.toLowerCase(str.charAt(strLength - i)))
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Returns true iff str.toLowerCase().endsWith(".class")
+ * implementation is not creating extra strings.
+ */
+ public final static boolean isClassFileName(String name) {
+ int nameLength = name == null ? 0 : name.length();
+ int suffixLength = SUFFIX_CLASS.length;
+ if (nameLength < suffixLength) return false;
+
+ for (int i = 0; i < suffixLength; i++) {
+ char c = name.charAt(nameLength - i - 1);
+ int suffixIndex = suffixLength - i - 1;
+ if (c != SUFFIX_class[suffixIndex] && c != SUFFIX_CLASS[suffixIndex]) return false;
+ }
+ return true;
+ }
+
+ /**
+ * Returns true iff str.toLowerCase().endsWith(".java")
+ * implementation is not creating extra strings.
+ */
+ public final static boolean isJavaFileName(String name) {
+ int nameLength = name == null ? 0 : name.length();
+ int suffixLength = SUFFIX_JAVA.length;
+ if (nameLength < suffixLength) return false;
+
+ for (int i = 0; i < suffixLength; i++) {
+ char c = name.charAt(nameLength - i - 1);
+ int suffixIndex = suffixLength - i - 1;
+ if (c != SUFFIX_java[suffixIndex] && c != SUFFIX_JAVA[suffixIndex]) return false;
+ }
+ return true;
+ }
+
+/**
+ * Creates a NLS catalog for the given locale.
+ */
+public static void relocalize() {
+ bundle = ResourceBundle.getBundle(bundleName, Locale.getDefault());
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ValidateSourceElementOperation.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ValidateSourceElementOperation.java
index 4f3579348c..6bb454f5e5 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ValidateSourceElementOperation.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/ValidateSourceElementOperation.java
@@ -18,50 +18,41 @@ import org.eclipse.jdt.core.*;
* to an <code>IResource</code>.
*/
public class ValidateSourceElementOperation extends JavaModelOperation {
- /**
- * Validate the given Java Model element.
- */
- public ValidateSourceElementOperation(IJavaElement element) {
- super(element);
- }
-
- /**
- * Validate the element - TBD.
- */
- protected void executeOperation() throws JavaModelException {
+/**
+ * Validate the given Java Model element.
+ */
+public ValidateSourceElementOperation(IJavaElement element) {
+ super(element);
+}
+/**
+ * Validate the element - TBD.
+ */
+protected void executeOperation() throws JavaModelException {}
+/**
+ * Returns the errors and warnings as a set of <code>IMarkers</code>,
+ * or <code>null</code> if no errors or warnings were found.
+ */
+public IMarker[] getResult() {
+ return null;
+}
+/**
+ * Possible failures: <ul>
+ * <li>ELEMENTS_TO_PROCESS - an element was not provided
+ * <li>INVALID_ELEMENT_TYPES - the element provided is not a source element
+ * <li>ELEMENT_NOT_PRESENT - the element does not exist
+ * </ul>
+ */
+public IJavaModelStatus verify() {
+ IJavaModelStatus status = super.verify();
+ if (!status.isOK()) {
+ return status;
}
-
- /**
- * Returns the errors and warnings as a set of <code>IMarkers</code>,
- * or <code>null</code> if no errors or warnings were found.
- */
- public IMarker[] getResult() {
- return null;
+ if (!(getElementToProcess() instanceof ISourceReference)) {
+ return new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, getElementToProcess());
}
-
- /**
- * Possible failures: <ul>
- * <li>ELEMENTS_TO_PROCESS - an element was not provided
- * <li>INVALID_ELEMENT_TYPES - the element provided is not a source element
- * <li>ELEMENT_NOT_PRESENT - the element does not exist
- * </ul>
- */
- public IJavaModelStatus verify() {
- IJavaModelStatus status = super.verify();
- if (!status.isOK()) {
- return status;
- }
- if (!(getElementToProcess() instanceof ISourceReference)) {
- return new JavaModelStatus(
- IJavaModelStatusConstants.INVALID_ELEMENT_TYPES,
- getElementToProcess());
- }
- if (!getElementToProcess().exists()) {
- return new JavaModelStatus(
- IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST,
- getElementToProcess());
- }
- return JavaModelStatus.VERIFIED_OK;
+ if (!getElementToProcess().exists()) {
+ return new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, getElementToProcess());
}
-
+ return JavaModelStatus.VERIFIED_OK;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/WorkingCopy.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/WorkingCopy.java
index 99e8d5095c..d2dde904a8 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/WorkingCopy.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/WorkingCopy.java
@@ -19,9 +19,9 @@ import java.util.Vector;
* from.
*/
-/* package */
-class WorkingCopy extends CompilationUnit {
+/* package */ class WorkingCopy extends CompilationUnit {
+
/**
* A boolean indicating if this working copy has been
* destroyed. Once destroyed, it cannot be opened
@@ -29,313 +29,284 @@ class WorkingCopy extends CompilationUnit {
* never true if this compilation unit is not a working
* copy.
*/
- protected boolean fDestroyed = false;
- /**
- */
- protected WorkingCopy(IPackageFragment parent, String name) {
- super(parent, name);
- }
-
- /**
- * @see IWorkingCopy
- */
- public void commit(boolean force, IProgressMonitor monitor)
- throws JavaModelException {
- CommitWorkingCopyOperation op = new CommitWorkingCopyOperation(this, force);
- runOperation(op, monitor);
- }
-
- /**
- * Returns a new element info for this element.
- */
- protected OpenableElementInfo createElementInfo() {
- return new WorkingCopyElementInfo();
+ protected boolean fDestroyed= false;
+/**
+ */
+protected WorkingCopy(IPackageFragment parent, String name) {
+ super(parent, name);
+}
+/**
+ * @see IWorkingCopy
+ */
+public void commit(boolean force, IProgressMonitor monitor) throws JavaModelException {
+ CommitWorkingCopyOperation op= new CommitWorkingCopyOperation(this, force);
+ runOperation(op, monitor);
+}
+/**
+ * Returns a new element info for this element.
+ */
+protected OpenableElementInfo createElementInfo() {
+ return new WorkingCopyElementInfo();
+}
+/**
+ * @see IWorkingCopy
+ */
+public void destroy() {
+ try {
+ close();
+ } catch (JavaModelException e) {
+ // do nothing
}
-
- /**
- * @see IWorkingCopy
- */
- public void destroy() {
- try {
- close();
- } catch (JavaModelException e) {
- // do nothing
- }
- fDestroyed = true;
+ fDestroyed= true;
+}
+/**
+ * Working copies must be identical to be equal.
+ *
+ * @see Object#equals
+ */
+public boolean equals(Object o) {
+ return this == o;
+}
+/**
+ * @see IWorkingCopy
+ */
+public IJavaElement getOriginal(IJavaElement workingCopyElement) {
+ //not a element contained in a compilation unit
+ int javaElementType = workingCopyElement.getElementType();
+ if (javaElementType < COMPILATION_UNIT || javaElementType == CLASS_FILE) {
+ return null;
}
-
- /**
- * Working copies must be identical to be equal.
- *
- * @see Object#equals
- */
- public boolean equals(Object o) {
- return this == o;
+ if (workingCopyElement instanceof BinaryMember) {
+ return null;
}
-
- /**
- * @see IWorkingCopy
- */
- public IJavaElement getOriginal(IJavaElement workingCopyElement) {
- //not a element contained in a compilation unit
- int javaElementType = workingCopyElement.getElementType();
- if (javaElementType < COMPILATION_UNIT || javaElementType == CLASS_FILE) {
- return null;
- }
- if (workingCopyElement instanceof BinaryMember) {
- return null;
- }
- IJavaElement parent = workingCopyElement.getParent();
- Vector hierarchy = new Vector(4);
-
- while (parent.getElementType() > COMPILATION_UNIT) {
- hierarchy.addElement(parent);
- parent = parent.getParent();
- }
- if (parent.getElementType() == COMPILATION_UNIT) {
- hierarchy.addElement(((ICompilationUnit) parent).getOriginalElement());
- }
-
- ICompilationUnit cu = (ICompilationUnit) getOriginalElement();
- if (javaElementType == COMPILATION_UNIT) {
- parent = workingCopyElement;
- }
- if (((ICompilationUnit) parent).isWorkingCopy()
- && !((ICompilationUnit) parent).getOriginalElement().equals(cu)) {
- return null;
- }
- switch (javaElementType) {
- case PACKAGE_DECLARATION :
- return cu.getPackageDeclaration(workingCopyElement.getElementName());
- case IMPORT_DECLARATION :
- return cu.getImport(workingCopyElement.getElementName());
- case TYPE :
- if (hierarchy.size() == 1) {
- return cu.getType(workingCopyElement.getElementName());
- } else {
- //inner type
- return getOriginalType(hierarchy).getType(workingCopyElement.getElementName());
- }
- case METHOD :
- IType type;
- if (hierarchy.size() == 2) {
- String typeName = ((IJavaElement) hierarchy.elementAt(0)).getElementName();
- type = cu.getType(typeName);
- } else {
- //inner type
- type = getOriginalType(hierarchy);
- }
- return type.getMethod(
- workingCopyElement.getElementName(),
- ((IMethod) workingCopyElement).getParameterTypes());
- case FIELD :
- if (hierarchy.size() == 2) {
- String typeName = ((IJavaElement) hierarchy.elementAt(0)).getElementName();
- type = cu.getType(typeName);
- } else {
- //inner type
- type = getOriginalType(hierarchy);
- }
- return type.getField(workingCopyElement.getElementName());
- case INITIALIZER :
- if (hierarchy.size() == 2) {
- String typeName = ((IJavaElement) hierarchy.elementAt(0)).getElementName();
- type = cu.getType(typeName);
- } else {
- //inner type
- type = getOriginalType(hierarchy);
- }
- return type.getInitializer(
- ((Initializer) workingCopyElement).getOccurrenceCount());
- case COMPILATION_UNIT :
- return cu;
- default :
- return null;
- }
+ IJavaElement parent = workingCopyElement.getParent();
+ Vector hierarchy = new Vector(4);
+
+ while (parent.getElementType() > COMPILATION_UNIT) {
+ hierarchy.addElement(parent);
+ parent = parent.getParent();
}
-
- /**
- * @see IWorkingCopy
- */
- public IJavaElement getOriginalElement() {
- return new CompilationUnit((IPackageFragment) getParent(), getElementName());
+ if (parent.getElementType() == COMPILATION_UNIT) {
+ hierarchy.addElement(((ICompilationUnit)parent).getOriginalElement());
}
-
- protected IType getOriginalType(Vector hierarchy) {
- int size = hierarchy.size() - 1;
- ICompilationUnit typeCU = (ICompilationUnit) hierarchy.elementAt(size);
- String typeName =
- ((IJavaElement) hierarchy.elementAt(size - 1)).getElementName();
- IType type = typeCU.getType(typeName);
- size = size - 2;
- while (size > -1) {
- typeName = ((IJavaElement) hierarchy.elementAt(size)).getElementName();
- type = ((IType) type).getType(typeName);
- size--;
- }
- return type;
+
+ ICompilationUnit cu = (ICompilationUnit) getOriginalElement();
+ if (javaElementType == COMPILATION_UNIT) {
+ parent = workingCopyElement;
}
-
- /**
- * Returns <code>null<code> - a working copy does not have an underlying resource.
- *
- * @see IJavaElement
- */
- public IResource getUnderlyingResource() throws JavaModelException {
+ if (((ICompilationUnit) parent).isWorkingCopy() && !((ICompilationUnit) parent).getOriginalElement().equals(cu)) {
return null;
}
-
- /**
- * @see IWorkingCopy
- */
- public IJavaElement getWorkingCopy() throws JavaModelException {
- return this;
+ switch (javaElementType) {
+ case PACKAGE_DECLARATION :
+ return cu.getPackageDeclaration(workingCopyElement.getElementName());
+ case IMPORT_DECLARATION :
+ return cu.getImport(workingCopyElement.getElementName());
+ case TYPE :
+ if (hierarchy.size() == 1) {
+ return cu.getType(workingCopyElement.getElementName());
+ } else {
+ //inner type
+ return getOriginalType(hierarchy).getType(workingCopyElement.getElementName());
+ }
+ case METHOD :
+ IType type;
+ if (hierarchy.size() == 2) {
+ String typeName = ((IJavaElement) hierarchy.elementAt(0)).getElementName();
+ type = cu.getType(typeName);
+ } else {
+ //inner type
+ type = getOriginalType(hierarchy);
+ }
+ return type.getMethod(workingCopyElement.getElementName(), ((IMethod) workingCopyElement).getParameterTypes());
+ case FIELD :
+ if (hierarchy.size() == 2) {
+ String typeName = ((IJavaElement) hierarchy.elementAt(0)).getElementName();
+ type = cu.getType(typeName);
+ } else {
+ //inner type
+ type = getOriginalType(hierarchy);
+ }
+ return type.getField(workingCopyElement.getElementName());
+ case INITIALIZER :
+ if (hierarchy.size() == 2) {
+ String typeName = ((IJavaElement) hierarchy.elementAt(0)).getElementName();
+ type = cu.getType(typeName);
+ } else {
+ //inner type
+ type = getOriginalType(hierarchy);
+ }
+ return type.getInitializer(((Initializer) workingCopyElement).getOccurrenceCount());
+ case COMPILATION_UNIT :
+ return cu;
+ default :
+ return null;
}
-
- /**
- * @see IWorkingCopy
- */
- public boolean isBasedOn(IResource resource) {
- if (resource.getType() != IResource.FILE) {
- return false;
- }
- if (fDestroyed) {
- return false;
- }
- try {
- // if resource got deleted, then #getModificationStamp() will answer IResource.NULL_STAMP, which is always different from the cached
- // timestamp
- return ((CompilationUnitElementInfo) getElementInfo()).fTimestamp
- == ((IFile) resource).getModificationStamp();
- } catch (JavaModelException e) {
- return false;
- }
+}
+/**
+ * @see IWorkingCopy
+ */
+public IJavaElement getOriginalElement() {
+ return new CompilationUnit((IPackageFragment)getParent(), getElementName());
+}
+protected IType getOriginalType(Vector hierarchy) {
+ int size = hierarchy.size() - 1;
+ ICompilationUnit typeCU = (ICompilationUnit) hierarchy.elementAt(size);
+ String typeName = ((IJavaElement) hierarchy.elementAt(size - 1)).getElementName();
+ IType type = typeCU.getType(typeName);
+ size= size - 2;
+ while (size > -1) {
+ typeName = ((IJavaElement) hierarchy.elementAt(size)).getElementName();
+ type = ((IType) type).getType(typeName);
+ size--;
}
-
- /**
- * @see IWorkingCopy
- */
- public boolean isWorkingCopy() {
- return true;
+ return type;
+}
+/**
+ * Returns <code>null<code> - a working copy does not have an underlying resource.
+ *
+ * @see IJavaElement
+ */
+public IResource getUnderlyingResource() throws JavaModelException {
+ return null;
+}
+/**
+ * @see IWorkingCopy
+ */
+public IJavaElement getWorkingCopy() throws JavaModelException {
+ return this;
+}
+/**
+ * @see IWorkingCopy
+ */
+public boolean isBasedOn(IResource resource) {
+ if (resource.getType() != IResource.FILE) {
+ return false;
}
-
- /**
- * @see IOpenable
- * @see IWorkingCopy
- *
- * @exception JavaModelException attempting to open a read only element for something other than navigation
- * or if this is a working copy being opened after it has been destroyed.
- */
- public void open(IProgressMonitor pm) throws JavaModelException {
- if (fDestroyed) {
- throw newNotPresentException();
- } else {
- super.open(pm);
- }
+ if (fDestroyed) {
+ return false;
}
-
- /**
- * @see Openable
- */
- protected IBuffer openBuffer(IProgressMonitor pm) throws JavaModelException {
- ICompilationUnit original = (ICompilationUnit) this.getOriginalElement();
- IBuffer buf =
- getBufferManager().openBuffer(
- original.getBuffer().getCharacters(),
- pm,
- this,
- isReadOnly());
- buf.addBufferChangedListener(this);
- return buf;
+ try {
+ // if resource got deleted, then #getModificationStamp() will answer IResource.NULL_STAMP, which is always different from the cached
+ // timestamp
+ return ((CompilationUnitElementInfo) getElementInfo()).fTimestamp == ((IFile) resource).getModificationStamp();
+ } catch (JavaModelException e) {
+ return false;
}
+}
+/**
+ * @see IWorkingCopy
+ */
+public boolean isWorkingCopy() {
+ return true;
+}
+/**
+ * @see IOpenable
+ * @see IWorkingCopy
+ *
+ * @exception JavaModelException attempting to open a read only element for something other than navigation
+ * or if this is a working copy being opened after it has been destroyed.
+ */
+public void open(IProgressMonitor pm) throws JavaModelException {
+ if (fDestroyed) {
+ throw newNotPresentException();
+ } else {
+ super.open(pm);
+ }
+}
+/**
+ * @see Openable
+ */
+protected IBuffer openBuffer(IProgressMonitor pm) throws JavaModelException {
+ ICompilationUnit original= (ICompilationUnit)this.getOriginalElement();
+ IBuffer buf= getBufferManager().openBuffer((char[])original.getBuffer().getCharacters().clone(), pm, this, isReadOnly());
+ buf.addBufferChangedListener(this);
+ return buf;
+}
+/**
+ * @see IWorkingCopy
+ */
+public IMarker[] reconcile() throws JavaModelException {
+ // create the delta builder (this remembers the current content of the cu)
+ JavaElementDeltaBuilder deltaBuilder = new JavaElementDeltaBuilder(this);
- /**
- * @see IWorkingCopy
- */
- public IMarker[] reconcile() throws JavaModelException {
- // create the delta builder (this remembers the current content of the cu)
- JavaElementDeltaBuilder deltaBuilder = new JavaElementDeltaBuilder(this);
-
- // update the element infos with the content of the working copy
- this.makeConsistent(null);
-
- // build the deltas
- deltaBuilder.buildDeltas();
+ // update the element infos with the content of the working copy
+ this.makeConsistent(null);
- // fire the deltas
- boolean shouldFire = false;
- JavaModelManager manager = null;
- if (deltaBuilder.delta != null) {
- manager = (JavaModelManager) JavaModelManager.getJavaModelManager();
- if (deltaBuilder.delta.getAffectedChildren().length > 0) {
- manager.registerJavaModelDelta(deltaBuilder.delta);
- shouldFire = true;
- }
+ // build the deltas
+ deltaBuilder.buildDeltas();
+
+ // fire the deltas
+ boolean shouldFire = false;
+ JavaModelManager manager = null;
+ if (deltaBuilder.delta != null) {
+ manager = (JavaModelManager)JavaModelManager.getJavaModelManager();
+ if (deltaBuilder.delta.getAffectedChildren().length > 0) {
+ manager.registerJavaModelDelta(deltaBuilder.delta);
+ shouldFire = true;
}
- if (shouldFire)
- manager.fire();
-
- // report syntax problems
- return null;
- /* DISABLED because of 1GAJJ3A: ITPJUI:WINNT - Deadlock in Java Editor
- try {
- WorkingCopyElementInfo info = (WorkingCopyElementInfo)JavaModelManager.getJavaModelManager().getInfo(this);
- IProblem[] problems = info.problems;
- int length;
- IResource resource = getOriginalElement().getUnderlyingResource();
-
- // flush previous markers first
- IMarker[] markers = resource.findMarkers(IJavaModelMarker.TRANSIENT_PROBLEM, true, IResource.DEPTH_ONE);
- resource.getWorkspace().deleteMarkers(markers);
-
- // create markers if needed
- if (problems == null || (length = problems.length) == 0) return null;
- markers = new IMarker[length];
- for (int i = 0; i < length; i++) {
- IProblem problem = problems[i];
- IMarker marker = resource.createMarker(IJavaModelMarker.TRANSIENT_PROBLEM);
- marker.setAttribute(IJavaModelMarker.ID, problem.getID());
- marker.setAttribute(IJavaModelMarker.CHAR_START, problem.getSourceStart());
- marker.setAttribute(IJavaModelMarker.CHAR_END, problem.getSourceEnd() + 1);
- marker.setAttribute(IJavaModelMarker.LINE_NUMBER, problem.getSourceLineNumber());
- marker.setAttribute(IMarker.LOCATION, "#" + problem.getSourceLineNumber());
- marker.setAttribute(IMarker.MESSAGE, problem.getMessage());
- marker.setAttribute(IMarker.PRIORITY, (problem.isWarning() ? IMarker.PRIORITY_LOW : IMarker.PRIORITY_HIGH));
- markers[i] = marker;
- }
- return markers;
- } catch (CoreException e) {
- throw new JavaModelException(e);
- }
- */
}
+ if (shouldFire)
+ manager.fire();
- /**
- * @see IWorkingCopy
- */
- public void restore() throws JavaModelException {
- if (!fDestroyed) {
- CompilationUnit original = (CompilationUnit) getOriginalElement();
- getBuffer().setContents(original.getContents());
+ // report syntax problems
+ return null;
+/* DISABLED because of 1GAJJ3A: ITPJUI:WINNT - Deadlock in Java Editor
+ try {
+ WorkingCopyElementInfo info = (WorkingCopyElementInfo)JavaModelManager.getJavaModelManager().getInfo(this);
+ IProblem[] problems = info.problems;
+ int length;
+ IResource resource = getOriginalElement().getUnderlyingResource();
+
+ // flush previous markers first
+ IMarker[] markers = resource.findMarkers(IJavaModelMarker.TRANSIENT_PROBLEM, true, IResource.DEPTH_ONE);
+ resource.getWorkspace().deleteMarkers(markers);
- long timeStamp =
- ((IFile) original.getUnderlyingResource()).getModificationStamp();
- if (timeStamp == IResource.NULL_STAMP) {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.INVALID_RESOURCE));
- }
- ((CompilationUnitElementInfo) getElementInfo()).fTimestamp = timeStamp;
- makeConsistent(null);
+ // create markers if needed
+ if (problems == null || (length = problems.length) == 0) return null;
+ markers = new IMarker[length];
+ for (int i = 0; i < length; i++) {
+ IProblem problem = problems[i];
+ IMarker marker = resource.createMarker(IJavaModelMarker.TRANSIENT_PROBLEM);
+ marker.setAttribute(IJavaModelMarker.ID, problem.getID());
+ marker.setAttribute(IJavaModelMarker.CHAR_START, problem.getSourceStart());
+ marker.setAttribute(IJavaModelMarker.CHAR_END, problem.getSourceEnd() + 1);
+ marker.setAttribute(IJavaModelMarker.LINE_NUMBER, problem.getSourceLineNumber());
+ marker.setAttribute(IMarker.LOCATION, "#" + problem.getSourceLineNumber());
+ marker.setAttribute(IMarker.MESSAGE, problem.getMessage());
+ marker.setAttribute(IMarker.PRIORITY, (problem.isWarning() ? IMarker.PRIORITY_LOW : IMarker.PRIORITY_HIGH));
+ markers[i] = marker;
}
+ return markers;
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
}
+*/
+}
+/**
+ * @see IWorkingCopy
+ */
+public void restore() throws JavaModelException {
+ if (!fDestroyed) {
+ CompilationUnit original = (CompilationUnit) getOriginalElement();
+ getBuffer().setContents(original.getContents());
- /**
- * @private Debugging purposes
- */
- protected void toString(int tab, StringBuffer buffer) {
- buffer.append(this.tabString(tab));
- buffer.append("(working copy)\n");
- super.toString(tab, buffer);
+ long timeStamp =
+ ((IFile) original.getUnderlyingResource()).getModificationStamp();
+ if (timeStamp == IResource.NULL_STAMP) {
+ throw new JavaModelException(
+ new JavaModelStatus(IJavaModelStatusConstants.INVALID_RESOURCE));
+ }
+ ((CompilationUnitElementInfo) getElementInfo()).fTimestamp = timeStamp;
+ makeConsistent(null);
}
-
+}
+/**
+ * @private Debugging purposes
+ */
+protected void toString(int tab, StringBuffer buffer) {
+ buffer.append(this.tabString(tab));
+ buffer.append("(working copy)\n"/*nonNLS*/);
+ super.toString(tab, buffer);
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/BinaryBrokerKey.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/BinaryBrokerKey.java
index 2ba61f7dcf..63a2ecc5e6 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/BinaryBrokerKey.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/BinaryBrokerKey.java
@@ -26,30 +26,24 @@ public class BinaryBrokerKey {
fType = type;
fCRC = crc;
}
-
public boolean equals(Object o) {
- if (this == o)
- return true;
- if (!(o instanceof BinaryBrokerKey))
- return false;
+ if (this == o) return true;
+ if (!(o instanceof BinaryBrokerKey)) return false;
BinaryBrokerKey k = (BinaryBrokerKey) o;
return fCRC == k.fCRC && fType.equals(k.fType);
}
-
/**
* Returns the CRC.
*/
public int getCRC() {
return fCRC;
}
-
/**
* Returns the type.
*/
public IType getType() {
return fType;
}
-
/**
* Returns the hash code.
*/
@@ -57,5 +51,4 @@ public class BinaryBrokerKey {
// The CRC should be unique enough for a hash code.
return fCRC;
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/BuildEvent.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/BuildEvent.java
index d8eea28d19..87c981dbb1 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/BuildEvent.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/BuildEvent.java
@@ -10,19 +10,18 @@ public class BuildEvent {
* Internal - Constructs a new build event object.
*/
public BuildEvent(
- ISourceFragment sourceFragment,
- int newErrorCount,
- int fixedErrorCount,
- int newWarningCount,
+ ISourceFragment sourceFragment,
+ int newErrorCount,
+ int fixedErrorCount,
+ int newWarningCount,
int fixedWarningCount) {
-
+
fSourceFragment = sourceFragment;
fNewErrorCount = newErrorCount;
fFixedErrorCount = fixedErrorCount;
fNewWarningCount = newWarningCount;
fFixedWarningCount = fixedWarningCount;
}
-
/**
* Returns the number of errors fixed since
* the beginning of the build.
@@ -30,7 +29,6 @@ public class BuildEvent {
public int getFixedErrorCount() {
return fFixedErrorCount;
}
-
/**
* Returns the number of warnings fixed since
* the beginning of the build.
@@ -38,7 +36,6 @@ public class BuildEvent {
public int getFixedWarningCount() {
return fFixedWarningCount;
}
-
/**
* Returns the number of new errors found since
* the beginning of the build.
@@ -46,7 +43,6 @@ public class BuildEvent {
public int getNewErrorCount() {
return fNewErrorCount;
}
-
/**
* Returns the number of new warnings found since
* the beginning of the build.
@@ -54,7 +50,6 @@ public class BuildEvent {
public int getNewWarningCount() {
return fNewWarningCount;
}
-
/**
* Returns the source fragment of the most recently
* (re)compiled element. May be null if the notification
@@ -64,5 +59,4 @@ public class BuildEvent {
public ISourceFragment getSourceFragment() {
return fSourceFragment;
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/DeltaKey.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/DeltaKey.java
index 5abf36fe14..206cd477fc 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/DeltaKey.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/DeltaKey.java
@@ -19,20 +19,21 @@ import java.io.*;
* the copy.
*/
public class DeltaKey implements IDeltaKey, Serializable {
-
+
/**
* Names of the branches of the key
*/
protected Object[] fLocalNames;
-
+
/**
* Singleton root node instance.
*/
protected static DeltaKey NodeRoot = new DeltaKey(0);
/** Version UID for serialization purposes (as of LF 143)
- */
- protected static final long serialVersionUID = 1379863541613390307L;
+ */
+ protected static final long serialVersionUID = 1379863541613390307L;
+
/**
* Sets the names of the key
@@ -40,68 +41,65 @@ public class DeltaKey implements IDeltaKey, Serializable {
public DeltaKey(Object[] names) {
fLocalNames = names;
}
-
/**
* Creates a new key of the given length.
*/
- protected DeltaKey(int length) {
+ protected DeltaKey (int length) {
fLocalNames = new Object[length];
}
-
/**
* Returns a new key describing the key's child with the given local name.
* This replaces the "/" syntax in the Smalltalk implementation
*/
public DeltaKey add(Object localName) {
+
/* Calculate length of new key */
int length = this.size();
DeltaKey newKey = new DeltaKey(length + 1);
-
+
/* Copy names from receiver to new key */
newKey.replaceFromToWithStartingAt(0, length - 1, this, 0);
-
+
/* Add new local name at end of new key */
newKey.fLocalNames[length] = localName;
-
+
return newKey;
}
-
/**
* Returns the local name at the given index in the receiver
*/
public Object at(int index) {
return fLocalNames[index];
}
-
/**
* Returns true if the receiver has the exact same local names as anObject.
* Returns false otherwise.
* Returns false if anObject is not an instance of NodeKey
*/
- public boolean equals(Object anObject) {
-
+ public boolean equals (Object anObject) {
+
DeltaKey aKey;
- int result;
-
+ int result;
+
/* return true if the same object */
if (this == anObject) {
return true;
}
-
+
/* return false if different class of object */
if (anObject instanceof DeltaKey) {
aKey = (DeltaKey) anObject;
} else {
return false;
}
-
+
/* return false if not the same number of names */
if (this.size() != aKey.size()) {
return false;
}
-
+
/* not equal if any local names are not equal */
for (int i = this.size() - 1; i >= 0; i--) {
if (!this.at(i).equals(aKey.at(i))) {
@@ -110,7 +108,6 @@ public class DeltaKey implements IDeltaKey, Serializable {
}
return true;
}
-
/**
* Returns the receiver's local name (the name of the last child). If the
* receiver is a root key, answer null
@@ -122,21 +119,18 @@ public class DeltaKey implements IDeltaKey, Serializable {
return fLocalNames[fLocalNames.length - 1];
}
}
-
/**
* Returns the local names of the key
*/
protected Object[] getLocalNames() {
return fLocalNames;
}
-
/**
* Returns the singleton root node instance.
*/
public static DeltaKey getRoot() {
return NodeRoot;
}
-
/**
* Returns the hash value of the receiver. Objects which are equal have
* the same hash value.
@@ -144,18 +138,18 @@ public class DeltaKey implements IDeltaKey, Serializable {
public int hashCode() {
int hash, selfSize;
-
+
selfSize = this.size();
if (selfSize == 0) {
return 0;
- }
-
+ }
+
/* Hash the first element */
hash = this.at(0).hashCode();
if (selfSize == 1) {
return hash;
}
-
+
/* Hash the last element */
hash ^= this.at(selfSize - 1).hashCode();
if (selfSize == 2) {
@@ -166,13 +160,12 @@ public class DeltaKey implements IDeltaKey, Serializable {
hash ^= this.at(selfSize / 2).hashCode();
return hash & 32767;
}
-
/**
* Returns true if the receiver is a prefix of the given key, false otherwise.
* Keys which are equal are considered to be prefixes of each other (so
* true is answered in this case).
*/
- public boolean isPrefixOf(DeltaKey key) {
+ public boolean isPrefixOf (DeltaKey key) {
int size;
@@ -198,7 +191,7 @@ public class DeltaKey implements IDeltaKey, Serializable {
if (--size <= 0) {
return true;
}
-
+
/* Check the first element next */
if (this.fLocalNames[0] != key.fLocalNames[0]) {
return false;
@@ -206,70 +199,34 @@ public class DeltaKey implements IDeltaKey, Serializable {
if (size == 1) {
return true;
}
-
+
/* Unroll the loop for increased performance */
- if (this.fLocalNames[size] != key.fLocalNames[size]) {
- return false;
- }
- if (--size == 1) {
- return true;
- }
+ if (this.fLocalNames[size] != key.fLocalNames[size]) {return false;}
+ if (--size == 1) {return true;}
- if (this.fLocalNames[size] != key.fLocalNames[size]) {
- return false;
- }
- if (--size == 1) {
- return true;
- }
+ if (this.fLocalNames[size] != key.fLocalNames[size]) {return false;}
+ if (--size == 1) {return true;}
- if (this.fLocalNames[size] != key.fLocalNames[size]) {
- return false;
- }
- if (--size == 1) {
- return true;
- }
+ if (this.fLocalNames[size] != key.fLocalNames[size]) {return false;}
+ if (--size == 1) {return true;}
- if (this.fLocalNames[size] != key.fLocalNames[size]) {
- return false;
- }
- if (--size == 1) {
- return true;
- }
+ if (this.fLocalNames[size] != key.fLocalNames[size]) {return false;}
+ if (--size == 1) {return true;}
- if (this.fLocalNames[size] != key.fLocalNames[size]) {
- return false;
- }
- if (--size == 1) {
- return true;
- }
+ if (this.fLocalNames[size] != key.fLocalNames[size]) {return false;}
+ if (--size == 1) {return true;}
- if (this.fLocalNames[size] != key.fLocalNames[size]) {
- return false;
- }
- if (--size == 1) {
- return true;
- }
+ if (this.fLocalNames[size] != key.fLocalNames[size]) {return false;}
+ if (--size == 1) {return true;}
- if (this.fLocalNames[size] != key.fLocalNames[size]) {
- return false;
- }
- if (--size == 1) {
- return true;
- }
+ if (this.fLocalNames[size] != key.fLocalNames[size]) {return false;}
+ if (--size == 1) {return true;}
- if (this.fLocalNames[size] != key.fLocalNames[size]) {
- return false;
- }
- if (--size == 1) {
- return true;
- }
+ if (this.fLocalNames[size] != key.fLocalNames[size]) {return false;}
+ if (--size == 1) {return true;}
- if (this.fLocalNames[size] != key.fLocalNames[size]) {
- return false;
- }
- if (--size == 1) {
- return true;
- }
+ if (this.fLocalNames[size] != key.fLocalNames[size]) {return false;}
+ if (--size == 1) {return true;}
while (size > 1) {
if (this.fLocalNames[size] != key.fLocalNames[size]) {
@@ -278,34 +235,31 @@ public class DeltaKey implements IDeltaKey, Serializable {
}
return true;
}
-
/**
* Returns true if the receiver is the root key, false otherwise
*/
public boolean isRoot() {
return (this.size() == 0);
}
-
/**
* Returns the key describing the receiver's parent, or null if the receiver
* is the root key.
*/
- public DeltaKey parent() {
+ public DeltaKey parent() {
int size = this.size() - 1;
DeltaKey newKey;
-
+
if (size < 0) {
return null;
} else {
- newKey = new DeltaKey(size);
-
+ newKey = new DeltaKey (size);
+
/* copy children from receiver */
- newKey.replaceFromToWithStartingAt(0, size - 1, this, 0);
+ newKey.replaceFromToWithStartingAt(0, size -1, this, 0);
return newKey;
}
}
-
/**
* Returns a new key containing the first few local names in the
* receiver.
@@ -316,30 +270,27 @@ public class DeltaKey implements IDeltaKey, Serializable {
* receiver contains fewer than count local names, or count is
* negative."
*/
- public DeltaKey prefix(int count) {
+ public DeltaKey prefix (int count) {
DeltaKey newNode;
if (count < 0 || this.size() < count) {
- throw new IllegalArgumentException(new Integer(count).toString());
+ throw new IllegalArgumentException (new Integer(count).toString());
}
-
+
newNode = new DeltaKey(count);
-
+
/* copy children */
- newNode.replaceFromToWithStartingAt(0, count - 1, this, 0);
+ newNode.replaceFromToWithStartingAt (0, count - 1, this, 0);
return newNode;
}
-
- private void readObject(ObjectInputStream in)
- throws IOException, ClassNotFoundException {
- int l = in.readInt();
- fLocalNames = new String[l];
- for (int i = 0; i < l; ++i) {
- fLocalNames[i] = in.readObject();
- }
+private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
+ int l = in.readInt();
+ fLocalNames = new String[l];
+ for (int i = 0; i < l; ++i) {
+ fLocalNames[i] = in.readObject();
}
-
+}
/**
* Replaces the elements of the receiver between the given indices
* with the elements of the supplied key starting at a particular point.
@@ -360,43 +311,37 @@ public class DeltaKey implements IDeltaKey, Serializable {
* index to start copying from in the replacement key
* @return the modified key
*/
- private DeltaKey replaceFromToWithStartingAt(
- int start,
- int stop,
- DeltaKey replacementKey,
- int repStart) {
-
- int repCount = repStart;
-
- for (int i = start; i <= stop; i++, repCount++) {
- this.fLocalNames[i] = replacementKey.fLocalNames[repCount];
- }
- return this;
- }
-
+ private DeltaKey replaceFromToWithStartingAt (int start, int stop,
+ DeltaKey replacementKey, int repStart) {
+
+ int repCount = repStart;
+
+ for (int i = start; i <= stop; i++, repCount++) {
+ this.fLocalNames[i] = replacementKey.fLocalNames[repCount];
+ }
+ return this;
+ }
/**
* Sets the local names of the key
*/
protected void setLocalNames(String[] names) {
fLocalNames = names;
}
-
/**
* Returns the branch length of the key
*/
public int size() {
return fLocalNames.length;
}
-
/**
* Returns a unicode representation of the receiver. This method is used
* for debugging purposes only (no NLS needed)
*/
- public String toString() {
+ public String toString () {
StringBuffer buffer = new StringBuffer();
-
+
buffer.append("DeltaKey(");
-
+
for (int i = 0; i < this.fLocalNames.length; i++) {
buffer.append(this.fLocalNames[i]);
if (i < this.fLocalNames.length - 1) {
@@ -407,7 +352,6 @@ public class DeltaKey implements IDeltaKey, Serializable {
return buffer.toString();
}
-
/**
* Returns a new key containing everything but the first few local
* names in the receiver.
@@ -418,27 +362,25 @@ public class DeltaKey implements IDeltaKey, Serializable {
* receiver contains fewer than count local names, or count is
* negative.
*/
- public DeltaKey withoutPrefix(int count) {
+ public DeltaKey withoutPrefix (int count) {
DeltaKey newNode;
int newSize;
if (count < 0 || this.size() < count) {
- throw new IllegalArgumentException(new Integer(count).toString());
+ throw new IllegalArgumentException (new Integer (count).toString());
}
-
+
newSize = this.size() - count;
- newNode = new DeltaKey(newSize);
- newNode.replaceFromToWithStartingAt(0, newSize - 1, this, count);
+ newNode = new DeltaKey (newSize);
+ newNode.replaceFromToWithStartingAt (0, newSize - 1, this, count);
return newNode;
}
-
- private void writeObject(ObjectOutputStream out) throws IOException {
- int l = fLocalNames.length;
- out.writeInt(l);
- for (int i = 0; i < l; ++i) {
- out.writeObject(fLocalNames[i]);
- }
+private void writeObject(ObjectOutputStream out) throws IOException {
+ int l = fLocalNames.length;
+ out.writeInt(l);
+ for (int i = 0; i < l; ++i) {
+ out.writeObject(fLocalNames[i]);
}
-
-} // end class definition
+}
+}// end class definition
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IConstructor.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IConstructor.java
index 5cfbd42452..341de55fa5 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IConstructor.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IConstructor.java
@@ -2,6 +2,7 @@ package org.eclipse.jdt.internal.core.builder;
public interface IConstructor extends IMember {
+
/**
* Compares this Constructor handle against the specified object.
* Returns true if the objects are the same. Two Constructor
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IDelta.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IDelta.java
index d145fcbe94..85688b1e40 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IDelta.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IDelta.java
@@ -19,7 +19,8 @@ import java.util.Enumeration;
* @see DeltaKey
* @see ICheck
*/
-public interface IDelta {
+public interface IDelta
+{
/*
* The constants below for known statuses are assigned different
* bits, rather than consecutive values, to allow sets
@@ -44,6 +45,7 @@ public interface IDelta {
/** Constant indicating that the status of a delta is unknown. */
int UNKNOWN = -1;
+
/**
* Returns positive, negative, or zero, depending on whether aKey is greater than,
* less than or equal to the receiver, respectively.
@@ -183,24 +185,24 @@ public interface IDelta {
* broken down into subdeltas.
*/
boolean hasSubdeltas();
- /**
- * Return a string of either the form:
- * status this.data.name this.data.oldState ==> this.data.newState
- * OR
- * status / this.data.name
- *
- * status will be one of the following:
- * + if status is ADDED
- * - if status is REMOVED
- * " " if status is CHANGED
- * = if status is SAME
- * ? if status is UNKNOWN
- * The first string will be returned from a delta check which
- * relates specifically to the image, all other delta checks
- * will return the second string.
- * The string returned is only for debugging purposes,
- * and the contents of the string may change in the future.
- * @return java.lang.String
- */
- public String toString();
+/**
+ * Return a string of either the form:
+ * status this.data.name this.data.oldState ==> this.data.newState
+ * OR
+ * status / this.data.name
+ *
+ * status will be one of the following:
+ * + if status is ADDED
+ * - if status is REMOVED
+ * " " if status is CHANGED
+ * = if status is SAME
+ * ? if status is UNKNOWN
+ * The first string will be returned from a delta check which
+ * relates specifically to the image, all other delta checks
+ * will return the second string.
+ * The string returned is only for debugging purposes,
+ * and the contents of the string may change in the future.
+ * @return java.lang.String
+ */
+public String toString();
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IDeltaKey.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IDeltaKey.java
index e0892ee34d..81188232ef 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IDeltaKey.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IDeltaKey.java
@@ -20,7 +20,7 @@ public interface IDeltaKey {
* Keys which are equal are considered to be prefixes of each other (so
* true is answered in this case).
*/
- boolean isPrefixOf(DeltaKey key);
+ boolean isPrefixOf (DeltaKey key);
/**
* Returns true if the receiver is the root key, false otherwise
*/
@@ -29,7 +29,7 @@ public interface IDeltaKey {
* Returns the key describing the receiver's parent, or null if the receiver
* is the root key.
*/
- DeltaKey parent();
+ DeltaKey parent();
/**
* Returns a new key containing the first few local names in the
* receiver.
@@ -40,7 +40,7 @@ public interface IDeltaKey {
* receiver contains fewer than count local names, or count is
* negative."
*/
- DeltaKey prefix(int count);
+ DeltaKey prefix (int count);
/**
* Returns the branch length of the key
*/
@@ -55,5 +55,5 @@ public interface IDeltaKey {
* receiver contains fewer than count local names, or count is
* negative.
*/
- DeltaKey withoutPrefix(int count);
+ DeltaKey withoutPrefix (int count);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IDevelopmentContext.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IDevelopmentContext.java
index 893087ef91..d995d75115 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IDevelopmentContext.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IDevelopmentContext.java
@@ -101,10 +101,7 @@ public interface IDevelopmentContext {
* @see IState#applySourceDelta
* @see IState#getBuildContext
*/
- IImageBuilder createState(
- IProject project,
- IImageContext buildContext,
- IProblemReporter problemReporter);
+ IImageBuilder createState(IProject project, IImageContext buildContext, IProblemReporter problemReporter);
/**
* Compare two Objects for equality. Returns true iff they represent the
* same development context.
@@ -172,8 +169,8 @@ public interface IDevelopmentContext {
* separately, and reassociated with the state when it is restored.
* Because of this quirk, this class does not implement
* <code>java.io.Externalizable</code>.
- * @exception NotPresentException when no current state has been set.
- * @exception java.io.IOException Includes any I/O exceptions that may occur
+ * @exception NotPresentException when no current state has been set.
+ * @exception java.io.IOException Includes any I/O exceptions that may occur
* @see #restoreState
*/
void saveState(IState state, java.io.DataOutputStream out)
@@ -206,13 +203,13 @@ public interface IDevelopmentContext {
* lazy builds.
*/
public void setProgressMonitor(IProgressMonitor monitor);
- /**
- * Return a string of the form:
- * JDC#?
- * where ? is the instance number of the DevelopmentContext.
- * The string returned is only for debugging purposes,
- * and the contents of the string may change in the future.
- * @return java.lang.String
- */
- public String toString();
+/**
+ * Return a string of the form:
+ * JDC#?
+ * where ? is the instance number of the DevelopmentContext.
+ * The string returned is only for debugging purposes,
+ * and the contents of the string may change in the future.
+ * @return java.lang.String
+ */
+public String toString();
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IField.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IField.java
index 0db82c6690..763e943a36 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IField.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IField.java
@@ -2,6 +2,7 @@ package org.eclipse.jdt.internal.core.builder;
public interface IField extends IMember {
+
/**
* Compares this Field handle against the specified object. Returns
* true if the objects are the same. Two Field handles are the same if
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IHandle.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IHandle.java
index 022c08ac2f..a341e518e1 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IHandle.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IHandle.java
@@ -1,6 +1,7 @@
package org.eclipse.jdt.internal.core.builder;
-public interface IHandle {
+public interface IHandle
+{
int K_JAVA_IMAGE = 1;
int K_JAVA_PACKAGE = 2;
int K_JAVA_TYPE = 3;
@@ -8,6 +9,7 @@ public interface IHandle {
int K_JAVA_METHOD = 5;
int K_JAVA_CONSTRUCTOR = 6;
+
/**
* Compares this handle against the specified object.
* Returns true if the objects are the same. Two handles are
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IImage.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IImage.java
index 9e406a8e7a..175a0278f1 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IImage.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IImage.java
@@ -24,7 +24,9 @@ import org.eclipse.core.runtime.IPath;
* Image is considered to be always present.
*/
-public interface IImage extends IHandle {
+public interface IImage extends IHandle
+{
+
/*
* The following methods are needed for the following reasons:
@@ -56,8 +58,7 @@ public interface IImage extends IHandle {
* @see #getPackages
* @see #getAllClasses
*/
- IImageContext createImageContext(IPackage[] packages)
- throws StateSpecificException;
+ IImageContext createImageContext(IPackage[] packages) throws StateSpecificException;
/** Returns the Type representing the primitive type double. */
IType doubleType();
/**
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IImageBuilder.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IImageBuilder.java
index 86e966485f..6192f062a6 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IImageBuilder.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IImageBuilder.java
@@ -1,6 +1,8 @@
package org.eclipse.jdt.internal.core.builder;
-public interface IImageBuilder {
+public interface IImageBuilder
+{
+
/**
* If the new state is being built incrementally, returns an object
@@ -29,19 +31,19 @@ public interface IImageBuilder {
* otherwise returns null.
*/
IState getOldState();
- /**
- * Return a string of the form:
- * batch image builder for:
- * new state: this.data.newstate
- * OR
- * incremental image builder for:
- * new state: this.data.newstate
- * old state: this.data.oldstate
- * Obviously, which string gets returned depends
- * on the type of image builder.
- * The string returned is only for debugging purposes,
- * and the contents of the string may change in the future.
- * @return java.lang.String
- */
- public String toString();
+/**
+ * Return a string of the form:
+ * batch image builder for:
+ * new state: this.data.newstate
+ * OR
+ * incremental image builder for:
+ * new state: this.data.newstate
+ * old state: this.data.oldstate
+ * Obviously, which string gets returned depends
+ * on the type of image builder.
+ * The string returned is only for debugging purposes,
+ * and the contents of the string may change in the future.
+ * @return java.lang.String
+ */
+public String toString();
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IImageContext.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IImageContext.java
index f3267c4c8a..90deeba8aa 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IImageContext.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IImageContext.java
@@ -1,6 +1,7 @@
package org.eclipse.jdt.internal.core.builder;
-public interface IImageContext {
+public interface IImageContext
+{
/**
* Returns the DevelopmentContext for which the ImageContext was created.
@@ -13,17 +14,17 @@ public interface IImageContext {
* @return an array of non-state-specific Package handles.
*/
IPackage[] getPackages();
- /**
- * Return a string of the form:
- * image context with packages:
- * this.data.package[0]
- * this.data.package[1]
- * ...
- * this.data.package[n-1]
- *
- * The string returned is only for debugging purposes,
- * and the contents of the string may change in the future.
- * @return java.lang.String
- */
- public String toString();
+/**
+ * Return a string of the form:
+ * image context with packages:
+ * this.data.package[0]
+ * this.data.package[1]
+ * ...
+ * this.data.package[n-1]
+ *
+ * The string returned is only for debugging purposes,
+ * and the contents of the string may change in the future.
+ * @return java.lang.String
+ */
+public String toString();
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IMember.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IMember.java
index f2e0d2441b..39401fe3b9 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IMember.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IMember.java
@@ -2,6 +2,7 @@ package org.eclipse.jdt.internal.core.builder;
public interface IMember extends IHandle {
+
/**
* Returns the Type object representing the class or interface
* that declares the the member represented by this object.
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IMethod.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IMethod.java
index 489d654e29..2de8e6e17d 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IMethod.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IMethod.java
@@ -2,6 +2,7 @@ package org.eclipse.jdt.internal.core.builder;
public interface IMethod extends IMember {
+
/**
* Compares this Method handle against the specified object. Returns
* true if the objects are the same. Two Method handles are the same if
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IPackage.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IPackage.java
index b63318ce15..6b98250e7f 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IPackage.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IPackage.java
@@ -2,6 +2,7 @@ package org.eclipse.jdt.internal.core.builder;
public interface IPackage extends IHandle {
+
/**
* Compares this Package handle against the specified object. Returns
* true if the objects are the same. Two Package handles are the same if
@@ -87,7 +88,7 @@ public interface IPackage extends IHandle {
*
* @exception NotPresentException if this package is not present.
*/
- IPackage[] getReferencedPackages() throws NotPresentException;
+ IPackage[] getReferencedPackages() throws NotPresentException;
/**
* Returns an array of Package objects representing all packages
* in the given image context which directly reference this package.
@@ -102,8 +103,7 @@ public interface IPackage extends IHandle {
* @param context the ImageContext in which to restrict the search.
* @exception NotPresentException if this package is not present.
*/
- IPackage[] getReferencingPackages(IImageContext context)
- throws NotPresentException;
+ IPackage[] getReferencingPackages(IImageContext context) throws NotPresentException;
/**
* Returns an array of SourceFragments describing the source package
* fragments from which this built package is derived.
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IProblemReporter.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IProblemReporter.java
index f96154e7e7..37db145292 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IProblemReporter.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IProblemReporter.java
@@ -14,62 +14,62 @@ import java.util.Enumeration;
* by the image builder.
*/
public interface IProblemReporter {
- /**
- * Creates a copy of this problem reporter.
- */
- public IProblemReporter copy();
- /**
- * Returns an enumeration of all problems with elements of the image,
- * but not with the image itself.
- * Returns an Enumeration of IProblemDetail.
- */
- public Enumeration getAllProblems();
- /**
- * Returns the problems with the image itself. Returns null if no
- * problems exist for the image. An example of such a problem is
- * duplicate types in a package.
- * Returns an Enumeration of IProblemDetail.
- */
- public Enumeration getImageProblems();
- /**
- * Returns an enumeration of problem table keys (sourceID objects)
- */
- public Enumeration getProblemKeys();
- /**
- * Returns an enumeration of problems for a given source.
- */
- public Enumeration getProblems(Object sourceID);
- /**
- * Returns a vector of problems for a given source,
- * or null if no problems.
- */
- public Vector getProblemVector(Object sourceID);
- /**
- * Returns whether the given source has any problems.
- */
- public boolean hasProblems(Object sourceID);
- /**
- * Adds a problem to this problem reporter for a source with the given ID.
- * If the problem is a duplicate, it is not added and an error message is
- * printed to the console.
- */
- public void putProblem(Object sourceID, IProblemDetail problem);
- /**
- * Removes all problems except syntax errors for the given source.
- */
- public void removeNonSyntaxErrors(Object sourceID);
- /**
- * Removes all problems for the given source.
- */
- public void removeProblems(Object sourceID);
- /**
- * Removes all syntax errors for the given source.
- */
- public void removeSyntaxErrors(Object sourceID);
+/**
+ * Creates a copy of this problem reporter.
+ */
+public IProblemReporter copy();
+/**
+ * Returns an enumeration of all problems with elements of the image,
+ * but not with the image itself.
+ * Returns an Enumeration of IProblemDetail.
+ */
+public Enumeration getAllProblems();
+/**
+ * Returns the problems with the image itself. Returns null if no
+ * problems exist for the image. An example of such a problem is
+ * duplicate types in a package.
+ * Returns an Enumeration of IProblemDetail.
+ */
+public Enumeration getImageProblems();
+/**
+ * Returns an enumeration of problem table keys (sourceID objects)
+ */
+public Enumeration getProblemKeys();
+/**
+ * Returns an enumeration of problems for a given source.
+ */
+public Enumeration getProblems(Object sourceID);
+/**
+ * Returns a vector of problems for a given source,
+ * or null if no problems.
+ */
+public Vector getProblemVector(Object sourceID);
+/**
+ * Returns whether the given source has any problems.
+ */
+public boolean hasProblems(Object sourceID);
+/**
+ * Adds a problem to this problem reporter for a source with the given ID.
+ * If the problem is a duplicate, it is not added and an error message is
+ * printed to the console.
+ */
+public void putProblem(Object sourceID, IProblemDetail problem);
+/**
+ * Removes all problems except syntax errors for the given source.
+ */
+public void removeNonSyntaxErrors(Object sourceID);
+/**
+ * Removes all problems for the given source.
+ */
+public void removeProblems(Object sourceID);
+/**
+ * Removes all syntax errors for the given source.
+ */
+public void removeSyntaxErrors(Object sourceID);
- /**
- * Initializes this problem reporter for the given project.
- * This is used only when deserializing a state.
- */
- public void initialize(IProject project, IDevelopmentContext devContext);
+/**
+ * Initializes this problem reporter for the given project.
+ * This is used only when deserializing a state.
+ */
+public void initialize(IProject project, IDevelopmentContext devContext);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IReportCard.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IReportCard.java
index d1ac090a23..35500c8862 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IReportCard.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IReportCard.java
@@ -11,47 +11,47 @@ import org.eclipse.core.runtime.IPath;
*/
public interface IReportCard {
- /**
- * Calculates the paths for all resources that have a changed problem state between
- * this report card and previous.
- */
- IPath[] changedPaths(IReportCard previous);
- /**
- * Returns this report card's image context.
- */
- IImageContext getImageContext();
- /**
- * Returns the problem details pertaining to built objects having the
- * given path, or having the path as a prefix of their path.
- * That is, this returns all problems with the specified element and all its children.
- * Only objects within the scope of the report card's image context are considered.
- * If null is passed, all problems within the image context are returned,
- * as well as problems reported against the image itself (e.g. missing required classes).
- */
- IProblemDetail[] getLeafProblemsFor(IPath path);
- /**
- * Returns the paths of resources whose built objects have problems.
- * Only objects having the given path, or having the given path
- * as a prefix of their path, are considered.
- * Only objects within the scope of the report card's image context are considered.
- * If null is passed, all objects within the image context are considered.
- * Note that problems which have no path, such as problems reported against
- * the image itself, are not considered.
- * To get all problems, use <code>getLeafProblemsFor(IPath path)</code> instead.
- *
- * @see #getLeafProblemsFor
- */
- IPath[] getProblemPaths(IPath path);
- /**
- * Returns this report card's state.
- */
- IState getState();
- /**
- * Returns whether there are problems pertaining to built objects having the
- * given path, or having the given path as a prefix of their path.
- * See <code>getLeafProblemsFor(IPath path)</code> for more details.
- *
- * @see #getLeafProblemsFor
- */
- boolean hasLeafProblems(IPath path);
+/**
+ * Calculates the paths for all resources that have a changed problem state between
+ * this report card and previous.
+ */
+IPath[] changedPaths(IReportCard previous);
+/**
+ * Returns this report card's image context.
+ */
+IImageContext getImageContext();
+/**
+ * Returns the problem details pertaining to built objects having the
+ * given path, or having the path as a prefix of their path.
+ * That is, this returns all problems with the specified element and all its children.
+ * Only objects within the scope of the report card's image context are considered.
+ * If null is passed, all problems within the image context are returned,
+ * as well as problems reported against the image itself (e.g. missing required classes).
+ */
+IProblemDetail[] getLeafProblemsFor(IPath path);
+/**
+ * Returns the paths of resources whose built objects have problems.
+ * Only objects having the given path, or having the given path
+ * as a prefix of their path, are considered.
+ * Only objects within the scope of the report card's image context are considered.
+ * If null is passed, all objects within the image context are considered.
+ * Note that problems which have no path, such as problems reported against
+ * the image itself, are not considered.
+ * To get all problems, use <code>getLeafProblemsFor(IPath path)</code> instead.
+ *
+ * @see #getLeafProblemsFor
+ */
+IPath[] getProblemPaths(IPath path);
+/**
+ * Returns this report card's state.
+ */
+IState getState();
+/**
+ * Returns whether there are problems pertaining to built objects having the
+ * given path, or having the given path as a prefix of their path.
+ * See <code>getLeafProblemsFor(IPath path)</code> for more details.
+ *
+ * @see #getLeafProblemsFor
+ */
+boolean hasLeafProblems(IPath path);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ISearch.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ISearch.java
index bb3e13ec20..353f64c65b 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ISearch.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ISearch.java
@@ -1,73 +1,74 @@
package org.eclipse.jdt.internal.core.builder;
-public interface ISearch extends Runnable {
- /**
- * Adds the specified action listener to receive progress and result events
- * from this search. Progress events occur as a search examines the types
- * and packages in the search scope. Result events occur as a search finds
- * matches to the search criteria.
- * @param listener the search listener
- * @see ISearchListener
- * @see SearchProgressEvent
- * @see SearchResultEvent
- * @see ISearch#removeSearchListener
- */
- void addSearchListener(ISearchListener listener);
- /**
- * Cancels the search. If the search is not running, this operation has no
- * effect.
- */
- void cancelSearch();
- /**
- * Returns whether two ISearch objects are equal or not.
- * Two ISearch objects are considered to be equal if
- * they are the same object OR:
- * <ul>
- * <li> neither is equal to null AND
- * <li> both searches have the same kind (i.e.. search for type), name
- * (i.e., type named 'Foo') return type, number and type of parameters
- * (even if not used -- as in the case of search for type), and search
- * context (i.e., ISearchFactory.SEARCH_FOR_DECLS)
- * <li> their scopes are equal (contain the same IPackage and IType handles, in any order)
- * </ul>
- */
+public interface ISearch extends Runnable
+{
+/**
+ * Adds the specified action listener to receive progress and result events
+ * from this search. Progress events occur as a search examines the types
+ * and packages in the search scope. Result events occur as a search finds
+ * matches to the search criteria.
+ * @param listener the search listener
+ * @see ISearchListener
+ * @see SearchProgressEvent
+ * @see SearchResultEvent
+ * @see ISearch#removeSearchListener
+ */
+void addSearchListener(ISearchListener listener);
+/**
+ * Cancels the search. If the search is not running, this operation has no
+ * effect.
+ */
+void cancelSearch();
+/**
+ * Returns whether two ISearch objects are equal or not.
+ * Two ISearch objects are considered to be equal if
+ * they are the same object OR:
+ * <ul>
+ * <li> neither is equal to null AND
+ * <li> both searches have the same kind (i.e.. search for type), name
+ * (i.e., type named 'Foo') return type, number and type of parameters
+ * (even if not used -- as in the case of search for type), and search
+ * context (i.e., ISearchFactory.SEARCH_FOR_DECLS)
+ * <li> their scopes are equal (contain the same IPackage and IType handles, in any order)
+ * </ul>
+ */
- boolean equals(Object obj);
- /**
- * Returns the item <i>n</i>th item in the search result. This may be a field,
- * method, constructor, package, or type object.
- */
- IHandle getItem(int n);
- /**
- * Returns the number of items in the search scope which matched the
- * search goal so far. Note that the result may not include all matches
- * within the search space if the search is still running or was cancelled.
- */
- int getItemCount();
- /**
- * Returns the positions for the <i>n</i>th item in the search result.
- * If no positions exist, null is returned.
- */
- int[] getPositions(int n);
- /**
- * Returns whether a search is currently in progress.
- */
- boolean isSearching();
- /**
- * Removes the specified action listener so that it no longer
- * receives progress and result events from the search.
- * @param listener the search listener
- * @see ISearchListener
- * @see SearchProgressEvent
- * @see SearchResultEvent
- * @see ISearch#addSearchListener
- */
- void removeSearchListener(ISearchListener listener);
- /**
- * Performs the search. Upon return the results can be obtained via
- * <code>getItem</code>. During the search, the results are made available
- * as they are found, and progress and results are reported to registered
- * <code>ISearchListener</code>s.
- */
- void run();
+boolean equals(Object obj);
+/**
+ * Returns the item <i>n</i>th item in the search result. This may be a field,
+ * method, constructor, package, or type object.
+ */
+IHandle getItem(int n);
+/**
+ * Returns the number of items in the search scope which matched the
+ * search goal so far. Note that the result may not include all matches
+ * within the search space if the search is still running or was cancelled.
+ */
+int getItemCount();
+/**
+ * Returns the positions for the <i>n</i>th item in the search result.
+ * If no positions exist, null is returned.
+ */
+int[] getPositions(int n);
+/**
+ * Returns whether a search is currently in progress.
+ */
+boolean isSearching();
+/**
+ * Removes the specified action listener so that it no longer
+ * receives progress and result events from the search.
+ * @param listener the search listener
+ * @see ISearchListener
+ * @see SearchProgressEvent
+ * @see SearchResultEvent
+ * @see ISearch#addSearchListener
+ */
+void removeSearchListener(ISearchListener listener);
+/**
+ * Performs the search. Upon return the results can be obtained via
+ * <code>getItem</code>. During the search, the results are made available
+ * as they are found, and progress and results are reported to registered
+ * <code>ISearchListener</code>s.
+ */
+void run();
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ISearchFactory.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ISearchFactory.java
index 485ccd8f25..217f472543 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ISearchFactory.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ISearchFactory.java
@@ -1,6 +1,7 @@
package org.eclipse.jdt.internal.core.builder;
-public interface ISearchFactory {
+public interface ISearchFactory
+{
/* Flags for search context */
/**
@@ -29,203 +30,212 @@ public interface ISearchFactory {
*/
int SEARCH_FOR_SOURCE_REFS = 0x04;
- /**
- * Returns an <code>ISearch</code> that will look for fields with a matching
- * name.
- * <p>
- * <b>Example:</b> Searching for declarations of fields named <code>width</code>
- * in package <code>java.awt</code>.
- * <pre><code>
- * IImage image = dc.getImage();
- * ISearchFactory sf = image.newSearchFactory();
- * IHandle[] scope = {image.getPackageHandle("java.awt", false)};
- * ISearch search =
- * sf.searchForField(
- * "width",
- * scope,
- * ISearchFactory.SEARCH_FOR_DECLS);
- * search.run();
- * </code></pre>
- * @param fieldName the name of the field to search for, possibly containing
- * wildcards ("*")
- * @param scope the packages and types to search in
- * @param context the context flags. SEARCH_FOR_DECLS, and
- * SEARCH_FOR_SOURCE_REFS are valid flags for field searches.
- * SEARCH_FOR_PRINCIPLE_STRUCTURE_REFS will not have any effect on
- * the search because there are no field references in the principle
- * structure.
- *
- *
- * @see ISearch
- */
- ISearch searchForField(String fieldName, IHandle[] scope, int context);
- /**
- * Returns an <code>ISearch</code> that will look for methods or constructors
- * with matching name, parameter types, and return type.
- * <p>
- * When searching for a constructor, the return type is ignored.
- * <p>
- * <b>Example:</b> Search for declarations of methods named <code>toString</code>
- * whose second argument is <code>int</code>. The search will be conducted
- * in the scope of the <code>hanoiExample</code> package.
- * <code><pre>
- * IImage image = dc.getImage();
- * ISearchFactory factory = image.newSearchFactory();
- * IHandle[] scope = {image.getPackageHandle("hanoiExample")};
- * ISearch search =
- * factory.searchForMethod(
- * "toString",
- * new String[] {"*", "int"},
- * "*",
- * scope,
- * SEARCH_FOR_DECLS);
- * search.run();
- * </code></pre>
- * <br>
- * @param methodName the method name to search for, possibly containing wildcards ("*")
- * @param paramTypes the names of parameter types the method being searched for must
- * have, possibly containing wildcards. An empty array indicates a method with
- * zero parameters.
- * @param returnType the name of the return type the method being
- * searched for must have, possibly containing wildcards. A return type
- * of "*" effectively ignores the return type.
- * @param scope the packages and types to search in
- * @param context the context flags. SEARCH_FOR_DECLS make sense as a flag for
- * this method search. Using SEARCH_FOR_PRINCIPLE_STRUCTURE_REFS will have no effect since methods
- * cannot be referenced in the principle structure. When searching the source,
- * SEARCH_FOR_SOURCE_REFS will ignore the return type, and only use the
- * number of parameters, not the parameter types. This is because at the source
- * level only the method name and number of parameters are
- * known.
- * @see ISearch
- */
- ISearch searchForMethod(
+/**
+ * Returns an <code>ISearch</code> that will look for fields with a matching
+ * name.
+ * <p>
+ * <b>Example:</b> Searching for declarations of fields named <code>width</code>
+ * in package <code>java.awt</code>.
+ * <pre><code>
+ * IImage image = dc.getImage();
+ * ISearchFactory sf = image.newSearchFactory();
+ * IHandle[] scope = {image.getPackageHandle("java.awt", false)};
+ * ISearch search =
+ * sf.searchForField(
+ * "width",
+ * scope,
+ * ISearchFactory.SEARCH_FOR_DECLS);
+ * search.run();
+ * </code></pre>
+ * @param fieldName the name of the field to search for, possibly containing
+ * wildcards ("*")
+ * @param scope the packages and types to search in
+ * @param context the context flags. SEARCH_FOR_DECLS, and
+ * SEARCH_FOR_SOURCE_REFS are valid flags for field searches.
+ * SEARCH_FOR_PRINCIPLE_STRUCTURE_REFS will not have any effect on
+ * the search because there are no field references in the principle
+ * structure.
+ *
+ *
+ * @see ISearch
+ */
+ISearch searchForField(
+ String fieldName,
+ IHandle[] scope,
+ int context);
+/**
+ * Returns an <code>ISearch</code> that will look for methods or constructors
+ * with matching name, parameter types, and return type.
+ * <p>
+ * When searching for a constructor, the return type is ignored.
+ * <p>
+ * <b>Example:</b> Search for declarations of methods named <code>toString</code>
+ * whose second argument is <code>int</code>. The search will be conducted
+ * in the scope of the <code>hanoiExample</code> package.
+ * <code><pre>
+ * IImage image = dc.getImage();
+ * ISearchFactory factory = image.newSearchFactory();
+ * IHandle[] scope = {image.getPackageHandle("hanoiExample")};
+ * ISearch search =
+ * factory.searchForMethod(
+ * "toString",
+ * new String[] {"*", "int"},
+ * "*",
+ * scope,
+ * SEARCH_FOR_DECLS);
+ * search.run();
+ * </code></pre>
+ * <br>
+ * @param methodName the method name to search for, possibly containing wildcards ("*")
+ * @param paramTypes the names of parameter types the method being searched for must
+ * have, possibly containing wildcards. An empty array indicates a method with
+ * zero parameters.
+ * @param returnType the name of the return type the method being
+ * searched for must have, possibly containing wildcards. A return type
+ * of "*" effectively ignores the return type.
+ * @param scope the packages and types to search in
+ * @param context the context flags. SEARCH_FOR_DECLS make sense as a flag for
+ * this method search. Using SEARCH_FOR_PRINCIPLE_STRUCTURE_REFS will have no effect since methods
+ * cannot be referenced in the principle structure. When searching the source,
+ * SEARCH_FOR_SOURCE_REFS will ignore the return type, and only use the
+ * number of parameters, not the parameter types. This is because at the source
+ * level only the method name and number of parameters are
+ * known.
+ * @see ISearch
+ */
+ISearch searchForMethod(
String methodName,
String[] paramTypes,
String returnType,
IHandle[] scope,
int context);
- /**
- * Returns an <code>ISearch</code> that will look for methods or constructors
- * with matching name, number of parameters, and return type. A parameter count
- * of -1 indicates that the number of parameters doesn't matter.
- * <p>
- * When searching for a constructor, the return type is ignored.
- * <p>
- * <b>Example 1:</b> Search for declarations and references to methods named <code>add</code>
- * which have 2 arguments. The search will be conducted in the scope of the <code>hanoiExample</code>
- * package. Note that the principle structure is not searched for references
- * since it never contains information about references to methods.
- * <code><pre>
- * IImage image = dc.getImage();
- * ISearchFactory factory = image.newSearchFactory();
- * IHandle[] scope = {image.getPackageHandle("hanoiExample")};
- * ISearch search =
- * factory.searchForMethod(
- * "add",
- * 2,
- * "*",
- * scope,
- * SEARCH_FOR_DECLS |
- * SEARCH_FOR_SOURCE_REFS);
- * search.run();
- * </code></pre>
- * <br>
- * <b>Example 2:</b> Search for references to a constructor for a class named
- * <code>Disk</code> which takes any number of arguments. The search will be conducted in
- * the scope of the <code>hanoiExample</code> package. Note that the principle structure is not searched for references
- * since it never contains information about references to methods.
- * <code><pre>
- * IImage image = dc.getImage();
- * ISearchFactory factory = image.newSearchFactory();
- * IHandle[] scope = {image.getPackageHandle("hanoiExample")};
- * ISearch search =
- * factory.searchForMethod(
- * "Disk",
- * -1,
- * "", // return type ignored for constructors
- * scope,
- * SEARCH_FOR_SOURCE_REFS);
- * search.run();
- * </code></pre>
- *
- * @param methodName the method name to search for, possibly containing wildcards ("*")
- * @param parameterCount the number of parameters the method being
- * searched for has. Use -1 if number of parameters doesn't matter
- * @param returnType the name of the return type the method being
- * searched for must have, possibly containing wildcards. A return type of
- * "*" effectively ignores return type.
- * @param scope the packages and types to search in
- * @param context the context flags. SEARCH_FOR_DECLS and
- * SEARCH_FOR_SOURCE_REFS make sense as flags for this method search.
- * SEARCH_FOR_PRINCIPLE_STRUCTURE_REFS will not have any effect since
- * principle structures cannot reference methods.
- *
- * @see ISearch
- */
- ISearch searchForMethod(
+/**
+ * Returns an <code>ISearch</code> that will look for methods or constructors
+ * with matching name, number of parameters, and return type. A parameter count
+ * of -1 indicates that the number of parameters doesn't matter.
+ * <p>
+ * When searching for a constructor, the return type is ignored.
+ * <p>
+ * <b>Example 1:</b> Search for declarations and references to methods named <code>add</code>
+ * which have 2 arguments. The search will be conducted in the scope of the <code>hanoiExample</code>
+ * package. Note that the principle structure is not searched for references
+ * since it never contains information about references to methods.
+ * <code><pre>
+ * IImage image = dc.getImage();
+ * ISearchFactory factory = image.newSearchFactory();
+ * IHandle[] scope = {image.getPackageHandle("hanoiExample")};
+ * ISearch search =
+ * factory.searchForMethod(
+ * "add",
+ * 2,
+ * "*",
+ * scope,
+ * SEARCH_FOR_DECLS |
+ * SEARCH_FOR_SOURCE_REFS);
+ * search.run();
+ * </code></pre>
+ * <br>
+ * <b>Example 2:</b> Search for references to a constructor for a class named
+ * <code>Disk</code> which takes any number of arguments. The search will be conducted in
+ * the scope of the <code>hanoiExample</code> package. Note that the principle structure is not searched for references
+ * since it never contains information about references to methods.
+ * <code><pre>
+ * IImage image = dc.getImage();
+ * ISearchFactory factory = image.newSearchFactory();
+ * IHandle[] scope = {image.getPackageHandle("hanoiExample")};
+ * ISearch search =
+ * factory.searchForMethod(
+ * "Disk",
+ * -1,
+ * "", // return type ignored for constructors
+ * scope,
+ * SEARCH_FOR_SOURCE_REFS);
+ * search.run();
+ * </code></pre>
+ *
+ * @param methodName the method name to search for, possibly containing wildcards ("*")
+ * @param parameterCount the number of parameters the method being
+ * searched for has. Use -1 if number of parameters doesn't matter
+ * @param returnType the name of the return type the method being
+ * searched for must have, possibly containing wildcards. A return type of
+ * "*" effectively ignores return type.
+ * @param scope the packages and types to search in
+ * @param context the context flags. SEARCH_FOR_DECLS and
+ * SEARCH_FOR_SOURCE_REFS make sense as flags for this method search.
+ * SEARCH_FOR_PRINCIPLE_STRUCTURE_REFS will not have any effect since
+ * principle structures cannot reference methods.
+ *
+ * @see ISearch
+ */
+ISearch searchForMethod(
String methodName,
- int parameterCount,
+ int parameterCount,
String returnType,
IHandle[] scope,
int context);
- /**
- * Returns an <code>ISearch</code> that will look for packages with a matching
- * name.
- * <p>
- * <b>Example:</b><br>
- * Searching for all references (principle structure and source) to packages
- * matching <code>java.aw*</code> in the scope of the <code>hanoiExample</code>
- * package.
- * <pre><code>
- * IImage image = dc.getImage();
- * ISearchFactory sf = image.newSearchFactory();
- * IHandle[] scope = {image.getPackageHandle("hanoiExample", false)};
- * ISearch search =
- * sf.searchForPackage(
- * "java.aw*",
- * scope,
- * ISearchFactory.SEARCH_FOR_PRINCIPLE_STRUCTURE_REFS |
- * ISearchFactory.SEARCH_FOR_SOURCE_REFS);
- * search.run();
- * </code></pre>
- *
- * @param packageName the name of the package to search for, possibly
- * containing wildcards ("*")
- * @param scope the packages and types to search in
- * @param context the context flags. SEARCH_FOR_PRINCIPLE_STRUCTURE_REFS,
- * and SEARCH_FOR_SOURCE_REFS make sense as flags for package
- * searches. Using SEARCH_FOR_DECLS will not have any effect because
- * packages are not declared anywhere.
- *
- * @see ISearch
- */
- ISearch searchForPackage(String packageName, IHandle[] scope, int context);
- /**
- * Returns an <code>ISearch</code> that will look for types with a matching
- * name.
- * <p>
- * <b>Example:</b><br>
- * Searching for all declarations of a type named <code>Post</code> in the scope of
- * package <code>hanoiExample</code>.
- * <pre><code>
- * IImage image = dc.getImage();
- * ISearchFactory sf = image.newSearchFactory();
- * IHandle[] scope = {image.getPackageHandle("hanoiExample", false)};
- * ISearch search =
- * sf.searchForType(
- * "Post",
- * scope,
- * ISearchFactory.SEARCH_FOR_DECLS);
- * search.run();
- * </code></pre>
- * @param typeName the simple name of the type to search for, possibly
- * containing wildcards ("*")
- * @param scope the packages and types to search in
- * @param context the context flags. SEARCH_FOR_DECLS, SEARCH_FOR_PRINCIPLE_STRUCTURE_REFS,
- * and SEARCH_FOR_SOURCE_REFS all make sense as flags for type searches.
- *
- * @see ISearch
- */
- ISearch searchForType(String typeName, IHandle[] scope, int context);
+/**
+ * Returns an <code>ISearch</code> that will look for packages with a matching
+ * name.
+ * <p>
+ * <b>Example:</b><br>
+ * Searching for all references (principle structure and source) to packages
+ * matching <code>java.aw*</code> in the scope of the <code>hanoiExample</code>
+ * package.
+ * <pre><code>
+ * IImage image = dc.getImage();
+ * ISearchFactory sf = image.newSearchFactory();
+ * IHandle[] scope = {image.getPackageHandle("hanoiExample", false)};
+ * ISearch search =
+ * sf.searchForPackage(
+ * "java.aw*",
+ * scope,
+ * ISearchFactory.SEARCH_FOR_PRINCIPLE_STRUCTURE_REFS |
+ * ISearchFactory.SEARCH_FOR_SOURCE_REFS);
+ * search.run();
+ * </code></pre>
+ *
+ * @param packageName the name of the package to search for, possibly
+ * containing wildcards ("*")
+ * @param scope the packages and types to search in
+ * @param context the context flags. SEARCH_FOR_PRINCIPLE_STRUCTURE_REFS,
+ * and SEARCH_FOR_SOURCE_REFS make sense as flags for package
+ * searches. Using SEARCH_FOR_DECLS will not have any effect because
+ * packages are not declared anywhere.
+ *
+ * @see ISearch
+ */
+ISearch searchForPackage(
+ String packageName,
+ IHandle[] scope,
+ int context);
+/**
+ * Returns an <code>ISearch</code> that will look for types with a matching
+ * name.
+ * <p>
+ * <b>Example:</b><br>
+ * Searching for all declarations of a type named <code>Post</code> in the scope of
+ * package <code>hanoiExample</code>.
+ * <pre><code>
+ * IImage image = dc.getImage();
+ * ISearchFactory sf = image.newSearchFactory();
+ * IHandle[] scope = {image.getPackageHandle("hanoiExample", false)};
+ * ISearch search =
+ * sf.searchForType(
+ * "Post",
+ * scope,
+ * ISearchFactory.SEARCH_FOR_DECLS);
+ * search.run();
+ * </code></pre>
+ * @param typeName the simple name of the type to search for, possibly
+ * containing wildcards ("*")
+ * @param scope the packages and types to search in
+ * @param context the context flags. SEARCH_FOR_DECLS, SEARCH_FOR_PRINCIPLE_STRUCTURE_REFS,
+ * and SEARCH_FOR_SOURCE_REFS all make sense as flags for type searches.
+ *
+ * @see ISearch
+ */
+ISearch searchForType(
+ String typeName,
+ IHandle[] scope,
+ int context);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ISearchListener.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ISearchListener.java
index 68d435dd28..d4031d2387 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ISearchListener.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ISearchListener.java
@@ -1,26 +1,26 @@
package org.eclipse.jdt.internal.core.builder;
public interface ISearchListener extends java.util.EventListener {
- /**
- * Reports that the search has been cancelled and is no longer running.
- */
- public void cancelled();
- /**
- * Reports that the search has finished.
- */
- public void done();
- /**
- * Reports that the search has moved to the type or package named
- * in the event.
- *
- * @see SearchProgressEvent
- */
- public void progressUpdated(SearchProgressEvent e);
- /**
- * Reports that the search has found the result given
- * in the event.
- *
- * @see SearchResultEvent
- */
- public void resultsUpdated(SearchResultEvent e);
+/**
+ * Reports that the search has been cancelled and is no longer running.
+ */
+public void cancelled();
+/**
+ * Reports that the search has finished.
+ */
+public void done();
+/**
+ * Reports that the search has moved to the type or package named
+ * in the event.
+ *
+ * @see SearchProgressEvent
+ */
+public void progressUpdated(SearchProgressEvent e);
+/**
+ * Reports that the search has found the result given
+ * in the event.
+ *
+ * @see SearchResultEvent
+ */
+public void resultsUpdated(SearchResultEvent e);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ISourceFragment.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ISourceFragment.java
index 983bf72d12..d7e6f44b51 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ISourceFragment.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/ISourceFragment.java
@@ -15,7 +15,8 @@ import org.eclipse.core.runtime.IPath;
*
* @see IMember#getSourceFragment
*/
-public interface ISourceFragment {
+public interface ISourceFragment
+{
/**
* Compare two Objects for equality. Returns true iff they represent the same
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IState.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IState.java
index a5f3477d87..f37e6987e0 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IState.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IState.java
@@ -11,28 +11,25 @@ import org.eclipse.core.resources.IResourceDelta;
* This represents a specific, immutable state of the image described by the Development Context.
*/
public interface IState {
- /**
- * Performs an incremental build, given a new project
- * and a delta describing the differences between
- * the project for this state and the new project.
- * Returns an ImageBuilder representing the process of building
- * the new state. The result object can be queried for the
- * new state and for the image delta between this state and
- * the new state.
- *
- * <p> The given delta must represent the differences
- * between the project for this state and the new project.
- *
- * <p> Optionally, the build context for the new state can be
- * specified. If null is specified, this state's build context
- * is given to the new state.
- *
- * @see #getBuildContext
- */
- IImageBuilder applySourceDelta(
- IProject newProject,
- IResourceDelta delta,
- IImageContext buildContext);
+/**
+ * Performs an incremental build, given a new project
+ * and a delta describing the differences between
+ * the project for this state and the new project.
+ * Returns an ImageBuilder representing the process of building
+ * the new state. The result object can be queried for the
+ * new state and for the image delta between this state and
+ * the new state.
+ *
+ * <p> The given delta must represent the differences
+ * between the project for this state and the new project.
+ *
+ * <p> Optionally, the build context for the new state can be
+ * specified. If null is specified, this state's build context
+ * is given to the new state.
+ *
+ * @see #getBuildContext
+ */
+IImageBuilder applySourceDelta(IProject newProject, IResourceDelta delta, IImageContext buildContext);
/**
* Compare two Objects for equality. Returns true iff they represent the same state
* in the same development context.
@@ -74,21 +71,21 @@ public interface IState {
* @see IDevelopmentContext#getImage
*/
IImage getImage();
- /**
- * Returns the project which provides the source for this state.
- */
- IProject getProject();
- /**
- * Returns a report card for this state., restricted to
- * the given image context.
- * Problems are organized by workspace element identifiers.
- * This method is on <code>IState</code> rather than
- * <code>IImage</code> to make it clear that
- * the result is inherently state-specific.
- * @param imageContext the image context in which to
- * restrict the report card.
- */
- IReportCard getReportCard(IImageContext imageContext);
+/**
+ * Returns the project which provides the source for this state.
+ */
+IProject getProject();
+/**
+ * Returns a report card for this state., restricted to
+ * the given image context.
+ * Problems are organized by workspace element identifiers.
+ * This method is on <code>IState</code> rather than
+ * <code>IImage</code> to make it clear that
+ * the result is inherently state-specific.
+ * @param imageContext the image context in which to
+ * restrict the report card.
+ */
+IReportCard getReportCard(IImageContext imageContext);
/**
* Returns a new image delta representing the differences between the this
* state and another one. The delta is naive in that no delta information is initially provided.
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IType.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IType.java
index 17adcf25ad..2603694e5b 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IType.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/IType.java
@@ -2,6 +2,7 @@ package org.eclipse.jdt.internal.core.builder;
public interface IType extends IMember {
+
/**
* Compares this Type handle against the specified object. Returns
* true if the objects are the same. Two Types handles are the same if
@@ -144,20 +145,20 @@ public interface IType extends IMember {
* @see Modifier
*/
int getDeclaredModifiers() throws NotPresentException;
- /**
- * Returns the declared name of the class or interface represented
- * by this object, as a String.
- * The name is the simple, unqualified name used in the source code.
- * If this represents an inner class, it does not include the names
- * of any containing classes.
- * If this represents an anonymous class, it returns a String of length 0.
- * If this does not represent a class or interface, it returns
- * a String of length 0.
- *
- * @return the declared name of the class or interface
- * represented by this object.
- * @exception NotPresentException if this class or interface is not present.
- */
+ /**
+ * Returns the declared name of the class or interface represented
+ * by this object, as a String.
+ * The name is the simple, unqualified name used in the source code.
+ * If this represents an inner class, it does not include the names
+ * of any containing classes.
+ * If this represents an anonymous class, it returns a String of length 0.
+ * If this does not represent a class or interface, it returns
+ * a String of length 0.
+ *
+ * @return the declared name of the class or interface
+ * represented by this object.
+ * @exception NotPresentException if this class or interface is not present.
+ */
String getDeclaredName() throws NotPresentException;
/**
* If the class or interface represented by this Type object is
@@ -200,14 +201,13 @@ public interface IType extends IMember {
* Returns an array of length 0 if this object does not represent
* an interface.
* The resulting Types are in no particular order.
- * See <em>The Java Language Specification</em> section 8.1.4
+ * See <em>The Java Language Specification</em> section 8.1.4
* for more details.
*
* @param imageContext the ImageContext in which to restrict the search.
* @exception NotPresentException if this interface is not present.
*/
- IType[] getImplementingClasses(IImageContext imageContext)
- throws NotPresentException;
+ IType[] getImplementingClasses(IImageContext imageContext) throws NotPresentException;
/**
* Returns an array of Type objects representing the direct
* superinterfaces of the class or interface represented by this object.
@@ -228,7 +228,7 @@ public interface IType extends IMember {
* object represents neither a class nor an interface, this method
* returns an array of length 0.
*
- * See <em>The Java Language Specification</em> sections 8.1.4 and 9.1.3
+ * See <em>The Java Language Specification</em> sections 8.1.4 and 9.1.3
* for more details.
*
* @return an array of interfaces implemented by this class.
@@ -319,7 +319,7 @@ public interface IType extends IMember {
* Returns an array of length 0 if this object does not represent
* a class.
* The resulting Types are in no particular order.
- * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
+ * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
* for more details.
*
* @param imageContext the ImageContext in which to restrict the search.
@@ -333,14 +333,13 @@ public interface IType extends IMember {
* Returns an array of length 0 if this object does not represent
* an interface.
* The resulting Types are in no particular order.
- * See <em>The Java Language Specification</em> section 9.1.3
+ * See <em>The Java Language Specification</em> section 9.1.3
* for more details.
*
* @param imageContext the ImageContext in which to restrict the search.
* @exception NotPresentException if this interface is not present.
*/
- IType[] getSubinterfaces(IImageContext imageContext)
- throws NotPresentException;
+ IType[] getSubinterfaces(IImageContext imageContext) throws NotPresentException;
/**
* If this object represents any class other than the class
* <code>java.lang.Object</code>, then the object that represents
@@ -352,7 +351,7 @@ public interface IType extends IMember {
* If this object represents an array type, then the Type that represents
* class <code>java.lang.Object</code> is returned.
* <p>
- * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
+ * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
* for more details.
*
* @return the superclass of the class represented by this object.
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/InvalidKeyException.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/InvalidKeyException.java
index e243be0236..e633ea9d5d 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/InvalidKeyException.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/InvalidKeyException.java
@@ -7,7 +7,6 @@ public class InvalidKeyException extends RuntimeException {
public InvalidKeyException() {
super();
}
-
/**
* Constructs an <code>InvalidKeyException</code> with a detail message.
*
@@ -16,5 +15,4 @@ public class InvalidKeyException extends RuntimeException {
public InvalidKeyException(String s) {
super(s);
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/MemoryBinaryBroker.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/MemoryBinaryBroker.java
index bfedf09853..d1dc63136e 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/MemoryBinaryBroker.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/MemoryBinaryBroker.java
@@ -14,52 +14,48 @@ import java.util.*;
public class MemoryBinaryBroker implements IBinaryBroker {
Hashtable fTable = new Hashtable();
- /**
- * @see IBinaryBroker
- */
- public synchronized void close() {
- // NOP
- }
-
- /**
- * @see IBinaryBroker
- */
- public synchronized void garbageCollect(Hashtable keysInUse) {
- Vector toRemove = new Vector();
- for (Enumeration e = fTable.keys(); e.hasMoreElements();) {
- BinaryBrokerKey key = (BinaryBrokerKey) e.nextElement();
- if (!keysInUse.containsKey(key)) {
- toRemove.addElement(key);
- }
- }
- for (Enumeration e = toRemove.elements(); e.hasMoreElements();) {
- BinaryBrokerKey key = (BinaryBrokerKey) e.nextElement();
- fTable.remove(key);
+/**
+ * @see IBinaryBroker
+ */
+public synchronized void close() {
+ // NOP
+}
+/**
+ * @see IBinaryBroker
+ */
+public synchronized void garbageCollect(Hashtable keysInUse) {
+ Vector toRemove = new Vector();
+ for (Enumeration e = fTable.keys(); e.hasMoreElements();) {
+ BinaryBrokerKey key = (BinaryBrokerKey) e.nextElement();
+ if (!keysInUse.containsKey(key)) {
+ toRemove.addElement(key);
}
}
-
- /**
- * @see IBinaryBroker
- */
- public synchronized byte[] getBinary(BinaryBrokerKey key) {
- return (byte[]) fTable.get(key);
+ for (Enumeration e = toRemove.elements(); e.hasMoreElements();) {
+ BinaryBrokerKey key = (BinaryBrokerKey) e.nextElement();
+ fTable.remove(key);
}
-
- /**
- * @see IBinaryBroker
- */
- public synchronized void putBinary(BinaryBrokerKey key, byte[] bytes) {
- byte[] old = (byte[]) fTable.get(key);
- /* Sanity check that old is same as new */
- if (old != null) {
- Assert.isTrue(old.length == bytes.length);
- for (int i = old.length; --i >= 0;) {
- if (old[i] != bytes[i]) {
- Assert.isTrue(false);
- }
+}
+/**
+ * @see IBinaryBroker
+ */
+public synchronized byte[] getBinary(BinaryBrokerKey key) {
+ return (byte[]) fTable.get(key);
+}
+/**
+ * @see IBinaryBroker
+ */
+public synchronized void putBinary(BinaryBrokerKey key, byte[] bytes) {
+ byte[] old = (byte[]) fTable.get(key);
+ /* Sanity check that old is same as new */
+ if (old != null) {
+ Assert.isTrue(old.length == bytes.length);
+ for (int i = old.length; --i >= 0;) {
+ if (old[i] != bytes[i]) {
+ Assert.isTrue(false);
}
}
- fTable.put(key, bytes);
}
-
+ fTable.put(key, bytes);
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/NotPresentException.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/NotPresentException.java
index 4f2fbb568d..270104a3f9 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/NotPresentException.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/NotPresentException.java
@@ -1,6 +1,8 @@
package org.eclipse.jdt.internal.core.builder;
-public class NotPresentException extends RuntimeException {
+public class NotPresentException extends RuntimeException
+{
+
/**
* Constructs a <code>NotPresentException</code> without a detail message.
@@ -8,7 +10,6 @@ public class NotPresentException extends RuntimeException {
public NotPresentException() {
super();
}
-
/**
* Constructs a <code>NotPresentException</code> with a detail message.
*
@@ -17,5 +18,4 @@ public class NotPresentException extends RuntimeException {
public NotPresentException(String s) {
super(s);
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/SearchProgressEvent.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/SearchProgressEvent.java
index 5a3796db2d..7e36a1aff5 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/SearchProgressEvent.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/SearchProgressEvent.java
@@ -2,21 +2,19 @@ package org.eclipse.jdt.internal.core.builder;
public class SearchProgressEvent extends java.util.EventObject {
String name;
- /**
- * Creates a new <code>SearchProgressEvent</code> with the fully-qualified
- * name of the package or type that is now being searched.
- */
- public SearchProgressEvent(String name) {
- super(name);
- this.name = name;
- }
-
- /**
- * Returns the name of the package or type that this
- * progress event represents.
- */
- public String getName() {
- return name;
- }
-
+/**
+ * Creates a new <code>SearchProgressEvent</code> with the fully-qualified
+ * name of the package or type that is now being searched.
+ */
+public SearchProgressEvent(String name) {
+ super(name);
+ this.name = name;
+}
+/**
+ * Returns the name of the package or type that this
+ * progress event represents.
+ */
+public String getName() {
+ return name;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/SearchResultEvent.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/SearchResultEvent.java
index d8beeecd3c..1e36d7cfd6 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/SearchResultEvent.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/SearchResultEvent.java
@@ -3,41 +3,36 @@ package org.eclipse.jdt.internal.core.builder;
public class SearchResultEvent extends java.util.EventObject {
IHandle result;
int[] fMatchingPositions;
- /**
- * Creates a new <code>SearchResultEvent</code> with the handle
- * of the result that has been found.
- */
- public SearchResultEvent(IHandle result) {
- this(result, null);
- }
-
- /**
- * Creates a new <code>SearchResultEvent</code> with the handle
- * of the result that has been found.
- */
- public SearchResultEvent(IHandle result, int[] positions) {
- super(result);
- this.result = result;
- this.fMatchingPositions = positions;
- }
-
- /**
- * Returns the matching char offset positions within the workspace element.
- * Returns null if matching positions are not known.
- */
- public int[] getMatchingPositions() {
- return fMatchingPositions;
- }
-
- /**
- * Returns the result that this progress event represents.
- */
- public IHandle getResult() {
- return result;
- }
-
- public String toString() {
- return result.toString();
- }
-
+/**
+ * Creates a new <code>SearchResultEvent</code> with the handle
+ * of the result that has been found.
+ */
+public SearchResultEvent(IHandle result) {
+ this(result, null);
+}
+/**
+ * Creates a new <code>SearchResultEvent</code> with the handle
+ * of the result that has been found.
+ */
+public SearchResultEvent(IHandle result, int[] positions) {
+ super(result);
+ this.result = result;
+ this.fMatchingPositions = positions;
+}
+/**
+ * Returns the matching char offset positions within the workspace element.
+ * Returns null if matching positions are not known.
+ */
+public int[] getMatchingPositions() {
+ return fMatchingPositions;
+}
+/**
+ * Returns the result that this progress event represents.
+ */
+public IHandle getResult() {
+ return result;
+}
+public String toString() {
+ return result.toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/StateSpecificException.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/StateSpecificException.java
index ceef0fcc87..c8d38bf711 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/StateSpecificException.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/StateSpecificException.java
@@ -1,6 +1,8 @@
package org.eclipse.jdt.internal.core.builder;
-public class StateSpecificException extends RuntimeException {
+public class StateSpecificException extends RuntimeException
+{
+
/**
* Constructs a <code>StateSpecificException</code> without a detail message.
@@ -8,7 +10,6 @@ public class StateSpecificException extends RuntimeException {
public StateSpecificException() {
super();
}
-
/**
* Constructs a <code>StateSpecificException</code> with a detail message.
*
@@ -17,5 +18,4 @@ public class StateSpecificException extends RuntimeException {
public StateSpecificException(String s) {
super(s);
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractImageBuilder.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractImageBuilder.java
index 6bcb0ca2ff..4222a1ca2b 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractImageBuilder.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractImageBuilder.java
@@ -16,8 +16,7 @@ import java.util.*;
* Provides the building and compilation mechanism
* in common with the batch and incremental builders.
*/
-public abstract class AbstractImageBuilder
- implements IImageBuilder, ICompilerRequestor {
+public abstract class AbstractImageBuilder implements IImageBuilder, ICompilerRequestor {
protected JavaDevelopmentContextImpl fDC;
protected StateImpl fOldState;
protected StateImpl fNewState;
@@ -28,175 +27,148 @@ public abstract class AbstractImageBuilder
protected ConfigurableOption[] fCompilerOptions;
protected Vector fCompilationResults;
public int MAX_AT_ONCE = 1000;
- /**
- * Creates a new builder.
- */
- protected AbstractImageBuilder() {
- }
-
- public void acceptResult(CompilationResult result) {
- ConvertedCompilationResult convertedResult =
- fNewState.convertCompilationResult(
- result,
- getBuilderEnvironment().getDefaultPackage());
- PackageElement element = convertedResult.getPackageElement();
- if (!fWorkQueue.hasBeenCompiled(element)) {
- fCompilationResults.addElement(convertedResult);
- fNotifier.compiled((CompilerCompilationUnit) result.getCompilationUnit());
- fWorkQueue.compiled(element);
- }
- }
-
- /**
- * Check whether the build has been canceled.
- */
- protected void checkCancel() {
- fNotifier.checkCancel();
- }
-
- /**
- * Since the image builder is given as a result, let go of
- * any unneeded structures.
- */
- protected void cleanUp() {
- fCompiler = null;
- fCompilationResults = null;
- fWorkQueue = null;
- fBuilderEnvironment = null;
- fNotifier = null;
- fNewState.cleanUp();
+/**
+ * Creates a new builder.
+ */
+protected AbstractImageBuilder() {
+}
+public void acceptResult(CompilationResult result) {
+ ConvertedCompilationResult convertedResult = fNewState.convertCompilationResult(result, getBuilderEnvironment().getDefaultPackage());
+ PackageElement element = convertedResult.getPackageElement();
+ if (!fWorkQueue.hasBeenCompiled(element)) {
+ fCompilationResults.addElement(convertedResult);
+ fNotifier.compiled((CompilerCompilationUnit) result.getCompilationUnit());
+ fWorkQueue.compiled(element);
}
-
- /**
- * Compile the given elements, adding more elements to the work queue
- * if they are affected by the changes.
- */
- protected void compile(Vector vToCompile) {
- int i = 0;
- Vector vToCompileAtOnce = new Vector(Math.min(vToCompile.size(), MAX_AT_ONCE));
- while (i < vToCompile.size()) {
- vToCompileAtOnce.removeAllElements();
- while (i < vToCompile.size() && vToCompileAtOnce.size() < MAX_AT_ONCE) {
- PackageElement unit = (PackageElement) vToCompile.elementAt(i);
- // Although it needed compiling when this method was called,
- // it may have already been compiled due to being brought in
- // by another unit.
- if (fWorkQueue.needsCompile(unit)) {
- SourceEntry sEntry = fNewState.getSourceEntry(unit);
- CompilerCompilationUnit compUnit =
- new CompilerCompilationUnit(fNewState, sEntry, fNotifier);
- compiling(compUnit);
- vToCompileAtOnce.addElement(compUnit);
- checkCancel();
- }
- ++i;
- }
- if (vToCompileAtOnce.size() > 0) {
- CompilerCompilationUnit[] toCompile =
- new CompilerCompilationUnit[vToCompileAtOnce.size()];
- vToCompileAtOnce.copyInto(toCompile);
- try {
- fDC.inCompiler = true;
- getCompiler().compile(toCompile);
- } finally {
- fDC.inCompiler = false;
- }
-
- /* Check for cancel immediately after a compile, because the compile may have been
- * canceled but without propagating the build canceled exception. */
- checkCancel();
-
- /* store results in new state and get new units to compile */
- ConvertedCompilationResult[] results = getCompilationResults();
- updateState(results);
+}
+/**
+ * Check whether the build has been canceled.
+ */
+protected void checkCancel() {
+ fNotifier.checkCancel();
+}
+/**
+ * Since the image builder is given as a result, let go of
+ * any unneeded structures.
+ */
+protected void cleanUp() {
+ fCompiler = null;
+ fCompilationResults = null;
+ fWorkQueue = null;
+ fBuilderEnvironment = null;
+ fNotifier = null;
+ fNewState.cleanUp();
+}
+/**
+ * Compile the given elements, adding more elements to the work queue
+ * if they are affected by the changes.
+ */
+protected void compile(Vector vToCompile) {
+ int i = 0;
+ Vector vToCompileAtOnce = new Vector(Math.min(vToCompile.size(), MAX_AT_ONCE));
+ while (i < vToCompile.size()) {
+ vToCompileAtOnce.removeAllElements();
+ while (i < vToCompile.size() && vToCompileAtOnce.size() < MAX_AT_ONCE) {
+ PackageElement unit = (PackageElement) vToCompile.elementAt(i);
+ // Although it needed compiling when this method was called,
+ // it may have already been compiled due to being brought in
+ // by another unit.
+ if (fWorkQueue.needsCompile(unit)) {
+ SourceEntry sEntry = fNewState.getSourceEntry(unit);
+ CompilerCompilationUnit compUnit = new CompilerCompilationUnit(fNewState, sEntry, fNotifier);
+ compiling(compUnit);
+ vToCompileAtOnce.addElement(compUnit);
checkCancel();
}
+ ++i;
}
- }
-
- /**
- * A unit is being (re)compiled. Save any previous type structure.
- */
- protected void compiling(CompilerCompilationUnit unit) {
- }
-
- /**
- * Returns the builder environment to use for this builder.
- */
- public BuilderEnvironment getBuilderEnvironment() {
- if (fBuilderEnvironment == null) {
- fBuilderEnvironment = new BuilderEnvironment(this);
- fBuilderEnvironment.setDefaultPackage(fNewState.defaultPackageForProject());
- }
- return fBuilderEnvironment;
- }
+ if (vToCompileAtOnce.size() > 0) {
+ CompilerCompilationUnit[] toCompile = new CompilerCompilationUnit[vToCompileAtOnce.size()];
+ vToCompileAtOnce.copyInto(toCompile);
+ try {
+ fDC.inCompiler = true;
+ getCompiler().compile(toCompile);
+ } finally {
+ fDC.inCompiler = false;
+ }
- /**
- * Returns the results of the last compile.
- */
- protected ConvertedCompilationResult[] getCompilationResults() {
- ConvertedCompilationResult[] results =
- new ConvertedCompilationResult[fCompilationResults.size()];
- fCompilationResults.copyInto(results);
- fCompilationResults = null;
- return results;
- }
+ /* Check for cancel immediately after a compile, because the compile may have been
+ * canceled but without propagating the build canceled exception. */
+ checkCancel();
- /**
- * Returns the compiler to use.
- */
- protected Compiler getCompiler() {
- // Make sure to clear the results before starting a new compile.
- fCompilationResults = new Vector();
- if (fCompiler == null) {
- IErrorHandlingPolicy errorPolicy =
- DefaultErrorHandlingPolicies.proceedWithAllProblems();
- IProblemFactory problemFactory =
- ProblemFactory.getProblemFactory(Locale.getDefault());
- fCompiler =
- new Compiler(
- getBuilderEnvironment(),
- errorPolicy,
- fCompilerOptions,
- this,
- problemFactory);
+ /* store results in new state and get new units to compile */
+ ConvertedCompilationResult[] results = getCompilationResults();
+ updateState(results);
+ checkCancel();
}
- return fCompiler;
}
-
- /**
- * Returns the state that is being built.
- */
- public IState getNewState() {
- return fNewState;
- }
-
- /**
- * Returns the old state if the image is being built incrementally
- */
- public IState getOldState() {
- return fOldState;
- }
-
- /**
- * Returns true if the given source entry must be recompiled, false otherwise.
- */
- protected boolean isInvalid(SourceEntry sEntry) {
- return fWorkQueue.needsCompile(fNewState.packageElementFromSourceEntry(sEntry));
+}
+/**
+ * A unit is being (re)compiled. Save any previous type structure.
+ */
+protected void compiling(CompilerCompilationUnit unit) {
+}
+/**
+ * Returns the builder environment to use for this builder.
+ */
+public BuilderEnvironment getBuilderEnvironment() {
+ if (fBuilderEnvironment == null) {
+ fBuilderEnvironment = new BuilderEnvironment(this);
+ fBuilderEnvironment.setDefaultPackage(fNewState.defaultPackageForProject());
}
-
- /**
- * Stores the results of a compilation in the appropriate state tables.
- * Keeps track of what compilation units need to be compiled as a result
- * of the changes.
- */
- protected void updateState(ConvertedCompilationResult[] results) {
- // Must store all compilation results, so state has sufficient information
- // to calculate changes.
- fNewState.putCompilationResults(results);
-
- // Notify listeners
- fNotifier.notifyElementsChanged(results, fOldState, fNewState);
+ return fBuilderEnvironment;
+}
+/**
+ * Returns the results of the last compile.
+ */
+protected ConvertedCompilationResult[] getCompilationResults() {
+ ConvertedCompilationResult[] results = new ConvertedCompilationResult[fCompilationResults.size()];
+ fCompilationResults.copyInto(results);
+ fCompilationResults = null;
+ return results;
+}
+/**
+ * Returns the compiler to use.
+ */
+protected Compiler getCompiler() {
+ // Make sure to clear the results before starting a new compile.
+ fCompilationResults = new Vector();
+ if (fCompiler == null) {
+ IErrorHandlingPolicy errorPolicy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
+ IProblemFactory problemFactory = ProblemFactory.getProblemFactory(Locale.getDefault());
+ fCompiler = new Compiler(getBuilderEnvironment(), errorPolicy, fCompilerOptions, this, problemFactory);
}
-
+ return fCompiler;
+}
+/**
+ * Returns the state that is being built.
+ */
+public IState getNewState() {
+ return fNewState;
+}
+/**
+ * Returns the old state if the image is being built incrementally
+ */
+public IState getOldState() {
+ return fOldState;
+}
+/**
+ * Returns true if the given source entry must be recompiled, false otherwise.
+ */
+protected boolean isInvalid(SourceEntry sEntry) {
+ return fWorkQueue.needsCompile(fNewState.packageElementFromSourceEntry(sEntry));
+}
+/**
+ * Stores the results of a compilation in the appropriate state tables.
+ * Keeps track of what compilation units need to be compiled as a result
+ * of the changes.
+ */
+protected void updateState(ConvertedCompilationResult[] results) {
+ // Must store all compilation results, so state has sufficient information
+ // to calculate changes.
+ fNewState.putCompilationResults(results);
+
+ // Notify listeners
+ fNotifier.notifyElementsChanged(results, fOldState, fNewState);
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractMemberHandle.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractMemberHandle.java
index 7bb21b5ca7..971bdbc703 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractMemberHandle.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractMemberHandle.java
@@ -5,10 +5,9 @@ package org.eclipse.jdt.internal.core.builder.impl;
* All Rights Reserved.
*/
import org.eclipse.jdt.internal.core.builder.*;
+import org.eclipse.jdt.internal.core.Util;
-public abstract class AbstractMemberHandle
- extends NonStateSpecificHandleImpl
- implements IMember {
+public abstract class AbstractMemberHandle extends NonStateSpecificHandleImpl implements IMember{
/**
* The owner of the member
*/
@@ -25,58 +24,50 @@ public abstract class AbstractMemberHandle
String computeSignature(String name, IType[] parameterTypes) {
if (parameterTypes.length == 0) {
- return name + "()";
+ return name + "()"/*nonNLS*/;
}
-
+
StringBuffer sb = new StringBuffer(name);
sb.append('(');
for (int i = 0; i < parameterTypes.length; i++) {
try {
- ((TypeImpl) parameterTypes[i]).appendSignature(sb, true);
+ ((TypeImpl)parameterTypes[i]).appendSignature(sb, true);
} catch (ClassCastException e) {
- throw new StateSpecificException("incompatible parameter types");
+ throw new StateSpecificException(Util.bind("build.incompatibleParameterTypes"/*nonNLS*/));
}
}
sb.append(')');
return sb.toString();
}
-
/**
* Compares two members
*/
public boolean equals(Object o) {
- if (this == o)
- return true;
- if (!(o instanceof AbstractMemberHandle))
- return false;
+ if (this == o) return true;
+ if (!(o instanceof AbstractMemberHandle)) return false;
AbstractMemberHandle member = (AbstractMemberHandle) o;
- return member.fSignature.equals(this.fSignature)
- && member.fOwner.equals(this.fOwner);
+ return member.fSignature.equals(this.fSignature) && member.fOwner.equals(this.fOwner);
}
-
/**
* Returns the owning class of this member.
*/
public IType getDeclaringClass() {
return fOwner;
}
-
- /**
- * getInternalDC method comment.
- */
- JavaDevelopmentContextImpl getInternalDC() {
- return fOwner.getInternalDC();
- }
-
+/**
+ * getInternalDC method comment.
+ */
+JavaDevelopmentContextImpl getInternalDC() {
+ return fOwner.getInternalDC();
+}
/**
* Returns the Java language modifiers for the member
* represented by this object, as an integer.
*/
public int getModifiers() {
- return ((AbstractMemberHandleSWH) inCurrentState()).getModifiers();
+ return ((AbstractMemberHandleSWH)inCurrentState()).getModifiers();
}
-
/**
* Returns the simple name of the member represented by this object.
* If this Member represents a constructor, this returns
@@ -94,30 +85,26 @@ public abstract class AbstractMemberHandle
String getSignature() {
return fSignature;
}
-
/**
* Returns a consistent hash code for this object
*/
public int hashCode() {
return fSignature.hashCode();
}
-
/**
* Returns true if this represents a binary member, false otherwise.
* A binary member is one for which the declaring class is in .class
* file format in the source tree.
*/
public boolean isBinary() {
- return ((IMember) inCurrentState()).isBinary();
+ return ((IMember)inCurrentState()).isBinary();
}
-
/**
* @see IMember
*/
public boolean isDeprecated() {
- return ((AbstractMemberHandleSWH) inCurrentState()).isDeprecated();
+ return ((AbstractMemberHandleSWH)inCurrentState()).isDeprecated();
}
-
/**
* Returns true if the member represented by this object is
* synthetic, false otherwise. A synthetic object is one that
@@ -126,14 +113,12 @@ public abstract class AbstractMemberHandle
* A synthetic object is not the same as a fictitious object.
*/
public boolean isSynthetic() {
- return ((AbstractMemberHandleSWH) inCurrentState()).isSynthetic();
+ return ((AbstractMemberHandleSWH)inCurrentState()).isSynthetic();
}
-
- /**
- * kind method comment.
- */
- public int kind() {
- return 0;
- }
-
+/**
+ * kind method comment.
+ */
+public int kind() {
+ return 0;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractMemberHandleSWH.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractMemberHandleSWH.java
index 5f1c2db1fb..dff636c782 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractMemberHandleSWH.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractMemberHandleSWH.java
@@ -6,9 +6,7 @@ package org.eclipse.jdt.internal.core.builder.impl;
*/
import org.eclipse.jdt.internal.core.builder.*;
-public abstract class AbstractMemberHandleSWH
- extends StateSpecificHandleImpl
- implements IMember {
+public abstract class AbstractMemberHandleSWH extends StateSpecificHandleImpl implements IMember{
/**
* Returns the Type object representing the class or interface
* that declares the member represented by this object.
@@ -16,9 +14,8 @@ public abstract class AbstractMemberHandleSWH
* This is a handle-only method.
*/
public IType getDeclaringClass() {
- return (IType) getHandle().getDeclaringClass().inState(fState);
+ return (IType)getHandle().getDeclaringClass().inState(fState);
}
-
/**
* Returns the handle for this member
*/
@@ -34,33 +31,28 @@ public abstract class AbstractMemberHandleSWH
* the simple name of its declaring class.
* This is a handle-only method.
*/
- public String getName() {
- return ((IMember) nonStateSpecific()).getName();
+ public String getName() {
+ return ((IMember)nonStateSpecific()).getName();
}
-
/**
* Returns the type structure entry for the class or interface.
*/
TypeStructureEntry getTypeStructureEntry() throws NotPresentException {
- TypeStructureEntry tsEntry =
- fState.getTypeStructureEntry(getHandle().getDeclaringClass(), true);
+ TypeStructureEntry tsEntry = fState.getTypeStructureEntry(getHandle().getDeclaringClass(), true);
if (tsEntry == null) {
throw new NotPresentException();
}
return tsEntry;
}
-
/**
* Returns true if this represents a binary member, false otherwise.
* A binary member is one for which the declaring class is in .class
* file format in the source tree.
*/
public boolean isBinary() {
- if (!isPresent())
- throw new NotPresentException();
+ if (!isPresent()) throw new NotPresentException();
return getDeclaringClass().isBinary();
}
-
/**
* @see IMember
*/
@@ -76,5 +68,4 @@ public abstract class AbstractMemberHandleSWH
//Do we have synthetic fields right now?
return false;
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractMethodCollaboratorIndictment.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractMethodCollaboratorIndictment.java
index baa07ef229..b6c4016445 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractMethodCollaboratorIndictment.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractMethodCollaboratorIndictment.java
@@ -15,39 +15,32 @@ import org.eclipse.jdt.internal.core.builder.IType;
class AbstractMethodCollaboratorIndictment extends Indictment {
protected IType fType;
-
- /**
- * Creates a new AbstractMethodCollaboratorIndictment for the given type.
- */
- protected AbstractMethodCollaboratorIndictment(IType type) {
- super(type.getName().toCharArray());
- fType = type;
- }
-
+
+/**
+ * Creates a new AbstractMethodCollaboratorIndictment for the given type.
+ */
+protected AbstractMethodCollaboratorIndictment(IType type) {
+ super(type.getName().toCharArray());
+ fType = type;
+}
/**
* Returns what kind of indictment this is
*/
public int getKind() {
return K_ABSTRACT_METHOD;
}
-
/**
* Returns the type handle.
*/
public IType getType() {
return fType;
}
-
- /**
- * Returns a string representation of this class. For debugging purposes
- * only (NON-NLS).
- */
- public String toString() {
- // don't use + with char[]
- return new StringBuffer("AbstractMethodCollaboratorIndictment(")
- .append(fName)
- .append(")")
- .toString();
- }
-
+/**
+ * Returns a string representation of this class. For debugging purposes
+ * only (NON-NLS).
+ */
+public String toString() {
+ // don't use + with char[]
+ return new StringBuffer("AbstractMethodCollaboratorIndictment("/*nonNLS*/).append(fName).append(")"/*nonNLS*/).toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractNode.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractNode.java
index 3aedc021dd..20ecafa7eb 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractNode.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/AbstractNode.java
@@ -45,31 +45,28 @@ public abstract class AbstractNode implements INode, IDumpable, Cloneable {
*/
protected AbstractNode() {
}
-
/**
* Adds a node that depends on this node.
* IMPORTANT: This should only be called by addDependency.
*/
public void addDependent(INode nodeThatDependsOnMe) {
/* check if I already have this dependent */
- /*
- for (int i = fNumDependents; --i >= 0;) {
- if (fDependents[i] == nodeThatDependsOnMe) {
- System.out.println("Attempt to add duplicate dependent " + nodeThatDependsOnMe.getElement() + " to " + getElement());
- return;
- }
- }
- */
+/*
+ for (int i = fNumDependents; --i >= 0;) {
+ if (fDependents[i] == nodeThatDependsOnMe) {
+ System.out.println("Attempt to add duplicate dependent " + nodeThatDependsOnMe.getElement() + " to " + getElement());
+ return;
+ }
+ }
+*/
if (fNumDependents >= fDependents.length) {
/* grow array */
- INode[] newDependents =
- new INode[fNumDependents == 0 ? 5 : fNumDependents * 2 + 1];
+ INode[] newDependents = new INode[fNumDependents == 0 ? 5 : fNumDependents*2+1];
System.arraycopy(fDependents, 0, newDependents, 0, fNumDependents);
fDependents = newDependents;
}
fDependents[fNumDependents++] = nodeThatDependsOnMe;
}
-
/**
* Clears all outgoing dependency links for this node
*/
@@ -83,7 +80,6 @@ public abstract class AbstractNode implements INode, IDumpable, Cloneable {
fDependencies = fgEmptyNodeList;
invalidateOrder();
}
-
/**
* Returns a copy of this node, without copying dependencies. Used
* by DependencyGraph.copy().
@@ -104,31 +100,29 @@ public abstract class AbstractNode implements INode, IDumpable, Cloneable {
boolean found = false;
/* binary search until on or next to first non-null entry */
- try {
- while (max > min) {
- if (fDependents[mid] == null) {
- /* look in lower half */
- max = mid - 1;
- } else {
- /* look in higher half */
- min = mid + 1;
- }
- mid = (max + min) / 2;
- }
-
- /* linear search for first non-null entry */
- while (fDependents[min] != null) {
- min++;
+try {
+ while (max > min) {
+ if (fDependents[mid] == null) {
+ /* look in lower half */
+ max = mid - 1;
+ } else {
+ /* look in higher half */
+ min = mid + 1;
}
+ mid = (max + min) / 2;
+ }
- /* add the dependent */
- fDependents[min] = nodeThatDependsOnMe;
- } catch (ArrayIndexOutOfBoundsException e) {
- System.out.println(
- "ArrayIndexOutOfBoundsException in AbstractNode.copyAddDependent()");
+ /* linear search for first non-null entry */
+ while (fDependents[min] != null) {
+ min++;
}
- }
+ /* add the dependent */
+ fDependents[min] = nodeThatDependsOnMe;
+} catch (ArrayIndexOutOfBoundsException e) {
+ System.out.println("ArrayIndexOutOfBoundsException in AbstractNode.copyAddDependent()");
+}
+ }
/**
* Returns a copy of this node, but with the dependents and dependencies
* left unchanged. They are later replaced using replaceDeps().
@@ -145,35 +139,33 @@ public abstract class AbstractNode implements INode, IDumpable, Cloneable {
for (int i = depCount; --i >= 0;) {
newNode.fDependencies[i] = fDependencies[i];
}
-
+
newNode.fNumDependents = fNumDependents;
newNode.fDependents = new INode[fNumDependents];
newNode.fOrder = fOrder;
return newNode;
}
-
- /**
- * For debugging only.
- */
- public void dump(Dumper dumper) {
- dumper.dump("element", getElement());
- if (getKind() == JCU_NODE)
- dumper.dump("types", getTypes());
-
- Object[] dependencies = new Object[fDependencies.length];
- for (int i = 0; i < fDependencies.length; ++i) {
- dependencies[i] = fDependencies[i].getElement();
- }
- dumper.dump("dependencies", dependencies);
-
- Object[] dependents = new Object[fNumDependents];
- for (int i = 0; i < fDependents.length; ++i) {
- dependents[i] = fDependents[i].getElement();
- }
- dumper.dump("dependents", dependents);
-
+/**
+ * For debugging only.
+ */
+public void dump(Dumper dumper) {
+ dumper.dump("element", getElement());
+ if (getKind() == JCU_NODE)
+ dumper.dump("types", getTypes());
+
+ Object[] dependencies = new Object[fDependencies.length];
+ for (int i = 0; i < fDependencies.length; ++i) {
+ dependencies[i] = fDependencies[i].getElement();
}
-
+ dumper.dump("dependencies", dependencies);
+
+ Object[] dependents = new Object[fNumDependents];
+ for (int i = 0; i < fDependents.length; ++i) {
+ dependents[i] = fDependents[i].getElement();
+ }
+ dumper.dump("dependents", dependents);
+
+}
/**
* Make sure equality tests are never carried out on nodes
*/
@@ -181,7 +173,6 @@ public abstract class AbstractNode implements INode, IDumpable, Cloneable {
Assert.isTrue(false, "Equality not defined for dependency graph nodes");
return false;
}
-
/**
* Returns the nodes that this node depends on. A change to the principal structure
* of any of these nodes may affect the principal structure of this node.
@@ -189,23 +180,16 @@ public abstract class AbstractNode implements INode, IDumpable, Cloneable {
public INode[] getDependencies() {
return fDependencies;
}
-
/**
* Returns the nodes that depend on this node. A change to the principal structure
* of this node may affect the principal structure of the returned dependents.
*/
public INode[] getDependents() {
if (fNumDependents < fDependents.length) {
- System.arraycopy(
- fDependents,
- 0,
- fDependents = new INode[fNumDependents],
- 0,
- fNumDependents);
+ System.arraycopy(fDependents, 0, fDependents = new INode[fNumDependents], 0, fNumDependents);
}
return fDependents;
- }
-
+ }
/**
* Returns the number of bytes that this node uses.
* For debugging and profiling purposes only.
@@ -223,14 +207,12 @@ public abstract class AbstractNode implements INode, IDumpable, Cloneable {
}
return size;
}
-
/**
* @see INode
*/
public int getOrder() {
return getOrder(0);
}
-
/**
* Returns the order number, calculating it if not already done.
* seen is a set of previously visited nodes.
@@ -240,9 +222,9 @@ public abstract class AbstractNode implements INode, IDumpable, Cloneable {
return fOrder;
}
- // trace(recursionLevel, -1);
+// trace(recursionLevel, -1);
- fOrder = 0; // Mark as non-invalid to break cycles
+ fOrder = 0; // Mark as non-invalid to break cycles
int max = -1;
for (int i = 0, len = fDependencies.length; i < len; ++i) {
int order = ((AbstractNode) fDependencies[i]).getOrder(recursionLevel + 1);
@@ -251,11 +233,10 @@ public abstract class AbstractNode implements INode, IDumpable, Cloneable {
}
}
fOrder = max + 1;
-
- // trace(recursionLevel, fOrder);
+
+// trace(recursionLevel, fOrder);
return fOrder;
}
-
/**
* Returns the types that belong to this node
*/
@@ -263,7 +244,6 @@ public abstract class AbstractNode implements INode, IDumpable, Cloneable {
Assert.isTrue(false, "My subclass should have implemented this");
return null;
}
-
/**
* Invalidates the order number, for this node and all dependents.
*/
@@ -276,7 +256,6 @@ public abstract class AbstractNode implements INode, IDumpable, Cloneable {
}
}
}
-
/**
* Removes a node on which this node depends.
* This -does- remove the backwards link from the other node.
@@ -300,7 +279,6 @@ public abstract class AbstractNode implements INode, IDumpable, Cloneable {
}
}
}
-
/**
* Removes a node that depends on this node.
* This does not remove the backwards link.
@@ -323,7 +301,6 @@ public abstract class AbstractNode implements INode, IDumpable, Cloneable {
}
}
}
-
/**
* This node has previously been copied without updating its
* dependency references. Now replace the dependency references
@@ -341,8 +318,7 @@ public abstract class AbstractNode implements INode, IDumpable, Cloneable {
newNode.copyAddDependent(this);
fDependencies[i] = newNode;
}
- }
-
+ }
/**
* Sets the nodes that this node depends on.
* Backwards links are added automatically.
@@ -360,7 +336,6 @@ public abstract class AbstractNode implements INode, IDumpable, Cloneable {
invalidateOrder();
}
-
public void trace(int recursionLevel, int refCount) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < recursionLevel; ++i)
@@ -370,5 +345,4 @@ public abstract class AbstractNode implements INode, IDumpable, Cloneable {
sb.append(refCount);
System.out.println(sb.toString());
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ArrayTypeHandleImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ArrayTypeHandleImpl.java
index 31508a90d6..48e86e7cde 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ArrayTypeHandleImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ArrayTypeHandleImpl.java
@@ -18,7 +18,6 @@ public class ArrayTypeHandleImpl extends TypeImpl {
fNestingDepth = depth;
fElementType = type;
}
-
/**
* Appends the signature for this type to the StringBuffer.
* If includeUnnamed is true, then the identifiers for unnamed packages
@@ -31,7 +30,6 @@ public class ArrayTypeHandleImpl extends TypeImpl {
}
fElementType.appendSignature(sb, includeUnnamed);
}
-
/**
* Appends the VM signature of the type to the StringBuffer.
*/
@@ -41,140 +39,123 @@ public class ArrayTypeHandleImpl extends TypeImpl {
}
getElementType().appendVMSignature(sb);
}
-
/**
* Compares this object against the specified object.
* Returns true if the objects are the same.
*/
public boolean equals(Object o) {
- if (this == o)
- return true;
- if (!(o instanceof ArrayTypeHandleImpl))
- return false;
+ if (this == o) return true;
+ if (!(o instanceof ArrayTypeHandleImpl)) return false;
ArrayTypeHandleImpl array = (ArrayTypeHandleImpl) o;
- return fElementType.equals(array.fElementType)
- && fNestingDepth == array.fNestingDepth;
- }
-
- /**
- * Returns a Type object representing an array type with
- * the type represented by this object as its component type.
- * This is a handle-only method.
- */
- public org.eclipse.jdt.internal.core.builder.IType getArrayHandle() {
- return new ArrayTypeHandleImpl(fElementType, fNestingDepth + 1);
- }
-
- /**
- * If this class represents an array type, returns the Type
- * object representing the component type of the array; otherwise
- * returns null. The component type of an array may itself be
- * an array type.
- * This is a handle-only method.
- */
- public org.eclipse.jdt.internal.core.builder.IType getComponentType() {
- if (fNestingDepth == 1)
- return fElementType;
- return new ArrayTypeHandleImpl(fElementType, fNestingDepth - 1);
+ return fElementType.equals(array.fElementType) &&
+ fNestingDepth == array.fNestingDepth;
}
-
- /**
- * If this is an array type, answer its element type (the leaf non-array type),
- * otherwise answer this type.
- */
-
- TypeImpl getElementType() {
+/**
+ * Returns a Type object representing an array type with
+ * the type represented by this object as its component type.
+ * This is a handle-only method.
+ */
+public org.eclipse.jdt.internal.core.builder.IType getArrayHandle() {
+ return new ArrayTypeHandleImpl(fElementType, fNestingDepth + 1);
+}
+/**
+ * If this class represents an array type, returns the Type
+ * object representing the component type of the array; otherwise
+ * returns null. The component type of an array may itself be
+ * an array type.
+ * This is a handle-only method.
+ */
+public org.eclipse.jdt.internal.core.builder.IType getComponentType() {
+ if (fNestingDepth == 1)
return fElementType;
- }
+ return new ArrayTypeHandleImpl(fElementType, fNestingDepth - 1);
+}
+/**
+ * If this is an array type, answer its element type (the leaf non-array type),
+ * otherwise answer this type.
+ */
+TypeImpl getElementType() {
+ return fElementType;
+}
public JavaDevelopmentContextImpl getInternalDC() {
return fElementType.getInternalDC();
}
-
- /**
- * Returns the fully-qualified name of the type (class, interface,
- * array, or primitive) represented by this object, as a String.
- * For classes and interfaces, the name is the VM class name,
- * including the package name.
- * For inner classes, the name is as described in the
- * <em>Inner Classes Specification</em>.
- * For array types, the name is the name of the component type, followed by '[]'.
- * For primitive types, the name is the keyword for the primitive type.
- * This is a handle-only method.
- */
- public String getName() {
- String name = fElementType.getName();
- for (int i = 0; i < fNestingDepth; i++)
- name += "[]";
- return name;
- }
-
- /**
- * Return the array nesting depth
- */
- int getNestingDepth() {
- return fNestingDepth;
- }
-
- /**
- * getSimpleName method comment.
- */
- public String getSimpleName() {
- String simpleName = fElementType.getSimpleName();
- for (int i = 0; i < fNestingDepth; i++)
- simpleName += "[]";
- return simpleName;
- }
-
- /**
- * If this object represents any class other than the class
- * <code>java.lang.Object</code>, then the object that represents
- * the direct superclass of that class is returned.
- * <p>
- * If this object represents the class <code>java.lang.Object</code>
- * or this object represents an interface or a primitive type,
- * <code>null</code> is returned.
- * If this object represents an array type, then the Type that represents
- * class <code>java.lang.Object</code> is returned.
- * <p>
- * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
- * for more details.
- */
- public IType getSuperclass() throws NotPresentException {
- return getInternalDC().getRootClassHandle();
- }
-
+/**
+ * Returns the fully-qualified name of the type (class, interface,
+ * array, or primitive) represented by this object, as a String.
+ * For classes and interfaces, the name is the VM class name,
+ * including the package name.
+ * For inner classes, the name is as described in the
+ * <em>Inner Classes Specification</em>.
+ * For array types, the name is the name of the component type, followed by '[]'.
+ * For primitive types, the name is the keyword for the primitive type.
+ * This is a handle-only method.
+ */
+public String getName() {
+ String name = fElementType.getName();
+ for (int i = 0; i < fNestingDepth; i++)
+ name += "[]";
+ return name;
+}
+/**
+ * Return the array nesting depth
+ */
+int getNestingDepth() {
+ return fNestingDepth;
+}
+/**
+ * getSimpleName method comment.
+ */
+public String getSimpleName() {
+ String simpleName = fElementType.getSimpleName();
+ for (int i = 0; i < fNestingDepth; i++)
+ simpleName += "[]";
+ return simpleName;
+}
+/**
+ * If this object represents any class other than the class
+ * <code>java.lang.Object</code>, then the object that represents
+ * the direct superclass of that class is returned.
+ * <p>
+ * If this object represents the class <code>java.lang.Object</code>
+ * or this object represents an interface or a primitive type,
+ * <code>null</code> is returned.
+ * If this object represents an array type, then the Type that represents
+ * class <code>java.lang.Object</code> is returned.
+ * <p>
+ * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
+ * for more details.
+ */
+public IType getSuperclass() throws NotPresentException {
+ return getInternalDC().getRootClassHandle();
+}
/**
* Returns a consistent hash code for this object
*/
public int hashCode() {
return fElementType.hashCode() + (fNestingDepth * 131);
}
-
/**
* Returns a state specific version of this handle in the given state.
*/
- public IHandle inState(IState s)
- throws org.eclipse.jdt.internal.core.builder.StateSpecificException {
-
+ public IHandle inState(IState s) throws org.eclipse.jdt.internal.core.builder.StateSpecificException {
+
return new ArrayTypeHandleImplSWH((StateImpl) s, this);
}
-
- /**
- * If this Type object represents an array type, returns true,
- * otherwise returns false.
- * This is a handle-only method.
- */
- public boolean isArray() {
- return true;
- }
-
- /**
- * Set the array nesting depth
- */
- void setNestingDepth(int depth) {
- fNestingDepth = depth;
- }
-
+/**
+ * If this Type object represents an array type, returns true,
+ * otherwise returns false.
+ * This is a handle-only method.
+ */
+public boolean isArray() {
+ return true;
+}
+/**
+ * Set the array nesting depth
+ */
+void setNestingDepth(int depth) {
+ fNestingDepth = depth;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ArrayTypeHandleImplSWH.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ArrayTypeHandleImplSWH.java
index 8d3383df43..10c106b0cd 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ArrayTypeHandleImplSWH.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ArrayTypeHandleImplSWH.java
@@ -15,77 +15,67 @@ public class ArrayTypeHandleImplSWH extends TypeImplSWH {
fState = state;
fHandle = handle;
}
+/**
+ * If this class represents an array type, returns the Type
+ * object representing the component type of the array; otherwise
+ * returns null. The component type of an array may itself be
+ * an array type.
+ * This is a handle-only method.
+ */
+public IType getComponentType() {
+ return (IType) fHandle.getComponentType().inState(fState);
+}
+/**
+ * If this is an array type, answer its element type (the leaf non-array type),
+ * otherwise answer this type.
+ */
- /**
- * If this class represents an array type, returns the Type
- * object representing the component type of the array; otherwise
- * returns null. The component type of an array may itself be
- * an array type.
- * This is a handle-only method.
- */
- public IType getComponentType() {
- return (IType) fHandle.getComponentType().inState(fState);
- }
-
- /**
- * If this is an array type, answer its element type (the leaf non-array type),
- * otherwise answer this type.
- */
-
- TypeImplSWH getElementType() {
- return (TypeImplSWH) fHandle.getElementType().inState(fState);
- }
-
+TypeImplSWH getElementType() {
+ return (TypeImplSWH) fHandle.getElementType().inState(fState);
+}
/**
* Returns the non state specific handle
*/
- protected TypeImpl getHandle() {
- return fHandle;
- }
-
- /**
- * Return the array nesting depth
- */
- int getNestingDepth() {
- return fHandle.fNestingDepth;
- }
-
- /**
- * If this object represents any class other than the class
- * <code>java.lang.Object</code>, then the object that represents
- * the direct superclass of that class is returned.
- * <p>
- * If this object represents the class <code>java.lang.Object</code>
- * or this object represents an interface or a primitive type,
- * <code>null</code> is returned.
- * If this object represents an array type, then the Type that represents
- * class <code>java.lang.Object</code> is returned.
- * <p>
- * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
- * for more details.
- */
- public IType getSuperclass() throws NotPresentException {
- return (IType) ((JavaDevelopmentContextImpl) getDevelopmentContext())
- .getRootClassHandle()
- .inState(fState);
- }
-
- /**
- * If this Type object represents an array type, returns true,
- * otherwise returns false.
- * This is a handle-only method.
- */
- public boolean isArray() {
- return true;
- }
-
- /**
- * If this Type object represents an array type, returns true,
- * otherwise returns false.
- * This is a handle-only method.
- */
- public boolean isPresent() {
- return getElementType().isPresent();
- }
-
+ protected TypeImpl getHandle() {
+ return fHandle;
+ }
+/**
+ * Return the array nesting depth
+ */
+int getNestingDepth() {
+ return fHandle.fNestingDepth;
+}
+/**
+ * If this object represents any class other than the class
+ * <code>java.lang.Object</code>, then the object that represents
+ * the direct superclass of that class is returned.
+ * <p>
+ * If this object represents the class <code>java.lang.Object</code>
+ * or this object represents an interface or a primitive type,
+ * <code>null</code> is returned.
+ * If this object represents an array type, then the Type that represents
+ * class <code>java.lang.Object</code> is returned.
+ * <p>
+ * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
+ * for more details.
+ */
+public IType getSuperclass() throws NotPresentException {
+ return (IType) ((JavaDevelopmentContextImpl)getDevelopmentContext()).getRootClassHandle().inState(fState);
+}
+/**
+ * If this Type object represents an array type, returns true,
+ * otherwise returns false.
+ * This is a handle-only method.
+ */
+public boolean isArray() {
+ return true;
+}
+/**
+ * If this Type object represents an array type, returns true,
+ * otherwise returns false.
+ * This is a handle-only method.
+ */
+public boolean isPresent() {
+ return getElementType().isPresent();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BatchImageBuilder.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BatchImageBuilder.java
index 5049eb6e15..fb3ba82580 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BatchImageBuilder.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BatchImageBuilder.java
@@ -13,109 +13,100 @@ import java.util.*;
/**
* The batch image builder - builds a state from scratch.
*/
-public class BatchImageBuilder
- extends AbstractImageBuilder
- implements IImageBuilder, ICompilerRequestor {
+public class BatchImageBuilder extends AbstractImageBuilder implements IImageBuilder, ICompilerRequestor {
/**
* A flag indicating we are doing a batch build rather than
* background lazy builds.
*/
protected boolean fDoingBatchBuild = false;
- /**
- * Creates a new batch image builder on the given new state.
- * The builder will compile everything in the state's project.
- */
- public BatchImageBuilder(StateImpl state) {
- this(state, JavaDevelopmentContextImpl.getDefaultCompilerOptions());
- }
-
- /**
- * Creates a new batch image builder on the given new state.
- * The batch builder will build all classes within the state's project.
- * This constructor has been created for testing purposes. This allows
- * tests to control the compiler options used by the batch build.
- */
- protected BatchImageBuilder(StateImpl state, ConfigurableOption[] options) {
- fDC = (JavaDevelopmentContextImpl) state.getDevelopmentContext();
- state.setCompilerOptions(options);
- fCompilerOptions = options;
- fNewState = state;
- fWorkQueue = new WorkQueue();
- }
-
- /**
- * Builds the entire image from scratch, based on the provided workspace.
- */
- public void build() {
- fDoingBatchBuild = true;
- fNotifier = new BuildNotifier(fDC, true);
- getBuilderEnvironment().setNotifier(fNotifier);
- fNotifier.begin();
- try {
- fNewState.readClassPath();
- fNotifier.subTask("Scrubbing output folder");
- fNewState.getBinaryOutput().scrubOutput();
- fNotifier.updateProgressDelta(0.05f);
- fNotifier.subTask("Analyzing packages");
- fNewState.buildInitialPackageMap();
- fNotifier.updateProgressDelta(0.05f);
+/**
+ * Creates a new batch image builder on the given new state.
+ * The builder will compile everything in the state's project.
+ */
+public BatchImageBuilder(StateImpl state) {
+ this(state, JavaDevelopmentContextImpl.getDefaultCompilerOptions());
+}
+/**
+ * Creates a new batch image builder on the given new state.
+ * The batch builder will build all classes within the state's project.
+ * This constructor has been created for testing purposes. This allows
+ * tests to control the compiler options used by the batch build.
+ */
+protected BatchImageBuilder(StateImpl state, ConfigurableOption[] options) {
+ fDC = (JavaDevelopmentContextImpl) state.getDevelopmentContext();
+ state.setCompilerOptions(options);
+ fCompilerOptions = options;
+ fNewState = state;
+ fWorkQueue = new WorkQueue();
+}
+/**
+ * Builds the entire image from scratch, based on the provided workspace.
+ */
+public void build() {
+ fDoingBatchBuild = true;
+ fNotifier = new BuildNotifier(fDC, true);
+ getBuilderEnvironment().setNotifier(fNotifier);
+ fNotifier.begin();
+ try {
+ fNewState.readClassPath();
+ fNotifier.subTask("Scrubbing output folder");
+ fNewState.getBinaryOutput().scrubOutput();
+ fNotifier.updateProgressDelta(0.05f);
+ fNotifier.subTask("Analyzing packages");
+ fNewState.buildInitialPackageMap();
+ fNotifier.updateProgressDelta(0.05f);
- /* Force build all in build context */
- fNotifier.subTask("Analyzing sources");
- IPackage[] pkgs = fNewState.getPackageMap().getAllPackagesAsArray();
- for (int i = 0; i < pkgs.length; ++i) {
- fNotifier.checkCancel();
- SourceEntry[] entries = fNewState.getSourceEntries(pkgs[i]);
- if (entries != null) {
- for (int j = 0; j < entries.length; ++j) {
- SourceEntry sEntry = entries[j];
- if (sEntry.isSource()) {
- PackageElement element = fNewState.packageElementFromSourceEntry(sEntry);
- fWorkQueue.add(element);
- }
+ /* Force build all in build context */
+ fNotifier.subTask("Analyzing sources");
+ IPackage[] pkgs = fNewState.getPackageMap().getAllPackagesAsArray();
+ for (int i = 0; i < pkgs.length; ++i) {
+ fNotifier.checkCancel();
+ SourceEntry[] entries = fNewState.getSourceEntries(pkgs[i]);
+ if (entries != null) {
+ for (int j = 0; j < entries.length; ++j) {
+ SourceEntry sEntry = entries[j];
+ if (sEntry.isSource()) {
+ PackageElement element = fNewState.packageElementFromSourceEntry(sEntry);
+ fWorkQueue.add(element);
}
}
}
- fNotifier.updateProgressDelta(0.05f);
- Vector vToCompile = fWorkQueue.getElementsToCompile();
- if (vToCompile.size() > 0) {
- fNotifier.setProgressPerCompilationUnit(0.75f / vToCompile.size());
- compile(vToCompile);
- }
- /* Copy resources to binary output */
- new ProjectResourceCopier(fNewState.getJavaProject(), fDC, fNotifier, 0.10f)
- .copyAllResourcesOnClasspath();
-
- fNotifier.done();
- } finally {
- cleanUp();
}
+ fNotifier.updateProgressDelta(0.05f);
+ Vector vToCompile = fWorkQueue.getElementsToCompile();
+ if (vToCompile.size() > 0) {
+ fNotifier.setProgressPerCompilationUnit(0.75f / vToCompile.size());
+ compile(vToCompile);
+ }
+ /* Copy resources to binary output */
+ new ProjectResourceCopier(fNewState.getJavaProject(), fDC, fNotifier, 0.10f).copyAllResourcesOnClasspath();
+
+ fNotifier.done();
+ } finally {
+ cleanUp();
}
-
- /**
- * Returns an image delta between old and new states in the image context.
- * This does not apply to the batch builder.
- * @see IImageBuilder
- */
- public IDelta getImageDelta(IImageContext imageContext) {
- return null;
- }
-
- /**
- * Builds a given compilation unit.
- */
- public void lazyBuild(PackageElement unit) {
- // String msg = "Attempt to lazy build " + unit.getPackage().getName() + "." + unit.getFileName();
- // System.err.println(msg + ". " + "Lazy building has been disabled.");
- Assert.isTrue(false, "Lazy building has been disabled.");
- }
-
- /**
- * Returns a string describe the builder
- * @see IImageBuilder
- */
- public String toString() {
- return "batch image builder for:\n\tnew state: " + getNewState();
- }
-
+}
+/**
+ * Returns an image delta between old and new states in the image context.
+ * This does not apply to the batch builder.
+ * @see IImageBuilder
+ */
+public IDelta getImageDelta(IImageContext imageContext) {
+ return null;
+}
+/**
+ * Builds a given compilation unit.
+ */
+public void lazyBuild(PackageElement unit) {
+ // String msg = "Attempt to lazy build " + unit.getPackage().getName() + "." + unit.getFileName();
+ // System.err.println(msg + ". " + "Lazy building has been disabled.");
+ Assert.isTrue(false, "Lazy building has been disabled.");
+}
+/**
+ * Returns a string describe the builder
+ * @see IImageBuilder
+ */
+public String toString() {
+ return "batch image builder for:\n\tnew state: " + getNewState();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BinaryBrokerOutput.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BinaryBrokerOutput.java
index fa0a182acf..b39138080c 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BinaryBrokerOutput.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BinaryBrokerOutput.java
@@ -17,82 +17,72 @@ import java.util.Hashtable;
*/
public class BinaryBrokerOutput extends BinaryOutput {
IBinaryBroker fBinaryBroker;
- /**
- * Creates a new BinaryBrokerOutput for the given binary broker.
- */
- public BinaryBrokerOutput(IBinaryBroker broker) {
- fBinaryBroker = broker;
- }
-
- /**
- * Stores the binary in a manner specific to this BinaryOutput.
- */
- protected void basicPutBinary(
- TypeStructureEntry tsEntry,
- byte[] binary,
- int crc) {
- BinaryBrokerKey key = new BinaryBrokerKey(tsEntry.getType(), crc);
- fBinaryBroker.putBinary(key, binary);
- }
-
- /**
- * @see BinaryOutput
- */
- public void deleteBinary(IType type) {
- // Cannot delete a binary from a binary broker
- }
-
- /**
- * @see BinaryOutput
- *
- * This releases any binaries in the binary broker
- * which aren't needed for the given states.
- */
- public void garbageCollect(IState[] statesInUse) {
- // estimate size of keysInUse set
- int size = 0;
- for (int i = 0; i < statesInUse.length; ++i) {
- StateImpl state = (StateImpl) statesInUse[i];
- size += state.getPrincipalStructureTable().size();
- }
-
- // collect keysInUse
- Hashtable keysInUse = new Hashtable(size * 2 + 1);
- for (int i = 0; i < statesInUse.length; ++i) {
- StateImpl state = (StateImpl) statesInUse[i];
- state.collectBinaryBrokerKeys(keysInUse);
- }
-
- // tell the broker to GC
- fBinaryBroker.garbageCollect(keysInUse);
- }
-
- /**
- * @see BinaryOutput
- */
- public byte[] getBinary(TypeStructureEntry tsEntry, IType type) {
- /* get cached CRC value */
- int crc = tsEntry.getCRC32();
- if (crc == 0) {
- // Never had the binary.
- return null;
- }
- BinaryBrokerKey key = new BinaryBrokerKey(type, crc);
- return fBinaryBroker.getBinary(key);
+/**
+ * Creates a new BinaryBrokerOutput for the given binary broker.
+ */
+public BinaryBrokerOutput(IBinaryBroker broker) {
+ fBinaryBroker = broker;
+}
+/**
+ * Stores the binary in a manner specific to this BinaryOutput.
+ */
+protected void basicPutBinary(TypeStructureEntry tsEntry, byte[] binary, int crc) {
+ BinaryBrokerKey key = new BinaryBrokerKey(tsEntry.getType(), crc);
+ fBinaryBroker.putBinary(key, binary);
+}
+/**
+ * @see BinaryOutput
+ */
+public void deleteBinary(IType type) {
+ // Cannot delete a binary from a binary broker
+}
+/**
+ * @see BinaryOutput
+ *
+ * This releases any binaries in the binary broker
+ * which aren't needed for the given states.
+ */
+public void garbageCollect(IState[] statesInUse) {
+ // estimate size of keysInUse set
+ int size = 0;
+ for (int i = 0; i < statesInUse.length; ++i) {
+ StateImpl state = (StateImpl) statesInUse[i];
+ size += state.getPrincipalStructureTable().size();
}
- /**
- * Returns the binary broker for this binary broker output.
- */
- public IBinaryBroker getBinaryBroker() {
- return fBinaryBroker;
+ // collect keysInUse
+ Hashtable keysInUse = new Hashtable(size * 2 + 1);
+ for (int i = 0; i < statesInUse.length; ++i) {
+ StateImpl state = (StateImpl) statesInUse[i];
+ state.collectBinaryBrokerKeys(keysInUse);
}
- /**
- * @see BinaryOutput
- */
- public void scrubOutput() {
- // Cannot delete anything from a binary broker
+ // tell the broker to GC
+ fBinaryBroker.garbageCollect(keysInUse);
+}
+/**
+ * @see BinaryOutput
+ */
+public byte[] getBinary(TypeStructureEntry tsEntry, IType type) {
+ /* get cached CRC value */
+ int crc = tsEntry.getCRC32();
+ if (crc == 0) {
+ // Never had the binary.
+ return null;
}
-
+ BinaryBrokerKey key = new BinaryBrokerKey(type, crc);
+ return fBinaryBroker.getBinary(key);
+}
+/**
+ * Returns the binary broker for this binary broker output.
+ */
+public IBinaryBroker getBinaryBroker() {
+ return fBinaryBroker;
+}
+/**
+ * @see BinaryOutput
+ */
+public void scrubOutput() {
+ // Cannot delete anything from a binary broker
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BinaryOutput.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BinaryOutput.java
index 4f5e39e3eb..695d196753 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BinaryOutput.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BinaryOutput.java
@@ -14,57 +14,52 @@ import org.eclipse.jdt.internal.core.builder.IType;
public abstract class BinaryOutput {
private static final boolean COMPUTE_CRC = false; // disabled since unused
- /**
- * Stores the binary in a manner specific to this BinaryOutput.
- */
- abstract protected void basicPutBinary(
- TypeStructureEntry tsEntry,
- byte[] binary,
- int crc);
- /**
- * Computes a 32-bit CRC on the given binary.
- */
- int crc32(byte[] binary) {
- java.util.zip.CRC32 crc = new java.util.zip.CRC32();
- crc.update(binary);
- return (int) crc.getValue();
- }
-
- /**
- * Deletes the binary previously produced for a type.
- */
- public abstract void deleteBinary(IType type);
- /**
- * Garbage collect any resources maintained by this binary
- * output which are no longer needed, given the states which
- * are still in use.
- */
- public abstract void garbageCollect(IState[] statesInUse);
- /**
- * Returns the binary previously produced for a type.
- * Returns null if the binary could not be found.
- */
- public abstract byte[] getBinary(TypeStructureEntry tsEntry, IType type);
- /**
- * Stores the binary produced by compiling a type.
- */
- public void putBinary(TypeStructureEntry tsEntry, byte[] binary) {
- /* store crc in type structure entry */
- int crc;
-
- if (COMPUTE_CRC) {
- crc = crc32(binary);
- tsEntry.setCRC32(crc);
- } else {
- crc = 0;
- }
-
- /* store binary */
- basicPutBinary(tsEntry, binary, crc);
+/**
+ * Stores the binary in a manner specific to this BinaryOutput.
+ */
+abstract protected void basicPutBinary(TypeStructureEntry tsEntry, byte[] binary, int crc);
+/**
+ * Computes a 32-bit CRC on the given binary.
+ */
+int crc32(byte[] binary) {
+ java.util.zip.CRC32 crc = new java.util.zip.CRC32();
+ crc.update(binary);
+ return (int) crc.getValue();
+}
+/**
+ * Deletes the binary previously produced for a type.
+ */
+public abstract void deleteBinary(IType type);
+/**
+ * Garbage collect any resources maintained by this binary
+ * output which are no longer needed, given the states which
+ * are still in use.
+ */
+public abstract void garbageCollect(IState[] statesInUse);
+/**
+ * Returns the binary previously produced for a type.
+ * Returns null if the binary could not be found.
+ */
+public abstract byte[] getBinary(TypeStructureEntry tsEntry, IType type);
+/**
+ * Stores the binary produced by compiling a type.
+ */
+public void putBinary(TypeStructureEntry tsEntry, byte[] binary) {
+ /* store crc in type structure entry */
+ int crc;
+
+ if (COMPUTE_CRC){
+ crc = crc32(binary);
+ tsEntry.setCRC32(crc);
+ } else {
+ crc = 0;
}
-
- /**
- * Deletes everything in this binary output.
- */
- public abstract void scrubOutput();
+
+ /* store binary */
+ basicPutBinary(tsEntry, binary, crc);
+}
+/**
+ * Deletes everything in this binary output.
+ */
+public abstract void scrubOutput();
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BinaryStructure.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BinaryStructure.java
index c3533da017..e1d7879af9 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BinaryStructure.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BinaryStructure.java
@@ -10,402 +10,357 @@ import org.eclipse.jdt.internal.core.builder.*;
import org.eclipse.jdt.internal.compiler.util.*;
import org.eclipse.jdt.internal.core.Util;
+
/**
* Utility class for interpreting the contents of IBinaryType objects.
*/
public abstract class BinaryStructure {
- /**
- * Should not instantiate.
- */
- private BinaryStructure() {
- }
-
- protected static boolean compare(IBinaryField[] listA, IBinaryField[] listB) {
- if (listA == listB)
- return true;
- if (listA == null || listB == null)
- return false;
- if (listA.length != listB.length)
- return false;
- Util.Comparer comparer = new Util.Comparer() {
- public int compare(Object a, Object b) {
- IBinaryField fa = (IBinaryField) a;
- IBinaryField fb = (IBinaryField) b;
- int code = Util.compare(fa.getName(), fb.getName());
- if (code != 0)
- return code;
- return Util.compare(fa.getTypeName(), fb.getTypeName());
- }
- };
- Object[] sortedA = Util.sortCopy(listA, comparer);
- Object[] sortedB = Util.sortCopy(listB, comparer);
- for (int i = 0; i < listA.length; ++i) {
- if (!compare((IBinaryField) sortedA[i], (IBinaryField) sortedB[i]))
- return false;
- }
+/**
+ * Should not instantiate.
+ */
+private BinaryStructure() {
+}
+protected static boolean compare(IBinaryField[] listA, IBinaryField[] listB) {
+ if (listA == listB)
return true;
- }
-
- protected static boolean compare(
- IBinaryMethod[] listA,
- IBinaryMethod[] listB) {
- if (listA == listB)
- return true;
- if (listA == null || listB == null)
- return false;
- if (listA.length != listB.length)
- return false;
- Util.Comparer comparer = new Util.Comparer() {
- public int compare(Object a, Object b) {
- IBinaryMethod ma = (IBinaryMethod) a;
- IBinaryMethod mb = (IBinaryMethod) b;
- int code = Util.compare(ma.getSelector(), mb.getSelector());
- if (code != 0)
- return code;
- return Util.compare(ma.getMethodDescriptor(), mb.getMethodDescriptor());
- }
- };
- Object[] sortedA = Util.sortCopy(listA, comparer);
- Object[] sortedB = Util.sortCopy(listB, comparer);
- for (int i = 0; i < listA.length; ++i) {
- if (!compare((IBinaryMethod) sortedA[i], (IBinaryMethod) sortedB[i]))
- return false;
+ if (listA == null || listB == null)
+ return false;
+ if (listA.length != listB.length)
+ return false;
+ Util.Comparer comparer = new Util.Comparer() {
+ public int compare(Object a, Object b) {
+ IBinaryField fa = (IBinaryField) a;
+ IBinaryField fb = (IBinaryField) b;
+ int code = Util.compare(fa.getName(), fb.getName());
+ if (code != 0)
+ return code;
+ return Util.compare(fa.getTypeName(), fb.getTypeName());
}
- return true;
- }
-
- protected static boolean compare(
- IBinaryNestedType[] listA,
- IBinaryNestedType[] listB) {
- if (listA == listB)
- return true;
- if (listA == null || listB == null)
- return false;
- if (listA.length != listB.length)
+ };
+ Object[] sortedA = Util.sortCopy(listA, comparer);
+ Object[] sortedB = Util.sortCopy(listB, comparer);
+ for (int i = 0; i < listA.length; ++i) {
+ if (!compare((IBinaryField) sortedA[i], (IBinaryField) sortedB[i]))
return false;
- for (int i = 0; i < listA.length; ++i) {
- if (!compare((IBinaryNestedType) listA[i], (IBinaryNestedType) listB[i]))
- return false;
- }
- return true;
}
-
- public static boolean compare(IBinaryField a, IBinaryField b) {
- if (a == b)
- return true;
- if (!CharOperation.equals(a.getName(), b.getName()))
- return false;
- if (!CharOperation.equals(a.getTypeName(), b.getTypeName()))
- return false;
- if (a.getModifiers() != b.getModifiers())
- return false;
- if (!Util.equalOrNull(a.getConstant(), b.getConstant()))
- return false;
+ return true;
+}
+protected static boolean compare(IBinaryMethod[] listA, IBinaryMethod[] listB) {
+ if (listA == listB)
return true;
- }
-
- public static boolean compare(IBinaryMethod a, IBinaryMethod b) {
- if (a == b)
- return true;
- if (!CharOperation.equals(a.getSelector(), b.getSelector()))
- return false;
- if (!CharOperation.equals(a.getMethodDescriptor(), b.getMethodDescriptor()))
- return false;
- if (a.getModifiers() != b.getModifiers())
- return false;
- if (!CharOperation
- .equals(a.getExceptionTypeNames(), b.getExceptionTypeNames()))
+ if (listA == null || listB == null)
+ return false;
+ if (listA.length != listB.length)
+ return false;
+ Util.Comparer comparer = new Util.Comparer() {
+ public int compare(Object a, Object b) {
+ IBinaryMethod ma = (IBinaryMethod) a;
+ IBinaryMethod mb = (IBinaryMethod) b;
+ int code = Util.compare(ma.getSelector(), mb.getSelector());
+ if (code != 0)
+ return code;
+ return Util.compare(ma.getMethodDescriptor(), mb.getMethodDescriptor());
+ }
+ };
+ Object[] sortedA = Util.sortCopy(listA, comparer);
+ Object[] sortedB = Util.sortCopy(listB, comparer);
+ for (int i = 0; i < listA.length; ++i) {
+ if (!compare((IBinaryMethod) sortedA[i], (IBinaryMethod) sortedB[i]))
return false;
- return true;
}
-
- protected static boolean compare(IBinaryNestedType a, IBinaryNestedType b) {
- if (a == b)
- return true;
- if (!CharOperation.equals(a.getName(), b.getName()))
- return false;
- if (a.getModifiers() != b.getModifiers())
- return false;
- if (!CharOperation.equals(a.getEnclosingTypeName(), b.getEnclosingTypeName()))
- return false;
+ return true;
+}
+protected static boolean compare(IBinaryNestedType[] listA, IBinaryNestedType[] listB) {
+ if (listA == listB)
return true;
- }
-
- public static boolean compare(IBinaryType a, IBinaryType b) {
- if (a == b)
- return true;
- if (!CharOperation.equals(a.getName(), b.getName()))
- return false;
- if (a.getModifiers() != b.getModifiers())
- return false;
- if (!CharOperation.equals(a.getSuperclassName(), b.getSuperclassName()))
- return false;
- if (!CharOperation.equals(a.getInterfaceNames(), b.getInterfaceNames()))
- return false;
- if (!compare(a.getFields(), b.getFields()))
+ if (listA == null || listB == null)
+ return false;
+ if (listA.length != listB.length)
+ return false;
+ for (int i = 0; i < listA.length; ++i) {
+ if (!compare((IBinaryNestedType) listA[i], (IBinaryNestedType) listB[i]))
return false;
- if (!compare(a.getMethods(), b.getMethods()))
- return false;
- if (!compare(a.getMemberTypes(), b.getMemberTypes()))
- return false;
- return true;
}
-
- /**
- * Converts from the compiler's name representation to ours.
- * i.e., converts from char[] some/pkg/Type$Subtype to
- * String some.pkg.Type$Subtype
- */
- public static String convertTypeName(char[] vmName) {
- char[] builderName = new char[vmName.length];
- for (int i = vmName.length; --i >= 0;) {
- if (vmName[i] == '/') {
- builderName[i] = '.';
- } else {
- builderName[i] = vmName[i];
- }
+ return true;
+}
+public static boolean compare(IBinaryField a, IBinaryField b) {
+ if (a == b)
+ return true;
+ if (!CharOperation.equals(a.getName(), b.getName()))
+ return false;
+ if (!CharOperation.equals(a.getTypeName(), b.getTypeName()))
+ return false;
+ if (a.getModifiers() != b.getModifiers())
+ return false;
+ if (!Util.equalOrNull(a.getConstant(), b.getConstant()))
+ return false;
+ return true;
+}
+public static boolean compare(IBinaryMethod a, IBinaryMethod b) {
+ if (a == b)
+ return true;
+ if (!CharOperation.equals(a.getSelector(), b.getSelector()))
+ return false;
+ if (!CharOperation.equals(a.getMethodDescriptor(), b.getMethodDescriptor()))
+ return false;
+ if (a.getModifiers() != b.getModifiers())
+ return false;
+ if (!CharOperation.equals(a.getExceptionTypeNames(), b.getExceptionTypeNames()))
+ return false;
+ return true;
+}
+protected static boolean compare(IBinaryNestedType a, IBinaryNestedType b) {
+ if (a == b)
+ return true;
+ if (!CharOperation.equals(a.getName(), b.getName()))
+ return false;
+ if (a.getModifiers() != b.getModifiers())
+ return false;
+ if (!CharOperation.equals(a.getEnclosingTypeName(), b.getEnclosingTypeName()))
+ return false;
+ return true;
+}
+public static boolean compare(IBinaryType a, IBinaryType b) {
+ if (a == b)
+ return true;
+ if (!CharOperation.equals(a.getName(), b.getName()))
+ return false;
+ if (a.getModifiers() != b.getModifiers())
+ return false;
+ if (!CharOperation.equals(a.getSuperclassName(), b.getSuperclassName()))
+ return false;
+ if (!CharOperation.equals(a.getInterfaceNames(), b.getInterfaceNames()))
+ return false;
+ if (!compare(a.getFields(), b.getFields()))
+ return false;
+ if (!compare(a.getMethods(), b.getMethods()))
+ return false;
+ if (!compare(a.getMemberTypes(), b.getMemberTypes()))
+ return false;
+ return true;
+}
+/**
+ * Converts from the compiler's name representation to ours.
+ * i.e., converts from char[] some/pkg/Type$Subtype to
+ * String some.pkg.Type$Subtype
+ */
+public static String convertTypeName(char[] vmName) {
+ char[] builderName = new char[vmName.length];
+ for (int i = vmName.length; --i >=0;) {
+ if (vmName[i] == '/') {
+ builderName[i] = '.';
+ } else {
+ builderName[i] = vmName[i];
}
- return new String(builderName);
}
-
- /**
- * Returns the constructor of the type, corresponding to the given constructor handle signature,
- * or null if there is none which matches.
- */
- public static IBinaryMethod getConstructor(
- IBinaryType type,
- String handleSig) {
- IBinaryMethod[] methods = type.getMethods();
- if (methods != null) {
- char[] sig = handleSig.replace('.', '/').toCharArray();
- for (int i = 0; i < methods.length; i++) {
- IBinaryMethod m = (IBinaryMethod) methods[i];
- if (m.isConstructor()
- && CharOperation.startsWith(m.getMethodDescriptor(), sig))
- return m;
- }
+ return new String(builderName);
+}
+/**
+ * Returns the constructor of the type, corresponding to the given constructor handle signature,
+ * or null if there is none which matches.
+ */
+public static IBinaryMethod getConstructor(IBinaryType type, String handleSig) {
+ IBinaryMethod[] methods = type.getMethods();
+ if (methods != null) {
+ char[] sig = handleSig.replace('.', '/').toCharArray();
+ for (int i = 0; i < methods.length; i++) {
+ IBinaryMethod m = (IBinaryMethod) methods[i];
+ if (m.isConstructor() && CharOperation.startsWith(m.getMethodDescriptor(), sig))
+ return m;
}
- return null;
}
-
- /**
- * Returns the non-state-specific constructor handle for an IBinaryMethod, given the containing
- * non-state-specific type handle.
- */
- public static IConstructor getConstructorHandle(
- IBinaryMethod method,
- ClassOrInterfaceHandleImpl type) {
- char[] sig = method.getMethodDescriptor();
- sig = CharOperation.subarray(sig, 0, sig.length - 1); // Trim off V trailer
- String convertedSig = new String(sig).replace('/', '.');
- return new ConstructorImpl(type, convertedSig);
+ return null;
+}
+/**
+ * Returns the non-state-specific constructor handle for an IBinaryMethod, given the containing
+ * non-state-specific type handle.
+ */
+public static IConstructor getConstructorHandle(IBinaryMethod method, ClassOrInterfaceHandleImpl type) {
+ char[] sig = method.getMethodDescriptor();
+ sig = CharOperation.subarray(sig, 0, sig.length - 1); // Trim off V trailer
+ String convertedSig = new String(sig).replace('/', '.');
+ return new ConstructorImpl(type, convertedSig);
+}
+/**
+ * Returns the declared name (name as it appears in the source) for the given type.
+ */
+public static char[] getDeclaredName(IBinaryNestedType type) {
+ char[] name = type.getName();
+ int lastDot = CharOperation.lastIndexOf('/', name);
+ if (lastDot != -1) {
+ name = CharOperation.subarray(name, lastDot + 1, name.length);
}
-
- /**
- * Returns the declared name (name as it appears in the source) for the given type.
- */
- public static char[] getDeclaredName(IBinaryNestedType type) {
- char[] name = type.getName();
- int lastDot = CharOperation.lastIndexOf('/', name);
- if (lastDot != -1) {
- name = CharOperation.subarray(name, lastDot + 1, name.length);
- }
- int lastDollar = CharOperation.lastIndexOf('$', name);
- if (lastDollar != -1) {
- name = CharOperation.subarray(name, lastDollar + 1, name.length);
- }
- return name;
+ int lastDollar = CharOperation.lastIndexOf('$', name);
+ if (lastDollar != -1) {
+ name = CharOperation.subarray(name, lastDollar + 1, name.length);
}
-
- /**
- * Returns the declared name (name as it appears in the source) for the given type.
- */
- public static char[] getDeclaredName(IBinaryType type) {
- char[] name = type.getName();
- int lastDot = CharOperation.lastIndexOf('/', name);
- if (lastDot != -1) {
- name = CharOperation.subarray(name, lastDot + 1, name.length);
- }
- int lastDollar = CharOperation.lastIndexOf('$', name);
- if (lastDollar != -1) {
- name = CharOperation.subarray(name, lastDollar + 1, name.length);
- }
- return name;
+ return name;
+}
+/**
+ * Returns the declared name (name as it appears in the source) for the given type.
+ */
+public static char[] getDeclaredName(IBinaryType type) {
+ char[] name = type.getName();
+ int lastDot = CharOperation.lastIndexOf('/', name);
+ if (lastDot != -1) {
+ name = CharOperation.subarray(name, lastDot + 1, name.length);
}
-
- /**
- * Returns the name of the enclosing type, or null.
- */
- public static char[] getEnclosingTypeName(IBinaryType type) {
- IBinaryNestedType t = getInnerClassEntry(type);
- return t == null ? null : t.getEnclosingTypeName();
+ int lastDollar = CharOperation.lastIndexOf('$', name);
+ if (lastDollar != -1) {
+ name = CharOperation.subarray(name, lastDollar + 1, name.length);
}
-
- /**
- * Returns the field of the type, with the given name,
- * or null if there is none which matches.
- */
- public static IBinaryField getField(IBinaryType type, String name) {
- IBinaryField[] fields = type.getFields();
- if (fields != null) {
- char[] nameChars = name.toCharArray();
- for (int i = 0; i < fields.length; i++) {
- IBinaryField f = (IBinaryField) fields[i];
- if (CharOperation.equals(f.getName(), nameChars))
- return f;
- }
+ return name;
+}
+/**
+ * Returns the name of the enclosing type, or null.
+ */
+public static char[] getEnclosingTypeName(IBinaryType type) {
+ IBinaryNestedType t = getInnerClassEntry(type);
+ return t == null ? null : t.getEnclosingTypeName();
+}
+/**
+ * Returns the field of the type, with the given name,
+ * or null if there is none which matches.
+ */
+public static IBinaryField getField(IBinaryType type, String name) {
+ IBinaryField[] fields = type.getFields();
+ if (fields != null) {
+ char[] nameChars = name.toCharArray();
+ for (int i = 0; i < fields.length; i++) {
+ IBinaryField f = (IBinaryField) fields[i];
+ if (CharOperation.equals(f.getName(), nameChars))
+ return f;
}
- return null;
- }
-
- /**
- * Returns the non-state-specific field handle for an IBinaryField, given the containing
- * non-state-specific type handle.
- */
- public static IField getFieldHandle(
- IBinaryField field,
- ClassOrInterfaceHandleImpl type) {
- return type.getFieldHandle(new String(field.getName()));
}
-
- /**
- * Returns the fully qualified name of the given binary type
- */
- public static String getFullyQualifiedName(IBinaryType type) {
- return convertTypeName(type.getName());
- }
-
- /**
- * Returns the inner class entry representing this type, or null if not applicable.
- */
- protected static IBinaryNestedType getInnerClassEntry(IBinaryType type) {
- IBinaryNestedType[] inners = type.getMemberTypes();
- if (inners != null) {
- char[] name = type.getName();
- for (int i = 0, max = inners.length; i < max; ++i) {
- IBinaryNestedType t = (IBinaryNestedType) inners[i];
- if (CharOperation.equals(t.getName(), name)) {
- return t;
- }
+ return null;
+}
+/**
+ * Returns the non-state-specific field handle for an IBinaryField, given the containing
+ * non-state-specific type handle.
+ */
+public static IField getFieldHandle(IBinaryField field, ClassOrInterfaceHandleImpl type) {
+ return type.getFieldHandle(new String(field.getName()));
+}
+/**
+ * Returns the fully qualified name of the given binary type
+ */
+public static String getFullyQualifiedName(IBinaryType type) {
+ return convertTypeName(type.getName());
+}
+/**
+ * Returns the inner class entry representing this type, or null if not applicable.
+ */
+protected static IBinaryNestedType getInnerClassEntry(IBinaryType type) {
+ IBinaryNestedType[] inners = type.getMemberTypes();
+ if (inners != null) {
+ char[] name = type.getName();
+ for (int i = 0, max = inners.length; i < max; ++i) {
+ IBinaryNestedType t = (IBinaryNestedType) inners[i];
+ if (CharOperation.equals(t.getName(), name)) {
+ return t;
}
}
- return null;
}
-
- /**
- * Returns the names of inner types in the inner class entries which have this type
- * as their outer type. May include both local (pre JDK1.2) and member types.
- */
- public static char[][] getInnerTypes(IBinaryType type) {
- IBinaryNestedType[] nested = type.getMemberTypes();
- if (nested == null) {
- return new char[0][];
- } else {
- char[][] result = new char[nested.length][];
- int count = 0;
- for (int i = 0; i < nested.length; ++i) {
- IBinaryNestedType t = nested[i];
- if (CharOperation.equals(t.getEnclosingTypeName(), type.getName())) {
- result[count++] = t.getName();
- }
- }
- if (count < result.length) {
- System.arraycopy(result, 0, result = new char[count][], 0, count);
+ return null;
+}
+/**
+ * Returns the names of inner types in the inner class entries which have this type
+ * as their outer type. May include both local (pre JDK1.2) and member types.
+ */
+public static char[][] getInnerTypes(IBinaryType type) {
+ IBinaryNestedType[] nested = type.getMemberTypes();
+ if (nested == null) {
+ return new char[0][];
+ } else {
+ char[][] result = new char[nested.length][];
+ int count = 0;
+ for (int i = 0; i < nested.length; ++i) {
+ IBinaryNestedType t = nested[i];
+ if (CharOperation.equals(t.getEnclosingTypeName(), type.getName())) {
+ result[count++] = t.getName();
}
- return result;
}
- }
-
- /**
- * Returns the method of the type, corresponding to the given method handle signature,
- * or null if there is none which matches.
- */
- public static IBinaryMethod getMethod(IBinaryType type, String handleSig) {
- IBinaryMethod[] methods = type.getMethods();
- if (methods != null) {
- char[] sig = handleSig.replace('.', '/').toCharArray();
- int paren = CharOperation.indexOf('(', sig);
- if (paren == -1)
- return null;
- char[] sel = CharOperation.subarray(sig, 0, paren);
- char[] desc = CharOperation.subarray(sig, paren, sig.length);
- for (int i = 0; i < methods.length; i++) {
- IBinaryMethod m = (IBinaryMethod) methods[i];
- if (!m.isConstructor()
- && CharOperation.equals(m.getSelector(), sel)
- && CharOperation.startsWith(m.getMethodDescriptor(), desc))
- return m;
- }
+ if (count < result.length) {
+ System.arraycopy(result, 0, result = new char[count][], 0, count);
}
- return null;
+ return result;
}
-
- /**
- * Returns the non-state-specific method handle for an IBinaryMethod, given the containing
- * non-state-specific type handle.
- */
- public static IMethod getMethodHandle(
- IBinaryMethod method,
- ClassOrInterfaceHandleImpl type) {
-
- /**
- * Note that DC method signatures have the following grammar rule:
- * - MethodSignature: selector ( ParameterDescriptor* )
- * Whereas the VM signature format in IBinaryMethod is:
- * - MethodDescriptor: ( ParameterDescriptor* ) ReturnDescriptor
- */
-
- char[] sig = method.getMethodDescriptor();
- int i = CharOperation.lastIndexOf(')', sig);
- if (i != -1)
- sig = CharOperation.subarray(sig, 0, i + 1); // Trim return type
-
- sig = CharOperation.concat(method.getSelector(), sig);
- String convertedSig = new String(sig).replace('/', '.');
- return new MethodImpl(type, convertedSig);
- }
-
- /**
- * Returns a type handle for the given type name. The name
- * must be in IBinaryType format.
- * The TypeStructureEntry is passed in case the default package needs to be determined
- * relative to the referring type.
- */
- public static IType getType(
- StateImpl state,
- TypeStructureEntry referringType,
- char[] name) {
- /* null is a valid type name */
- if (name == null) {
+}
+/**
+ * Returns the method of the type, corresponding to the given method handle signature,
+ * or null if there is none which matches.
+ */
+public static IBinaryMethod getMethod(IBinaryType type, String handleSig) {
+ IBinaryMethod[] methods = type.getMethods();
+ if (methods != null) {
+ char[] sig = handleSig.replace('.', '/').toCharArray();
+ int paren = CharOperation.indexOf('(', sig);
+ if (paren == -1)
return null;
+ char[] sel = CharOperation.subarray(sig, 0, paren);
+ char[] desc = CharOperation.subarray(sig, paren, sig.length);
+ for (int i = 0; i < methods.length; i++) {
+ IBinaryMethod m = (IBinaryMethod) methods[i];
+ if (!m.isConstructor() && CharOperation.equals(m.getSelector(), sel) && CharOperation.startsWith(m.getMethodDescriptor(), desc))
+ return m;
}
- return state.typeNameToHandle(
- referringType,
- new String(name).replace('/', '.'));
}
+ return null;
+}
+/**
+ * Returns the non-state-specific method handle for an IBinaryMethod, given the containing
+ * non-state-specific type handle.
+ */
+public static IMethod getMethodHandle(IBinaryMethod method, ClassOrInterfaceHandleImpl type) {
/**
- * Returns whether the type is an anonymous type (local, without a name).
+ * Note that DC method signatures have the following grammar rule:
+ * - MethodSignature: selector ( ParameterDescriptor* )
+ * Whereas the VM signature format in IBinaryMethod is:
+ * - MethodDescriptor: ( ParameterDescriptor* ) ReturnDescriptor
*/
- public static boolean isAnonymous(IBinaryType type) {
- /* TBD: Don't have access to declared name, but assume it's anonymous if it's local. */
- return isLocal(type);
- }
- /**
- * Returns whether the type is a local type (not a top-level or member type).
- */
- public static boolean isLocal(IBinaryType type) {
- /* As of JDK 1.2, the inner class entry for local types have null for the enclosing type. */
- IBinaryNestedType t = getInnerClassEntry(type);
- return t != null && t.getEnclosingTypeName() == null;
- }
+ char[] sig = method.getMethodDescriptor();
+ int i = CharOperation.lastIndexOf(')', sig);
+ if (i != -1)
+ sig = CharOperation.subarray(sig, 0, i + 1); // Trim return type
- /**
- * Returns whether the type is a package member (not a nested type).
- */
- public static boolean isPackageMember(IBinaryType type) {
- return getInnerClassEntry(type) == null;
+ sig = CharOperation.concat(method.getSelector(), sig);
+ String convertedSig = new String(sig).replace('/', '.');
+ return new MethodImpl(type, convertedSig);
+}
+/**
+ * Returns a type handle for the given type name. The name
+ * must be in IBinaryType format.
+ * The TypeStructureEntry is passed in case the default package needs to be determined
+ * relative to the referring type.
+ */
+public static IType getType(StateImpl state, TypeStructureEntry referringType, char[] name) {
+ /* null is a valid type name */
+ if (name == null) {
+ return null;
}
-
+ return state.typeNameToHandle(referringType, new String(name).replace('/', '.'));
+}
+/**
+ * Returns whether the type is an anonymous type (local, without a name).
+ */
+public static boolean isAnonymous(IBinaryType type) {
+ /* TBD: Don't have access to declared name, but assume it's anonymous if it's local. */
+ return isLocal(type);
+}
+/**
+ * Returns whether the type is a local type (not a top-level or member type).
+ */
+public static boolean isLocal(IBinaryType type) {
+ /* As of JDK 1.2, the inner class entry for local types have null for the enclosing type. */
+ IBinaryNestedType t = getInnerClassEntry(type);
+ return t != null && t.getEnclosingTypeName() == null;
+}
+/**
+ * Returns whether the type is a package member (not a nested type).
+ */
+public static boolean isPackageMember(IBinaryType type) {
+ return getInnerClassEntry(type) == null;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BuildMonitorImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BuildMonitorImpl.java
index 54c10fef28..ff7cae588f 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BuildMonitorImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BuildMonitorImpl.java
@@ -13,7 +13,7 @@ import java.util.Vector;
* given build. This allows test suites to evaluate the efficiency of incremental
* compilation.
*/
-public class BuildMonitorImpl implements IBuildMonitor {
+public class BuildMonitorImpl implements IBuildMonitor{
protected Vector fClasses = new Vector();
/**
@@ -21,30 +21,26 @@ public class BuildMonitorImpl implements IBuildMonitor {
*/
public BuildMonitorImpl() {
}
-
/**
* Signals that a new build has begun.
*/
public void beginBuild(String message) {
- // System.out.println(message);
+// System.out.println(message);
fClasses.removeAllElements();
}
-
/**
* Signals that a compilation unit with the given name has been compiled
*/
public void compiled(String jcu) {
- // System.out.println("<BM>Compiled: " + jcu);
+// System.out.println("<BM>Compiled: " + jcu);
fClasses.addElement(jcu);
}
-
/**
* Signals that a new build has begun.
*/
public void endBuild(String message) {
- // System.out.println(message);
+// System.out.println(message);
}
-
/**
* Returns the compiled classes
*/
@@ -53,5 +49,4 @@ public class BuildMonitorImpl implements IBuildMonitor {
fClasses.copyInto(results);
return results;
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BuildNotifier.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BuildNotifier.java
index 4e020def42..207d2b6bb6 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BuildNotifier.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BuildNotifier.java
@@ -7,6 +7,7 @@ package org.eclipse.jdt.internal.core.builder.impl;
import org.eclipse.core.runtime.*;
import org.eclipse.jdt.internal.core.builder.*;
+import org.eclipse.jdt.internal.core.Util;
import org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
import java.text.NumberFormat;
@@ -35,26 +36,23 @@ public class BuildNotifier {
public static boolean DEBUG = false;
protected String previousSubtask;
- public BuildNotifier(JavaDevelopmentContextImpl dc, boolean isBatch) {
- fDC = dc;
- fIsBatch = isBatch;
- fProgress = dc.getProgressMonitor();
- fBuildMonitor = dc.getBuildMonitor();
- fBuildListeners = dc.getBuildListeners();
- fTotalWork = 1000000;
+public BuildNotifier(JavaDevelopmentContextImpl dc, boolean isBatch) {
+ fDC = dc;
+ fIsBatch = isBatch;
+ fProgress = dc.getProgressMonitor();
+ fBuildMonitor = dc.getBuildMonitor();
+ fBuildListeners = dc.getBuildListeners();
+ fTotalWork = 1000000;
+}
+public void begin() {
+ if (fBuildMonitor != null) {
+ fBuildMonitor.beginBuild(fIsBatch ? "Begin batch build" : "Begin incremental build");
}
-
- public void begin() {
- if (fBuildMonitor != null) {
- fBuildMonitor.beginBuild(
- fIsBatch ? "Begin batch build" : "Begin incremental build");
- }
- if (fProgress != null) {
- fProgress.beginTask("", fTotalWork);
- }
- this.previousSubtask = null;
+ if (fProgress != null) {
+ fProgress.beginTask(""/*nonNLS*/, fTotalWork);
}
-
+ this.previousSubtask = null;
+}
/**
* Check whether the build has been canceled.
*/
@@ -63,240 +61,201 @@ public class BuildNotifier {
throw new OperationCanceledException();
}
}
-
- /**
- * Check whether the build has been canceled.
- * Must use this call instead of checkCancel() when within the compiler.
- */
- public void checkCancelWithinCompiler() {
- if (fProgress != null && fProgress.isCanceled() && !fCancelling) {
- // Once the compiler has been canceled, don't check again.
- setCancelling(true);
- // Only AbortCompilation can stop the compiler cleanly.
- // We check cancelation again following the call to compile.
- throw new AbortCompilation(true, null);
- }
+/**
+ * Check whether the build has been canceled.
+ * Must use this call instead of checkCancel() when within the compiler.
+ */
+public void checkCancelWithinCompiler() {
+ if (fProgress != null && fProgress.isCanceled() && !fCancelling) {
+ // Once the compiler has been canceled, don't check again.
+ setCancelling(true);
+ // Only AbortCompilation can stop the compiler cleanly.
+ // We check cancelation again following the call to compile.
+ throw new AbortCompilation(true, null);
}
-
- /**
- * Notification while within a compile that a unit has finished being compiled.
- */
- public void compiled(CompilerCompilationUnit unit) {
- compiling(unit);
+}
+/**
+ * Notification while within a compile that a unit has finished being compiled.
+ */
+public void compiled(CompilerCompilationUnit unit) {
+ compiling(unit);
+}
+/**
+ * Notification while within a compile that a unit is starting to be compiled.
+ */
+public void compiling(CompilerCompilationUnit unit) {
+ String message = new String(unit.getFileName());
+ message = message.replace('\\', '/');
+ // Trim off project names
+ int start = message.indexOf('/', 1);
+ int end = message.lastIndexOf('/');
+ if (end <= start){
+ message = Util.bind("build.compiling"/*nonNLS*/, message.substring(start+1));
+ } else {
+ message = Util.bind("build.compilingContent"/*nonNLS*/, message.substring(start+1, end));
}
-
- /**
- * Notification while within a compile that a unit is starting to be compiled.
- */
- public void compiling(CompilerCompilationUnit unit) {
- String message = new String(unit.getFileName());
- message = message.replace('\\', '/');
- // Trim off project names
- int start = message.indexOf('/', 1);
- int end = message.lastIndexOf('/');
- if (end <= start) {
- message = "Compiling " + message.substring(start + 1);
- } else {
- message = "Compiling content of " + message.substring(start + 1, end);
- }
- subTask(message);
- updateProgressDelta(fProgressPerCompilationUnit / 2);
- checkCancelWithinCompiler();
+ subTask(message);
+ updateProgressDelta(fProgressPerCompilationUnit/2);
+ checkCancelWithinCompiler();
+}
+public void done() {
+ updateProgress(1.0f);
+ subTask("Build done");
+ if (fProgress != null) {
+ fProgress.done();
}
+ if (fBuildMonitor != null) {
+ fBuildMonitor.endBuild(fIsBatch ? "->End batch build" : "->End incremental build");
+ }
+ this.previousSubtask = null;
+}
+/**
+ * Notify listeners that elements have changed.
+ */
+public void notifyElementsChanged(ConvertedCompilationResult[] results, StateImpl oldState, StateImpl newState) {
+ // if (fBuildListeners.size() == 0) {
+ // return;
+ // }
+ for (int i = 0; i < results.length; ++i) {
+ ConvertedCompilationResult result = results[i];
+ PackageElement element = result.getPackageElement();
- public void done() {
- updateProgress(1.0f);
- subTask("Build done");
- if (fProgress != null) {
- fProgress.done();
- }
+ /* notify the build monitor */
if (fBuildMonitor != null) {
- fBuildMonitor.endBuild(
- fIsBatch ? "->End batch build" : "->End incremental build");
+ String typeName = element.getFileName();
+ int lastDot = typeName.lastIndexOf('.');
+ typeName = typeName.substring(0, lastDot);
+ fBuildMonitor.compiled(element.getPackage().getName() + '.' + typeName);
}
- this.previousSubtask = null;
- }
-
- /**
- * Notify listeners that elements have changed.
- */
- public void notifyElementsChanged(
- ConvertedCompilationResult[] results,
- StateImpl oldState,
- StateImpl newState) {
- // if (fBuildListeners.size() == 0) {
- // return;
- // }
- for (int i = 0; i < results.length; ++i) {
- ConvertedCompilationResult result = results[i];
- PackageElement element = result.getPackageElement();
-
- /* notify the build monitor */
- if (fBuildMonitor != null) {
- String typeName = element.getFileName();
- int lastDot = typeName.lastIndexOf('.');
- typeName = typeName.substring(0, lastDot);
- fBuildMonitor.compiled(element.getPackage().getName() + '.' + typeName);
- }
- Vector oldProblems = null;
- Vector newProblems = null;
- if (oldState != null) {
- SourceEntry oldEntry = oldState.getSourceEntry(element);
- if (oldEntry != null) {
- oldProblems = oldState.getProblemReporter().getProblemVector(oldEntry);
- }
- }
- SourceEntry newEntry = newState.getSourceEntry(element);
- if (newEntry != null) {
- newProblems = newState.getProblemReporter().getProblemVector(newEntry);
- }
- updateProblemCounts(oldProblems, newProblems);
- ISourceFragment fragment =
- (newEntry == null ? null : new SourceFragmentImpl(newEntry));
- BuildEvent event =
- new BuildEvent(
- fragment,
- fNewErrorCount,
- fFixedErrorCount,
- fNewWarningCount,
- fFixedWarningCount);
- for (int j = 0, size = fBuildListeners.size(); j < size; ++j) {
- ((IBuildListener) fBuildListeners.elementAt(j)).buildUpdate(event);
+ Vector oldProblems = null;
+ Vector newProblems = null;
+ if (oldState != null) {
+ SourceEntry oldEntry = oldState.getSourceEntry(element);
+ if (oldEntry != null) {
+ oldProblems = oldState.getProblemReporter().getProblemVector(oldEntry);
}
}
- }
-
- /**
- * Returns a string describing the problems.
- */
- protected String problemsMessage() {
- int numNew = fNewErrorCount + fNewWarningCount;
- int numFixed = fFixedErrorCount + fFixedWarningCount;
- if (numNew == 0 && numFixed == 0) {
- return "";
+ SourceEntry newEntry = newState.getSourceEntry(element);
+ if (newEntry != null) {
+ newProblems = newState.getProblemReporter().getProblemVector(newEntry);
+ }
+ updateProblemCounts(oldProblems, newProblems);
+ ISourceFragment fragment = (newEntry == null ? null : new SourceFragmentImpl(newEntry));
+ BuildEvent event = new BuildEvent(fragment, fNewErrorCount, fFixedErrorCount, fNewWarningCount, fFixedWarningCount);
+ for (int j = 0, size = fBuildListeners.size(); j < size; ++j) {
+ ((IBuildListener) fBuildListeners.elementAt(j)).buildUpdate(event);
}
- if (numFixed == 0) {
- return "(" + numNew + " " + (numNew == 1 ? "problem" : "problems") + " found)";
- } else
- if (numNew == 0) {
- return "("
- + numFixed
- + " "
- + (numFixed == 1 ? "problem" : "problems")
- + " fixed)";
- } else {
- return "("
- + numFixed
- + " "
- + (numFixed == 1 ? "problem" : "problems")
- + " fixed, "
- + numNew
- + " "
- + (numNew == 1 ? "problem" : "problems")
- + " found)";
- }
- }
-
- /**
- * Sets the cancelling flag, which indicates we are in the middle
- * of being cancelled. Certain places (those callable indirectly from the compiler)
- * should not check cancel again while this is true, to avoid OperationCanceledException
- * being thrown at an inopportune time.
- */
- public void setCancelling(boolean cancelling) {
- fCancelling = cancelling;
}
-
- /**
- * Sets the amount of progress to report for compiling each compilation unit.
- */
- public void setProgressPerCompilationUnit(float progress) {
- fProgressPerCompilationUnit = progress;
+}
+/**
+ * Returns a string describing the problems.
+ */
+protected String problemsMessage() {
+ int numNew = fNewErrorCount + fNewWarningCount;
+ int numFixed = fFixedErrorCount + fFixedWarningCount;
+ if (numNew == 0 && numFixed == 0) {
+ return "";
}
+ if (numFixed == 0) {
+ return "(" + numNew + " " + (numNew == 1 ? "problem" : "problems") + " found)";
+ } else
+ if (numNew == 0) {
+ return "(" + numFixed + " " + (numFixed == 1 ? "problem" : "problems") + " fixed)";
+ } else {
+ return "(" + numFixed + " " + (numFixed == 1 ? "problem" : "problems") + " fixed, " + numNew + " " + (numNew == 1 ? "problem" : "problems") + " found)";
+ }
+}
+/**
+ * Sets the cancelling flag, which indicates we are in the middle
+ * of being cancelled. Certain places (those callable indirectly from the compiler)
+ * should not check cancel again while this is true, to avoid OperationCanceledException
+ * being thrown at an inopportune time.
+ */
+public void setCancelling(boolean cancelling) {
+ fCancelling = cancelling;
+}
+/**
+ * Sets the amount of progress to report for compiling each compilation unit.
+ */
+public void setProgressPerCompilationUnit(float progress) {
+ fProgressPerCompilationUnit = progress;
+}
+public void subTask(String message) {
+ String pm = problemsMessage();
+ String msg = pm.length() == 0 ? message : pm + " " + message;
- public void subTask(String message) {
- String pm = problemsMessage();
- String msg = pm.length() == 0 ? message : pm + " " + message;
-
- if (msg.equals(this.previousSubtask))
- return; // avoid refreshing with same one
- if (DEBUG)
- System.out.println(msg);
- if (fProgress != null)
- fProgress.subTask(msg);
-
- this.previousSubtask = msg;
- }
+ if (msg.equals(this.previousSubtask)) return; // avoid refreshing with same one
+ if (DEBUG) System.out.println(msg);
+ if (fProgress != null) fProgress.subTask(msg);
- /**
- * Update the problem counts given the old and new problems,
- * either of which may be null.
- */
- protected void updateProblemCounts(Vector oldProblems, Vector newProblems) {
- if (oldProblems != null) {
- for (int i = 0, oldSize = oldProblems.size(); i < oldSize; ++i) {
- ProblemDetailImpl oldProblem = (ProblemDetailImpl) oldProblems.elementAt(i);
- ProblemDetailImpl newProblem = null;
- if (newProblems != null) {
- for (int j = 0, newSize = newProblems.size(); j < newSize; ++j) {
- ProblemDetailImpl pb = (ProblemDetailImpl) newProblems.elementAt(j);
- if (oldProblem.equals(pb, true)) {
- newProblem = pb;
- break;
- }
+ this.previousSubtask = msg;
+}
+/**
+ * Update the problem counts given the old and new problems,
+ * either of which may be null.
+ */
+protected void updateProblemCounts(Vector oldProblems, Vector newProblems) {
+ if (oldProblems != null) {
+ for (int i = 0, oldSize = oldProblems.size(); i < oldSize; ++i) {
+ ProblemDetailImpl oldProblem = (ProblemDetailImpl) oldProblems.elementAt(i);
+ ProblemDetailImpl newProblem = null;
+ if (newProblems != null) {
+ for (int j = 0, newSize = newProblems.size(); j < newSize; ++j) {
+ ProblemDetailImpl pb = (ProblemDetailImpl) newProblems.elementAt(j);
+ if (oldProblem.equals(pb, true)) {
+ newProblem = pb;
+ break;
}
}
- if (newProblem == null) {
- if ((oldProblem.getSeverity() & IProblemDetail.S_ERROR) != 0) {
- fFixedErrorCount++;
- } else {
- fFixedWarningCount++;
- }
+ }
+ if (newProblem == null) {
+ if ((oldProblem.getSeverity() & IProblemDetail.S_ERROR) != 0) {
+ fFixedErrorCount++;
+ } else {
+ fFixedWarningCount++;
}
}
}
- if (newProblems != null) {
- for (int i = 0, newSize = newProblems.size(); i < newSize; ++i) {
- ProblemDetailImpl newProblem = (ProblemDetailImpl) newProblems.elementAt(i);
- ProblemDetailImpl oldProblem = null;
- if (oldProblems != null) {
- for (int j = 0, oldSize = oldProblems.size(); j < oldSize; ++j) {
- ProblemDetailImpl pb = (ProblemDetailImpl) oldProblems.elementAt(j);
- if (newProblem.equals(pb, true)) {
- oldProblem = pb;
- break;
- }
+ }
+ if (newProblems != null) {
+ for (int i = 0, newSize = newProblems.size(); i < newSize; ++i) {
+ ProblemDetailImpl newProblem = (ProblemDetailImpl) newProblems.elementAt(i);
+ ProblemDetailImpl oldProblem = null;
+ if (oldProblems != null) {
+ for (int j = 0, oldSize = oldProblems.size(); j < oldSize; ++j) {
+ ProblemDetailImpl pb = (ProblemDetailImpl) oldProblems.elementAt(j);
+ if (newProblem.equals(pb, true)) {
+ oldProblem = pb;
+ break;
}
}
- if (oldProblem == null) {
- if ((newProblem.getSeverity() & IProblemDetail.S_ERROR) != 0) {
- fNewErrorCount++;
- } else {
- fNewWarningCount++;
- }
+ }
+ if (oldProblem == null) {
+ if ((newProblem.getSeverity() & IProblemDetail.S_ERROR) != 0) {
+ fNewErrorCount++;
+ } else {
+ fNewWarningCount++;
}
}
}
}
-
- public void updateProgress(float percentComplete) {
- if (percentComplete > fPercentComplete) {
- fPercentComplete = Math.min(percentComplete, 1.0f);
- int work = Math.round(fPercentComplete * fTotalWork);
- if (work > fWorkDone) {
- if (fProgress != null) {
- fProgress.worked(work - fWorkDone);
- }
- if (DEBUG) {
- System.out.println(NumberFormat.getPercentInstance().format(fPercentComplete));
- }
- fWorkDone = work;
+}
+public void updateProgress(float percentComplete) {
+ if (percentComplete > fPercentComplete) {
+ fPercentComplete = Math.min(percentComplete, 1.0f);
+ int work = Math.round(fPercentComplete * fTotalWork);
+ if (work > fWorkDone) {
+ if (fProgress != null) {
+ fProgress.worked(work - fWorkDone);
+ }
+ if (DEBUG) {
+ System.out.println(NumberFormat.getPercentInstance().format(fPercentComplete));
}
+ fWorkDone = work;
}
}
-
- public void updateProgressDelta(float percentWorked) {
- updateProgress(fPercentComplete + percentWorked);
- }
-
+}
+public void updateProgressDelta(float percentWorked) {
+ updateProgress(fPercentComplete + percentWorked);
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BuilderEnvironment.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BuilderEnvironment.java
index 26ecd71609..32d64b2b3b 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BuilderEnvironment.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BuilderEnvironment.java
@@ -23,26 +23,23 @@ public class BuilderEnvironment implements INameEnvironment {
protected Hashtable fPackages;
protected IPackage fDefaultPackage = null;
protected BuildNotifier fNotifier = null;
- public BuilderEnvironment(AbstractImageBuilder builder) {
- fBuilder = builder;
- fState = (StateImpl) fBuilder.getNewState();
- fDevelopmentContext = fState.getDevelopmentContext();
- }
-
- protected void checkCancel() {
- if (fNotifier != null) {
- fNotifier.checkCancelWithinCompiler();
- }
- }
-
- /**
- * Notifies interested listeners that a compilation unit is
- * going to be compiled.
- */
- protected void compiling(CompilerCompilationUnit unit) {
- fBuilder.compiling(unit);
+public BuilderEnvironment(AbstractImageBuilder builder) {
+ fBuilder = builder;
+ fState = (StateImpl) fBuilder.getNewState();
+ fDevelopmentContext = fState.getDevelopmentContext();
+}
+protected void checkCancel() {
+ if (fNotifier != null) {
+ fNotifier.checkCancelWithinCompiler();
}
-
+}
+/**
+ * Notifies interested listeners that a compilation unit is
+ * going to be compiled.
+ */
+protected void compiling(CompilerCompilationUnit unit) {
+ fBuilder.compiling(unit);
+}
/**
* Create a table keyed by package name, including all package prefixes.
* If it's a real package, it maps to the handle, otherwise to null.
@@ -54,15 +51,14 @@ public class BuilderEnvironment implements INameEnvironment {
}
PackageMap packageMap = fState.getPackageMap();
for (Enumeration e = packageMap.getAllPackages(); e.hasMoreElements();) {
- IPackage pkg = (IPackage) e.nextElement();
+ IPackage pkg = (IPackage)e.nextElement();
if (!pkg.isUnnamed()) {
String name = pkg.getName();
table.put(name, pkg);
int i = -1;
while ((i = name.indexOf('.', i + 1)) != -1) {
String prefix = name.substring(0, i);
- if (!table.containsKey(prefix)) {
- // don't overwrite if there's a real package with the same prefix
+ if (!table.containsKey(prefix)) { // don't overwrite if there's a real package with the same prefix
table.put(prefix, prefix);
}
}
@@ -70,130 +66,116 @@ public class BuilderEnvironment implements INameEnvironment {
}
fPackages = table;
}
-
- /**
- * @see IBuilderEnvironment
- */
- protected NameEnvironmentAnswer find(
- String packageName,
- String simpleTypeName) {
- checkCancel();
- IPackage pkg = getPackageHandle(packageName);
- if (pkg == null) {
- return null;
- }
- IType type = pkg.getClassHandle(simpleTypeName);
- SourceEntry sEntry = null;
- TypeStructureEntry tsEntry = fState.getTypeStructureEntry(type, false);
- boolean isInvalid;
- if (tsEntry != null) {
- sEntry = tsEntry.getSourceEntry();
- isInvalid = fBuilder.isInvalid(sEntry);
- if (!isInvalid) {
- /* don't want to invoke a lazy build here */
- IBinaryType binaryType = fState.getBinaryTypeOrNull(tsEntry);
- if (binaryType != null) {
- return new NameEnvironmentAnswer(binaryType);
- }
- }
- } else {
- sEntry = fState.getSourceEntry(type);
- if (sEntry == null) {
- return null;
+/**
+ * @see IBuilderEnvironment
+ */
+protected NameEnvironmentAnswer find(String packageName, String simpleTypeName) {
+ checkCancel();
+ IPackage pkg = getPackageHandle(packageName);
+ if (pkg == null) {
+ return null;
+ }
+ IType type = pkg.getClassHandle(simpleTypeName);
+ SourceEntry sEntry = null;
+ TypeStructureEntry tsEntry = fState.getTypeStructureEntry(type, false);
+ boolean isInvalid;
+ if (tsEntry != null) {
+ sEntry = tsEntry.getSourceEntry();
+ isInvalid = fBuilder.isInvalid(sEntry);
+ if (!isInvalid) {
+ /* don't want to invoke a lazy build here */
+ IBinaryType binaryType = fState.getBinaryTypeOrNull(tsEntry);
+ if (binaryType != null) {
+ return new NameEnvironmentAnswer(binaryType);
}
- isInvalid = fBuilder.isInvalid(sEntry);
}
- if (sEntry != null && sEntry.isSource()) {
- // only accept if really a compilation unit, not from binary
- // If the type was unknown (as opposed to invalid), check to see if there are problems.
- // If there was no principal structure and there are problems,
- // then the compilation unit has tried to be compiled and it has failed,
- // so don't try again.
- // If the type was known, but needs to be recompiled because its principal structure was missing,
- // then recompile it regardless of whether it has problems.
- if (!isInvalid
- && (tsEntry == null && fState.getProblemReporter().hasProblems(sEntry))) {
- return null;
- }
- CompilerCompilationUnit unit =
- new CompilerCompilationUnit(fState, sEntry, fNotifier);
- compiling(unit);
- return new NameEnvironmentAnswer(unit);
+ } else {
+ sEntry = fState.getSourceEntry(type);
+ if (sEntry == null) {
+ return null;
}
- return null;
+ isInvalid = fBuilder.isInvalid(sEntry);
}
-
- /**
- * @see INameEnvironment
- */
- public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
- int last = compoundTypeName.length - 1;
- char[][] pkgName = new char[last][];
- System.arraycopy(compoundTypeName, 0, pkgName, 0, last);
- return findType(compoundTypeName[last], pkgName);
- }
-
- /**
- * @see INameEnvironment
- */
- public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
- return find(Util.toString(packageName), Util.toString(typeName));
+ if (sEntry != null && sEntry.isSource()) {
+ // only accept if really a compilation unit, not from binary
+ // If the type was unknown (as opposed to invalid), check to see if there are problems.
+ // If there was no principal structure and there are problems,
+ // then the compilation unit has tried to be compiled and it has failed,
+ // so don't try again.
+ // If the type was known, but needs to be recompiled because its principal structure was missing,
+ // then recompile it regardless of whether it has problems.
+ if (!isInvalid && (tsEntry == null && fState.getProblemReporter().hasProblems(sEntry))) {
+ return null;
+ }
+ CompilerCompilationUnit unit = new CompilerCompilationUnit(fState, sEntry, fNotifier);
+ compiling(unit);
+ return new NameEnvironmentAnswer(unit);
}
-
+ return null;
+}
+/**
+ * @see INameEnvironment
+ */
+public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
+ int last = compoundTypeName.length - 1;
+ char[][] pkgName = new char[last][];
+ System.arraycopy(compoundTypeName, 0, pkgName, 0, last);
+ return findType(compoundTypeName[last], pkgName);
+}
+/**
+ * @see INameEnvironment
+ */
+public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
+ return find(Util.toString(packageName), Util.toString(typeName));
+}
/**
* Return the default package or null.
*/
public IPackage getDefaultPackage() {
return fDefaultPackage;
}
-
/**
* Internal - Returns the package handle corresponding to the given package name.
*/
IPackage getPackageHandle(String packageName) {
-
+
if (fPackages == null) {
createPackageTable();
}
Object o = fPackages.get(packageName);
- if (o == null
- || !(o instanceof IPackage)) { // value is a string if it's only a package prefix
+ if (o == null || !(o instanceof IPackage)) { // value is a string if it's only a package prefix
return null;
}
return (IPackage) o;
}
-
- /**
- * @see INameEnvironment
- */
- public boolean isPackage(char[][] parentPackageName, char[] packageName) {
- checkCancel();
- if (fPackages == null) {
- createPackageTable();
- }
- String fullName = Util.toString(parentPackageName, packageName);
- return fPackages.containsKey(fullName);
+/**
+ * @see INameEnvironment
+ */
+public boolean isPackage(char[][] parentPackageName, char[] packageName) {
+ checkCancel();
+ if (fPackages == null) {
+ createPackageTable();
}
-
+ String fullName = Util.toString(parentPackageName, packageName);
+ return fPackages.containsKey(fullName);
+}
/**
* Set the default package or null. The compiler knows about at most one default package.
*/
public void setDefaultPackage(IPackage pkg) {
if (!Util.equalOrNull(fDefaultPackage, pkg)) {
- fPackages = null; // clear the table; it's reinitialized lazily
+ fPackages = null; // clear the table; it's reinitialized lazily
}
if (pkg.isStateSpecific()) {
- fDefaultPackage = (IPackage) pkg.nonStateSpecific();
+ fDefaultPackage = (IPackage)pkg.nonStateSpecific();
} else {
fDefaultPackage = pkg;
}
}
-
/**
* Set the notifier.
*/
public void setNotifier(BuildNotifier notifier) {
fNotifier = notifier;
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BuilderType.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BuilderType.java
index 881c46f4c4..0b9b003119 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BuilderType.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/BuilderType.java
@@ -28,194 +28,165 @@ public abstract class BuilderType {
*/
protected boolean fComputedHierarchy;
protected boolean fHasHierarchyChange;
- /**
- * Creates a new BuilderType.
- */
- public BuilderType(
- IncrementalImageBuilder builder,
- boolean hasComputedHierarchy,
- boolean hasHierarchyChange) {
- fBuilder = builder;
- fComputedHierarchy = hasComputedHierarchy;
- fHasHierarchyChange = hasHierarchyChange;
+/**
+ * Creates a new BuilderType.
+ */
+public BuilderType(IncrementalImageBuilder builder, boolean hasComputedHierarchy, boolean hasHierarchyChange) {
+ fBuilder = builder;
+ fComputedHierarchy = hasComputedHierarchy;
+ fHasHierarchyChange = hasHierarchyChange;
+}
+/**
+ * Computes the indictments for this type and adds them to the
+ * given indictment set.
+ */
+public abstract void computeIndictments(IndictmentSet indictments);
+/**
+ * Returns true if there is a change to the supertype hierarchy of this type.
+ * Needs to check the whole hierarchy because changes from higher up are -not-
+ * automatically propagated through the dependency graph.
+ */
+protected boolean detectHierarchyChange() {
+ /* If we've already done the work, return the result */
+ if (fComputedHierarchy) {
+ return fHasHierarchyChange;
+ }
+ fComputedHierarchy = true;
+ if (getNewTypeStructureEntry() == null) {
+ return fHasHierarchyChange = true;
+ }
+ IBinaryType oldType = getOldBinaryType();
+ if (oldType == null){
+ return fHasHierarchyChange = true;
}
+ IBinaryType newType = getNewBinaryType();
- /**
- * Computes the indictments for this type and adds them to the
- * given indictment set.
- */
- public abstract void computeIndictments(IndictmentSet indictments);
- /**
- * Returns true if there is a change to the supertype hierarchy of this type.
- * Needs to check the whole hierarchy because changes from higher up are -not-
- * automatically propagated through the dependency graph.
- */
- protected boolean detectHierarchyChange() {
- /* If we've already done the work, return the result */
- if (fComputedHierarchy) {
- return fHasHierarchyChange;
- }
- fComputedHierarchy = true;
- if (getNewTypeStructureEntry() == null) {
- return fHasHierarchyChange = true;
- }
- IBinaryType oldType = getOldBinaryType();
- if (oldType == null) {
+ /* check superclasses */
+ char[] oldSuper = oldType.getSuperclassName();
+ char[] newSuper = newType.getSuperclassName();
+ if (oldSuper == null ^ newSuper == null) {
+ return fHasHierarchyChange = true;
+ }
+ if (oldSuper != null && newSuper != null) {
+ if (!CharOperation.equals(oldSuper, newSuper)) {
return fHasHierarchyChange = true;
}
- IBinaryType newType = getNewBinaryType();
- /* check superclasses */
- char[] oldSuper = oldType.getSuperclassName();
- char[] newSuper = newType.getSuperclassName();
- if (oldSuper == null ^ newSuper == null) {
+ /* recurse on superclass */
+ BuilderType superBuilderType = fBuilder.getBuilderType(BinaryStructure.getType(getNewState(), getNewTypeStructureEntry(), oldSuper));
+ if (superBuilderType.detectHierarchyChange()) {
return fHasHierarchyChange = true;
}
- if (oldSuper != null && newSuper != null) {
- if (!CharOperation.equals(oldSuper, newSuper)) {
- return fHasHierarchyChange = true;
- }
+ }
+
+ /* check interfaces */
+ char[][] oldInterfaces = oldType.getInterfaceNames();
+ char[][] newInterfaces = newType.getInterfaceNames();
+ if (!CharOperation.equals(oldInterfaces, newInterfaces)) {
+ return fHasHierarchyChange = true;
+ }
- /* recurse on superclass */
- BuilderType superBuilderType =
- fBuilder.getBuilderType(
- BinaryStructure.getType(getNewState(), getNewTypeStructureEntry(), oldSuper));
+ /* recurse on interfaces */
+ if (oldInterfaces != null) {
+ for (int i = 0; i < oldInterfaces.length; i++) {
+ BuilderType superBuilderType = fBuilder.getBuilderType(BinaryStructure.getType(getNewState(), getNewTypeStructureEntry(), oldInterfaces[i]));
if (superBuilderType.detectHierarchyChange()) {
return fHasHierarchyChange = true;
}
}
-
- /* check interfaces */
- char[][] oldInterfaces = oldType.getInterfaceNames();
- char[][] newInterfaces = newType.getInterfaceNames();
- if (!CharOperation.equals(oldInterfaces, newInterfaces)) {
- return fHasHierarchyChange = true;
- }
-
- /* recurse on interfaces */
- if (oldInterfaces != null) {
- for (int i = 0; i < oldInterfaces.length; i++) {
- BuilderType superBuilderType =
- fBuilder.getBuilderType(
- BinaryStructure.getType(
- getNewState(),
- getNewTypeStructureEntry(),
- oldInterfaces[i]));
- if (superBuilderType.detectHierarchyChange()) {
- return fHasHierarchyChange = true;
- }
- }
- }
- return fHasHierarchyChange = false;
- }
-
- /**
- * Returns the binary type in the new state
- */
- public IBinaryType getNewBinaryType() {
- return getNewState().getBinaryType(getNewTypeStructureEntry());
- }
-
- /**
- * Returns the new state
- */
- protected StateImpl getNewState() {
- return (StateImpl) fBuilder.getNewState();
}
-
- /**
- * Returns the tsEntry in the new state
- */
- public abstract TypeStructureEntry getNewTypeStructureEntry();
- /**
- * Returns the binary type in the old state
- */
- public IBinaryType getOldBinaryType() {
- return getOldState().getBinaryType(getOldTypeStructureEntry());
+ return fHasHierarchyChange = false;
+}
+/**
+ * Returns the binary type in the new state
+ */
+public IBinaryType getNewBinaryType() {
+ return getNewState().getBinaryType(getNewTypeStructureEntry());
+}
+/**
+ * Returns the new state
+ */
+protected StateImpl getNewState() {
+ return (StateImpl)fBuilder.getNewState();
+}
+/**
+ * Returns the tsEntry in the new state
+ */
+public abstract TypeStructureEntry getNewTypeStructureEntry();
+/**
+ * Returns the binary type in the old state
+ */
+public IBinaryType getOldBinaryType() {
+ return getOldState().getBinaryType(getOldTypeStructureEntry());
+}
+/**
+ * Returns the old state
+ */
+protected StateImpl getOldState() {
+ return (StateImpl)fBuilder.getOldState();
+}
+/**
+ * Returns the tsEntry in the old state
+ */
+public abstract TypeStructureEntry getOldTypeStructureEntry();
+/**
+ * Returns the non state-specific type handle for the superclass
+ * of this type, or null if the superclass is null.
+ */
+public IType getSuperclass() {
+ char[] newSuper = getNewBinaryType().getSuperclassName();
+ return BinaryStructure.getType(getNewState(), getNewTypeStructureEntry(), newSuper);
+}
+/**
+ * Returns true if the given type is either a direct or indirect superclass
+ * of this type, otherwise returns false. This method must never be
+ * called on a type that has had a hierarchy change.
+ */
+public boolean hasSuperclass(IType type) {
+ IType supr = getSuperclass();
+ if (supr == null) {
+ return false;
}
-
- /**
- * Returns the old state
- */
- protected StateImpl getOldState() {
- return (StateImpl) fBuilder.getOldState();
+ if (supr.equals(type)) {
+ return true;
}
-
- /**
- * Returns the tsEntry in the old state
- */
- public abstract TypeStructureEntry getOldTypeStructureEntry();
- /**
- * Returns the non state-specific type handle for the superclass
- * of this type, or null if the superclass is null.
- */
- public IType getSuperclass() {
- char[] newSuper = getNewBinaryType().getSuperclassName();
- return BinaryStructure.getType(
- getNewState(),
- getNewTypeStructureEntry(),
- newSuper);
+ return fBuilder.getBuilderType(supr).hasSuperclass(type);
+}
+/**
+ * Returns true if the given type is either a direct or indirect superclass
+ * of this type, otherwise returns false. This method must never be
+ * called on a type that has had a hierarchy change.
+ */
+public boolean hasSuperInterface(IType type) {
+ char[][] interfaces = getNewBinaryType().getInterfaceNames();
+ if (interfaces == null) {
+ return false;
}
-
- /**
- * Returns true if the given type is either a direct or indirect superclass
- * of this type, otherwise returns false. This method must never be
- * called on a type that has had a hierarchy change.
- */
- public boolean hasSuperclass(IType type) {
- IType supr = getSuperclass();
- if (supr == null) {
- return false;
- }
- if (supr.equals(type)) {
+ for (int i = 0; i < interfaces.length; i++) {
+ IType supr = BinaryStructure.getType(getNewState(), getNewTypeStructureEntry(), interfaces[i]);
+ if (supr.equals(type) || fBuilder.getBuilderType(supr).hasSuperInterface(type)) {
return true;
}
- return fBuilder.getBuilderType(supr).hasSuperclass(type);
- }
-
- /**
- * Returns true if the given type is either a direct or indirect superclass
- * of this type, otherwise returns false. This method must never be
- * called on a type that has had a hierarchy change.
- */
- public boolean hasSuperInterface(IType type) {
- char[][] interfaces = getNewBinaryType().getInterfaceNames();
- if (interfaces == null) {
- return false;
- }
- for (int i = 0; i < interfaces.length; i++) {
- IType supr =
- BinaryStructure.getType(
- getNewState(),
- getNewTypeStructureEntry(),
- interfaces[i]);
- if (supr.equals(type)
- || fBuilder.getBuilderType(supr).hasSuperInterface(type)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Returns true if the given type is either a direct or indirect supertype
- * of this type, otherwise returns false. This method must never be
- * called on a type that has had a hierarchy change.
- */
- public boolean hasSuperType(IType type) {
- return hasSuperclass(type) || hasSuperInterface(type);
- }
-
- /**
- * Returns true if the given type was affected by the build
- * (either added, removed, or changed)
- */
- public boolean isAffected() {
- return true;
}
-
- /**
- * Sets the tsEntry in the new state
- */
- public abstract void setNewTypeStructureEntry(TypeStructureEntry newEntry);
+ return false;
+}
+/**
+ * Returns true if the given type is either a direct or indirect supertype
+ * of this type, otherwise returns false. This method must never be
+ * called on a type that has had a hierarchy change.
+ */
+public boolean hasSuperType(IType type) {
+ return hasSuperclass(type) || hasSuperInterface(type);
+}
+/**
+ * Returns true if the given type was affected by the build
+ * (either added, removed, or changed)
+ */
+public boolean isAffected() {
+ return true;
+}
+/**
+ * Sets the tsEntry in the new state
+ */
+public abstract void setNewTypeStructureEntry(TypeStructureEntry newEntry);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ClassOrInterfaceHandleImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ClassOrInterfaceHandleImpl.java
index b224e1108d..0bfb955141 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ClassOrInterfaceHandleImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ClassOrInterfaceHandleImpl.java
@@ -17,7 +17,6 @@ public class ClassOrInterfaceHandleImpl extends TypeImpl {
fIdentifier = name;
fOwner = owner;
}
-
/**
* Appends the signature for this type to the StringBuffer.
* If includeUnnamed is true, then the identifiers for unnamed packages
@@ -26,13 +25,12 @@ public class ClassOrInterfaceHandleImpl extends TypeImpl {
void appendSignature(StringBuffer sb, boolean includeUnnamed) {
sb.append('L');
- if (((PackageImpl) fOwner).appendSignature(sb, includeUnnamed)) {
+ if (((PackageImpl)fOwner).appendSignature(sb, includeUnnamed)) {
sb.append('.');
}
sb.append(getSimpleName());
sb.append(';');
}
-
/**
* Appends the VM signature of the type to the StringBuffer.
*/
@@ -45,82 +43,73 @@ public class ClassOrInterfaceHandleImpl extends TypeImpl {
sb.append(fIdentifier);
sb.append(';');
}
-
- /**
- * Return the current state implementation.
- * Must be functionally equivalent to (StateImpl) getDevelopmentContext().getCurrentState().
- */
- private StateImpl currentState() {
- StateImpl state = fOwner.fDevelopmentContext.fCurrentState;
- if (state != null) {
- return state;
- }
- throw new NotPresentException();
+/**
+ * Return the current state implementation.
+ * Must be functionally equivalent to (StateImpl) getDevelopmentContext().getCurrentState().
+ */
+private StateImpl currentState() {
+ StateImpl state = fOwner.fDevelopmentContext.fCurrentState;
+ if (state != null) {
+ return state;
}
-
+ throw new NotPresentException();
+}
/**
* Compares this object against the specified object.
* Returns true if the objects are the same.
*/
public boolean equals(Object o) {
- if (this == o)
- return true;
- if (!(o instanceof ClassOrInterfaceHandleImpl))
- return false;
+ if (this == o) return true;
+ if (!(o instanceof ClassOrInterfaceHandleImpl)) return false;
ClassOrInterfaceHandleImpl clazz = (ClassOrInterfaceHandleImpl) o;
- return this.fIdentifier.equals(clazz.fIdentifier)
- && this.fOwner.equals(clazz.fOwner);
- }
-
- /**
- * Returns a Constructor object that represents the specified
- * constructor of the class represented by this object.
- * The parameterTypes parameter is an array of Type objects that
- * identify the constructor's formal parameter types, in declared
- * order.
- * Returns null if this type does not represent a class or interface.
- * This is a handle-only method; the specified constructor may
- * or may not actually be present in the class or interface.
- */
- public IConstructor getConstructorHandle(IType[] parameterTypes) {
- return new ConstructorImpl(this, parameterTypes);
- }
-
- /**
- * @see IType#getCRC
- */
- public int getCRC() throws NotPresentException {
- return inCurrentState0().getCRC();
- }
-
- /**
- * Returns an array of Type objects representing all the classes
- * and interfaces declared as members of the class represented by
- * this object. This includes public, protected, default
- * (package) access, and private classes and interfaces declared
- * by the class, but excludes inherited classes and interfaces.
- * Returns an array of length 0 if the class declares no classes
- * or interfaces as members, or if this object represents an
- * array type or primitive type.
- * The resulting Types are in no particular order.
- */
- public IType[] getDeclaredClasses() throws NotPresentException {
- return nonStateSpecific(inCurrentState0().getDeclaredClasses());
- }
-
- /**
- * Returns an array of Constructor objects representing all the
- * constructors declared by the class represented by this
- * object. These are public, protected, default (package) access,
- * and private constructors. Returns an array of length 0 if this
- * object represents an interface, an array type or a primitive type.
- * The resulting Constructors are in no particular order.
- */
- public IConstructor[] getDeclaredConstructors() throws NotPresentException {
- return nonStateSpecific(inCurrentState0().getDeclaredConstructors());
- }
-
+ return this.fIdentifier.equals(clazz.fIdentifier) &&
+ this.fOwner.equals(clazz.fOwner);
+ }
+/**
+ * Returns a Constructor object that represents the specified
+ * constructor of the class represented by this object.
+ * The parameterTypes parameter is an array of Type objects that
+ * identify the constructor's formal parameter types, in declared
+ * order.
+ * Returns null if this type does not represent a class or interface.
+ * This is a handle-only method; the specified constructor may
+ * or may not actually be present in the class or interface.
+ */
+public IConstructor getConstructorHandle(IType[] parameterTypes) {
+ return new ConstructorImpl(this, parameterTypes);
+}
+/**
+ * @see IType#getCRC
+ */
+public int getCRC() throws NotPresentException {
+ return inCurrentState0().getCRC();
+}
+/**
+ * Returns an array of Type objects representing all the classes
+ * and interfaces declared as members of the class represented by
+ * this object. This includes public, protected, default
+ * (package) access, and private classes and interfaces declared
+ * by the class, but excludes inherited classes and interfaces.
+ * Returns an array of length 0 if the class declares no classes
+ * or interfaces as members, or if this object represents an
+ * array type or primitive type.
+ * The resulting Types are in no particular order.
+ */
+public IType[] getDeclaredClasses() throws NotPresentException {
+ return nonStateSpecific(inCurrentState0().getDeclaredClasses());
+}
+/**
+ * Returns an array of Constructor objects representing all the
+ * constructors declared by the class represented by this
+ * object. These are public, protected, default (package) access,
+ * and private constructors. Returns an array of length 0 if this
+ * object represents an interface, an array type or a primitive type.
+ * The resulting Constructors are in no particular order.
+ */
+public IConstructor[] getDeclaredConstructors() throws NotPresentException {
+ return nonStateSpecific(inCurrentState0().getDeclaredConstructors());
+}
/**
* Returns an array of Field objects representing all the fields
* declared by the class or interface represented by this
@@ -135,402 +124,364 @@ public class ClassOrInterfaceHandleImpl extends TypeImpl {
public IField[] getDeclaredFields() throws NotPresentException {
return nonStateSpecific(inCurrentState0().getDeclaredFields());
}
-
- /**
- * Returns an array of Method objects representing all the methods
- * declared by the class or interface represented by this
- * object. This includes public, protected, default (package)
- * access, and private methods, but excludes inherited
- * methods. Returns an array of length 0 if the class or interface
- * declares no methods, or if this object represents an
- * array type or primitive type.
- * The resulting Methods are in no particular order.
- */
- public IMethod[] getDeclaredMethods() throws NotPresentException {
- return nonStateSpecific(inCurrentState0().getDeclaredMethods());
- }
-
- /**
- * Returns the declared Java language modifiers, as specified in the declaration
- * of this class or interface, encoded in an integer.
- * The modifiers consist of the Java Virtual Machine's constants
- * for public, protected, private, and final; they should be decoded
- * using the methods of class Modifier.
- * The result may not correspond to the modifiers in the compiled
- * binary, since the compiler may change them (in particular,
- * for inner classes). The <code>getModifiers()</code>
- * method should be used if the compiled modifiers are needed.
- * Returns 0 if this type does not represent a class or interface.
- *
- * <p>The modifier encodings are defined in <em>The Java Virtual
- * Machine Specification</em>, table 4.1.
- */
- public int getDeclaredModifiers() throws NotPresentException {
- return inCurrentState0().getDeclaredModifiers();
- }
-
- /**
- * Returns the declared name of the class or interface represented
- * by this object, as a String.
- * The name is the simple, unqualified name used in the source code.
- * If this represents an inner class, it does not include the names
- * of any containing classes.
- * If this represents an anonymous class, it returns a String of length 0.
- * If this does not represent a class or interface, it returns
- * a String of length 0.
- */
- public String getDeclaredName() throws NotPresentException {
- return inCurrentState0().getDeclaredName();
- }
-
- /**
- * If the class or interface represented by this Type object is
- * a member of another class or interface (i.e. it is a nested class),
- * this returns the Type object representing the class or interface
- * of which it is a member (its <em>declaring class</em>).
- * If this class or interface is a local class, returns the Type
- * object representing the class containing the member in which
- * this class is declared.
- * Returns null if this class or interface is not a nested class,
- * or if this type does not represent a class or interface.
- */
- public IType getDeclaringClass() {
- IType result = inCurrentState0().getDeclaringClass();
- if (result == null)
- return null;
- return (IType) result.nonStateSpecific();
- }
-
- /**
- * Returns a Field object that represents the specified
- * member field of the class or interface represented
- * by this object. The name parameter is a String specifying
- * the simple name of the desired field.
- * Returns null if this type does not represent a class or interface.
- * This is a handle-only method; the specified field may
- * or may not actually be present in the class or interface.
- */
- public IField getFieldHandle(String name) {
- return new FieldImpl(this, name);
- }
-
- /**
- * Returns an array of Type objects representing the
- * classes in the given ImageContext which directly implement this interface.
- * A class is said to directly implement this interface if the interface
- * appears in the <code>implements</code> clause of the class's declaration.
- * Although all array types are considered to implement the <code>Cloneable</code>
- * interface, this method never returns array types, only class types.
- * Returns an array of length 0 if this object does not represent
- * an interface.
- * The resulting Types are in no particular order.
- * See <em>The Java Language Specification</em> section 8.1.4
- * for more details.
- */
- public IType[] getImplementingClasses(IImageContext imageContext)
- throws NotPresentException {
- return nonStateSpecific(inCurrentState0().getImplementingClasses(imageContext));
- }
-
- /**
- * Returns an array of Type objects representing the direct
- * superinterfaces of the class or interface represented by this object.
- * <p>
- * If this object represents a class, the return value is an array
- * containing objects representing all interfaces directly implemented by the
- * class. The order of the interface objects in the array corresponds
- * to the order of the interface names in the <code>implements</code>
- * clause of the declaration of the class represented by this object.
- * <p>
- * If this object represents an interface, the array contains
- * objects representing all interfaces directly extended by the interface.
- * The order of the interface objects in the array corresponds to the
- * order of the interface names in the <code>extends</code> clause of
- * the declaration of the interface represented by this object.
- * <p>
- * If the class or interface implements no interfaces, or if this
- * object represents neither a class nor an interface, this method
- * returns an array of length 0.
- *
- * See <em>The Java Language Specification</em> sections 8.1.4 and 9.1.3
- * for more details.
- */
- public IType[] getInterfaces() throws NotPresentException {
- IType[] interfaces = inCurrentState0().getInterfaces();
- int len = interfaces.length;
- if (len == 0) {
- return interfaces;
- }
-
- IType[] results = new IType[len];
- for (int i = 0; i < len; i++) {
- results[i] = (IType) interfaces[i].nonStateSpecific();
- }
- return results;
- }
-
+/**
+ * Returns an array of Method objects representing all the methods
+ * declared by the class or interface represented by this
+ * object. This includes public, protected, default (package)
+ * access, and private methods, but excludes inherited
+ * methods. Returns an array of length 0 if the class or interface
+ * declares no methods, or if this object represents an
+ * array type or primitive type.
+ * The resulting Methods are in no particular order.
+ */
+public IMethod[] getDeclaredMethods() throws NotPresentException {
+ return nonStateSpecific(inCurrentState0().getDeclaredMethods());
+}
+/**
+ * Returns the declared Java language modifiers, as specified in the declaration
+ * of this class or interface, encoded in an integer.
+ * The modifiers consist of the Java Virtual Machine's constants
+ * for public, protected, private, and final; they should be decoded
+ * using the methods of class Modifier.
+ * The result may not correspond to the modifiers in the compiled
+ * binary, since the compiler may change them (in particular,
+ * for inner classes). The <code>getModifiers()</code>
+ * method should be used if the compiled modifiers are needed.
+ * Returns 0 if this type does not represent a class or interface.
+ *
+ * <p>The modifier encodings are defined in <em>The Java Virtual
+ * Machine Specification</em>, table 4.1.
+ */
+public int getDeclaredModifiers() throws NotPresentException {
+ return inCurrentState0().getDeclaredModifiers();
+}
+/**
+ * Returns the declared name of the class or interface represented
+ * by this object, as a String.
+ * The name is the simple, unqualified name used in the source code.
+ * If this represents an inner class, it does not include the names
+ * of any containing classes.
+ * If this represents an anonymous class, it returns a String of length 0.
+ * If this does not represent a class or interface, it returns
+ * a String of length 0.
+ */
+public String getDeclaredName() throws NotPresentException {
+ return inCurrentState0().getDeclaredName();
+}
+/**
+ * If the class or interface represented by this Type object is
+ * a member of another class or interface (i.e. it is a nested class),
+ * this returns the Type object representing the class or interface
+ * of which it is a member (its <em>declaring class</em>).
+ * If this class or interface is a local class, returns the Type
+ * object representing the class containing the member in which
+ * this class is declared.
+ * Returns null if this class or interface is not a nested class,
+ * or if this type does not represent a class or interface.
+ */
+public IType getDeclaringClass() {
+ IType result = inCurrentState0().getDeclaringClass();
+ if (result == null)
+ return null;
+ return (IType)result.nonStateSpecific();
+}
+/**
+ * Returns a Field object that represents the specified
+ * member field of the class or interface represented
+ * by this object. The name parameter is a String specifying
+ * the simple name of the desired field.
+ * Returns null if this type does not represent a class or interface.
+ * This is a handle-only method; the specified field may
+ * or may not actually be present in the class or interface.
+ */
+public IField getFieldHandle(String name) {
+ return new FieldImpl(this, name);
+}
+/**
+ * Returns an array of Type objects representing the
+ * classes in the given ImageContext which directly implement this interface.
+ * A class is said to directly implement this interface if the interface
+ * appears in the <code>implements</code> clause of the class's declaration.
+ * Although all array types are considered to implement the <code>Cloneable</code>
+ * interface, this method never returns array types, only class types.
+ * Returns an array of length 0 if this object does not represent
+ * an interface.
+ * The resulting Types are in no particular order.
+ * See <em>The Java Language Specification</em> section 8.1.4
+ * for more details.
+ */
+public IType[] getImplementingClasses(IImageContext imageContext) throws NotPresentException {
+ return nonStateSpecific(inCurrentState0().getImplementingClasses(imageContext));
+}
+/**
+ * Returns an array of Type objects representing the direct
+ * superinterfaces of the class or interface represented by this object.
+ * <p>
+ * If this object represents a class, the return value is an array
+ * containing objects representing all interfaces directly implemented by the
+ * class. The order of the interface objects in the array corresponds
+ * to the order of the interface names in the <code>implements</code>
+ * clause of the declaration of the class represented by this object.
+ * <p>
+ * If this object represents an interface, the array contains
+ * objects representing all interfaces directly extended by the interface.
+ * The order of the interface objects in the array corresponds to the
+ * order of the interface names in the <code>extends</code> clause of
+ * the declaration of the interface represented by this object.
+ * <p>
+ * If the class or interface implements no interfaces, or if this
+ * object represents neither a class nor an interface, this method
+ * returns an array of length 0.
+ *
+ * See <em>The Java Language Specification</em> sections 8.1.4 and 9.1.3
+ * for more details.
+ */
+public IType[] getInterfaces() throws NotPresentException {
+ IType[] interfaces = inCurrentState0().getInterfaces();
+ int len = interfaces.length;
+ if (len == 0) {
+ return interfaces;
+ }
+
+ IType[] results = new IType[len];
+ for (int i = 0; i < len; i++) {
+ results[i] = (IType)interfaces[i].nonStateSpecific();
+ }
+ return results;
+}
public JavaDevelopmentContextImpl getInternalDC() {
return fOwner.getInternalDC();
}
-
- /**
- * Returns a Method object that represents the specified
- * member method of the class or interface represented
- * by this object. The name parameter is a String specifying the
- * simple name the desired method, and the parameterTypes
- * parameter is an array of Type objects that identify the
- * method's formal parameter types, in declared order.
- * Returns null if this type does not represent a class or interface.
- * This is a handle-only method; the specified method may
- * or may not actually be present in the class or interface.
- */
- public IMethod getMethodHandle(String name, IType[] parameterTypes) {
- return new MethodImpl(this, name, parameterTypes);
- }
-
- /**
- * Returns the compiled Java language modifiers for this class or
- * interface, encoded in an integer. The modifiers consist of the
- * Java Virtual Machine's constants for public, protected,
- * private, and final; they should be decoded using the
- * methods of class Modifier.
- * The result may not correspond to the modifiers as declared in
- * the source, since the compiler may change them (in particular,
- * for inner classes). The <code>getDeclaredModifiers()</code>
- * method should be used if the original modifiers are needed.
- * Returns 0 if this type does not represent a class or interface.
- */
- public int getModifiers() throws NotPresentException {
- return inCurrentState0().getModifiers();
- }
-
- /**
- * getName method comment.
- */
- public String getName() {
- if (fOwner.isUnnamed())
- return fIdentifier;
- return Util.concat(fOwner.getName(), '.', fIdentifier);
- }
-
- /**
- * Returns the Package in which this class or interface is declared.
- * Returns null if this object represents a primitive type or array type.
- * This is a handle-only method.
- */
- public IPackage getPackage() {
- return fOwner;
- }
-
- /**
- * getSimpleName method comment.
- */
- public String getSimpleName() {
+/**
+ * Returns a Method object that represents the specified
+ * member method of the class or interface represented
+ * by this object. The name parameter is a String specifying the
+ * simple name the desired method, and the parameterTypes
+ * parameter is an array of Type objects that identify the
+ * method's formal parameter types, in declared order.
+ * Returns null if this type does not represent a class or interface.
+ * This is a handle-only method; the specified method may
+ * or may not actually be present in the class or interface.
+ */
+public IMethod getMethodHandle(String name, IType[] parameterTypes) {
+ return new MethodImpl(this, name, parameterTypes);
+}
+/**
+ * Returns the compiled Java language modifiers for this class or
+ * interface, encoded in an integer. The modifiers consist of the
+ * Java Virtual Machine's constants for public, protected,
+ * private, and final; they should be decoded using the
+ * methods of class Modifier.
+ * The result may not correspond to the modifiers as declared in
+ * the source, since the compiler may change them (in particular,
+ * for inner classes). The <code>getDeclaredModifiers()</code>
+ * method should be used if the original modifiers are needed.
+ * Returns 0 if this type does not represent a class or interface.
+ */
+public int getModifiers() throws NotPresentException {
+ return inCurrentState0().getModifiers();
+}
+/**
+ * getName method comment.
+ */
+public String getName() {
+ if (fOwner.isUnnamed())
return fIdentifier;
+ return Util.concat(fOwner.getName(), '.', fIdentifier);
+}
+/**
+ * Returns the Package in which this class or interface is declared.
+ * Returns null if this object represents a primitive type or array type.
+ * This is a handle-only method.
+ */
+public IPackage getPackage() {
+ return fOwner;
+}
+/**
+ * getSimpleName method comment.
+ */
+public String getSimpleName() {
+ return fIdentifier;
+}
+/**
+ * Returns a SourceFragment describing the fragment of source
+ * from which this member is derived.
+ * Returns null if this type represent a primitive type or an
+ * array type, or if this type is not derived directly from source
+ * (e.g. a fictional type, which is created by the image builder).
+ */
+public ISourceFragment getSourceFragment() throws NotPresentException {
+ return inCurrentState0().getSourceFragment();
+}
+/**
+ * Returns an array of Type objects representing the
+ * classes in the given ImageContext which are direct subclasses of
+ * this class.
+ * Returns an array of length 0 if this object does not represent
+ * a class.
+ * The resulting Types are in no particular order.
+ * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
+ * for more details.
+ */
+public IType[] getSubclasses(IImageContext imageContext) throws NotPresentException {
+ return nonStateSpecific(inCurrentState0().getSubclasses(imageContext));
+}
+/**
+ * Returns an array of Type objects representing the
+ * interfaces in the given ImageContext which are direct subinterfaces of
+ * this interface.
+ * Returns an array of length 0 if this object does not represent
+ * an interface.
+ * The resulting Types are in no particular order.
+ * See <em>The Java Language Specification</em> section 9.1.3
+ * for more details.
+ */
+public IType[] getSubinterfaces(IImageContext imageContext) throws NotPresentException {
+ return nonStateSpecific(inCurrentState0().getSubinterfaces(imageContext));
+}
+/**
+ * If this object represents any class other than the class
+ * <code>java.lang.Object</code>, then the object that represents
+ * the direct superclass of that class is returned.
+ * <p>
+ * If this object represents the class <code>java.lang.Object</code>
+ * or this object represents an interface or a primitive type,
+ * <code>null</code> is returned.
+ * If this object represents an array type, then the Type that represents
+ * class <code>java.lang.Object</code> is returned.
+ * <p>
+ * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
+ * for more details.
+ */
+public IType getSuperclass() throws NotPresentException {
+ IType supr = inCurrentState0().getSuperclass();
+ if (supr != null) {
+ return (IType)supr.nonStateSpecific();
}
-
- /**
- * Returns a SourceFragment describing the fragment of source
- * from which this member is derived.
- * Returns null if this type represent a primitive type or an
- * array type, or if this type is not derived directly from source
- * (e.g. a fictional type, which is created by the image builder).
- */
- public ISourceFragment getSourceFragment() throws NotPresentException {
- return inCurrentState0().getSourceFragment();
- }
-
- /**
- * Returns an array of Type objects representing the
- * classes in the given ImageContext which are direct subclasses of
- * this class.
- * Returns an array of length 0 if this object does not represent
- * a class.
- * The resulting Types are in no particular order.
- * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
- * for more details.
- */
- public IType[] getSubclasses(IImageContext imageContext)
- throws NotPresentException {
- return nonStateSpecific(inCurrentState0().getSubclasses(imageContext));
- }
-
- /**
- * Returns an array of Type objects representing the
- * interfaces in the given ImageContext which are direct subinterfaces of
- * this interface.
- * Returns an array of length 0 if this object does not represent
- * an interface.
- * The resulting Types are in no particular order.
- * See <em>The Java Language Specification</em> section 9.1.3
- * for more details.
- */
- public IType[] getSubinterfaces(IImageContext imageContext)
- throws NotPresentException {
- return nonStateSpecific(inCurrentState0().getSubinterfaces(imageContext));
- }
-
- /**
- * If this object represents any class other than the class
- * <code>java.lang.Object</code>, then the object that represents
- * the direct superclass of that class is returned.
- * <p>
- * If this object represents the class <code>java.lang.Object</code>
- * or this object represents an interface or a primitive type,
- * <code>null</code> is returned.
- * If this object represents an array type, then the Type that represents
- * class <code>java.lang.Object</code> is returned.
- * <p>
- * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
- * for more details.
- */
- public IType getSuperclass() throws NotPresentException {
- IType supr = inCurrentState0().getSuperclass();
- if (supr != null) {
- return (IType) supr.nonStateSpecific();
- }
- return supr;
- }
-
+ return supr;
+}
/**
* Returns a consistent hash code for this object
*/
public int hashCode() {
return fIdentifier.hashCode();
}
-
- private ClassOrInterfaceHandleImplSWH inCurrentState0() {
- return new ClassOrInterfaceHandleImplSWH(
- fOwner.fDevelopmentContext.fCurrentState,
- this);
- }
-
- /**
- * Returns a state specific version of this handle in the given state.
- */
- public IHandle inState(IState s)
- throws org.eclipse.jdt.internal.core.builder.StateSpecificException {
-
- return new ClassOrInterfaceHandleImplSWH((StateImpl) s, this);
- }
-
- /**
- * Returns true if this object represents an anonymous class,
- * false otherwise.
- * An anonymous class is a local inner class with no declared name.
- * <p>
- * See the <em>Java Inner Classes Specification</em> for more details.
- */
- public boolean isAnonymous() throws NotPresentException {
- return inCurrentState0().isAnonymous();
- }
-
- /**
- * Return true if this represents a binary class or interface, false otherwise.
- * A binary type is one which is in .class file format in the source tree.
- * Returns false if this represents a primitive type or an array type.
- */
- public boolean isBinary() throws NotPresentException {
- return inCurrentState0().isBinary();
- }
-
- /**
- * Determines if this object represents a class type.
- * This returns false if this object represents an interface,
- * an array type, or a primitive type.
- */
- public boolean isClass() throws NotPresentException {
- return inCurrentState0().isClass();
- }
-
- /**
- * Returns true if the type represented by this object is
- * deprecated, false otherwise. A deprecated object is one that
- * has a deprecated tag in its doc comment.
- * Returns false if this represents a primitive type or an array type.
- */
- public boolean isDeprecated() throws NotPresentException {
- return inCurrentState0().isDeprecated();
- }
-
- /**
- * Returns true if this object represents an inner class or interface,
- * false otherwise.
- * An inner class is one which can only be created in the context of
- * an instance of its outer class. This does not include package member
- * classes or other top-level classes. Such a class cannot be static.
- * <p>
- * See the <em>Java Inner Classes Specification</em> for more details.
- */
- public boolean isInnerClass() throws NotPresentException {
- return inCurrentState0().isInnerClass();
- }
-
- /**
- * Determines if this object represents an interface type.
- * This returns false if this object represents a class,
- * an array type, or a primitive type.
- */
- public boolean isInterface() throws NotPresentException {
- return inCurrentState0().isInterface();
- }
-
- /**
- * Returns true if this object represents a local inner class,
- * false otherwise.
- * A local inner class is an inner class which is defined in the body of
- * a method or other block, not as a class field.
- * <p>
- * See the <em>Java Inner Classes Specification</em> for more details.
- */
- public boolean isLocal() throws NotPresentException {
- return inCurrentState0().isLocal();
- }
-
- /**
- * Returns true if this object represents a class or interface
- * which is declared as a package member (i.e. a 'normal' class
- * as in JDK 1.02). Returns false otherwise.
- * In particular, this method returns false if this object represents a
- * top-level class which is declared as a member of a class.
- * For the sake of consistent terminology, a class which is
- * not a package member is considered 'nested', whether or not
- * it is top-level.
- * <p>
- * See the <em>Java Inner Classes Specification</em> for more details.
- */
- public boolean isPackageMember() throws NotPresentException {
- return inCurrentState0().isPackageMember();
- }
-
- /**
- * Returns true if the type represented by this object is
- * synthetic, false otherwise. A synthetic object is one that
- * was invented by the compiler, but was not declared in the source.
- * See <em>The Inner Classes Specification</em>.
- * A synthetic object is not the same as a fictitious object.
- */
- public boolean isSynthetic() throws NotPresentException {
- return inCurrentState0().isSynthetic();
- }
-
- /**
- * Returns true if this object represents a top-level class or interface,
- * false otherwise.
- * A top-level class is declared either as a package member or as a
- * static member of another top-level class. Unlike inner classes,
- * instances of top-level classes are not created in the context of
- * another object.
- * Given the appropriate access modifiers, a top-level class can be
- * referred to directly by a qualified name.
- * <p>
- * See the <em>Java Inner Classes Specification</em> for more details.
- */
- public boolean isTopLevel()
- throws org.eclipse.jdt.internal.core.builder.NotPresentException {
- return inCurrentState0().isTopLevel();
- }
-
+private ClassOrInterfaceHandleImplSWH inCurrentState0() {
+ return new ClassOrInterfaceHandleImplSWH(fOwner.fDevelopmentContext.fCurrentState, this);
+}
+/**
+ * Returns a state specific version of this handle in the given state.
+ */
+public IHandle inState(IState s) throws org.eclipse.jdt.internal.core.builder.StateSpecificException {
+
+ return new ClassOrInterfaceHandleImplSWH((StateImpl) s, this);
+}
+/**
+ * Returns true if this object represents an anonymous class,
+ * false otherwise.
+ * An anonymous class is a local inner class with no declared name.
+ * <p>
+ * See the <em>Java Inner Classes Specification</em> for more details.
+ */
+public boolean isAnonymous() throws NotPresentException {
+ return inCurrentState0().isAnonymous();
+}
+/**
+ * Return true if this represents a binary class or interface, false otherwise.
+ * A binary type is one which is in .class file format in the source tree.
+ * Returns false if this represents a primitive type or an array type.
+ */
+public boolean isBinary() throws NotPresentException {
+ return inCurrentState0().isBinary();
+}
+/**
+ * Determines if this object represents a class type.
+ * This returns false if this object represents an interface,
+ * an array type, or a primitive type.
+ */
+public boolean isClass() throws NotPresentException {
+ return inCurrentState0().isClass();
+}
+/**
+ * Returns true if the type represented by this object is
+ * deprecated, false otherwise. A deprecated object is one that
+ * has a deprecated tag in its doc comment.
+ * Returns false if this represents a primitive type or an array type.
+ */
+public boolean isDeprecated() throws NotPresentException {
+ return inCurrentState0().isDeprecated();
+}
+/**
+ * Returns true if this object represents an inner class or interface,
+ * false otherwise.
+ * An inner class is one which can only be created in the context of
+ * an instance of its outer class. This does not include package member
+ * classes or other top-level classes. Such a class cannot be static.
+ * <p>
+ * See the <em>Java Inner Classes Specification</em> for more details.
+ */
+public boolean isInnerClass() throws NotPresentException {
+ return inCurrentState0().isInnerClass();
+}
+/**
+ * Determines if this object represents an interface type.
+ * This returns false if this object represents a class,
+ * an array type, or a primitive type.
+ */
+public boolean isInterface() throws NotPresentException {
+ return inCurrentState0().isInterface();
+}
+/**
+ * Returns true if this object represents a local inner class,
+ * false otherwise.
+ * A local inner class is an inner class which is defined in the body of
+ * a method or other block, not as a class field.
+ * <p>
+ * See the <em>Java Inner Classes Specification</em> for more details.
+ */
+public boolean isLocal() throws NotPresentException {
+ return inCurrentState0().isLocal();
+}
+/**
+ * Returns true if this object represents a class or interface
+ * which is declared as a package member (i.e. a 'normal' class
+ * as in JDK 1.02). Returns false otherwise.
+ * In particular, this method returns false if this object represents a
+ * top-level class which is declared as a member of a class.
+ * For the sake of consistent terminology, a class which is
+ * not a package member is considered 'nested', whether or not
+ * it is top-level.
+ * <p>
+ * See the <em>Java Inner Classes Specification</em> for more details.
+ */
+public boolean isPackageMember() throws NotPresentException {
+ return inCurrentState0().isPackageMember();
+}
+/**
+ * Returns true if the type represented by this object is
+ * synthetic, false otherwise. A synthetic object is one that
+ * was invented by the compiler, but was not declared in the source.
+ * See <em>The Inner Classes Specification</em>.
+ * A synthetic object is not the same as a fictitious object.
+ */
+public boolean isSynthetic() throws NotPresentException {
+ return inCurrentState0().isSynthetic();
+}
+/**
+ * Returns true if this object represents a top-level class or interface,
+ * false otherwise.
+ * A top-level class is declared either as a package member or as a
+ * static member of another top-level class. Unlike inner classes,
+ * instances of top-level classes are not created in the context of
+ * another object.
+ * Given the appropriate access modifiers, a top-level class can be
+ * referred to directly by a qualified name.
+ * <p>
+ * See the <em>Java Inner Classes Specification</em> for more details.
+ */
+public boolean isTopLevel() throws org.eclipse.jdt.internal.core.builder.NotPresentException {
+ return inCurrentState0().isTopLevel();
+}
/**
* Returns the source name, estimated from looking at the class name.
* The source name does not include any enclosing types.
@@ -550,5 +501,4 @@ public class ClassOrInterfaceHandleImpl extends TypeImpl {
return simpleName;
}
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ClassOrInterfaceHandleImplSWH.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ClassOrInterfaceHandleImplSWH.java
index f1d9ffcde0..6f5d52fc72 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ClassOrInterfaceHandleImplSWH.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ClassOrInterfaceHandleImplSWH.java
@@ -14,483 +14,432 @@ public class ClassOrInterfaceHandleImplSWH extends TypeImplSWH {
/**
* Creates a new method handle in the given state
*/
- ClassOrInterfaceHandleImplSWH(
- StateImpl state,
- ClassOrInterfaceHandleImpl handle)
- throws NotPresentException {
- if (state == null)
- throw new NotPresentException();
+ ClassOrInterfaceHandleImplSWH(StateImpl state, ClassOrInterfaceHandleImpl handle) throws NotPresentException {
+ if (state == null) throw new NotPresentException();
fState = state;
fHandle = handle;
}
-
- /**
- * Returns the IBinaryType for this class or interface.
- * Throws a not present exception if the type is not present.
- */
- protected IBinaryType getBinaryType() throws NotPresentException {
- return fState.getBinaryType(getTypeStructureEntry());
- }
-
- /**
- * Returns the IBinaryType for this class or interface.
- */
- protected IBinaryType getBinaryType(TypeStructureEntry tsEntry) {
- return fState.getBinaryType(tsEntry);
- }
-
- /**
- * Returns a Constructor object that represents the specified
- * constructor of the class represented by this object.
- * The parameterTypes parameter is an array of Type objects that
- * identify the constructor's formal parameter types, in declared
- * order.
- * Returns null if this type does not represent a class or interface.
- * This is a handle-only method; the specified constructor may
- * or may not actually be present in the class or interface.
- */
- public IConstructor getConstructorHandle(IType[] parameterTypes) {
- IType[] params = new IType[parameterTypes.length];
- for (int i = 0; i < params.length; i++)
- params[i] = (IType) parameterTypes[i].nonStateSpecific();
- return (IConstructor) fHandle.getConstructorHandle(params).inState(fState);
- }
-
- /**
- * @see IType#getCRC
- */
- public int getCRC() throws NotPresentException {
- TypeStructureEntry tsEntry = getTypeStructureEntry();
- int crc = tsEntry.getCRC32();
- if (crc == 0) {
- /* If it's a class file, then read the binary from the workspace and compute the CRC */
- if (tsEntry.isBinary()) {
- byte[] binary = fState.getElementContentBytes(tsEntry.getSourceEntry());
- crc = fState.getBinaryOutput().crc32(binary);
- tsEntry.setCRC32(crc);
- }
+/**
+ * Returns the IBinaryType for this class or interface.
+ * Throws a not present exception if the type is not present.
+ */
+protected IBinaryType getBinaryType() throws NotPresentException {
+ return fState.getBinaryType(getTypeStructureEntry());
+}
+/**
+ * Returns the IBinaryType for this class or interface.
+ */
+protected IBinaryType getBinaryType(TypeStructureEntry tsEntry) {
+ return fState.getBinaryType(tsEntry);
+}
+/**
+ * Returns a Constructor object that represents the specified
+ * constructor of the class represented by this object.
+ * The parameterTypes parameter is an array of Type objects that
+ * identify the constructor's formal parameter types, in declared
+ * order.
+ * Returns null if this type does not represent a class or interface.
+ * This is a handle-only method; the specified constructor may
+ * or may not actually be present in the class or interface.
+ */
+public IConstructor getConstructorHandle(IType[] parameterTypes) {
+ IType[] params = new IType[parameterTypes.length];
+ for (int i = 0; i < params.length; i++)
+ params[i] = (IType)parameterTypes[i].nonStateSpecific();
+ return (IConstructor) fHandle.getConstructorHandle(params).inState(fState);
+}
+/**
+ * @see IType#getCRC
+ */
+public int getCRC() throws NotPresentException {
+ TypeStructureEntry tsEntry = getTypeStructureEntry();
+ int crc = tsEntry.getCRC32();
+ if (crc == 0) {
+ /* If it's a class file, then read the binary from the workspace and compute the CRC */
+ if (tsEntry.isBinary()) {
+ byte[] binary = fState.getElementContentBytes(tsEntry.getSourceEntry());
+ crc = fState.getBinaryOutput().crc32(binary);
+ tsEntry.setCRC32(crc);
}
- return crc;
}
-
- /**
- * Returns an array of Type objects representing all the classes
- * and interfaces declared as members of the class represented by
- * this object. This includes public, protected, default
- * (package) access, and private classes and interfaces declared
- * by the class, but excludes inherited classes and interfaces.
- * Returns an array of length 0 if the class declares no classes
- * or interfaces as members, or if this object represents an
- * array type or primitive type.
- * The resulting Types are in no particular order.
- */
- public IType[] getDeclaredClasses() throws NotPresentException {
- TypeStructureEntry tsEntry = getTypeStructureEntry();
- IBinaryType binaryType = getBinaryType(tsEntry);
- char[][] names = BinaryStructure.getInnerTypes(binaryType);
- int len = names.length;
- IType[] types = new IType[len];
- int count = 0;
- for (int i = 0; i < len; i++) {
- IType type =
- (IType) fState
- .typeNameToHandle(tsEntry, BinaryStructure.convertTypeName(names[i]))
- .inState(fState);
- if (!type.isLocal()) {
- types[count++] = type;
- }
- }
- if (count < len) {
- System.arraycopy(types, 0, types = new IType[count], 0, count);
+ return crc;
+}
+/**
+ * Returns an array of Type objects representing all the classes
+ * and interfaces declared as members of the class represented by
+ * this object. This includes public, protected, default
+ * (package) access, and private classes and interfaces declared
+ * by the class, but excludes inherited classes and interfaces.
+ * Returns an array of length 0 if the class declares no classes
+ * or interfaces as members, or if this object represents an
+ * array type or primitive type.
+ * The resulting Types are in no particular order.
+ */
+public IType[] getDeclaredClasses() throws NotPresentException {
+ TypeStructureEntry tsEntry = getTypeStructureEntry();
+ IBinaryType binaryType = getBinaryType(tsEntry);
+ char[][] names = BinaryStructure.getInnerTypes(binaryType);
+ int len = names.length;
+ IType[] types = new IType[len];
+ int count = 0;
+ for (int i = 0; i < len; i++) {
+ IType type = (IType) fState.typeNameToHandle(tsEntry, BinaryStructure.convertTypeName(names[i])).inState(fState);
+ if (!type.isLocal()) {
+ types[count++] = type;
}
- return types;
}
-
- /**
- * Returns an array of Constructor objects representing all the
- * constructors declared by the class represented by this
- * object. These are public, protected, default (package) access,
- * and private constructors. Returns an array of length 0 if this
- * object represents an interface, an array type or a primitive type.
- * The resulting Constructors are in no particular order.
- */
- public IConstructor[] getDeclaredConstructors() throws NotPresentException {
- IBinaryMethod[] methods = getBinaryType().getMethods();
- if (methods == null)
- return new IConstructor[0];
-
- // count constructors
- int n = 0;
- for (int i = 0; i < methods.length; i++) {
- if (methods[i].isConstructor()) {
- ++n;
- }
- }
- IConstructor[] result = new IConstructor[n];
- int k = 0;
- for (int i = 0; i < methods.length; i++) {
- if (methods[i].isConstructor()) {
- result[k++] =
- (IConstructor) BinaryStructure
- .getConstructorHandle(methods[i], fHandle)
- .inState(fState);
- }
- }
- return result;
+ if (count < len) {
+ System.arraycopy(types, 0, types = new IType[count], 0, count);
}
-
- /**
- * Returns an array of Field objects representing all the fields
- * declared by the class or interface represented by this
- * object. This includes public, protected, default (package)
- * access, and private fields, but excludes inherited
- * fields. Returns an array of length 0 if the class or interface
- * declares no fields, or if this object represents a
- * primitive type or an array type (the implicit <code>length</code>
- * field of array types is not considered to be a declared field).
- * The resulting Fields are in no particular order.
- */
- public IField[] getDeclaredFields() throws NotPresentException {
- IBinaryField[] fields = getBinaryType().getFields();
- if (fields == null)
- return new IField[0];
- IField[] handles = new IField[fields.length];
- for (int i = 0; i < fields.length; i++) {
- handles[i] =
- (IField) BinaryStructure.getFieldHandle(fields[i], fHandle).inState(fState);
+ return types;
+}
+/**
+ * Returns an array of Constructor objects representing all the
+ * constructors declared by the class represented by this
+ * object. These are public, protected, default (package) access,
+ * and private constructors. Returns an array of length 0 if this
+ * object represents an interface, an array type or a primitive type.
+ * The resulting Constructors are in no particular order.
+ */
+public IConstructor[] getDeclaredConstructors() throws NotPresentException {
+ IBinaryMethod[] methods = getBinaryType().getMethods();
+ if (methods == null)
+ return new IConstructor[0];
+
+ // count constructors
+ int n = 0;
+ for (int i = 0; i < methods.length; i++) {
+ if (methods[i].isConstructor()) {
+ ++n;
}
- return handles;
}
-
- /**
- * Returns an array of Method objects representing all the methods
- * declared by the class or interface represented by this
- * object. This includes public, protected, default (package)
- * access, and private methods, but excludes inherited
- * methods. Returns an array of length 0 if the class or interface
- * declares no methods, or if this object represents an
- * array type or primitive type.
- * The resulting Methods are in no particular order.
- */
- public IMethod[] getDeclaredMethods() throws NotPresentException {
- IBinaryMethod[] methods = getBinaryType().getMethods();
- if (methods == null)
- return new IMethod[0];
-
- // count methods
- int n = 0;
- for (int i = 0; i < methods.length; i++) {
- if (!methods[i].isConstructor()
- && methods[i].getSelector()[0] != '<') { // TBD: need IBinaryMethod.isClinit()
- ++n;
- }
+ IConstructor[] result = new IConstructor[n];
+ int k = 0;
+ for (int i = 0; i < methods.length; i++) {
+ if (methods[i].isConstructor()) {
+ result[k++] = (IConstructor) BinaryStructure.getConstructorHandle(methods[i], fHandle).inState(fState);
}
- IMethod[] result = new IMethod[n];
- int k = 0;
- for (int i = 0; i < methods.length; i++) {
- if (!methods[i].isConstructor()
- && methods[i].getSelector()[0] != '<') { // TBD: need IBinaryMethod.isClinit()
- result[k++] =
- (IMethod) BinaryStructure.getMethodHandle(methods[i], fHandle).inState(fState);
- }
- }
- return result;
- }
-
- /**
- * Returns the declared Java language modifiers, as specified in the declaration
- * of this class or interface, encoded in an integer.
- * The modifiers consist of the Java Virtual Machine's constants
- * for public, protected, private, and final; they should be decoded
- * using the methods of class Modifier.
- * The result may not correspond to the modifiers in the compiled
- * binary, since the compiler may change them (in particular,
- * for inner classes). The <code>getModifiers()</code>
- * method should be used if the compiled modifiers are needed.
- * Returns 0 if this type does not represent a class or interface.
- *
- * <p>The modifier encodings are defined in <em>The Java Virtual
- * Machine Specification</em>, table 4.1.
- */
- public int getDeclaredModifiers() throws NotPresentException {
-
- return getModifiers();
}
-
- /**
- * Returns the declared name of the class or interface represented
- * by this object, as a String.
- * The name is the simple, unqualified name used in the source code.
- * If this represents an inner class, it does not include the names
- * of any containing classes.
- * If this represents an anonymous class, it returns a String of length 0.
- * If this does not represent a class or interface, it returns
- * a String of length 0.
- */
- public String getDeclaredName() throws NotPresentException {
-
- if (isAnonymous()) {
- return "";
+ return result;
+}
+/**
+ * Returns an array of Field objects representing all the fields
+ * declared by the class or interface represented by this
+ * object. This includes public, protected, default (package)
+ * access, and private fields, but excludes inherited
+ * fields. Returns an array of length 0 if the class or interface
+ * declares no fields, or if this object represents a
+ * primitive type or an array type (the implicit <code>length</code>
+ * field of array types is not considered to be a declared field).
+ * The resulting Fields are in no particular order.
+ */
+public IField[] getDeclaredFields() throws NotPresentException {
+ IBinaryField[] fields = getBinaryType().getFields();
+ if (fields == null)
+ return new IField[0];
+ IField[] handles = new IField[fields.length];
+ for (int i = 0; i < fields.length; i++) {
+ handles[i] = (IField) BinaryStructure.getFieldHandle(fields[i], fHandle).inState(fState);
+ }
+ return handles;
+}
+/**
+ * Returns an array of Method objects representing all the methods
+ * declared by the class or interface represented by this
+ * object. This includes public, protected, default (package)
+ * access, and private methods, but excludes inherited
+ * methods. Returns an array of length 0 if the class or interface
+ * declares no methods, or if this object represents an
+ * array type or primitive type.
+ * The resulting Methods are in no particular order.
+ */
+public IMethod[] getDeclaredMethods() throws NotPresentException {
+ IBinaryMethod[] methods = getBinaryType().getMethods();
+ if (methods == null)
+ return new IMethod[0];
+
+ // count methods
+ int n = 0;
+ for (int i = 0; i < methods.length; i++) {
+ if (!methods[i].isConstructor() && methods[i].getSelector()[0] != '<') { // TBD: need IBinaryMethod.isClinit()
+ ++n;
}
-
- String name = fHandle.getSimpleName();
- return name.substring(name.lastIndexOf('$') + 1);
}
-
- /**
- * If the class or interface represented by this Type object is
- * a member of another class or interface (i.e. it is a nested class),
- * this returns the Type object representing the class or interface
- * of which it is a member (its <em>declaring class</em>).
- * If this class or interface is a local class, returns the Type
- * object representing the class containing the member in which
- * this class is declared.
- * Returns null if this class or interface is not a nested class,
- * or if this type does not represent a class or interface.
- */
- public IType getDeclaringClass() {
- TypeStructureEntry tsEntry = getTypeStructureEntry();
- IBinaryType binaryType = getBinaryType(tsEntry);
- char[] enclosing = BinaryStructure.getEnclosingTypeName(binaryType);
- if (enclosing == null) {
- return null;
+ IMethod[] result = new IMethod[n];
+ int k = 0;
+ for (int i = 0; i < methods.length; i++) {
+ if (!methods[i].isConstructor() && methods[i].getSelector()[0] != '<') { // TBD: need IBinaryMethod.isClinit()
+ result[k++] = (IMethod) BinaryStructure.getMethodHandle(methods[i], fHandle).inState(fState);
}
- return (IType) fState
- .typeNameToHandle(tsEntry, BinaryStructure.convertTypeName(enclosing))
- .inState(fState);
}
+ return result;
+}
+/**
+ * Returns the declared Java language modifiers, as specified in the declaration
+ * of this class or interface, encoded in an integer.
+ * The modifiers consist of the Java Virtual Machine's constants
+ * for public, protected, private, and final; they should be decoded
+ * using the methods of class Modifier.
+ * The result may not correspond to the modifiers in the compiled
+ * binary, since the compiler may change them (in particular,
+ * for inner classes). The <code>getModifiers()</code>
+ * method should be used if the compiled modifiers are needed.
+ * Returns 0 if this type does not represent a class or interface.
+ *
+ * <p>The modifier encodings are defined in <em>The Java Virtual
+ * Machine Specification</em>, table 4.1.
+ */
+public int getDeclaredModifiers() throws NotPresentException {
- /**
- * Returns a Field object that represents the specified
- * member field of the class or interface represented
- * by this object. The name parameter is a String specifying
- * the simple name of the desired field.
- * Returns null if this type does not represent a class or interface.
- * This is a handle-only method; the specified field may
- * or may not actually be present in the class or interface.
- */
- public IField getFieldHandle(String name) {
- return (IField) ((IType) fHandle).getFieldHandle(name).inState(fState);
+ return getModifiers();
+}
+/**
+ * Returns the declared name of the class or interface represented
+ * by this object, as a String.
+ * The name is the simple, unqualified name used in the source code.
+ * If this represents an inner class, it does not include the names
+ * of any containing classes.
+ * If this represents an anonymous class, it returns a String of length 0.
+ * If this does not represent a class or interface, it returns
+ * a String of length 0.
+ */
+public String getDeclaredName() throws NotPresentException {
+
+ if (isAnonymous()) {
+ return ""/*nonNLS*/;
}
+ String name = fHandle.getSimpleName();
+ return name.substring(name.lastIndexOf('$') + 1);
+}
+/**
+ * If the class or interface represented by this Type object is
+ * a member of another class or interface (i.e. it is a nested class),
+ * this returns the Type object representing the class or interface
+ * of which it is a member (its <em>declaring class</em>).
+ * If this class or interface is a local class, returns the Type
+ * object representing the class containing the member in which
+ * this class is declared.
+ * Returns null if this class or interface is not a nested class,
+ * or if this type does not represent a class or interface.
+ */
+public IType getDeclaringClass() {
+ TypeStructureEntry tsEntry = getTypeStructureEntry();
+ IBinaryType binaryType = getBinaryType(tsEntry);
+ char[] enclosing = BinaryStructure.getEnclosingTypeName(binaryType);
+ if (enclosing == null) {
+ return null;
+ }
+ return (IType) fState.typeNameToHandle(tsEntry, BinaryStructure.convertTypeName(enclosing)).inState(fState);
+}
+/**
+ * Returns a Field object that represents the specified
+ * member field of the class or interface represented
+ * by this object. The name parameter is a String specifying
+ * the simple name of the desired field.
+ * Returns null if this type does not represent a class or interface.
+ * This is a handle-only method; the specified field may
+ * or may not actually be present in the class or interface.
+ */
+public IField getFieldHandle(String name) {
+ return (IField) ((IType)fHandle).getFieldHandle(name).inState(fState);
+}
/**
* Returns the non state specific handle
*/
- protected TypeImpl getHandle() {
- return fHandle;
- }
-
- /**
- * Returns an array of Type objects representing the
- * classes in the given ImageContext which directly implement this interface.
- * A class is said to directly implement this interface if the interface
- * appears in the <code>implements</code> clause of the class's declaration.
- * Although all array types are considered to implement the <code>Cloneable</code>
- * interface, this method never returns array types, only class types.
- * Returns an array of length 0 if this object does not represent
- * an interface.
- * The resulting Types are in no particular order.
- * See <em>The Java Language Specification</em> section 8.1.4
- * for more details.
- */
- public IType[] getImplementingClasses(IImageContext imageContext)
- throws NotPresentException {
-
- return getSubtypes(imageContext, true, false);
- }
+ protected TypeImpl getHandle() {
+ return fHandle;
+ }
+/**
+ * Returns an array of Type objects representing the
+ * classes in the given ImageContext which directly implement this interface.
+ * A class is said to directly implement this interface if the interface
+ * appears in the <code>implements</code> clause of the class's declaration.
+ * Although all array types are considered to implement the <code>Cloneable</code>
+ * interface, this method never returns array types, only class types.
+ * Returns an array of length 0 if this object does not represent
+ * an interface.
+ * The resulting Types are in no particular order.
+ * See <em>The Java Language Specification</em> section 8.1.4
+ * for more details.
+ */
+public IType[] getImplementingClasses(IImageContext imageContext) throws NotPresentException {
- /**
- * Returns an array of Type objects representing the direct
- * superinterfaces of the class or interface represented by this object.
- * <p>
- * If this object represents a class, the return value is an array
- * containing objects representing all interfaces directly implemented by the
- * class. The order of the interface objects in the array corresponds
- * to the order of the interface names in the <code>implements</code>
- * clause of the declaration of the class represented by this object.
- * <p>
- * If this object represents an interface, the array contains
- * objects representing all interfaces directly extended by the interface.
- * The order of the interface objects in the array corresponds to the
- * order of the interface names in the <code>extends</code> clause of
- * the declaration of the interface represented by this object.
- * <p>
- * If the class or interface implements no interfaces, or if this
- * object represents neither a class nor an interface, this method
- * returns an array of length 0.
- *
- * See <em>The Java Language Specification</em> sections 8.1.4 and 9.1.3
- * for more details.
- */
- public IType[] getInterfaces() throws NotPresentException {
- char[][] interfaces = getBinaryType().getInterfaceNames();
- if (interfaces == null) {
- return new IType[0];
- }
- int len = interfaces.length;
- IType[] results = new IType[len];
- if (len > 0) {
- TypeStructureEntry tsEntry = getTypeStructureEntry();
- for (int i = 0; i < len; i++) {
- results[i] = (IType) BinaryStructure.getType(fState, tsEntry, interfaces[i]);
- }
+ return getSubtypes(imageContext, true, false);
+}
+/**
+ * Returns an array of Type objects representing the direct
+ * superinterfaces of the class or interface represented by this object.
+ * <p>
+ * If this object represents a class, the return value is an array
+ * containing objects representing all interfaces directly implemented by the
+ * class. The order of the interface objects in the array corresponds
+ * to the order of the interface names in the <code>implements</code>
+ * clause of the declaration of the class represented by this object.
+ * <p>
+ * If this object represents an interface, the array contains
+ * objects representing all interfaces directly extended by the interface.
+ * The order of the interface objects in the array corresponds to the
+ * order of the interface names in the <code>extends</code> clause of
+ * the declaration of the interface represented by this object.
+ * <p>
+ * If the class or interface implements no interfaces, or if this
+ * object represents neither a class nor an interface, this method
+ * returns an array of length 0.
+ *
+ * See <em>The Java Language Specification</em> sections 8.1.4 and 9.1.3
+ * for more details.
+ */
+public IType[] getInterfaces() throws NotPresentException {
+ char[][] interfaces = getBinaryType().getInterfaceNames();
+ if (interfaces == null) {
+ return new IType[0];
+ }
+ int len = interfaces.length;
+ IType[] results = new IType[len];
+ if (len > 0) {
+ TypeStructureEntry tsEntry = getTypeStructureEntry();
+ for (int i = 0; i < len; i++) {
+ results[i] = (IType) BinaryStructure.getType(fState, tsEntry, interfaces[i]);
}
- return results;
- }
-
- /**
- * Returns a Method object that represents the specified
- * member method of the class or interface represented
- * by this object. The name parameter is a String specifying the
- * simple name the desired method, and the parameterTypes
- * parameter is an array of Type objects that identify the
- * method's formal parameter types, in declared order.
- * Returns null if this type does not represent a class or interface.
- * This is a handle-only method; the specified method may
- * or may not actually be present in the class or interface.
- */
- public IMethod getMethodHandle(String name, IType[] parameterTypes) {
- IType[] paramNSS = new IType[parameterTypes.length];
- // non-state-specific handles
- for (int i = 0; i < parameterTypes.length; i++)
- paramNSS[i] = (IType) parameterTypes[i].nonStateSpecific();
-
- return (IMethod) ((IType) fHandle).getMethodHandle(name, paramNSS).inState(
- fState);
- }
-
- /**
- * Returns the compiled Java language modifiers for this class or
- * interface, encoded in an integer. The modifiers consist of the
- * Java Virtual Machine's constants for public, protected,
- * private, and final; they should be decoded using the
- * methods of class Modifier.
- * The result may not correspond to the modifiers as declared in
- * the source, since the compiler may change them (in particular,
- * for inner classes). The <code>getDeclaredModifiers()</code>
- * method should be used if the original modifiers are needed.
- * Returns 0 if this type does not represent a class or interface.
- */
- public int getModifiers() throws NotPresentException {
- int flags = getBinaryType().getModifiers();
- return flags & (0xFFFF & ~IConstants.AccInterface & ~IConstants.AccSuper);
- // clear out special flags and interface flag
- }
-
- /**
- * Returns the Package in which this class or interface is declared.
- * Returns null if this object represents a primitive type or array type.
- * This is a handle-only method.
- */
- public IPackage getPackage() {
- return (IPackage) fHandle.getPackage().inState(fState);
}
+ return results;
+}
+/**
+ * Returns a Method object that represents the specified
+ * member method of the class or interface represented
+ * by this object. The name parameter is a String specifying the
+ * simple name the desired method, and the parameterTypes
+ * parameter is an array of Type objects that identify the
+ * method's formal parameter types, in declared order.
+ * Returns null if this type does not represent a class or interface.
+ * This is a handle-only method; the specified method may
+ * or may not actually be present in the class or interface.
+ */
+public IMethod getMethodHandle(String name, IType[] parameterTypes) {
+ IType[] paramNSS = new IType[parameterTypes.length]; // non-state-specific handles
+ for (int i = 0; i < parameterTypes.length; i++)
+ paramNSS[i] = (IType) parameterTypes[i].nonStateSpecific();
- /**
- * Returns a SourceFragment describing the fragment of source
- * from which this member is derived.
- * Returns null if this type represent a primitive type or an
- * array type, or if this type is not derived directly from source
- * (e.g. a fictional type, which is created by the image builder).
- */
- public ISourceFragment getSourceFragment() throws NotPresentException {
- return getTypeStructureEntry().getSourceFragment();
- }
-
- /**
- * Returns an array of Type objects representing the
- * classes in the given ImageContext which are direct subclasses of
- * this class.
- * Returns an array of length 0 if this object does not represent
- * a class.
- * The resulting Types are in no particular order.
- * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
- * for more details.
- */
- public IType[] getSubclasses(IImageContext imageContext)
- throws NotPresentException {
-
- return getSubtypes(imageContext, true, false);
- }
+ return (IMethod)((IType)fHandle).getMethodHandle(name, paramNSS).inState(fState);
+}
+/**
+ * Returns the compiled Java language modifiers for this class or
+ * interface, encoded in an integer. The modifiers consist of the
+ * Java Virtual Machine's constants for public, protected,
+ * private, and final; they should be decoded using the
+ * methods of class Modifier.
+ * The result may not correspond to the modifiers as declared in
+ * the source, since the compiler may change them (in particular,
+ * for inner classes). The <code>getDeclaredModifiers()</code>
+ * method should be used if the original modifiers are needed.
+ * Returns 0 if this type does not represent a class or interface.
+ */
+public int getModifiers() throws NotPresentException {
+ int flags = getBinaryType().getModifiers();
+ return flags & (0xFFFF & ~IConstants.AccInterface & ~IConstants.AccSuper); // clear out special flags and interface flag
+}
+/**
+ * Returns the Package in which this class or interface is declared.
+ * Returns null if this object represents a primitive type or array type.
+ * This is a handle-only method.
+ */
+public IPackage getPackage() {
+ return (IPackage)fHandle.getPackage().inState(fState);
+}
+/**
+ * Returns a SourceFragment describing the fragment of source
+ * from which this member is derived.
+ * Returns null if this type represent a primitive type or an
+ * array type, or if this type is not derived directly from source
+ * (e.g. a fictional type, which is created by the image builder).
+ */
+public ISourceFragment getSourceFragment() throws NotPresentException {
+ return getTypeStructureEntry().getSourceFragment();
+}
+/**
+ * Returns an array of Type objects representing the
+ * classes in the given ImageContext which are direct subclasses of
+ * this class.
+ * Returns an array of length 0 if this object does not represent
+ * a class.
+ * The resulting Types are in no particular order.
+ * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
+ * for more details.
+ */
+public IType[] getSubclasses(IImageContext imageContext) throws NotPresentException {
- /**
- * Returns an array of Type objects representing the
- * interfaces in the given ImageContext which are direct subinterfaces of
- * this interface.
- * Returns an array of length 0 if this object does not represent
- * an interface.
- * The resulting Types are in no particular order.
- * See <em>The Java Language Specification</em> section 9.1.3
- * for more details.
- */
- public IType[] getSubinterfaces(IImageContext imageContext)
- throws NotPresentException {
+ return getSubtypes(imageContext, true, false);
+}
+/**
+ * Returns an array of Type objects representing the
+ * interfaces in the given ImageContext which are direct subinterfaces of
+ * this interface.
+ * Returns an array of length 0 if this object does not represent
+ * an interface.
+ * The resulting Types are in no particular order.
+ * See <em>The Java Language Specification</em> section 9.1.3
+ * for more details.
+ */
+public IType[] getSubinterfaces(IImageContext imageContext) throws NotPresentException {
- return getSubtypes(imageContext, false, true);
+ return getSubtypes(imageContext, false, true);
+}
+/**
+ * Returns an array of Type objects representing the
+ * types in the given ImageContext which are direct subtypes of this interface.
+ * @param includeClasses true iff classes are candidates
+ * @param includeInterfaces true iff interfaces are candidates
+ */
+IType[] getSubtypes(
+ IImageContext imageContext,
+ boolean includeClasses,
+ boolean includeInterfaces) throws NotPresentException {
+
+ Hashtable table = fState.getSubtypesTable(imageContext);
+ TypeStructureEntry[] subtypes = (TypeStructureEntry[]) table.get(this);
+ if (subtypes == null) {
+ if (!isPresent())
+ throw new NotPresentException();
+ else
+ return new IType[0];
}
-
- /**
- * Returns an array of Type objects representing the
- * types in the given ImageContext which are direct subtypes of this interface.
- * @param includeClasses true iff classes are candidates
- * @param includeInterfaces true iff interfaces are candidates
- */
- IType[] getSubtypes(
- IImageContext imageContext,
- boolean includeClasses,
- boolean includeInterfaces)
- throws NotPresentException {
-
- Hashtable table = fState.getSubtypesTable(imageContext);
- TypeStructureEntry[] subtypes = (TypeStructureEntry[]) table.get(this);
- if (subtypes == null) {
- if (!isPresent())
- throw new NotPresentException();
- else
- return new IType[0];
+
+ int numSubtypes = subtypes.length;
+ int count = 0;
+ IType[] result = new IType[numSubtypes];
+ for (int i = 0, n = numSubtypes; i < n; i++) {
+ IType type = (IType)subtypes[i].getType().inState(fState);
+ if (type.isInterface()) {
+ if (!includeInterfaces) continue;
}
-
- int numSubtypes = subtypes.length;
- int count = 0;
- IType[] result = new IType[numSubtypes];
- for (int i = 0, n = numSubtypes; i < n; i++) {
- IType type = (IType) subtypes[i].getType().inState(fState);
- if (type.isInterface()) {
- if (!includeInterfaces)
- continue;
- } else {
- if (!includeClasses)
- continue;
- }
- result[count++] = type;
+ else {
+ if (!includeClasses) continue;
}
-
- if (count < numSubtypes)
- System.arraycopy(result, 0, result = new IType[count], 0, count);
- return result;
- }
-
- /**
- * If this object represents any class other than the class
- * <code>java.lang.Object</code>, then the object that represents
- * the direct superclass of that class is returned.
- * <p>
- * If this object represents the class <code>java.lang.Object</code>
- * or this object represents an interface or a primitive type,
- * <code>null</code> is returned.
- * If this object represents an array type, then the Type that represents
- * class <code>java.lang.Object</code> is returned.
- * <p>
- * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
- * for more details.
- */
- public IType getSuperclass() throws NotPresentException {
- return BinaryStructure.getType(
- fState,
- getTypeStructureEntry(),
- getBinaryType().getSuperclassName());
+ result[count++] = type;
}
+ if (count < numSubtypes)
+ System.arraycopy(result, 0, result = new IType[count], 0, count);
+ return result;
+}
+/**
+ * If this object represents any class other than the class
+ * <code>java.lang.Object</code>, then the object that represents
+ * the direct superclass of that class is returned.
+ * <p>
+ * If this object represents the class <code>java.lang.Object</code>
+ * or this object represents an interface or a primitive type,
+ * <code>null</code> is returned.
+ * If this object represents an array type, then the Type that represents
+ * class <code>java.lang.Object</code> is returned.
+ * <p>
+ * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
+ * for more details.
+ */
+public IType getSuperclass() throws NotPresentException {
+ return BinaryStructure.getType(fState, getTypeStructureEntry(), getBinaryType().getSuperclassName());
+}
/**
* Returns the type structure entry for this class or interface. Throws a
* not present exception if the type is not present.
@@ -502,97 +451,87 @@ public class ClassOrInterfaceHandleImplSWH extends TypeImplSWH {
}
throw new NotPresentException();
}
-
- /**
- * Returns true if this object represents an anonymous class,
- * false otherwise.
- * An anonymous class is a local inner class with no declared name.
- * <p>
- * See the <em>Java Inner Classes Specification</em> for more details.
- */
- public boolean isAnonymous()
- throws org.eclipse.jdt.internal.core.builder.NotPresentException {
- return BinaryStructure.isAnonymous(getBinaryType());
- }
-
- /**
- * Return true if this represents a binary class or interface, false otherwise.
- * A binary type is one which is in .class file format in the source tree.
- * Returns false if this represents a primitive type or an array type.
- */
- public boolean isBinary() throws NotPresentException {
- return getTypeStructureEntry().isBinary();
- }
-
- /**
- * Determines if this object represents a class type.
- * This returns false if this object represents an interface,
- * an array type, or a primitive type.
- */
- public boolean isClass() throws NotPresentException {
- return !isInterface();
- }
-
- /**
- * Returns true if the type represented by this object is
- * deprecated, false otherwise. A deprecated object is one that
- * has a deprecated tag in its doc comment.
- * Returns false if this represents a primitive type or an array type.
- */
- public boolean isDeprecated() throws NotPresentException {
- return (getBinaryType().getModifiers() & IConstants.AccDeprecated) != 0;
- }
-
- /**
- * Returns true if this object represents an inner class or interface,
- * false otherwise.
- * An inner class is one which can only be created in the context of
- * an instance of its outer class. This does not include package member
- * classes or other top-level classes. Such a class cannot be static.
- * <p>
- * See the <em>Java Inner Classes Specification</em> for more details.
- */
- public boolean isInnerClass() throws NotPresentException {
- return !isTopLevel();
- }
-
- /**
- * Determines if this object represents an interface type.
- * This returns false if this object represents a class,
- * an array type, or a primitive type.
- */
- public boolean isInterface() throws NotPresentException {
- return getBinaryType().isInterface();
- }
-
- /**
- * Returns true if this object represents a local inner class,
- * false otherwise.
- * A local inner class is an inner class which is defined in the body of
- * a method or other block, not as a class field.
- * <p>
- * See the <em>Java Inner Classes Specification</em> for more details.
- */
- public boolean isLocal() throws NotPresentException {
- return BinaryStructure.isLocal(getBinaryType());
- }
-
- /**
- * Returns true if this object represents a class or interface
- * which is declared as a package member (i.e. a 'normal' class
- * as in JDK 1.02). Returns false otherwise.
- * In particular, this method returns false if this object represents a
- * top-level class which is declared as a member of a class.
- * For the sake of consistent terminology, a class which is
- * not a package member is considered 'nested', whether or not
- * it is top-level.
- * <p>
- * See the <em>Java Inner Classes Specification</em> for more details.
- */
- public boolean isPackageMember() throws NotPresentException {
- return BinaryStructure.isPackageMember(getBinaryType());
- }
-
+/**
+ * Returns true if this object represents an anonymous class,
+ * false otherwise.
+ * An anonymous class is a local inner class with no declared name.
+ * <p>
+ * See the <em>Java Inner Classes Specification</em> for more details.
+ */
+public boolean isAnonymous() throws org.eclipse.jdt.internal.core.builder.NotPresentException {
+ return BinaryStructure.isAnonymous(getBinaryType());
+}
+/**
+ * Return true if this represents a binary class or interface, false otherwise.
+ * A binary type is one which is in .class file format in the source tree.
+ * Returns false if this represents a primitive type or an array type.
+ */
+public boolean isBinary() throws NotPresentException {
+ return getTypeStructureEntry().isBinary();
+}
+/**
+ * Determines if this object represents a class type.
+ * This returns false if this object represents an interface,
+ * an array type, or a primitive type.
+ */
+public boolean isClass() throws NotPresentException {
+ return !isInterface();
+}
+/**
+ * Returns true if the type represented by this object is
+ * deprecated, false otherwise. A deprecated object is one that
+ * has a deprecated tag in its doc comment.
+ * Returns false if this represents a primitive type or an array type.
+ */
+public boolean isDeprecated() throws NotPresentException {
+ return (getBinaryType().getModifiers() & IConstants.AccDeprecated) != 0;
+}
+/**
+ * Returns true if this object represents an inner class or interface,
+ * false otherwise.
+ * An inner class is one which can only be created in the context of
+ * an instance of its outer class. This does not include package member
+ * classes or other top-level classes. Such a class cannot be static.
+ * <p>
+ * See the <em>Java Inner Classes Specification</em> for more details.
+ */
+public boolean isInnerClass() throws NotPresentException {
+ return !isTopLevel();
+}
+/**
+ * Determines if this object represents an interface type.
+ * This returns false if this object represents a class,
+ * an array type, or a primitive type.
+ */
+public boolean isInterface() throws NotPresentException {
+ return getBinaryType().isInterface();
+}
+/**
+ * Returns true if this object represents a local inner class,
+ * false otherwise.
+ * A local inner class is an inner class which is defined in the body of
+ * a method or other block, not as a class field.
+ * <p>
+ * See the <em>Java Inner Classes Specification</em> for more details.
+ */
+public boolean isLocal() throws NotPresentException {
+ return BinaryStructure.isLocal(getBinaryType());
+}
+/**
+ * Returns true if this object represents a class or interface
+ * which is declared as a package member (i.e. a 'normal' class
+ * as in JDK 1.02). Returns false otherwise.
+ * In particular, this method returns false if this object represents a
+ * top-level class which is declared as a member of a class.
+ * For the sake of consistent terminology, a class which is
+ * not a package member is considered 'nested', whether or not
+ * it is top-level.
+ * <p>
+ * See the <em>Java Inner Classes Specification</em> for more details.
+ */
+public boolean isPackageMember() throws NotPresentException {
+ return BinaryStructure.isPackageMember(getBinaryType());
+}
/**
* A class or interface type is present if:
* - its package is present, and
@@ -601,51 +540,45 @@ public class ClassOrInterfaceHandleImplSWH extends TypeImplSWH {
public boolean isPresent() {
return fState.getTypeStructureEntry(fHandle, true) != null;
}
-
- /**
- * Returns true if the type represented by this object is
- * synthetic, false otherwise. A synthetic object is one that
- * was invented by the compiler, but was not declared in the source.
- * See <em>The Inner Classes Specification</em>.
- * A synthetic object is not the same as a fictitious object.
- */
- public boolean isSynthetic() throws NotPresentException {
- return (getBinaryType().getModifiers() & IConstants.AccSynthetic) != 0;
+/**
+ * Returns true if the type represented by this object is
+ * synthetic, false otherwise. A synthetic object is one that
+ * was invented by the compiler, but was not declared in the source.
+ * See <em>The Inner Classes Specification</em>.
+ * A synthetic object is not the same as a fictitious object.
+ */
+public boolean isSynthetic() throws NotPresentException {
+ return (getBinaryType().getModifiers() & IConstants.AccSynthetic) != 0;
+}
+/**
+ * Returns true if this object represents a top-level class or interface,
+ * false otherwise.
+ * A top-level class is declared either as a package member or as a
+ * static member of another top-level class. Unlike inner classes,
+ * instances of top-level classes are not created in the context of
+ * another object.
+ * Given the appropriate access modifiers, a top-level class can be
+ * referred to directly by a qualified name.
+ * <p>
+ * See the <em>Java Inner Classes Specification</em> for more details.
+ */
+public boolean isTopLevel() throws org.eclipse.jdt.internal.core.builder.NotPresentException {
+ IBinaryType binaryType = getBinaryType();
+ if (BinaryStructure.isPackageMember(binaryType)) {
+ return true;
}
-
- /**
- * Returns true if this object represents a top-level class or interface,
- * false otherwise.
- * A top-level class is declared either as a package member or as a
- * static member of another top-level class. Unlike inner classes,
- * instances of top-level classes are not created in the context of
- * another object.
- * Given the appropriate access modifiers, a top-level class can be
- * referred to directly by a qualified name.
- * <p>
- * See the <em>Java Inner Classes Specification</em> for more details.
- */
- public boolean isTopLevel()
- throws org.eclipse.jdt.internal.core.builder.NotPresentException {
- IBinaryType binaryType = getBinaryType();
- if (BinaryStructure.isPackageMember(binaryType)) {
- return true;
- }
- if (BinaryStructure.isLocal(binaryType)) {
- return false;
- }
- char[] enclosingType = BinaryStructure.getEnclosingTypeName(binaryType);
- if (enclosingType == null) {
- return true;
- }
- if ((binaryType.getModifiers() & IConstants.AccStatic) == 0) {
- return false;
- }
- TypeStructureEntry tsEntry = getTypeStructureEntry();
- IType enclosing =
- (IType) fState.typeNameToHandle(tsEntry, new String(enclosingType)).inState(
- fState);
- return enclosing.isTopLevel();
+ if (BinaryStructure.isLocal(binaryType)) {
+ return false;
}
-
+ char[] enclosingType = BinaryStructure.getEnclosingTypeName(binaryType);
+ if (enclosingType == null) {
+ return true;
+ }
+ if ((binaryType.getModifiers() & IConstants.AccStatic) == 0) {
+ return false;
+ }
+ TypeStructureEntry tsEntry = getTypeStructureEntry();
+ IType enclosing = (IType) fState.typeNameToHandle(tsEntry, new String(enclosingType)).inState(fState);
+ return enclosing.isTopLevel();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/CompilerCompilationUnit.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/CompilerCompilationUnit.java
index 1daaadc588..37a55091c4 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/CompilerCompilationUnit.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/CompilerCompilationUnit.java
@@ -23,59 +23,47 @@ public class CompilerCompilationUnit implements ICompilationUnit {
protected SourceEntry fSourceEntry;
protected BuildNotifier fNotifier;
protected char[] fContents;
- /**
- * Creates a new compilation unit for the given source entry.
- */
- public CompilerCompilationUnit(
- StateImpl state,
- SourceEntry sourceEntry,
- BuildNotifier notifier) {
- fState = state;
- fSourceEntry = sourceEntry;
- fNotifier = notifier;
- }
-
- /**
- * @see ICompilationUnit
- * See the discussion of remembering contents in the class comment.
- */
- public char[] getContents() {
- if (fContents == null) {
- if (fNotifier != null) {
- fNotifier.compiling(this);
- }
- fContents = fState.getElementContentCharArray(fSourceEntry);
+/**
+ * Creates a new compilation unit for the given source entry.
+ */
+public CompilerCompilationUnit(StateImpl state, SourceEntry sourceEntry, BuildNotifier notifier) {
+ fState = state;
+ fSourceEntry = sourceEntry;
+ fNotifier = notifier;
+}
+/**
+ * @see ICompilationUnit
+ * See the discussion of remembering contents in the class comment.
+ */
+public char[] getContents() {
+ if (fContents == null) {
+ if (fNotifier != null) {
+ fNotifier.compiling(this);
}
- return fContents;
- }
-
- /**
- * @see ICompilationUnit
- */
- public char[] getFileName() {
- return fSourceEntry.getPathWithZipEntryName().toCharArray();
- }
-
- /**
- * @see ICompilationUnit
- */
- public char[] getMainTypeName() {
- return fSourceEntry.getName().toCharArray();
- }
-
- /**
- * Returns the source entry
- */
- public SourceEntry getSourceEntry() {
- return fSourceEntry;
+ fContents = fState.getElementContentCharArray(fSourceEntry);
}
-
+ return fContents;
+}
+/**
+ * @see ICompilationUnit
+ */
+public char[] getFileName() {
+ return fSourceEntry.getPathWithZipEntryName().toCharArray();
+}
+/**
+ * @see ICompilationUnit
+ */
+public char[] getMainTypeName() {
+ return fSourceEntry.getName().toCharArray();
+}
+/**
+ * Returns the source entry
+ */
+public SourceEntry getSourceEntry() {
+ return fSourceEntry;
+}
public String toString() {
// don't use append(char[]) due to JDK1.2 problems
- return new StringBuffer("CompilationUnit(")
- .append(getFileName())
- .append(")")
- .toString();
+ return new StringBuffer("CompilationUnit("/*nonNLS*/).append(getFileName()).append(")"/*nonNLS*/).toString();
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ConsoleProgressMonitor.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ConsoleProgressMonitor.java
index 660f47ac52..6075165532 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ConsoleProgressMonitor.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ConsoleProgressMonitor.java
@@ -22,7 +22,6 @@ class ConsoleProgressMonitor implements IProgressMonitor {
fTotalWork = totalWork;
fWorkDone = 0;
}
-
/**
* done method comment.
*/
@@ -31,41 +30,35 @@ class ConsoleProgressMonitor implements IProgressMonitor {
fTotalWork = 0;
fWorkDone = 0;
}
-
- public void internalWorked(double work) {
+public void internalWorked(double work) {
fWorkDone += work;
- double percent = (double) fWorkDone / (double) fTotalWork;
+ double percent = (double)fWorkDone / (double)fTotalWork;
percent *= 100;
System.out.println("\t" + percent + "% work done");
}
-
/**
* isCanceled method comment.
*/
public boolean isCanceled() {
return false;
}
-
/**
* setCanceled method comment.
*/
public void setCanceled(boolean b) {
}
-
/**
* setTaskName method comment.
*/
public void setTaskName(String name) {
System.out.println("\t" + name);
}
-
/**
* subTask method comment.
*/
public void subTask(String name) {
System.out.println("\t" + name);
}
-
/**
* Returns a String that represents the value of this object.
* @return a string representation of the receiver
@@ -73,15 +66,13 @@ class ConsoleProgressMonitor implements IProgressMonitor {
public String toString() {
return "Default ImageBuilder Progress Monitor";
}
-
/**
* worked method comment.
*/
public void worked(int work) {
fWorkDone += work;
- double percent = (double) fWorkDone / (double) fTotalWork;
+ double percent = (double)fWorkDone / (double)fTotalWork;
percent *= 100;
System.out.println("\t" + percent + "% work done");
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ConstructorImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ConstructorImpl.java
index 0644ee724e..260240acea 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ConstructorImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ConstructorImpl.java
@@ -6,19 +6,15 @@ package org.eclipse.jdt.internal.core.builder.impl;
*/
import org.eclipse.jdt.internal.core.builder.*;
-public class ConstructorImpl
- extends AbstractMemberHandle
- implements IConstructor {
- ConstructorImpl(ClassOrInterfaceHandleImpl owner, IType[] paramTypes) {
+public class ConstructorImpl extends AbstractMemberHandle implements IConstructor {
+ ConstructorImpl (ClassOrInterfaceHandleImpl owner, IType[] paramTypes) {
fOwner = owner;
- fSignature = computeSignature("", paramTypes);
+ fSignature = computeSignature(""/*nonNLS*/, paramTypes);
}
-
public ConstructorImpl(ClassOrInterfaceHandleImpl owner, String signature) {
fOwner = owner;
fSignature = signature;
}
-
/**
* Returns an array of Type objects that represent the types of
* the checked exceptions thrown by the underlying constructor
@@ -30,9 +26,8 @@ public class ConstructorImpl
* The resulting Types are in no particular order.
*/
public IType[] getExceptionTypes() {
- return nonStateSpecific(((IConstructor) inCurrentState()).getExceptionTypes());
+ return nonStateSpecific(((IConstructor)inCurrentState()).getExceptionTypes());
}
-
/**
* Returns the simple name of the member represented by this object.
* If this Member represents a constructor, this returns
@@ -40,10 +35,8 @@ public class ConstructorImpl
* This is a handle-only method.
*/
public String getName() {
- return ((ClassOrInterfaceHandleImpl) getDeclaringClass())
- .sourceNameFromHandle();
+ return ((ClassOrInterfaceHandleImpl)getDeclaringClass()).sourceNameFromHandle();
}
-
/**
* Returns an array of Type objects that represent the formal
* parameter types, in declaration order, of the constructor
@@ -55,38 +48,33 @@ public class ConstructorImpl
public IType[] getParameterTypes() {
return getInternalDC().parameterTypesFromSignature(getSignature());
}
-
- /**
- * Returns a state specific version of this handle in the given state.
- */
- public IHandle inState(IState s)
- throws org.eclipse.jdt.internal.core.builder.StateSpecificException {
-
- return new ConstructorImplSWH((StateImpl) s, this);
- }
-
+/**
+ * Returns a state specific version of this handle in the given state.
+ */
+public IHandle inState(IState s) throws org.eclipse.jdt.internal.core.builder.StateSpecificException {
+
+ return new ConstructorImplSWH((StateImpl) s, this);
+}
/**
* Returns a constant indicating what kind of handle this is.
*/
public int kind() {
return IHandle.K_JAVA_CONSTRUCTOR;
}
-
- /**
- * toString method comment.
- */
- public String toString() {
- StringBuffer sb = new StringBuffer(getDeclaringClass().getName());
- sb.append('(');
- IType[] paramTypes = getParameterTypes();
- for (int i = 0; i < paramTypes.length; ++i) {
- if (i != 0) {
- sb.append(',');
- }
- sb.append(paramTypes[i].getName());
+/**
+ * toString method comment.
+ */
+public String toString() {
+ StringBuffer sb = new StringBuffer(getDeclaringClass().getName());
+ sb.append('(');
+ IType[] paramTypes = getParameterTypes();
+ for (int i = 0; i < paramTypes.length; ++i) {
+ if (i != 0) {
+ sb.append(',');
}
- sb.append(')');
- return sb.toString();
+ sb.append(paramTypes[i].getName());
}
-
+ sb.append(')');
+ return sb.toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ConstructorImplSWH.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ConstructorImplSWH.java
index b324e870ee..b987ba145d 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ConstructorImplSWH.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ConstructorImplSWH.java
@@ -8,9 +8,7 @@ import org.eclipse.jdt.internal.compiler.env.*;
import org.eclipse.jdt.internal.core.builder.*;
import org.eclipse.jdt.internal.core.Util;
-public class ConstructorImplSWH
- extends AbstractMemberHandleSWH
- implements IConstructor {
+public class ConstructorImplSWH extends AbstractMemberHandleSWH implements IConstructor {
ConstructorImpl fHandle;
/**
* Internal - Creates a new constructor handle in the given state
@@ -19,68 +17,58 @@ public class ConstructorImplSWH
fState = state;
fHandle = handle;
}
-
- /**
- * Internal - Returns the IBinaryMethod for this method.
- */
- protected IBinaryMethod getBinaryMethod() throws NotPresentException {
- return getBinaryMethod(getTypeStructureEntry());
- }
-
- /**
- * Internal - Returns the IBinaryMethod for this method.
- */
- protected IBinaryMethod getBinaryMethod(TypeStructureEntry tsEntry)
- throws NotPresentException {
- IBinaryType t = fState.getBinaryType(getTypeStructureEntry());
- IBinaryMethod m = BinaryStructure.getConstructor(t, fHandle.fSignature);
- if (m == null) {
- throw new NotPresentException();
- } else {
- return m;
- }
+/**
+ * Internal - Returns the IBinaryMethod for this method.
+ */
+protected IBinaryMethod getBinaryMethod() throws NotPresentException {
+ return getBinaryMethod(getTypeStructureEntry());
+}
+/**
+ * Internal - Returns the IBinaryMethod for this method.
+ */
+protected IBinaryMethod getBinaryMethod(TypeStructureEntry tsEntry) throws NotPresentException {
+ IBinaryType t = fState.getBinaryType(getTypeStructureEntry());
+ IBinaryMethod m = BinaryStructure.getConstructor(t, fHandle.fSignature);
+ if (m == null) {
+ throw new NotPresentException();
+ } else {
+ return m;
}
-
- /**
- * Returns an array of Type objects that represent the types of
- * the checked exceptions thrown by the underlying constructor
- * represented by this Constructor object.
- * Unchecked exceptions are not included in the result, even if
- * they are declared in the source.
- * Returns an array of length 0 if the constructor throws no checked
- * exceptions.
- * The resulting Types are in no particular order.
- */
- public IType[] getExceptionTypes() {
- TypeStructureEntry tsEntry = getTypeStructureEntry();
- char[][] exceptions = getBinaryMethod(tsEntry).getExceptionTypeNames();
- PackageImpl pkg = fHandle.fOwner.fOwner;
- int len = exceptions.length;
- IType[] results = new IType[len];
- for (int i = 0; i < len; i++) {
- results[i] =
- (IType) fState
- .typeNameToHandle(tsEntry, Util.convertTypeSignature(exceptions[i]))
- .inState(fState);
- }
- return results;
+}
+/**
+ * Returns an array of Type objects that represent the types of
+ * the checked exceptions thrown by the underlying constructor
+ * represented by this Constructor object.
+ * Unchecked exceptions are not included in the result, even if
+ * they are declared in the source.
+ * Returns an array of length 0 if the constructor throws no checked
+ * exceptions.
+ * The resulting Types are in no particular order.
+ */
+public IType[] getExceptionTypes() {
+ TypeStructureEntry tsEntry = getTypeStructureEntry();
+ char[][] exceptions = getBinaryMethod(tsEntry).getExceptionTypeNames();
+ PackageImpl pkg = fHandle.fOwner.fOwner;
+ int len = exceptions.length;
+ IType[] results = new IType[len];
+ for (int i = 0; i < len; i++) {
+ results[i] = (IType) fState.typeNameToHandle(tsEntry, Util.convertTypeSignature(exceptions[i])).inState(fState);
}
-
+ return results;
+}
/**
* Internal - Returns the non state specific handle
*/
IMember getHandle() {
return fHandle;
}
-
- /**
- * Returns the Java language modifiers for the member
- * represented by this object, as an integer.
- */
- public int getModifiers() {
- return getBinaryMethod().getModifiers() & 0xFFFF;
- }
-
+/**
+ * Returns the Java language modifiers for the member
+ * represented by this object, as an integer.
+ */
+public int getModifiers() {
+ return getBinaryMethod().getModifiers() & 0xFFFF;
+}
/**
* Returns an array of Type objects that represent the formal
* parameter types, in declaration order, of the constructor
@@ -94,52 +82,46 @@ public class ConstructorImplSWH
for (int i = 0; i < results.length; i++) {
results[i] = (IType) unwrapped[i].inState(fState);
}
- return results;
- }
-
- /**
- * Returns true if the member represented by this object is
- * deprecated, false otherwise. A deprecated object is one that
- * has a @ deprecated tag in its doc comment.
- */
- public boolean isDeprecated() {
- return (getBinaryMethod().getModifiers() & IConstants.AccDeprecated) != 0;
- }
-
- /**
- * Returns true if the object represented by the receiver is present
- * in the development context, false otherwise. If the receiver is
- * state-specific, checks whether it is present in this object's state,
- * otherwise checks whether it is present in the current state of the
- * development context.
- */
- public boolean isPresent() {
- TypeStructureEntry entry =
- fState.getTypeStructureEntry(fHandle.getDeclaringClass(), true);
- if (entry == null) {
- return false;
- }
- IBinaryType t = fState.getBinaryType(entry);
- IBinaryMethod m = BinaryStructure.getConstructor(t, fHandle.fSignature);
- return m != null;
+ return results;
}
-
- /**
- * Returns true if the member represented by this object is
- * synthetic, false otherwise. A synthetic object is one that
- * was invented by the compiler, but was not declared in the source.
- * See <em>The Inner Classes Specification</em>.
- * A synthetic object is not the same as a fictitious object.
- */
- public boolean isSynthetic() throws NotPresentException {
- return (getBinaryMethod().getModifiers() & IConstants.AccSynthetic) != 0;
+/**
+ * Returns true if the member represented by this object is
+ * deprecated, false otherwise. A deprecated object is one that
+ * has a @ deprecated tag in its doc comment.
+ */
+public boolean isDeprecated() {
+ return (getBinaryMethod().getModifiers() & IConstants.AccDeprecated) != 0;
+}
+/**
+ * Returns true if the object represented by the receiver is present
+ * in the development context, false otherwise. If the receiver is
+ * state-specific, checks whether it is present in this object's state,
+ * otherwise checks whether it is present in the current state of the
+ * development context.
+ */
+public boolean isPresent() {
+ TypeStructureEntry entry = fState.getTypeStructureEntry(fHandle.getDeclaringClass(), true);
+ if (entry == null) {
+ return false;
}
-
+ IBinaryType t = fState.getBinaryType(entry);
+ IBinaryMethod m = BinaryStructure.getConstructor(t, fHandle.fSignature);
+ return m != null;
+}
+/**
+ * Returns true if the member represented by this object is
+ * synthetic, false otherwise. A synthetic object is one that
+ * was invented by the compiler, but was not declared in the source.
+ * See <em>The Inner Classes Specification</em>.
+ * A synthetic object is not the same as a fictitious object.
+ */
+public boolean isSynthetic() throws NotPresentException {
+ return (getBinaryMethod().getModifiers() & IConstants.AccSynthetic) != 0;
+}
/**
* Returns the non state specific handle
*/
- public IHandle nonStateSpecific() {
- return fHandle;
- }
-
+ public IHandle nonStateSpecific() {
+ return fHandle;
+ }
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ConvertedCompilationResult.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ConvertedCompilationResult.java
index d7392fa927..d023e60cd2 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ConvertedCompilationResult.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ConvertedCompilationResult.java
@@ -14,39 +14,30 @@ public class ConvertedCompilationResult {
IProblemDetail[] fProblems;
TypeStructureEntry[] fTypes;
- ConvertedCompilationResult(
- PackageElement packageElement,
- Vector dependencies,
- IProblemDetail[] problems,
- TypeStructureEntry[] types) {
-
- fPackageElement = packageElement;
- fDependencies = dependencies;
- fProblems = problems;
- fTypes = types;
- }
-
+ConvertedCompilationResult(
+ PackageElement packageElement,
+ Vector dependencies,
+ IProblemDetail[] problems,
+ TypeStructureEntry[] types) {
+
+ fPackageElement = packageElement;
+ fDependencies = dependencies;
+ fProblems = problems;
+ fTypes = types;
+}
Vector getDependencies() {
return fDependencies;
}
-
PackageElement getPackageElement() {
return fPackageElement;
}
-
IProblemDetail[] getProblems() {
return fProblems;
}
-
TypeStructureEntry[] getTypes() {
return fTypes;
}
-
public String toString() {
- return (fProblems.length == 0 ? "" : "*")
- + "ConvertedCompilationResult("
- + fPackageElement
- + ")";
+ return (fProblems.length == 0 ? ""/*nonNLS*/ : "*"/*nonNLS*/) + "ConvertedCompilationResult("/*nonNLS*/ + fPackageElement + ")"/*nonNLS*/;
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/DeltaImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/DeltaImpl.java
index 7fb0da2cb5..dbf9941335 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/DeltaImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/DeltaImpl.java
@@ -14,10 +14,10 @@ import java.util.*;
class DeltaImpl implements IDelta {
protected IDelta fParent;
protected IDelta[] fChildren;
-
+
/* Non state specific object */
protected Object fObject;
-
+
protected String fName;
protected DeltaKey fKey;
@@ -29,7 +29,7 @@ class DeltaImpl implements IDelta {
/* names for checklist items */
public static final String fgImage = "Image";
-
+
public static final String fgPackageCategory = "Packages";
public static final String fgTypeCategory = "Types";
public static final String fgBinaryCategory = "Binaries";
@@ -57,60 +57,47 @@ class DeltaImpl implements IDelta {
/* shared empty array */
protected static final IDelta[] fgEmptyArray = new IDelta[0];
-
+
protected IncrementalImageBuilder fIncrementalBuilder;
static final int PS_CHANGED = 1; // has the principal structure changed?
- static final int BIN_CHANGED = 2; // has the binary changed?
-
+ static final int BIN_CHANGED = 2; // has the binary changed?
+
/**
* Creates a new root image delta
*/
DeltaImpl(IncrementalImageBuilder builder, IImageContext context) {
this(builder.getOldState(), builder.getNewState(), context, builder);
}
-
/**
* Creates a new root image delta
*/
- protected DeltaImpl(
- StateImpl oldState,
- StateImpl newState,
- String name,
- Object o,
- DeltaKey key,
- IDelta parent,
- int status) {
-
- fNewState = (StateImpl) newState;
- fOldState = (StateImpl) oldState;
+ protected DeltaImpl(StateImpl oldState, StateImpl newState, String name,
+ Object o, DeltaKey key, IDelta parent, int status) {
+
+ fNewState = (StateImpl)newState;
+ fOldState = (StateImpl)oldState;
fName = name;
fObject = o;
fParent = parent;
fKey = key;
fStatus = status;
- fChildren = fgEmptyArray;
+ fChildren = fgEmptyArray;
fContext = parent.getImageContext();
}
-
/**
* Creates a new root image delta
*/
DeltaImpl(IState oldState, IState newState, IImageContext context) {
this(oldState, newState, context, null);
}
-
/**
* Creates a new root image delta
*/
- DeltaImpl(
- IState oldState,
- IState newState,
- IImageContext context,
- IncrementalImageBuilder builder) {
+ DeltaImpl(IState oldState, IState newState, IImageContext context, IncrementalImageBuilder builder) {
try {
- fNewState = (StateImpl) newState;
- fOldState = (StateImpl) oldState;
+ fNewState = (StateImpl)newState;
+ fOldState = (StateImpl)oldState;
} catch (ClassCastException cce) {
Assert.isTrue(false, "Invalid states");
}
@@ -124,24 +111,22 @@ class DeltaImpl implements IDelta {
fIncrementalBuilder = builder;
computeImageDelta();
}
-
/**
* Creates and returns a child with the given name and object
*/
protected DeltaImpl add(String name, Object object, int status) {
return add(name, object, getKey().add(object), status);
}
-
/**
* Creates and returns a child with the given name and object
*/
protected DeltaImpl add(String name, Object object, DeltaKey key, int status) {
- return new DeltaImpl(fOldState, fNewState, //same states as me
- name, object, key, //given name, object and key
- this, //parent
- status); //added, removed, or changed
+ return new DeltaImpl(
+ fOldState, fNewState, //same states as me
+ name, object, key, //given name, object and key
+ this, //parent
+ status); //added, removed, or changed
}
-
/**
* Returns the child of this delta with the given object
*/
@@ -152,7 +137,8 @@ class DeltaImpl implements IDelta {
if (o.equals(fChildren[i].getName())) {
return fChildren[i];
}
- } else {
+ }
+ else {
if (o.equals(fChildren[i].getObject())) {
return fChildren[i];
}
@@ -161,54 +147,52 @@ class DeltaImpl implements IDelta {
/* not found */
return null;
}
+/**
+ * Compares the type in the old and new states.
+ * Returns a bit mask indicating whether the principal structure or binary have changed.
+ */
+protected int compareBuilderType(BuilderType type) {
- /**
- * Compares the type in the old and new states.
- * Returns a bit mask indicating whether the principal structure or binary have changed.
- */
- protected int compareBuilderType(BuilderType type) {
-
- if (!type.isAffected()) {
- return 0;
- }
-
- TypeStructureEntry oldEntry = type.getOldTypeStructureEntry();
- TypeStructureEntry newEntry = type.getNewTypeStructureEntry();
- if (oldEntry == null || newEntry == null) {
- return PS_CHANGED | BIN_CHANGED;
- }
- if (oldEntry == newEntry) {
- return 0;
- }
-
- int result = 0;
+ if (!type.isAffected()) {
+ return 0;
+ }
+
+ TypeStructureEntry oldEntry = type.getOldTypeStructureEntry();
+ TypeStructureEntry newEntry = type.getNewTypeStructureEntry();
+ if (oldEntry == null || newEntry == null) {
+ return PS_CHANGED | BIN_CHANGED;
+ }
+ if (oldEntry == newEntry) {
+ return 0;
+ }
- IBinaryType oldType = type.getOldBinaryType();
- IBinaryType newType = type.getNewBinaryType();
+ int result = 0;
- if (!BinaryStructure.compare(oldType, newType)) {
- result |= PS_CHANGED;
- }
- /*
- * If the source entry has changed, consider the binary to have changed
- * even if the binary is actually the same. Some clients, such as the
- * target manager, need to know when the source changes.
- */
- if (!oldEntry.getSourceEntry().equals(newEntry.getSourceEntry())) {
+ IBinaryType oldType = type.getOldBinaryType();
+ IBinaryType newType = type.getNewBinaryType();
+
+ if (!BinaryStructure.compare(oldType, newType)) {
+ result |= PS_CHANGED;
+ }
+ /*
+ * If the source entry has changed, consider the binary to have changed
+ * even if the binary is actually the same. Some clients, such as the
+ * target manager, need to know when the source changes.
+ */
+ if (!oldEntry.getSourceEntry().equals(newEntry.getSourceEntry())) {
+ result |= BIN_CHANGED;
+ } else
+ if (oldEntry.getCRC32() != newEntry.getCRC32()) {
result |= BIN_CHANGED;
- } else
- if (oldEntry.getCRC32() != newEntry.getCRC32()) {
+ } else {
+ boolean oldIsBinary = oldEntry.isBinary();
+ boolean newIsBinary = newEntry.isBinary();
+ if (oldIsBinary != newIsBinary) {
result |= BIN_CHANGED;
- } else {
- boolean oldIsBinary = oldEntry.isBinary();
- boolean newIsBinary = newEntry.isBinary();
- if (oldIsBinary != newIsBinary) {
- result |= BIN_CHANGED;
- }
}
- return result;
- }
-
+ }
+ return result;
+}
/**
* Returns an integer indicating whether anotherDelta is less than, equal to,
* or greater than this delta.
@@ -218,52 +202,50 @@ class DeltaImpl implements IDelta {
Assert.isTrue(false, "TBD");
return 0;
}
+/**
+ * Compares the type in the old and new states.
+ * Returns a bit mask indicating whether the principal structure or binary have changed.
+ */
+protected int compareTypes(IType handle) {
+ if (fIncrementalBuilder != null) {
+ return compareBuilderType(fIncrementalBuilder.getBuilderType(handle));
+ }
- /**
- * Compares the type in the old and new states.
- * Returns a bit mask indicating whether the principal structure or binary have changed.
- */
- protected int compareTypes(IType handle) {
- if (fIncrementalBuilder != null) {
- return compareBuilderType(fIncrementalBuilder.getBuilderType(handle));
- }
-
- TypeStructureEntry oldEntry = fOldState.getTypeStructureEntry(handle, true);
- TypeStructureEntry newEntry = fNewState.getTypeStructureEntry(handle, true);
- if (oldEntry == null || newEntry == null) {
- return PS_CHANGED | BIN_CHANGED;
- }
- if (oldEntry == newEntry) {
- return 0;
- }
- int result = 0;
-
- IBinaryType oldType = fOldState.getBinaryType(oldEntry);
- IBinaryType newType = fNewState.getBinaryType(newEntry);
+ TypeStructureEntry oldEntry = fOldState.getTypeStructureEntry(handle, true);
+ TypeStructureEntry newEntry = fNewState.getTypeStructureEntry(handle, true);
+ if (oldEntry == null || newEntry == null) {
+ return PS_CHANGED | BIN_CHANGED;
+ }
+ if (oldEntry == newEntry) {
+ return 0;
+ }
+ int result = 0;
- if (!BinaryStructure.compare(oldType, newType)) {
- result |= PS_CHANGED;
- }
- /*
- * If the source entry has changed, consider the binary to have changed
- * even if the binary is actually the same. Some clients, such as the
- * target manager, need to know when the source changes.
- */
- if (!oldEntry.getSourceEntry().equals(newEntry.getSourceEntry())) {
+ IBinaryType oldType = fOldState.getBinaryType(oldEntry);
+ IBinaryType newType = fNewState.getBinaryType(newEntry);
+
+ if (!BinaryStructure.compare(oldType, newType)) {
+ result |= PS_CHANGED;
+ }
+ /*
+ * If the source entry has changed, consider the binary to have changed
+ * even if the binary is actually the same. Some clients, such as the
+ * target manager, need to know when the source changes.
+ */
+ if (!oldEntry.getSourceEntry().equals(newEntry.getSourceEntry())) {
+ result |= BIN_CHANGED;
+ } else
+ if (oldEntry.getCRC32() != newEntry.getCRC32()) {
result |= BIN_CHANGED;
- } else
- if (oldEntry.getCRC32() != newEntry.getCRC32()) {
+ } else {
+ boolean oldIsBinary = oldEntry.isBinary();
+ boolean newIsBinary = newEntry.isBinary();
+ if (oldIsBinary != newIsBinary) {
result |= BIN_CHANGED;
- } else {
- boolean oldIsBinary = oldEntry.isBinary();
- boolean newIsBinary = newEntry.isBinary();
- if (oldIsBinary != newIsBinary) {
- result |= BIN_CHANGED;
- }
}
- return result;
- }
-
+ }
+ return result;
+}
/**
* Computes the added classes for each added package.
* Returns a DeltaInfo object for each package describing the affected
@@ -283,35 +265,30 @@ class DeltaImpl implements IDelta {
types[j] = (IType) types[j].nonStateSpecific();
}
infos[i].addedTypes = types;
- } //next package
+ }//next package
return infos;
- } //end function
-
+ }//end function
/**
* Computes added, removed, and changed classes for a set of packages.
* Stores vectors of IType handles.
*/
- protected void computeAllClasses(
- IPackage pkg,
- Vector added,
- Vector removed,
- Vector changedTypes,
- Vector changedBinaries) {
-
+ protected void computeAllClasses(IPackage pkg,
+ Vector added, Vector removed, Vector changedTypes, Vector changedBinaries) {
+
/* collect a set of all classes in old package */
/* we have to make a copy here to avoid destroying the state */
Hashtable oldTypeTable = new Hashtable();
IType[] oldTypes = ((IPackage) pkg.inState(fOldState)).getAllClasses();
for (int i = 0; i < oldTypes.length; i++) {
- IType handle = (IType) oldTypes[i].nonStateSpecific();
+ IType handle = (IType)oldTypes[i].nonStateSpecific();
oldTypeTable.put(handle, handle);
}
/* iterate through new classes */
- IType[] newTypes = ((IPackage) pkg.inState(fNewState)).getAllClasses();
+ IType[] newTypes = ((IPackage)pkg.inState(fNewState)).getAllClasses();
for (int i = 0; i < newTypes.length; i++) {
- IType handle = (IType) newTypes[i].nonStateSpecific();
+ IType handle = (IType)newTypes[i].nonStateSpecific();
if (oldTypeTable.remove(handle) != null) {
/* class is in both packages */
int code = compareTypes(handle);
@@ -332,7 +309,6 @@ class DeltaImpl implements IDelta {
removed.addElement(e.nextElement());
}
}
-
/**
* Computes added, removed, and changed packages. At this
* stage, if a package hasn't been added or removed, it is
@@ -342,34 +318,34 @@ class DeltaImpl implements IDelta {
* specific package handles.
*/
protected void computeAllPackages(
- Vector added,
- Vector removed,
- Vector changed) {
+ Vector added, Vector removed, Vector changed) {
/* do for each affected package */
- for (Enumeration e = getAffectedPackages(); e.hasMoreElements();) {
- IPackage pkg = (IPackage) e.nextElement();
+ for (Enumeration e = getAffectedPackages();e.hasMoreElements();) {
+ IPackage pkg = (IPackage)e.nextElement();
boolean inOld = pkg.inState(fOldState).isPresent();
boolean inNew = pkg.inState(fNewState).isPresent();
if (inOld) {
if (inNew) {
changed.addElement(pkg);
- } else {
+ }
+ else {
// Package was removed.
removed.addElement(pkg);
}
- } else {
+ }
+ else {
if (inNew) {
// Package was added.
added.addElement(pkg);
- } else {
+ }
+ else {
// Package was in image context but was not in either state.
// Ignore it.
}
}
}
}
-
/**
* Computes added, removed, and changed classes for a set of packages.
* Returns a DeltaInfo object for each package describing the affected
@@ -381,7 +357,7 @@ class DeltaImpl implements IDelta {
Vector toRemove = new Vector();
for (Enumeration pkgEnum = pkgs.elements(); pkgEnum.hasMoreElements();) {
- IPackage pkg = (IPackage) pkgEnum.nextElement();
+ IPackage pkg = (IPackage)pkgEnum.nextElement();
Vector vAdded = new Vector();
Vector vRemoved = new Vector();
@@ -401,10 +377,10 @@ class DeltaImpl implements IDelta {
pkgInfo.removedTypes = new IType[vRemoved.size()];
vRemoved.copyInto(pkgInfo.removedTypes);
-
+
pkgInfo.changedTypes = new IType[vChanged.size()];
vChanged.copyInto(pkgInfo.changedTypes);
-
+
pkgInfo.changedBinaries = new IType[vBinaries.size()];
vBinaries.copyInto(pkgInfo.changedBinaries);
@@ -413,7 +389,7 @@ class DeltaImpl implements IDelta {
/* remove the element -- can't delete while enumerating */
toRemove.addElement(pkg);
}
- } //next package
+ }//next package
/* remove packages with no changes */
for (Enumeration e = toRemove.elements(); e.hasMoreElements();) {
@@ -421,13 +397,12 @@ class DeltaImpl implements IDelta {
}
Assert.isTrue(vInfo.size() == pkgs.size(), "sanity check");
-
+
/* convert info vector to array */
PackageInfo[] infos = new PackageInfo[vInfo.size()];
vInfo.copyInto(infos);
return infos;
- } //end function
-
+ }//end function
/**
* Calculates the added, removed, and changed packages, types and methods
* that consitute an image delta. The results are stored in the supplied
@@ -449,7 +424,6 @@ class DeltaImpl implements IDelta {
return info;
}
-
/**
* Computes the image delta.
*/
@@ -459,29 +433,25 @@ class DeltaImpl implements IDelta {
DeltaInfo info = computeDeltaInfo();
/* create categories, any or all of them may be null */
- IDelta pkgCategory = createPackageCategory(this, info);
+ IDelta pkgCategory = createPackageCategory(this, info);
IDelta typeCategory = createCategory(this, info, fgTypeCategory);
IDelta binaryCategory = createCategory(this, info, fgBinaryCategory);
/* Create top level children */
int childCount = 0;
- if (pkgCategory != null)
- childCount++;
- if (typeCategory != null)
- childCount++;
- if (binaryCategory != null)
- childCount++;
+ if (pkgCategory != null) childCount++;
+ if (typeCategory != null) childCount++;
+ if (binaryCategory != null) childCount++;
fChildren = new IDelta[childCount];
childCount = 0;
- if (pkgCategory != null)
+ if (pkgCategory != null)
fChildren[childCount++] = pkgCategory;
- if (typeCategory != null)
+ if (typeCategory != null)
fChildren[childCount++] = typeCategory;
- if (binaryCategory != null)
+ if (binaryCategory != null)
fChildren[childCount++] = binaryCategory;
}
-
/**
* Computes the removed classes for each removed package.
* Returns a DeltaInfo object for each package describing the affected
@@ -501,19 +471,15 @@ class DeltaImpl implements IDelta {
types[j] = (IType) types[j].nonStateSpecific();
}
infos[i].removedTypes = types;
- } //next package
+ }//next package
return infos;
- } //end function
-
+ }//end function
/**
* Converts a vector of handles to an array of delta info objects of the given
* type.
*/
- protected IDelta[] convertHandlesToDeltaArray(
- Vector vHandles,
- String type,
- int status) {
+ protected IDelta[] convertHandlesToDeltaArray(Vector vHandles, String type, int status) {
int i = 0;
IDelta[] results = new IDelta[vHandles.size()];
@@ -522,20 +488,16 @@ class DeltaImpl implements IDelta {
}
return results;
}
-
/**
* Copies information from a PackageInfo to the children of a DeltaImpl.
* If types is true, copy the type information, otherwise copy the binary information
*/
- protected void copyInfoToChildren(
- DeltaImpl delta,
- PackageInfo info,
- boolean types) {
+ protected void copyInfoToChildren(DeltaImpl delta, PackageInfo info, boolean types) {
/* are we looking at binaries or types ? */
IType[] changed = types ? info.changedTypes : info.changedBinaries;
String name = types ? fgType : fgBinary;
-
+
int count = info.addedTypes.length + info.removedTypes.length + changed.length;
if (count == 0) {
delta.fStatus = SAME;
@@ -555,38 +517,27 @@ class DeltaImpl implements IDelta {
}
delta.setChildren(children);
}
-
/**
* Creates the types category of the image delta. Returns
* the Delta object for the category. If there are no added,
* removed, or changed types, returns null.
*/
- protected IDelta createCategory(
- DeltaImpl parent,
- DeltaInfo info,
- String categoryName) {
-
- int size =
- info.changedPkgs.length + info.addedPkgs.length + info.removedPkgs.length;
- if (size == 0)
- return null;
+ protected IDelta createCategory(DeltaImpl parent, DeltaInfo info, String categoryName) {
+ int size = info.changedPkgs.length + info.addedPkgs.length + info.removedPkgs.length;
+ if (size == 0) return null;
+
/* collection of packages that are children of the type category */
IDelta[] children = new IDelta[size];
/* create Type category node */
- DeltaImpl category =
- parent.add(
- categoryName,
- parent.getObject(),
- parent.getKey().add(categoryName),
- CHANGED);
-
+ DeltaImpl category = parent.add(categoryName, parent.getObject(), parent.getKey().add(categoryName), CHANGED);
+
/* create new deltas for changed packages */
int count = 0;
for (int i = 0; i < info.changedPkgs.length; i++) {
PackageInfo pkgInfo = info.changedPkgs[i];
- DeltaImpl child = (DeltaImpl) category.add(fgPackage, pkgInfo.pkg, CHANGED);
+ DeltaImpl child = (DeltaImpl)category.add(fgPackage, pkgInfo.pkg, CHANGED);
copyInfoToChildren(child, pkgInfo, categoryName == fgTypeCategory);
children[count++] = child;
}
@@ -596,14 +547,12 @@ class DeltaImpl implements IDelta {
children[count++] = category.packageForTypeCategory(ADDED, info.addedPkgs[i]);
}
for (int i = 0; i < info.removedPkgs.length; i++) {
- children[count++] =
- category.packageForTypeCategory(REMOVED, info.removedPkgs[i]);
+ children[count++] = category.packageForTypeCategory(REMOVED, info.removedPkgs[i]);
}
category.setChildren(children);
return category;
}
-
/**
* Creates the package category of the image delta. Returns
* the Delta object for the category. If there are no added,
@@ -613,17 +562,15 @@ class DeltaImpl implements IDelta {
protected IDelta createPackageCategory(DeltaImpl parent, DeltaInfo info) {
/* number of children of this category */
- int size =
- info.addedPkgs.length + info.changedPkgs.length + info.removedPkgs.length;
- if (size == 0)
- return null;
+ int size = info.addedPkgs.length + info.changedPkgs.length + info.removedPkgs.length;
+ if (size == 0) return null;
/* create the category */
- DeltaImpl category =
+ DeltaImpl category =
parent.add(
- fgPackageCategory,
- parent.getObject(),
- parent.getKey().add(fgPackageCategory),
+ fgPackageCategory,
+ parent.getObject(),
+ parent.getKey().add(fgPackageCategory),
CHANGED);
IDelta[] children = new IDelta[size];
@@ -636,10 +583,9 @@ class DeltaImpl implements IDelta {
}
for (int i = 0; i < info.changedPkgs.length; i++) {
IPackage pkg = info.changedPkgs[i].pkg;
- if (!Util
- .equalArraysOrNull(
- fOldState.getPackageMap().getFragments(pkg),
- fNewState.getPackageMap().getFragments(pkg))) {
+ if (!Util.equalArraysOrNull(
+ fOldState.getPackageMap().getFragments(pkg),
+ fNewState.getPackageMap().getFragments(pkg))) {
children[count++] = category.add(fgPackage, pkg, CHANGED);
}
}
@@ -648,7 +594,7 @@ class DeltaImpl implements IDelta {
if (count == 0) {
return null;
}
-
+
/* compact if some changed packages did not actually change */
if (count < children.length) {
System.arraycopy(children, 0, children = new IDelta[count], 0, count);
@@ -656,21 +602,18 @@ class DeltaImpl implements IDelta {
category.setChildren(children);
return category;
}
-
public void dump() {
dump(this, 0);
}
-
protected static void dump(IDelta delta, int depth) {
for (int i = 0; i < depth; ++i)
System.out.print(" ");
System.out.println(delta);
IDelta[] children = delta.getAffectedSubdeltas();
for (int i = 0; i < children.length; ++i) {
- dump(children[i], depth + 1);
+ dump(children[i], depth+1);
}
}
-
/**
* Returns the delta reached by navigating the given
* relative path from this object.
@@ -696,14 +639,12 @@ class DeltaImpl implements IDelta {
}
return delta;
}
-
/**
* Returns the immediate subdeltas of this delta that are additions
* (i.e. their status is Added).
*/
public IDelta[] getAddedSubdeltas() {
- if (fChildren == null)
- return fgEmptyArray;
+ if (fChildren == null) return fgEmptyArray;
Vector vAdded = new Vector();
for (int i = 0; i < fChildren.length; i++) {
if (fChildren[i].getStatus() == IDelta.ADDED) {
@@ -714,40 +655,33 @@ class DeltaImpl implements IDelta {
vAdded.copyInto(added);
return added;
}
-
- /**
- * Returns an enumeration of packages which are possibly affected.
- */
- public Enumeration getAffectedPackages() {
- /* Non-naive case - the image builder knows. */
- if (fIncrementalBuilder != null) {
- return fIncrementalBuilder.getAffectedPackages();
- }
-
- /* Naive case - take union of packages in old and new state. */
- Hashtable affected = new Hashtable(21);
- for (Enumeration e = fOldState.getPackageMap().getAllPackages();
- e.hasMoreElements();
- ) {
- IPackage pkg = (IPackage) e.nextElement();
- affected.put(pkg, pkg);
- }
- for (Enumeration e = fNewState.getPackageMap().getAllPackages();
- e.hasMoreElements();
- ) {
- IPackage pkg = (IPackage) e.nextElement();
- affected.put(pkg, pkg);
- }
- return affected.keys();
+/**
+ * Returns an enumeration of packages which are possibly affected.
+ */
+public Enumeration getAffectedPackages() {
+ /* Non-naive case - the image builder knows. */
+ if (fIncrementalBuilder != null) {
+ return fIncrementalBuilder.getAffectedPackages();
}
+ /* Naive case - take union of packages in old and new state. */
+ Hashtable affected = new Hashtable(21);
+ for (Enumeration e = fOldState.getPackageMap().getAllPackages(); e.hasMoreElements();) {
+ IPackage pkg = (IPackage) e.nextElement();
+ affected.put(pkg, pkg);
+ }
+ for (Enumeration e = fNewState.getPackageMap().getAllPackages(); e.hasMoreElements();) {
+ IPackage pkg = (IPackage) e.nextElement();
+ affected.put(pkg, pkg);
+ }
+ return affected.keys();
+}
/**
* Returns the immediate subdeltas of this delta that are
* not the same (i.e. their status is either Added, Removed, or Changed).
*/
public IDelta[] getAffectedSubdeltas() {
- if (fChildren == null)
- return fgEmptyArray;
+ if (fChildren == null) return fgEmptyArray;
Vector vAffected = new Vector();
for (int i = 0; i < fChildren.length; i++) {
if (fChildren[i].getStatus() != IDelta.SAME) {
@@ -758,14 +692,12 @@ class DeltaImpl implements IDelta {
vAffected.copyInto(affected);
return affected;
}
-
/**
* Returns the immediate subdeltas of this delta that are true
* changes, not additions or removals (i.e. their status is Changed).
*/
public IDelta[] getChangedSubdeltas() {
- if (fChildren == null)
- return fgEmptyArray;
+ if (fChildren == null) return fgEmptyArray;
Vector vChanged = new Vector();
for (int i = 0; i < fChildren.length; i++) {
if (fChildren[i].getStatus() == IDelta.CHANGED) {
@@ -776,7 +708,6 @@ class DeltaImpl implements IDelta {
vChanged.copyInto(changed);
return changed;
}
-
/**
* Returns the ImageContext that the delta is restricted to.
*
@@ -785,7 +716,6 @@ class DeltaImpl implements IDelta {
public IImageContext getImageContext() {
return fContext;
}
-
/**
* Returns the delta key for this delta.
* Delta keys often contain non-state-specific handles, but
@@ -796,14 +726,12 @@ class DeltaImpl implements IDelta {
public IDeltaKey getKey() {
return fKey;
}
-
/**
* Returns the name of the aspect being compared in this delta.
*/
public String getName() {
return fName;
}
-
/**
* Returns the object in the new state that is the focus of this delta.
* It only make sense to talk about the 'new object' if the object
@@ -815,21 +743,19 @@ class DeltaImpl implements IDelta {
public IHandle getNewObject() {
IHandle handle;
try {
- handle = (IHandle) fObject;
+ handle = (IHandle)fObject;
} catch (ClassCastException cce) {
//not a handle
return null;
}
return handle.inState(fNewState);
}
-
/**
* Returns the new state to which this delta pertains.
*/
public IState getNewState() {
return fNewState;
}
-
/**
* Returns the object that is the focus of this delta.
* The result is often a Handle, but in
@@ -839,7 +765,6 @@ class DeltaImpl implements IDelta {
public Object getObject() {
return fObject;
}
-
/**
* Returns the object in the old state that is the focus of this delta.
* It only make sense to talk about the 'old object' if the object
@@ -851,35 +776,31 @@ class DeltaImpl implements IDelta {
public IHandle getOldObject() {
IHandle handle;
try {
- handle = (IHandle) fObject;
+ handle = (IHandle)fObject;
} catch (ClassCastException cce) {
//not a handle
return null;
}
return handle.inState(fOldState);
}
-
/**
* Returns the old state to which this delta pertains.
*/
public org.eclipse.jdt.internal.core.builder.IState getOldState() {
return fOldState;
}
-
/**
* Returns the parent delta of this delta, or null if it has no parent.
*/
public IDelta getParent() {
return fParent;
}
-
/**
* Returns the immediate subdeltas of this delta that are removals
* (i.e. their status is Removed).
*/
public IDelta[] getRemovedSubdeltas() {
- if (fChildren == null)
- return fgEmptyArray;
+ if (fChildren == null) return fgEmptyArray;
Vector vRemoved = new Vector();
for (int i = 0; i < fChildren.length; i++) {
if (fChildren[i].getStatus() == IDelta.REMOVED) {
@@ -890,7 +811,6 @@ class DeltaImpl implements IDelta {
vRemoved.copyInto(removed);
return removed;
}
-
/**
* Returns the root delta of the tree containing this delta.
*/
@@ -902,7 +822,6 @@ class DeltaImpl implements IDelta {
return getParent().getRoot();
}
}
-
/**
* Returns the status of this delta. If this delta
* is not applicable, it always returns SAME.
@@ -912,7 +831,6 @@ class DeltaImpl implements IDelta {
public int getStatus() {
return fStatus;
}
-
/**
* Returns the status of this delta if it is known.
* Returns UNKNOWN if it is not known whether the object has changed.
@@ -921,7 +839,6 @@ class DeltaImpl implements IDelta {
public int getStatusIfKnown() {
return fStatus;
}
-
/**
* Returns an array of Delta objects that are children of this delta.
* Returns an array of length 0 if this delta has no children,
@@ -930,7 +847,6 @@ class DeltaImpl implements IDelta {
public IDelta[] getSubdeltas() {
return fChildren;
}
-
/**
* Returns whether this delta is a composite delta that is further
* broken down into subdeltas.
@@ -938,7 +854,6 @@ class DeltaImpl implements IDelta {
public boolean hasSubdeltas() {
return fChildren != null && fChildren.length > 0;
}
-
/**
* Creates a package delta for the types or binaries category.
* The package delta can be for either an added or removed package,
@@ -948,8 +863,8 @@ class DeltaImpl implements IDelta {
protected IDelta packageForTypeCategory(int status, PackageInfo info) {
/* create the package delta */
- DeltaImpl pkgDelta = (DeltaImpl) this.add(fgPackage, info.pkg, status);
-
+ DeltaImpl pkgDelta = (DeltaImpl)this.add(fgPackage, info.pkg, status);
+
IType[] types = (status == ADDED ? info.addedTypes : info.removedTypes);
IDelta[] children = new IDelta[types.length];
for (int i = 0; i < types.length; i++) {
@@ -958,14 +873,12 @@ class DeltaImpl implements IDelta {
pkgDelta.setChildren(children);
return pkgDelta;
}
-
/**
* Sets the children of this delta
*/
protected void setChildren(IDelta[] children) {
fChildren = children;
}
-
/**
* Return a string of the form:
* status key
@@ -983,29 +896,24 @@ class DeltaImpl implements IDelta {
public String toString() {
StringBuffer sb = new StringBuffer("DeltaImpl(");
switch (fStatus) {
- case ADDED :
- sb.append("+");
- break;
- case REMOVED :
- sb.append("-");
- break;
- case CHANGED :
- sb.append("*");
- break;
- case SAME :
- sb.append("=");
- break;
- case UNKNOWN :
- sb.append("?");
- break;
- default :
- sb.append("(ERROR)");
+ case ADDED: sb.append("+");
+ break;
+ case REMOVED: sb.append("-");
+ break;
+ case CHANGED: sb.append("*");
+ break;
+ case SAME: sb.append("=");
+ break;
+ case UNKNOWN: sb.append("?");
+ break;
+ default: sb.append("(ERROR)");
}
if (fKey.isRoot()) {
sb.append(fOldState);
sb.append("-->");
sb.append(fNewState);
- } else {
+ }
+ else {
for (int i = 0; i < fKey.size(); ++i) {
if (i != 0) {
sb.append('/');
@@ -1016,5 +924,4 @@ class DeltaImpl implements IDelta {
sb.append(')');
return sb.toString();
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/DependencyGraph.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/DependencyGraph.java
index 7c8e04ca6b..f01091c0c4 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/DependencyGraph.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/DependencyGraph.java
@@ -9,6 +9,7 @@ import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.internal.core.Assert;
import org.eclipse.jdt.internal.core.builder.*;
import org.eclipse.jdt.internal.core.util.*;
+import org.eclipse.jdt.internal.core.Util;
import java.util.*;
@@ -36,16 +37,15 @@ public class DependencyGraph implements IDumpable, Cloneable {
* Maps Strings (filenames) to INodes in the graph
*/
private LookupTable fZips;
- /**
- * DependencyGraph constructor comment.
- */
- public DependencyGraph() {
- fNamespaces = new LookupTable(11);
- fCompilationUnits = new LookupTable(11);
- fTypes = new LookupTable(11);
- fZips = new LookupTable(11);
- }
-
+/**
+ * DependencyGraph constructor comment.
+ */
+public DependencyGraph() {
+ fNamespaces = new LookupTable(11);
+ fCompilationUnits = new LookupTable(11);
+ fTypes = new LookupTable(11);
+ fZips = new LookupTable(11);
+}
/**
* Creates a node for the object. Returns the added node.
*/
@@ -58,50 +58,44 @@ public class DependencyGraph implements IDumpable, Cloneable {
}
return node;
}
+/**
+ * Add the compilation unit, its dependencies, and any other relevant info
+ * from the compilation result to the graph.
+ * The compilation unit has just been compiled, so its status is COMPILED.
+ */
+public void add(PackageElement resultUnit, IType[] types, Vector vDependencies) {
- /**
- * Add the compilation unit, its dependencies, and any other relevant info
- * from the compilation result to the graph.
- * The compilation unit has just been compiled, so its status is COMPILED.
- */
- public void add(
- PackageElement resultUnit,
- IType[] types,
- Vector vDependencies) {
-
- // force the package node if not yet present
- getNodeFor(resultUnit.getPackage());
+ // force the package node if not yet present
+ getNodeFor(resultUnit.getPackage());
- JCUNode unitNode = (JCUNode) getNodeFor(resultUnit);
- unitNode.setTypes(types);
- INode node = unitNode;
+ JCUNode unitNode = (JCUNode)getNodeFor(resultUnit);
+ unitNode.setTypes(types);
+ INode node = unitNode;
- // convert dependencies to INodes
- INode[] deps = new INode[vDependencies.size()];
- int count = 0;
- for (Enumeration e = vDependencies.elements(); e.hasMoreElements();) {
- Object o = e.nextElement();
- INode depNode = getNodeFor(o);
- deps[count++] = depNode;
- }
- node.setDependencies(deps);
+ // convert dependencies to INodes
+ INode[] deps = new INode[vDependencies.size()];
+ int count = 0;
+ for (Enumeration e = vDependencies.elements(); e.hasMoreElements();) {
+ Object o = e.nextElement();
+ INode depNode = getNodeFor(o);
+ deps[count++] = depNode;
}
-
+ node.setDependencies(deps);
+}
/**
* Returns a copy of the dependency graph with all counters and flags reset
*/
protected Object clone() {
- try {
+ try {
DependencyGraph newGraph = (DependencyGraph) super.clone();
/* First pass: copy tables and all nodes,
* leaving dependencies and dependents pointing to old nodes. */
newGraph.fNamespaces = copyTableAndNodesWithoutReplacingDeps(fNamespaces);
- newGraph.fCompilationUnits =
- copyTableAndNodesWithoutReplacingDeps(fCompilationUnits);
+ newGraph.fCompilationUnits = copyTableAndNodesWithoutReplacingDeps(fCompilationUnits);
newGraph.fTypes = copyTableAndNodesWithoutReplacingDeps(fTypes);
newGraph.fZips = copyTableAndNodesWithoutReplacingDeps(fZips);
-
+
/* Second pass: replace dependencies and dependents to point to new nodes. */
replaceDeps(newGraph.fNamespaces, newGraph);
replaceDeps(newGraph.fCompilationUnits, newGraph);
@@ -109,13 +103,13 @@ public class DependencyGraph implements IDumpable, Cloneable {
replaceDeps(newGraph.fZips, newGraph);
return newGraph;
- } catch (CloneNotSupportedException e) {
+ }
+ catch (CloneNotSupportedException e) {
// Should not happen since we implement Cloneable
- Assert.isTrue(false, "Unexpected clone exception in DependencyGraph.clone()");
+ Assert.isTrue(false, Util.bind("build.cloneException"/*nonNLS*/));
return null;
}
}
-
/**
* Returns a copy of the dependency graph with all counters and flags reset
*/
@@ -125,7 +119,6 @@ public class DependencyGraph implements IDumpable, Cloneable {
//newGraph.integrityCheck();
return newGraph;
}
-
/**
* Copies the edges from an old node to a new node. Any nodes that have
* to be created are added to the graph.
@@ -147,7 +140,6 @@ public class DependencyGraph implements IDumpable, Cloneable {
* will add newNode as a dependency, creating both directional links
*/
}
-
/**
* Returns a copy of a table of nodes, with copies of the nodes,
* but with their dependencies and dependents not copied.
@@ -160,7 +152,6 @@ public class DependencyGraph implements IDumpable, Cloneable {
}
return newTable;
}
-
/**
* Deletes the node in this graph corresponding to the given object,
* and answers it if found, or null if it wasn't found.
@@ -173,7 +164,6 @@ public class DependencyGraph implements IDumpable, Cloneable {
}
return toRemove;
}
-
/**
* Deletes the node in this graph corresponding to the given object,
* and answers it if found, or null if it wasn't found.
@@ -183,65 +173,60 @@ public class DependencyGraph implements IDumpable, Cloneable {
Assert.isTrue(toRemove.getDependents().length == 0);
Object value = null;
switch (toRemove.getKind()) {
- case INode.JCU_NODE :
+ case INode.JCU_NODE:
value = fCompilationUnits.remove(((JCUNode) toRemove).getPackageElement());
break;
- case INode.TYPE_NODE :
+ case INode.TYPE_NODE:
value = fTypes.remove(((TypeNode) toRemove).getPackageElement());
break;
- case INode.NAMESPACE_NODE :
+ case INode.NAMESPACE_NODE:
value = fNamespaces.remove(((NamespaceNode) toRemove).getPackage());
break;
- case INode.ZIP_NODE :
- value = fZips.remove(((ZipNode) toRemove).getZipFile());
+ case INode.ZIP_NODE:
+ value = fZips.remove(((ZipNode)toRemove).getZipFile());
break;
- default :
- Assert.isTrue(
- false,
- "Attempt to delete unknown node type from dependency graph");
- }
- return (INode) value;
- }
-
- /**
- * For debugging only. Dump the graph in readable form.
- */
- public void dump(Dumper dumper) {
- dumper.dumpMessage("Namespaces", "");
- dumper.indent();
- for (Enumeration e = fNamespaces.elements(); e.hasMoreElements();) {
- AbstractNode node = (AbstractNode) e.nextElement();
- dumper.dump(node);
- }
- dumper.outdent();
-
- dumper.dumpMessage("JCUs", "");
- dumper.indent();
- for (Enumeration e = fCompilationUnits.elements(); e.hasMoreElements();) {
- AbstractNode node = (AbstractNode) e.nextElement();
- dumper.dump(node);
- }
- dumper.outdent();
-
- dumper.dumpMessage("ZIPs", "");
- dumper.indent();
- for (Enumeration e = fZips.elements(); e.hasMoreElements();) {
- AbstractNode node = (AbstractNode) e.nextElement();
- dumper.dump(node);
+ default:
+ Assert.isTrue(false, Util.bind("build.errorDeletingNode"/*nonNLS*/));
}
- dumper.outdent();
+ return (INode)value;
}
-
- /**
- * Debugging - Force the order counts.
- */
- public void forceOrders() {
- for (Enumeration e = fCompilationUnits.elements(); e.hasMoreElements();) {
- AbstractNode node = (AbstractNode) e.nextElement();
- node.getOrder();
- }
+/**
+ * For debugging only. Dump the graph in readable form.
+ */
+public void dump(Dumper dumper) {
+ dumper.dumpMessage("Namespaces", ""/*nonNLS*/);
+ dumper.indent();
+ for (Enumeration e = fNamespaces.elements(); e.hasMoreElements();) {
+ AbstractNode node = (AbstractNode) e.nextElement();
+ dumper.dump(node);
+ }
+ dumper.outdent();
+
+ dumper.dumpMessage("JCUs", ""/*nonNLS*/);
+ dumper.indent();
+ for (Enumeration e = fCompilationUnits.elements(); e.hasMoreElements();) {
+ AbstractNode node = (AbstractNode) e.nextElement();
+ dumper.dump(node);
+ }
+ dumper.outdent();
+
+ dumper.dumpMessage("ZIPs", ""/*nonNLS*/);
+ dumper.indent();
+ for (Enumeration e = fZips.elements(); e.hasMoreElements();) {
+ AbstractNode node = (AbstractNode) e.nextElement();
+ dumper.dump(node);
+ }
+ dumper.outdent();
+}
+/**
+ * Debugging - Force the order counts.
+ */
+public void forceOrders() {
+ for (Enumeration e = fCompilationUnits.elements(); e.hasMoreElements();) {
+ AbstractNode node = (AbstractNode) e.nextElement();
+ node.getOrder();
}
-
+}
/**
* Returns the elements which directly depend on the given element.
*/
@@ -257,7 +242,6 @@ public class DependencyGraph implements IDumpable, Cloneable {
}
return dependents;
}
-
/**
* Returns the number of bytes that the nodes of the dependency graph use.
* For debugging and profiling purposes only.
@@ -270,7 +254,6 @@ public class DependencyGraph implements IDumpable, Cloneable {
size += getFootprint(fZips);
return size;
}
-
/**
* Returns the number of bytes that the nodes of the dependency graph use.
* For debugging and profiling purposes only.
@@ -278,19 +261,17 @@ public class DependencyGraph implements IDumpable, Cloneable {
public int getFootprint(Dictionary table) {
int size = 0;
for (Enumeration e = table.elements(); e.hasMoreElements();) {
- AbstractNode node = (AbstractNode) e.nextElement();
+ AbstractNode node = (AbstractNode)e.nextElement();
size += node.getFootprint();
}
return size;
}
-
- /**
- * Returns the JCU nodes in the graph.
- */
- public Enumeration getJCUNodes() {
- return fCompilationUnits.elements();
- }
-
+/**
+ * Returns the JCU nodes in the graph.
+ */
+public Enumeration getJCUNodes() {
+ return fCompilationUnits.elements();
+}
/**
* Returns the packages this source element is directly dependent on.
*/
@@ -303,7 +284,7 @@ public class DependencyGraph implements IDumpable, Cloneable {
INode[] dependencies = node.getDependencies();
for (int i = 0; i < dependencies.length; i++) {
if (dependencies[i].getKind() == INode.NAMESPACE_NODE) {
- vPackages.addElement(((NamespaceNode) dependencies[i]).getPackage());
+ vPackages.addElement(((NamespaceNode)dependencies[i]).getPackage());
}
}
@@ -311,7 +292,6 @@ public class DependencyGraph implements IDumpable, Cloneable {
vPackages.copyInto(results);
return results;
}
-
/**
* Returns a node in this graph corresponding to the given object.
* A new node is created if necessary.
@@ -319,26 +299,23 @@ public class DependencyGraph implements IDumpable, Cloneable {
public INode getNodeFor(Object o) {
return getNodeFor(o, true);
}
-
/**
* Returns a node in this graph corresponding to the given object.
* If create is true, the node is added if necessary.
*/
public INode getNodeFor(Object o, boolean create) {
if (o instanceof PackageElement) {
- return getNodeFor((PackageElement) o, create);
- } else
- if (o instanceof IPackage) {
- return getNodeFor((IPackage) o, create);
- } else
- if (o instanceof IPath) {
- return getNodeFor((IPath) o, create);
- } else {
- Assert.isTrue(false, "Unknown kind of node.");
- return null;
- }
+ return getNodeFor((PackageElement)o, create);
+ } else if (o instanceof IPackage) {
+ return getNodeFor((IPackage)o, create);
+ } else if (o instanceof IPath) {
+ return getNodeFor((IPath)o, create);
+ }
+ else {
+ Assert.isTrue(false, Util.bind("build.unknownNode"/*nonNLS*/));
+ return null;
+ }
}
-
/**
* Returns the node for a zip file. If create is true, the node is
* created if necessary.
@@ -354,7 +331,6 @@ public class DependencyGraph implements IDumpable, Cloneable {
}
return zipNode;
}
-
/**
* Returns a node in this graph corresponding to the given node, which
* may be from another graph. A new node is created if necessary.
@@ -362,7 +338,6 @@ public class DependencyGraph implements IDumpable, Cloneable {
INode getNodeFor(INode node) {
return getNodeFor(node.getElement(), true);
}
-
/**
* Returns the node for the given compilation unit. The node
* is added if necessary.
@@ -370,33 +345,31 @@ public class DependencyGraph implements IDumpable, Cloneable {
public INode getNodeFor(PackageElement e) {
return getNodeFor(e, true);
}
-
- /**
- * Returns the node for the given package element.
- * If create is true, the node is added if necessary.
- * A package element may be a JCU, a class file, or a zip file.
- * Class files are keyed by type handle, and zip files are keyed
- * by the filename.
- */
- public INode getNodeFor(PackageElement e, boolean create) {
- INode node;
- if (e.isSource()) {
- /* create a node for this unit if necessary */
- node = (INode) fCompilationUnits.get(e);
- if (node == null && create) {
- node = new JCUNode(e);
- fCompilationUnits.put(e, node);
- }
- } else {
- node = (INode) fTypes.get(e);
- if (node == null && create) {
- node = new TypeNode(e);
- fTypes.put(e, node);
- }
+/**
+ * Returns the node for the given package element.
+ * If create is true, the node is added if necessary.
+ * A package element may be a JCU, a class file, or a zip file.
+ * Class files are keyed by type handle, and zip files are keyed
+ * by the filename.
+ */
+public INode getNodeFor(PackageElement e, boolean create) {
+ INode node;
+ if (e.isSource()) {
+ /* create a node for this unit if necessary */
+ node = (INode)fCompilationUnits.get(e);
+ if (node == null && create) {
+ node = new JCUNode(e);
+ fCompilationUnits.put(e, node);
+ }
+ } else {
+ node = (INode)fTypes.get(e);
+ if (node == null && create) {
+ node = new TypeNode(e);
+ fTypes.put(e, node);
}
- return node;
}
-
+ return node;
+}
/**
* Returns the node for a builder package. The node is
* created if necessary.
@@ -404,7 +377,6 @@ public class DependencyGraph implements IDumpable, Cloneable {
public INode getNodeFor(IPackage pkg) {
return getNodeFor(pkg, true);
}
-
/**
* Returns the node for a builder package. If create is true, the node is
* created if necessary.
@@ -419,30 +391,26 @@ public class DependencyGraph implements IDumpable, Cloneable {
}
return pkgNode;
}
-
- /**
- * Returns an enumeration over all nodes in the graph. Uses a composite
- * enumerator to avoid copying all the elements.
- */
- public Enumeration getNodes() {
- Vector v =
- new Vector(
- fNamespaces.size() + fTypes.size() + fCompilationUnits.size() + fZips.size());
- for (Enumeration e = fNamespaces.elements(); e.hasMoreElements();) {
- v.addElement(e.nextElement());
- }
- for (Enumeration e = fTypes.elements(); e.hasMoreElements();) {
- v.addElement(e.nextElement());
- }
- for (Enumeration e = fCompilationUnits.elements(); e.hasMoreElements();) {
- v.addElement(e.nextElement());
- }
- for (Enumeration e = fZips.elements(); e.hasMoreElements();) {
- v.addElement(e.nextElement());
- }
- return v.elements();
+/**
+ * Returns an enumeration over all nodes in the graph. Uses a composite
+ * enumerator to avoid copying all the elements.
+ */
+public Enumeration getNodes() {
+ Vector v = new Vector(fNamespaces.size() + fTypes.size() + fCompilationUnits.size() + fZips.size());
+ for (Enumeration e = fNamespaces.elements(); e.hasMoreElements();) {
+ v.addElement(e.nextElement());
}
-
+ for (Enumeration e = fTypes.elements(); e.hasMoreElements();) {
+ v.addElement(e.nextElement());
+ }
+ for (Enumeration e = fCompilationUnits.elements(); e.hasMoreElements();) {
+ v.addElement(e.nextElement());
+ }
+ for (Enumeration e = fZips.elements(); e.hasMoreElements();) {
+ v.addElement(e.nextElement());
+ }
+ return v.elements();
+}
/**
* Returns the topological order number of the given element.
*/
@@ -450,7 +418,6 @@ public class DependencyGraph implements IDumpable, Cloneable {
AbstractNode node = (AbstractNode) getNodeFor(element, true);
return node.getOrder();
}
-
/**
* Returns the types this source element is directly dependent on.
*/
@@ -460,8 +427,8 @@ public class DependencyGraph implements IDumpable, Cloneable {
INode[] dependencies = node.getDependencies();
for (int i = 0; i < dependencies.length; i++) {
switch (dependencies[i].getKind()) {
- case INode.JCU_NODE :
- case INode.TYPE_NODE :
+ case INode.JCU_NODE:
+ case INode.TYPE_NODE:
IType[] types = dependencies[i].getTypes();
for (int j = 0; j < types.length; ++j) {
vTypes.addElement(types[j]);
@@ -474,7 +441,6 @@ public class DependencyGraph implements IDumpable, Cloneable {
vTypes.copyInto(results);
return results;
}
-
/**
* Returns the types that belong to the given source element, or null
* if the element is not present.
@@ -485,22 +451,20 @@ public class DependencyGraph implements IDumpable, Cloneable {
INode node = getNodeFor(element, true);
return node == null ? null : node.getTypes();
}
-
- /**
- * Returns a Vector of unused namespace nodes.
- * That is, namespace nodes which have no dependents.
- */
- public Vector getUnusedNamespaceNodes() {
- Vector v = new Vector();
- for (Enumeration e = fNamespaces.elements(); e.hasMoreElements();) {
- INode node = (INode) e.nextElement();
- if (node.getDependents().length == 0) {
- v.addElement(node);
- }
+/**
+ * Returns a Vector of unused namespace nodes.
+ * That is, namespace nodes which have no dependents.
+ */
+public Vector getUnusedNamespaceNodes() {
+ Vector v = new Vector();
+ for (Enumeration e = fNamespaces.elements(); e.hasMoreElements();) {
+ INode node = (INode)e.nextElement();
+ if (node.getDependents().length == 0) {
+ v.addElement(node);
}
- return v;
}
-
+ return v;
+}
/**
* For debugging only -- asserts graph integrity
*/
@@ -509,13 +473,11 @@ public class DependencyGraph implements IDumpable, Cloneable {
integrityCheck(fTypes);
integrityCheck(fNamespaces);
}
-
/**
* For debugging only -- asserts graph integrity
*/
public void integrityCheck(Dictionary table) {
- String msg =
- "Internal Error: the dependency graph is corrupt, do a full build to workaround error.";
+ String msg = Util.bind("build.graphCorrupt"/*nonNLS*/);
for (Enumeration e = table.elements(); e.hasMoreElements();) {
AbstractNode node = (AbstractNode) e.nextElement();
@@ -525,11 +487,11 @@ public class DependencyGraph implements IDumpable, Cloneable {
/* make sure current node is a dependency of the dependent node */
INode[] depDeps = nodesThatDependOnMe[i].getDependencies();
boolean found = false;
- for (int j = depDeps.length; --j >= 0;) {
- if (depDeps[j] == node) {
- found = true;
- }
- }
+ for (int j = depDeps.length; --j >= 0;) {
+ if (depDeps[j] == node) {
+ found = true;
+ }
+ }
Assert.isTrue(found, msg);
}
@@ -539,56 +501,52 @@ public class DependencyGraph implements IDumpable, Cloneable {
/* make sure current node is a dependent of the dependency node */
INode[] depDeps = nodesThatIDependOn[i].getDependents();
boolean found = false;
- for (int j = depDeps.length; --j >= 0;) {
- if (depDeps[j] == node) {
- found = true;
- }
- }
+ for (int j = depDeps.length; --j >= 0;) {
+ if (depDeps[j] == node) {
+ found = true;
+ }
+ }
Assert.isTrue(found, msg);
}
}
}
+/**
+ * Remove the node for the given element, and mark all dependents
+ * as having to be recompiled, if they haven't been already.
+ * Returns true if the node was successfully removed, and false
+ * if the node could not be found.
+ */
+public boolean remove(Object element) {
+ INode node = getNodeFor(element, false);
+ if (node == null) {
+ return false;
+ }
- /**
- * Remove the node for the given element, and mark all dependents
- * as having to be recompiled, if they haven't been already.
- * Returns true if the node was successfully removed, and false
- * if the node could not be found.
- */
- public boolean remove(Object element) {
- INode node = getNodeFor(element, false);
- if (node == null) {
- return false;
- }
-
- /* remove dependencies -- this removes backwards links as well */
- node.clearDependencies();
-
- /* do for each dependent (nodes that depend on me)
- note: these weren't cleared above */
- INode[] dependents = node.getDependents();
- for (int i = 0; i < dependents.length; i++) {
- INode dep = dependents[i];
+ /* remove dependencies -- this removes backwards links as well */
+ node.clearDependencies();
- /* remove the dependency */
- dep.removeDependency(node);
- // this must not cause the dependents local to be modified
- }
+ /* do for each dependent (nodes that depend on me)
+ note: these weren't cleared above */
+ INode[] dependents = node.getDependents();
+ for (int i = 0; i < dependents.length; i++) {
+ INode dep = dependents[i];
- return deleteNode(node) != null;
+ /* remove the dependency */
+ dep.removeDependency(node); // this must not cause the dependents local to be modified
}
- /**
- * A package is being removed from the state. Delete the corresponding namespace nodes,
- * but only if they have no dependents.
- */
- public void removePackage(IPackage pkg) {
- INode node = (INode) fNamespaces.get(pkg);
- if (node != null && node.getDependents().length == 0) {
- fNamespaces.remove(pkg);
- }
+ return deleteNode(node) != null;
+}
+/**
+ * A package is being removed from the state. Delete the corresponding namespace nodes,
+ * but only if they have no dependents.
+ */
+public void removePackage(IPackage pkg) {
+ INode node = (INode)fNamespaces.get(pkg);
+ if (node != null && node.getDependents().length == 0) {
+ fNamespaces.remove(pkg);
}
-
+}
/**
* Replaces the dependencies and dependents of nodes in the given
* table with the corresponding nodes in the new graph.
@@ -599,16 +557,13 @@ public class DependencyGraph implements IDumpable, Cloneable {
node.replaceDeps(newGraph);
}
}
-
/**
* Returns the number of nodes in the graph.
*/
public int size() {
return fNamespaces.size() + fTypes.size() + fCompilationUnits.size();
}
-
public String toString() {
- return "a DependencyGraph";
+ return "a DependencyGraph"/*nonNLS*/;
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/DependencyGraphImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/DependencyGraphImpl.java
index 1e1476f4b0..5b901f24b7 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/DependencyGraphImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/DependencyGraphImpl.java
@@ -12,13 +12,12 @@ import org.eclipse.jdt.internal.core.builder.*;
*/
public class DependencyGraphImpl implements IDependencyGraph {
StateImpl fState;
- /**
- * DependencyGraphImpl constructor comment.
- */
- DependencyGraphImpl(StateImpl state) {
- fState = state;
- }
-
+/**
+ * DependencyGraphImpl constructor comment.
+ */
+DependencyGraphImpl(StateImpl state) {
+ fState = state;
+}
/**
* @see IDependencyGraph#getNamespaceDependencies
*/
@@ -28,14 +27,12 @@ public class DependencyGraphImpl implements IDependencyGraph {
Object key = tsEntry.getDependencyGraphKey();
return fState.getInternalDependencyGraph().getNamespaceDependencies(key);
}
-
/**
* @see IDependencyGraph#getState
*/
public IState getState() {
return fState;
}
-
/**
* @see IDependencyGraph#getTypeDependencies
*/
@@ -45,5 +42,4 @@ public class DependencyGraphImpl implements IDependencyGraph {
Object key = tsEntry.getDependencyGraphKey();
return fState.getInternalDependencyGraph().getTypeDependencies(key);
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/FieldCollaboratorIndictment.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/FieldCollaboratorIndictment.java
index eaf1002aac..f7556bb209 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/FieldCollaboratorIndictment.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/FieldCollaboratorIndictment.java
@@ -1,30 +1,24 @@
package org.eclipse.jdt.internal.core.builder.impl;
class FieldCollaboratorIndictment extends Indictment {
- /**
- * Creates a new FieldCollaboratorIndictment.
- */
- protected FieldCollaboratorIndictment(char[] name) {
- super(name);
- }
-
+/**
+ * Creates a new FieldCollaboratorIndictment.
+ */
+protected FieldCollaboratorIndictment(char[] name) {
+ super(name);
+}
/**
* Returns what kind of indictment this is
*/
public int getKind() {
return K_FIELD;
}
-
- /**
- * Returns a string representation of this class. For debugging purposes
- * only (NON-NLS).
- */
- public String toString() {
- // don't use + with char[]
- return new StringBuffer("FieldIndictment(")
- .append(fName)
- .append(")")
- .toString();
- }
-
+/**
+ * Returns a string representation of this class. For debugging purposes
+ * only (NON-NLS).
+ */
+public String toString() {
+ // don't use + with char[]
+ return new StringBuffer("FieldIndictment("/*nonNLS*/).append(fName).append(")"/*nonNLS*/).toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/FieldImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/FieldImpl.java
index c8ee52ba4e..c2762ae8c0 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/FieldImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/FieldImpl.java
@@ -6,7 +6,7 @@ package org.eclipse.jdt.internal.core.builder.impl;
*/
import org.eclipse.jdt.internal.core.builder.*;
-public class FieldImpl extends AbstractMemberHandle implements IField {
+public class FieldImpl extends AbstractMemberHandle implements IField{
/**
* Creates a new non state specific field implementation
*/
@@ -14,43 +14,36 @@ public class FieldImpl extends AbstractMemberHandle implements IField {
fOwner = owner;
fSignature = name;
}
-
- /**
- * getName method comment.
- */
- public String getName() {
- return fSignature;
- }
-
+/**
+ * getName method comment.
+ */
+public String getName() {
+ return fSignature;
+}
/**
* Returns a Type object that identifies the declared type for
* the field represented by this Field object.
*/
public IType getType() {
- return (IType) ((IField) inCurrentState()).getType().nonStateSpecific();
- }
-
- /**
- * Returns a state specific version of this handle in the given state.
- */
- public IHandle inState(IState s)
- throws org.eclipse.jdt.internal.core.builder.StateSpecificException {
-
- return new FieldImplSWH((StateImpl) s, this);
+ return (IType)((IField)inCurrentState()).getType().nonStateSpecific();
}
-
+/**
+ * Returns a state specific version of this handle in the given state.
+ */
+public IHandle inState(IState s) throws org.eclipse.jdt.internal.core.builder.StateSpecificException {
+
+ return new FieldImplSWH((StateImpl) s, this);
+}
/**
* Returns a constant indicating what kind of handle this is.
*/
public int kind() {
return IHandle.K_JAVA_FIELD;
}
-
- /**
- * toString method comment.
- */
- public String toString() {
- return getDeclaringClass().getName() + "." + getName();
- }
-
+/**
+ * toString method comment.
+ */
+public String toString() {
+ return getDeclaringClass().getName() + "."/*nonNLS*/ + getName();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/FieldImplSWH.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/FieldImplSWH.java
index 2cba9938c8..9eb57f1365 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/FieldImplSWH.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/FieldImplSWH.java
@@ -17,106 +17,91 @@ public class FieldImplSWH extends AbstractMemberHandleSWH implements IField {
fState = state;
fHandle = handle;
}
-
- /**
- * Gets the IBinaryField for this field.
- */
- protected IBinaryField getBinaryField() throws NotPresentException {
- return getBinaryField(getTypeStructureEntry());
- }
-
- /**
- * Returns the IBinaryField for this field
- */
- protected IBinaryField getBinaryField(TypeStructureEntry tsEntry)
- throws NotPresentException {
- IBinaryType t = fState.getBinaryType(tsEntry);
- IBinaryField f = BinaryStructure.getField(t, fHandle.getName());
- if (f == null) {
- throw new NotPresentException();
- } else {
- return f;
- }
+/**
+ * Gets the IBinaryField for this field.
+ */
+protected IBinaryField getBinaryField() throws NotPresentException {
+ return getBinaryField(getTypeStructureEntry());
+}
+/**
+ * Returns the IBinaryField for this field
+ */
+protected IBinaryField getBinaryField(TypeStructureEntry tsEntry) throws NotPresentException {
+ IBinaryType t = fState.getBinaryType(tsEntry);
+ IBinaryField f = BinaryStructure.getField(t, fHandle.getName());
+ if (f == null) {
+ throw new NotPresentException();
+ } else {
+ return f;
}
-
+}
/**
* Returns the non state specific handle
*/
- IMember getHandle() {
- return fHandle;
- }
-
- /**
- * Returns the Java language modifiers for the member
- * represented by this object, as an integer.
- */
- public int getModifiers() {
- return getBinaryField().getModifiers() & 0xFFFF;
- }
-
+ IMember getHandle() {
+ return fHandle;
+ }
+/**
+ * Returns the Java language modifiers for the member
+ * represented by this object, as an integer.
+ */
+public int getModifiers() {
+ return getBinaryField().getModifiers() & 0xFFFF;
+}
/**
* Returns the name of the field.
*/
public String getName() {
return fHandle.getName();
}
-
- /**
- * Returns a Type object that identifies the declared type for
- * the field represented by this Field object.
- */
- public IType getType() {
- TypeStructureEntry tsEntry = getTypeStructureEntry();
- IBinaryField f = getBinaryField(tsEntry);
- char[] sig = f.getTypeName();
- return (IType) fState
- .typeSignatureToHandle(tsEntry, Util.convertTypeSignature(sig))
- .inState(fState);
- }
-
- /**
- * Returns true if the member represented by this object is
- * deprecated, false otherwise. A deprecated object is one that
- * has a @ deprecated tag in its doc comment.
- */
- public boolean isDeprecated() {
- return (getBinaryField().getModifiers() & IConstants.AccDeprecated) != 0;
- }
-
- /**
- * Returns true if the object represented by the receiver is present
- * in the development context, false otherwise. If the receiver is
- * state-specific, checks whether it is present in this object's state,
- * otherwise checks whether it is present in the current state of the
- * development context.
- */
- public boolean isPresent() {
- TypeStructureEntry entry =
- fState.getTypeStructureEntry(fHandle.getDeclaringClass(), true);
- if (entry == null) {
- return false;
- }
- IBinaryType t = fState.getBinaryType(entry);
- IBinaryField f = BinaryStructure.getField(t, fHandle.fSignature);
- return f != null;
- }
-
- /**
- * Returns true if the member represented by this object is
- * synthetic, false otherwise. A synthetic object is one that
- * was invented by the compiler, but was not declared in the source.
- * See <em>The Inner Classes Specification</em>.
- * A synthetic object is not the same as a fictitious object.
- */
- public boolean isSynthetic() throws NotPresentException {
- return (getBinaryField().getModifiers() & IConstants.AccSynthetic) != 0;
+/**
+ * Returns a Type object that identifies the declared type for
+ * the field represented by this Field object.
+ */
+public IType getType() {
+ TypeStructureEntry tsEntry = getTypeStructureEntry();
+ IBinaryField f = getBinaryField(tsEntry);
+ char[] sig = f.getTypeName();
+ return (IType) fState.typeSignatureToHandle(tsEntry, Util.convertTypeSignature(sig)).inState(fState);
+}
+/**
+ * Returns true if the member represented by this object is
+ * deprecated, false otherwise. A deprecated object is one that
+ * has a @ deprecated tag in its doc comment.
+ */
+public boolean isDeprecated() {
+ return (getBinaryField().getModifiers() & IConstants.AccDeprecated) != 0;
+}
+/**
+ * Returns true if the object represented by the receiver is present
+ * in the development context, false otherwise. If the receiver is
+ * state-specific, checks whether it is present in this object's state,
+ * otherwise checks whether it is present in the current state of the
+ * development context.
+ */
+public boolean isPresent() {
+ TypeStructureEntry entry = fState.getTypeStructureEntry(fHandle.getDeclaringClass(), true);
+ if (entry == null) {
+ return false;
}
-
+ IBinaryType t = fState.getBinaryType(entry);
+ IBinaryField f = BinaryStructure.getField(t, fHandle.fSignature);
+ return f != null;
+}
+/**
+ * Returns true if the member represented by this object is
+ * synthetic, false otherwise. A synthetic object is one that
+ * was invented by the compiler, but was not declared in the source.
+ * See <em>The Inner Classes Specification</em>.
+ * A synthetic object is not the same as a fictitious object.
+ */
+public boolean isSynthetic() throws NotPresentException {
+ return (getBinaryField().getModifiers() & IConstants.AccSynthetic) != 0;
+}
/**
* Returns the non state specific handle
*/
- public IHandle nonStateSpecific() {
- return fHandle;
- }
-
+ public IHandle nonStateSpecific() {
+ return fHandle;
+ }
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ImageBuilderInternalException.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ImageBuilderInternalException.java
index 813fb8aab0..2dcd49ab54 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ImageBuilderInternalException.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ImageBuilderInternalException.java
@@ -2,33 +2,29 @@ package org.eclipse.jdt.internal.core.builder.impl;
public class ImageBuilderInternalException extends RuntimeException {
protected Throwable fThrowable;
- /**
- * Creates the exception with no error message.
- */
- public ImageBuilderInternalException() {
- }
-
- /**
- * Creates the exception with an error message.
- */
- public ImageBuilderInternalException(String s) {
- super(s);
- }
-
- /**
- * Creates the exception, wrappering another throwable.
- */
- public ImageBuilderInternalException(Throwable t) {
- fThrowable = t;
- }
-
- /**
- * Returns the throwable which this wraps, or null if not applicable.
- */
- public Throwable getThrowable() {
- return fThrowable;
- }
-
+/**
+ * Creates the exception with no error message.
+ */
+public ImageBuilderInternalException() {
+}
+/**
+ * Creates the exception with an error message.
+ */
+public ImageBuilderInternalException(String s) {
+ super(s);
+}
+/**
+ * Creates the exception, wrappering another throwable.
+ */
+public ImageBuilderInternalException(Throwable t) {
+ fThrowable = t;
+}
+/**
+ * Returns the throwable which this wraps, or null if not applicable.
+ */
+public Throwable getThrowable() {
+ return fThrowable;
+}
/**
* Prints the exception to System.err.
*/
@@ -41,5 +37,4 @@ public class ImageBuilderInternalException extends RuntimeException {
super.printStackTrace();
}
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ImageContextImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ImageContextImpl.java
index 0feb744249..210df5cc37 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ImageContextImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ImageContextImpl.java
@@ -19,7 +19,6 @@ public class ImageContextImpl implements IImageContext {
fDevContext = context;
fPackages = packages;
}
-
/**
* Returns true if the image context contains the given package, false otherwise.
*/
@@ -31,24 +30,19 @@ public class ImageContextImpl implements IImageContext {
}
return false;
}
-
/**
* Returns true if the given image context is equal to this one. Returns
* false otherwise.
*/
public boolean equals(Object o) {
- if (this == o)
- return true;
- if (!(o instanceof ImageContextImpl))
- return false;
+ if (this == o) return true;
+ if (!(o instanceof ImageContextImpl)) return false;
- ImageContextImpl ctx = (ImageContextImpl) o;
+ ImageContextImpl ctx = (ImageContextImpl)o;
- if (!ctx.fDevContext.equals(fDevContext))
- return false;
+ if (!ctx.fDevContext.equals(fDevContext)) return false;
int pkgCount = fPackages.length;
- if (ctx.fPackages.length != pkgCount)
- return false;
+ if (ctx.fPackages.length != pkgCount) return false;
/* place packages of this in hashtable to avoid n squared search */
Hashtable pkgTable = new Hashtable(pkgCount * 2 + 1);
@@ -65,14 +59,12 @@ public class ImageContextImpl implements IImageContext {
}
return true;
}
-
/**
* Returns the development context for this image context.
*/
public IDevelopmentContext getDevelopmentContext() {
return fDevContext;
}
-
/**
* Returns the packages in this image context. The packages will always
* be non state-specific.
@@ -80,31 +72,25 @@ public class ImageContextImpl implements IImageContext {
public IPackage[] getPackages() {
return fPackages;
}
-
/**
* Returns true if all packages in this image context appear in the given one.
*/
public boolean isSubsetOf(ImageContextImpl other) {
- if (this == other)
- return true;
- if (Util.equalArraysOrNull(fPackages, other.fPackages))
- return true;
+ if (this == other) return true;
+ if (Util.equalArraysOrNull(fPackages, other.fPackages)) return true;
for (int i = 0; i < fPackages.length; ++i) {
- if (!other.containsPackage(fPackages[i]))
- return false;
+ if (!other.containsPackage(fPackages[i])) return false;
}
return true;
}
-
/**
* Return a string describing the image context. This is for debugging
* purposes only.
*/
public String toString() {
- StringBuffer buf = new StringBuffer("ImageContext with packages: \n");
+ StringBuffer buf = new StringBuffer("ImageContext with packages: \n"/*nonNLS*/);
for (int i = 0; i < fPackages.length; i++)
- buf.append(" " + fPackages[i].getName() + "\n");
+ buf.append(" "/*nonNLS*/ + fPackages[i].getName() + "\n"/*nonNLS*/);
return buf.toString();
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ImageImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ImageImpl.java
index 18deb547d0..1bf30c241f 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ImageImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ImageImpl.java
@@ -8,8 +8,10 @@ import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.internal.core.builder.*;
-public class ImageImpl extends NonStateSpecificHandleImpl implements IImage {
- JavaDevelopmentContextImpl fDevelopmentContext;
+public class ImageImpl
+ extends NonStateSpecificHandleImpl
+ implements IImage {
+ JavaDevelopmentContextImpl fDevelopmentContext;
/**
* Creates a new image
@@ -17,56 +19,50 @@ public class ImageImpl extends NonStateSpecificHandleImpl implements IImage {
public ImageImpl(JavaDevelopmentContextImpl dc) {
fDevelopmentContext = dc;
}
-
- /**
- * Returns the Type representing the primitive type boolean.
- */
- public IType booleanType() {
- return fDevelopmentContext.fBooleanType;
- }
-
- /**
- * Returns the Type representing the primitive type byte
- */
- public org.eclipse.jdt.internal.core.builder.IType byteType() {
- return fDevelopmentContext.fByteType;
- }
-
- /**
- *Returns the Type representing the primitive type char
- */
- public org.eclipse.jdt.internal.core.builder.IType charType() {
- return fDevelopmentContext.fCharType;
- }
-
- /**
- * Returns an Image Context consisting of all the given packages.
- * This object and the packages must all be non-state-specific.
- * This is a handle-only operation. The packages need not
- * be present in the image.
- */
- public IImageContext createImageContext(IPackage[] packages)
- throws StateSpecificException {
- // copy array and verify that the packages are non-state-specific
- IPackage[] pkgs = new IPackage[packages.length];
- for (int i = 0; i < packages.length; i++) {
- if ((packages[i].kind() != K_JAVA_PACKAGE)
- || (packages[i].isStateSpecific())) {
+/**
+ * Returns the Type representing the primitive type boolean.
+ */
+public IType booleanType() {
+ return fDevelopmentContext.fBooleanType;
+}
+/**
+ * Returns the Type representing the primitive type byte
+ */
+public org.eclipse.jdt.internal.core.builder.IType byteType() {
+ return fDevelopmentContext.fByteType;
+}
+/**
+ *Returns the Type representing the primitive type char
+ */
+public org.eclipse.jdt.internal.core.builder.IType charType() {
+ return fDevelopmentContext.fCharType;
+}
+/**
+ * Returns an Image Context consisting of all the given packages.
+ * This object and the packages must all be non-state-specific.
+ * This is a handle-only operation. The packages need not
+ * be present in the image.
+ */
+public IImageContext createImageContext(IPackage[] packages)
+ throws StateSpecificException {
+ // copy array and verify that the packages are non-state-specific
+ IPackage[] pkgs = new IPackage[packages.length];
+ for (int i = 0; i < packages.length; i++) {
+ if ((packages[i].kind() != K_JAVA_PACKAGE) ||
+ (packages[i].isStateSpecific())) {
throw new StateSpecificException();
- }
- pkgs[i] = packages[i];
}
- // create the image context
- return new ImageContextImpl(fDevelopmentContext, pkgs);
+ pkgs[i] = packages[i];
}
-
- /**
- * Returns the Type representing the primitive type double
- */
- public org.eclipse.jdt.internal.core.builder.IType doubleType() {
- return fDevelopmentContext.fDoubleType;
- }
-
+ // create the image context
+ return new ImageContextImpl(fDevelopmentContext, pkgs);
+}
+/**
+ * Returns the Type representing the primitive type double
+ */
+public org.eclipse.jdt.internal.core.builder.IType doubleType() {
+ return fDevelopmentContext.fDoubleType;
+}
/**
* Compares this Image handle against the specified object. Returns
* true if the objects are the same. Two Image handles are the same if
@@ -75,162 +71,140 @@ public class ImageImpl extends NonStateSpecificHandleImpl implements IImage {
* See Handle.equals() for more details.
*/
public boolean equals(Object o) {
- if (this == o)
- return true;
- if (!(o instanceof ImageImpl))
- return false;
+ if (this == o) return true;
+ if (!(o instanceof ImageImpl)) return false;
ImageImpl image = (ImageImpl) o;
return fDevelopmentContext.equals(image.fDevelopmentContext);
}
-
- /**
- * Returns the Type representing the primitive type float
- */
- public org.eclipse.jdt.internal.core.builder.IType floatType() {
- return fDevelopmentContext.fFloatType;
- }
-
- /**
- * Returns an array containing Type objects representing all
- * classes and interfaces in the given ImageContext.
- * This includes public and default (package) access top-level
- * classes, inner classes, and local inner classes.
- * The result is the intersection of all classes present in this image
- * and the classes in the ImageContext, so the resulting classes
- * are all present in the image.
- * The resulting Types are in no particular order.
- */
- public IType[] getAllClasses(IImageContext context) {
- StateImpl state = (StateImpl) getDevelopmentContext().getCurrentState();
- IPackage[] pkgs =
- (context == null
- ? state.getPackageMap().getAllPackagesAsArray()
- : context.getPackages());
- java.util.Vector result = new java.util.Vector(pkgs.length * 25);
- for (int i = 0; i < pkgs.length; ++i) {
- TypeStructureEntry[] entries = state.getAllTypesForPackage(pkgs[i]);
- // entries is null if package is missing
- if (entries != null) {
- for (int j = 0, len = entries.length; j < len; ++j) {
- result.addElement(entries[j].getType());
- }
+/**
+ * Returns the Type representing the primitive type float
+ */
+public org.eclipse.jdt.internal.core.builder.IType floatType() {
+ return fDevelopmentContext.fFloatType;
+}
+/**
+ * Returns an array containing Type objects representing all
+ * classes and interfaces in the given ImageContext.
+ * This includes public and default (package) access top-level
+ * classes, inner classes, and local inner classes.
+ * The result is the intersection of all classes present in this image
+ * and the classes in the ImageContext, so the resulting classes
+ * are all present in the image.
+ * The resulting Types are in no particular order.
+ */
+public IType[] getAllClasses(IImageContext context) {
+ StateImpl state = (StateImpl) getDevelopmentContext().getCurrentState();
+ IPackage[] pkgs = (context == null ? state.getPackageMap().getAllPackagesAsArray() : context.getPackages());
+ java.util.Vector result = new java.util.Vector(pkgs.length * 25);
+ for (int i = 0; i < pkgs.length; ++i) {
+ TypeStructureEntry[] entries = state.getAllTypesForPackage(pkgs[i]);
+ // entries is null if package is missing
+ if (entries != null) {
+ for (int j = 0, len = entries.length; j < len; ++j) {
+ result.addElement(entries[j].getType());
}
}
- // convert the Vector to an array
- IType[] types = new IType[result.size()];
- result.copyInto(types);
- return types;
}
-
+ // convert the Vector to an array
+ IType[] types = new IType[result.size()];
+ result.copyInto(types);
+ return types;
+}
/**
* Returns an array of all packages present in the image. Note that this
* method defies the concept of a potentially infinite image, and should only
* be used by clients that must operate over the entire image (search, code assist)
*/
public IPackage[] getAllPackages() {
- StateImpl state = (StateImpl) fDevelopmentContext.getCurrentState();
+ StateImpl state = (StateImpl)fDevelopmentContext.getCurrentState();
return state.getPackageMap().getAllPackagesAsArray();
}
-
/**
* @see IImage
*/
public IType[] getBuiltClasses(IPath path) {
return nonStateSpecific(((IImage) inCurrentState()).getBuiltClasses(path));
}
-
- /**
- * Return the internal representation of the development context that owns this object
- */
- JavaDevelopmentContextImpl getInternalDC() {
- return fDevelopmentContext;
- }
-
- /**
- * Returns a handle representing the package with the given
- * name. For named packages, this is the fully qualified
- * name. For unnamed packages, it is some internal identifying
- * string.
- * See <em>The Java Language Specification</em> section 7.4.1 and
- * 7.4.2 for more details.
- * This is a handle-only method; the specified package
- * may or may not actually be present in the image.
- */
- public IPackage getPackageHandle(String name, boolean isUnnamed) {
- return new PackageImpl(fDevelopmentContext, name, isUnnamed);
- }
-
- /**
- * Returns an array of Package objects representing all
- * packages contained in the given ImageContext.
- * The result is the intersection of the packages present in this image
- * and the packages in the ImageContext, so the resulting packages
- * are all present in the image.
- * The resulting Packages are in no particular order.
- */
- public IPackage[] getPackages(IImageContext context) {
- if (context == null) {
- return ((StateImpl) fDevelopmentContext.getCurrentState())
- .getAllPackagesAsArray();
- }
- return nonStateSpecific(((IImage) inCurrentState()).getPackages(context));
+/**
+ * Return the internal representation of the development context that owns this object
+ */
+JavaDevelopmentContextImpl getInternalDC() {
+ return fDevelopmentContext;
+}
+/**
+ * Returns a handle representing the package with the given
+ * name. For named packages, this is the fully qualified
+ * name. For unnamed packages, it is some internal identifying
+ * string.
+ * See <em>The Java Language Specification</em> section 7.4.1 and
+ * 7.4.2 for more details.
+ * This is a handle-only method; the specified package
+ * may or may not actually be present in the image.
+ */
+public IPackage getPackageHandle(String name, boolean isUnnamed) {
+ return new PackageImpl(fDevelopmentContext, name, isUnnamed);
+}
+/**
+ * Returns an array of Package objects representing all
+ * packages contained in the given ImageContext.
+ * The result is the intersection of the packages present in this image
+ * and the packages in the ImageContext, so the resulting packages
+ * are all present in the image.
+ * The resulting Packages are in no particular order.
+ */
+public IPackage[] getPackages(IImageContext context) {
+ if (context == null) {
+ return ((StateImpl) fDevelopmentContext.getCurrentState()).getAllPackagesAsArray();
}
-
+ return nonStateSpecific(((IImage) inCurrentState()).getPackages(context));
+}
/**
* Returns a consistent hash code for this object
*/
public int hashCode() {
return fDevelopmentContext.hashCode();
}
-
- /**
- * Returns the state wrapped handle
- */
- public IHandle inState(IState state) {
- return state.getImage();
- }
-
- /**
- * Returns the Type representing the primitive type int
- */
- public org.eclipse.jdt.internal.core.builder.IType intType() {
- return fDevelopmentContext.fIntType;
- }
-
- /**
- * kind method comment.
- */
- public int kind() {
- return K_JAVA_IMAGE;
- }
-
- /**
- * Returns the Type representing the primitive type long
- */
- public org.eclipse.jdt.internal.core.builder.IType longType() {
- return fDevelopmentContext.fLongType;
- }
-
- /**
- * Returns the Type representing the primitive type short
- */
- public org.eclipse.jdt.internal.core.builder.IType shortType() {
- return fDevelopmentContext.fShortType;
- }
-
+/**
+ * Returns the state wrapped handle
+ */
+public IHandle inState(IState state) {
+ return state.getImage();
+}
+/**
+ * Returns the Type representing the primitive type int
+ */
+public org.eclipse.jdt.internal.core.builder.IType intType() {
+ return fDevelopmentContext.fIntType;
+}
+/**
+ * kind method comment.
+ */
+public int kind() {
+ return K_JAVA_IMAGE;
+}
+/**
+ * Returns the Type representing the primitive type long
+ */
+public org.eclipse.jdt.internal.core.builder.IType longType() {
+ return fDevelopmentContext.fLongType;
+}
+/**
+ * Returns the Type representing the primitive type short
+ */
+public org.eclipse.jdt.internal.core.builder.IType shortType() {
+ return fDevelopmentContext.fShortType;
+}
/**
* Returns a string representation of the image handle.
*/
public String toString() {
- return "image";
- }
-
- /**
- * Returns the Type representing the primitive type void
- */
- public org.eclipse.jdt.internal.core.builder.IType voidType() {
- return fDevelopmentContext.fVoidType;
+ return "image"/*nonNLS*/;
}
-
+/**
+ * Returns the Type representing the primitive type void
+ */
+public org.eclipse.jdt.internal.core.builder.IType voidType() {
+ return fDevelopmentContext.fVoidType;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ImageImplSWH.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ImageImplSWH.java
index 95ab3943aa..1d35cebf32 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ImageImplSWH.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ImageImplSWH.java
@@ -23,87 +23,76 @@ public class ImageImplSWH extends StateSpecificHandleImpl implements IImage {
fState = state;
fHandle = handle;
}
-
- /**
- * booleanType method comment.
- */
- public IType booleanType() {
- return fState.fBooleanType;
- }
-
- /**
- * Returns the Type representing the primitive type byte
- */
- public IType byteType() {
- return fState.fByteType;
- }
-
- /**
- *Returns the Type representing the primitive type char
- */
- public IType charType() {
- return fState.fCharType;
- }
-
- /**
- * Returns an Image Context consisting of all the given packages.
- * This object and the packages must all be non-state-specific.
- * This is a handle-only operation. The packages need not
- * be present in the image.
- */
- public IImageContext createImageContext(IPackage[] packages)
- throws StateSpecificException {
+/**
+ * booleanType method comment.
+ */
+public IType booleanType() {
+ return fState.fBooleanType;
+}
+/**
+ * Returns the Type representing the primitive type byte
+ */
+public IType byteType() {
+ return fState.fByteType;
+}
+/**
+ *Returns the Type representing the primitive type char
+ */
+public IType charType() {
+ return fState.fCharType;
+}
+/**
+ * Returns an Image Context consisting of all the given packages.
+ * This object and the packages must all be non-state-specific.
+ * This is a handle-only operation. The packages need not
+ * be present in the image.
+ */
+public IImageContext createImageContext(IPackage[] packages)
+ throws StateSpecificException {
throw new StateSpecificException();
-
- }
-
- /**
- * Returns the Type representing the primitive type double
- */
- public IType doubleType() {
- return fState.fDoubleType;
- }
-
- /**
- * Returns the Type representing the primitive type float
- */
- public IType floatType() {
- return fState.fFloatType;
- }
-
- /**
- * Returns an array containing Type objects representing all
- * classes and interfaces in the given ImageContext.
- * This includes public and default (package) access top-level
- * classes, inner classes, and local inner classes.
- * The result is the intersection of all classes present in this image
- * and the classes in the ImageContext, so the resulting classes
- * are all present in the image.
- * The resulting Types are in no particular order.
- */
- public IType[] getAllClasses(IImageContext context) {
- StateImpl state = fState;
- IPackage[] pkgs =
- (context == null
- ? state.getPackageMap().getAllPackagesAsArray()
- : context.getPackages());
-
- java.util.Vector result = new java.util.Vector(pkgs.length * 25);
- for (int i = 0; i < pkgs.length; i++) {
- TypeStructureEntry[] entries = state.getAllTypesForPackage(pkgs[i]);
- // entries is null if package is missing
- if (entries != null) {
- for (int j = 0, len = entries.length; j < len; ++j) {
- result.addElement(entries[j].getType().inState(state));
- }
+
+}
+/**
+ * Returns the Type representing the primitive type double
+ */
+public IType doubleType() {
+ return fState.fDoubleType;
+}
+/**
+ * Returns the Type representing the primitive type float
+ */
+public IType floatType() {
+ return fState.fFloatType;
+}
+/**
+ * Returns an array containing Type objects representing all
+ * classes and interfaces in the given ImageContext.
+ * This includes public and default (package) access top-level
+ * classes, inner classes, and local inner classes.
+ * The result is the intersection of all classes present in this image
+ * and the classes in the ImageContext, so the resulting classes
+ * are all present in the image.
+ * The resulting Types are in no particular order.
+ */
+public IType[] getAllClasses(IImageContext context) {
+ StateImpl state = fState;
+ IPackage[] pkgs = (context == null ? state.getPackageMap().getAllPackagesAsArray() : context.getPackages());
+
+ java.util.Vector result = new java.util.Vector(pkgs.length * 25);
+ for (int i = 0; i < pkgs.length; i++) {
+ TypeStructureEntry[] entries = state.getAllTypesForPackage(pkgs[i]);
+ // entries is null if package is missing
+ if (entries != null) {
+ for (int j = 0, len = entries.length; j < len; ++j) {
+ result.addElement(entries[j].getType().inState(state));
}
}
- // convert the Vector to an array
- IType[] types = new IType[result.size()];
- result.copyInto(types);
- return types;
}
-
+ // convert the Vector to an array
+ IType[] types = new IType[result.size()];
+ result.copyInto(types);
+ return types;
+}
/**
* Returns an array of all packages present in the image. Note that this
* method defies the concept of a potentially infinite image, and should only
@@ -118,33 +107,32 @@ public class ImageImplSWH extends StateSpecificHandleImpl implements IImage {
}
return swh;
}
-
/**
* @see IImage
*/
public IType[] getBuiltClasses(IPath path) {
Vector vResult = new Vector();
- // try {
- String extension = path.getFileExtension().toLowerCase();
- if (extension.equals("java") || extension.equals("class")) {
- IPath pkgPath = path.removeLastSegments(1);
- IPackage pkg = fState.getPathMap().packageHandleFromPath(pkgPath);
- TypeStructureEntry[] tsEntries = fState.getAllTypesForPackage(pkg);
- if (tsEntries != null) { // present?
- for (int i = 0, len = tsEntries.length; i < len; ++i) {
- TypeStructureEntry tsEntry = tsEntries[i];
- if (path.equals(tsEntry.getSourceEntry().getPath())) {
- vResult.addElement(tsEntry.getType().inState(fState));
+// try {
+ String extension = path.getFileExtension().toLowerCase();
+ if (extension.equals("java"/*nonNLS*/) || extension.equals("class"/*nonNLS*/)) {
+ IPath pkgPath = path.removeLastSegments(1);
+ IPackage pkg = fState.getPathMap().packageHandleFromPath(pkgPath);
+ TypeStructureEntry[] tsEntries = fState.getAllTypesForPackage(pkg);
+ if (tsEntries != null) { // present?
+ for (int i = 0, len = tsEntries.length; i < len; ++i) {
+ TypeStructureEntry tsEntry = tsEntries[i];
+ if (path.equals(tsEntry.getSourceEntry().getPath())) {
+ vResult.addElement(tsEntry.getType().inState(fState));
+ }
}
}
}
- } else
- if (fState.isZipElement(path)) {
+ else if (fState.isZipElement(path)) {
IPackage[] pkgs = fState.getPathMap().packageHandlesFromPath(path);
for (int i = 0; i < pkgs.length; ++i) {
IPackage pkg = pkgs[i];
TypeStructureEntry[] tsEntries = fState.getAllTypesForPackage(pkg);
- if (tsEntries != null) { // present?
+ if (tsEntries != null) { // present?
for (int j = 0, len = tsEntries.length; j < len; ++j) {
TypeStructureEntry tsEntry = tsEntries[j];
if (path.equals(tsEntry.getSourceEntry().getPath())) {
@@ -153,7 +141,8 @@ public class ImageImplSWH extends StateSpecificHandleImpl implements IImage {
}
}
}
- } else {
+ }
+ else {
if (path.equals(fState.getProject().getFullPath())) {
try {
IResource[] members = fState.getProject().members();
@@ -166,10 +155,11 @@ public class ImageImplSWH extends StateSpecificHandleImpl implements IImage {
} catch (CoreException e) {
//couldn't access the project -- ignore and return empty array
}
- } else { // package
+ }
+ else { // package
IPackage pkg = fState.getPathMap().packageHandleFromPath(path);
TypeStructureEntry[] tsEntries = fState.getAllTypesForPackage(pkg);
- if (tsEntries != null) { // present?
+ if (tsEntries != null) { // present?
for (int i = 0, len = tsEntries.length; i < len; ++i) {
TypeStructureEntry tsEntry = tsEntries[i];
if (path.isPrefixOf(tsEntry.getSourceEntry().getPath())) {
@@ -179,107 +169,97 @@ public class ImageImplSWH extends StateSpecificHandleImpl implements IImage {
}
}
}
- // }
- // catch (ResourceAccessException e) {
- // fState.resourceAccessException(e);
- // }
+// }
+// catch (ResourceAccessException e) {
+// fState.resourceAccessException(e);
+// }
IType[] result = new IType[vResult.size()];
vResult.copyInto(result);
return result;
}
-
- /**
- * Returns a handle representing the package with the given
- * name. For named packages, this is the fully qualified
- * name. For unnamed packages, it is some internal identifying
- * string.
- * See <em>The Java Language Specification</em> section 7.4.1 and
- * 7.4.2 for more details.
- * This is a handle-only method; the specified package
- * may or may not actually be present in the image.
- *
- * @parameter name the name of the package.
- * @parameter isUnnamed a boolean indicating whether the package is unnamed.
- * @see IPackage#getName
- * @see IHandle
- */
- public IPackage getPackageHandle(String name, boolean isUnnamed) {
- return (IPackage) fHandle.getPackageHandle(name, isUnnamed).inState(fState);
- }
-
- /**
- * Returns an array of Package objects representing all
- * packages contained in the given ImageContext.
- * The result is the intersection of the packages present in this image
- * and the packages in the ImageContext, so the resulting packages
- * are all present in the image.
- * The resulting Packages are in no particular order.
- */
- public IPackage[] getPackages(IImageContext context) {
- if (context == null) {
- return getAllPackages();
- }
- IPackage[] ctxPkgs = context.getPackages();
- Vector result = new Vector();
- for (int i = 0; i < ctxPkgs.length; i++) {
- IPackage pkgSWH = (IPackage) ctxPkgs[i].inState(fState);
- if (pkgSWH.isPresent())
- result.addElement(pkgSWH);
- }
- // convert the Vector to an array
- IPackage[] pkgs = new IPackage[result.size()];
- result.copyInto(pkgs);
- return pkgs;
- }
-
- /**
- * Returns the Type representing the primitive type int
+/**
+ * Returns a handle representing the package with the given
+ * name. For named packages, this is the fully qualified
+ * name. For unnamed packages, it is some internal identifying
+ * string.
+ * See <em>The Java Language Specification</em> section 7.4.1 and
+ * 7.4.2 for more details.
+ * This is a handle-only method; the specified package
+ * may or may not actually be present in the image.
+ *
+ * @parameter name the name of the package.
+ * @parameter isUnnamed a boolean indicating whether the package is unnamed.
+ * @see IPackage#getName
+ * @see IHandle
*/
- public IType intType() {
- return fState.fIntType;
- }
-
- /**
- * Returns whether the image is present.
- */
- public boolean isPresent() {
- /* the image is always present */
- return true;
+ public IPackage getPackageHandle(String name, boolean isUnnamed) {
+ return (IPackage)fHandle.getPackageHandle(name, isUnnamed).inState(fState);
}
-
- /**
- * kind method comment.
- */
- public int kind() {
- return K_JAVA_IMAGE;
+/**
+ * Returns an array of Package objects representing all
+ * packages contained in the given ImageContext.
+ * The result is the intersection of the packages present in this image
+ * and the packages in the ImageContext, so the resulting packages
+ * are all present in the image.
+ * The resulting Packages are in no particular order.
+ */
+public IPackage[] getPackages(IImageContext context) {
+ if (context == null) {
+ return getAllPackages();
}
-
- /**
- * Returns the Type representing the primitive type long
- */
- public IType longType() {
- return fState.fLongType;
+ IPackage[] ctxPkgs = context.getPackages();
+ Vector result = new Vector();
+ for (int i = 0; i < ctxPkgs.length; i++) {
+ IPackage pkgSWH = (IPackage) ctxPkgs[i].inState(fState);
+ if (pkgSWH.isPresent())
+ result.addElement(pkgSWH);
}
-
+ // convert the Vector to an array
+ IPackage[] pkgs = new IPackage[result.size()];
+ result.copyInto(pkgs);
+ return pkgs;
+}
+/**
+ * Returns the Type representing the primitive type int
+ */
+public IType intType() {
+ return fState.fIntType;
+}
+/**
+ * Returns whether the image is present.
+ */
+public boolean isPresent() {
+ /* the image is always present */
+ return true;
+}
+/**
+ * kind method comment.
+ */
+public int kind() {
+ return K_JAVA_IMAGE;
+}
+/**
+ * Returns the Type representing the primitive type long
+ */
+public IType longType() {
+ return fState.fLongType;
+}
/**
* Returns the non state specific handle
*/
- public IHandle nonStateSpecific() {
- return fHandle;
- }
-
- /**
- * Returns the Type representing the primitive type short
- */
- public IType shortType() {
- return fState.fShortType;
- }
-
- /**
- * Returns the Type representing the primitive type void
- */
- public IType voidType() {
- return fState.fVoidType;
- }
-
+ public IHandle nonStateSpecific() {
+ return fHandle;
+ }
+/**
+ * Returns the Type representing the primitive type short
+ */
+public IType shortType() {
+ return fState.fShortType;
+}
+/**
+ * Returns the Type representing the primitive type void
+ */
+public IType voidType() {
+ return fState.fVoidType;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/IncrementalImageBuilder.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/IncrementalImageBuilder.java
index f4469f952d..94e5a0eecd 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/IncrementalImageBuilder.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/IncrementalImageBuilder.java
@@ -23,7 +23,7 @@ import org.eclipse.jdt.internal.core.builder.*;
import org.eclipse.jdt.internal.core.builder.IType;
import org.eclipse.jdt.internal.core.builder.NotPresentException;
import org.eclipse.jdt.internal.core.lookup.ReferenceInfo;
-
+import org.eclipse.jdt.internal.core.Util;
import org.eclipse.jdt.internal.compiler.util.*;
import org.eclipse.jdt.internal.core.*;
@@ -121,468 +121,446 @@ public class IncrementalImageBuilder extends AbstractImageBuilder {
* indictment processing
*/
protected Hashtable fBuilderTypeTable;
- /**
- * Creates a new incremental image builder on the given new workspace.
- * The builder will build all classes that have changed since the old state,
- * within the given image context.
- */
- protected IncrementalImageBuilder(
- StateImpl oldState,
- IProject newProject,
- IImageContext context) {
- fDC = (JavaDevelopmentContextImpl) oldState.getDevelopmentContext();
- fOldState = oldState;
- fNewProject = newProject;
- fImageContext = context;
- fBuilderTypeTable = new Hashtable(11);
- }
-
- /**
- * Given an element delta for a changed package, add the package elements
- * for changing elements to the table, keyed by package handle and file name.
- * Added and removed elements are ignored.
- */
- protected void addChangedFileNamesFromChangedPackage(
- IResourceDelta pkgDelta,
- Hashtable table) {
- IPackage[] pkgs =
- fNewState.getPathMap().packageHandlesFromPath(pkgDelta.getFullPath());
- for (int p = 0; p < pkgs.length; ++p) {
- IPackage pkg = pkgs[p];
- Hashtable pkgTable = (Hashtable) table.get(pkg);
- if (pkgTable == null) {
- pkgTable = new Hashtable(11);
- table.put(pkg, pkgTable);
- }
- IResourceDelta[] elementDeltas =
- pkgDelta.getAffectedChildren(IResourceDelta.CHANGED);
- for (int i = 0; i < elementDeltas.length; ++i) {
- IResourceDelta elementDelta = elementDeltas[i];
- // Only add if the contents are changing.
- if ((elementDelta.getFlags() & IResourceDelta.CONTENT) != 0) {
- IPath path = elementDelta.getFullPath();
- String extension = path.getFileExtension();
- if (extension != null) {
- if (extension.equalsIgnoreCase("java")
- || extension.equalsIgnoreCase("class")) {
- SourceEntry entry = new SourceEntry(path, null, null);
- PackageElement element = new PackageElement(pkg, entry);
- pkgTable.put(entry.getFileName(), element);
- }
+/**
+ * Creates a new incremental image builder on the given new workspace.
+ * The builder will build all classes that have changed since the old state,
+ * within the given image context.
+ */
+protected IncrementalImageBuilder(StateImpl oldState, IProject newProject, IImageContext context) {
+ fDC = (JavaDevelopmentContextImpl) oldState.getDevelopmentContext();
+ fOldState = oldState;
+ fNewProject = newProject;
+ fImageContext = context;
+ fBuilderTypeTable = new Hashtable(11);
+}
+/**
+ * Given an element delta for a changed package, add the package elements
+ * for changing elements to the table, keyed by package handle and file name.
+ * Added and removed elements are ignored.
+ */
+protected void addChangedFileNamesFromChangedPackage(IResourceDelta pkgDelta, Hashtable table) {
+ IPackage[] pkgs = fNewState.getPathMap().packageHandlesFromPath(pkgDelta.getFullPath());
+ for (int p = 0; p < pkgs.length; ++p) {
+ IPackage pkg = pkgs[p];
+ Hashtable pkgTable = (Hashtable) table.get(pkg);
+ if (pkgTable == null) {
+ pkgTable = new Hashtable(11);
+ table.put(pkg, pkgTable);
+ }
+ IResourceDelta[] elementDeltas = pkgDelta.getAffectedChildren(IResourceDelta.CHANGED);
+ for (int i = 0; i < elementDeltas.length; ++i) {
+ IResourceDelta elementDelta = elementDeltas[i];
+ // Only add if the contents are changing.
+ if ((elementDelta.getFlags() & IResourceDelta.CONTENT) != 0) {
+ IPath path = elementDelta.getFullPath();
+ String extension = path.getFileExtension();
+ if (extension != null) {
+ if (extension.equalsIgnoreCase("java"/*nonNLS*/) || extension.equalsIgnoreCase("class"/*nonNLS*/)) {
+ SourceEntry entry = new SourceEntry(path, null, null);
+ PackageElement element = new PackageElement(pkg, entry);
+ pkgTable.put(entry.getFileName(), element);
}
}
}
}
}
-
- /**
- * Adds the new classes for this build to the state.
- */
- protected void addNewClasses() {
- for (Enumeration e = fAddedClasses.elements(); e.hasMoreElements();) {
- addSourceElement((SourceEntry) e.nextElement());
- }
+}
+/**
+ * Adds the new classes for this build to the state.
+ */
+protected void addNewClasses() {
+ for (Enumeration e = fAddedClasses.elements(); e.hasMoreElements();) {
+ addSourceElement((SourceEntry) e.nextElement());
}
+}
+/**
+ * Adds the given source element to the new state's tables
+ * and dependency graph.
+ */
+protected void addSourceElement(SourceEntry newEntry) {
+ if (newEntry.isSource()) {
+ PackageElement element = fNewState.packageElementFromSourceEntry(newEntry);
+ IPackage pkg = element.getPackage();
- /**
- * Adds the given source element to the new state's tables
- * and dependency graph.
- */
- protected void addSourceElement(SourceEntry newEntry) {
- if (newEntry.isSource()) {
- PackageElement element = fNewState.packageElementFromSourceEntry(newEntry);
- IPackage pkg = element.getPackage();
-
- /* the addition must be in a package which is in the class path */
- Assert.isTrue(fNewState.getPackageMap().containsPackage(pkg));
- DependencyGraph graph = fNewState.getInternalDependencyGraph();
- graph.add(element);
- fWorkQueue.add(element);
- }
+ /* the addition must be in a package which is in the class path */
+ Assert.isTrue(fNewState.getPackageMap().containsPackage(pkg));
+ DependencyGraph graph = fNewState.getInternalDependencyGraph();
+ graph.add(element);
+ fWorkQueue.add(element);
+ }
+}
+/**
+ * Applies the deltas to the old state to build the new state.
+ * The old state and new state have been set.
+ * The new state knows its workspace and build context.
+ * This is the method that actually does the incremental build
+ */
+public void applySourceDelta(Hashtable deltas) {
+ fNotifier = new BuildNotifier(fDC, false);
+ fNotifier.begin();
+ fNotifier.subTask(Util.bind("build.preparingBuild"/*nonNLS*/));
+ fSourceDeltas = deltas;
+ fNewState = fOldState.copy(fNewProject, fImageContext);
+
+ // options might have changed since last builder run, thus refresh them
+ fCompilerOptions = JavaModelManager.convertConfigurableOptions(JavaCore.getOptions());
+ fNewState.setCompilerOptions(fCompilerOptions);
+
+ try {
+ /* find out what has changed at the package level */
+ fNotifier.subTask(Util.bind("build.analyzingPackage"/*nonNLS*/));
+ computeAllPackages();
+ checkCancel();
+
+ /* update the package map */
+ updatePackageMap();
+ fNewState.canonicalizeBuildContext();
+ fNotifier.updateProgressDelta(0.05f);
+ checkCancel();
+
+ /* Update the source element table and namespace table for the removed and changed packages.
+ * The tables are simply deleted. They will be rebuilt lazily for changed packages. */
+ for (Enumeration e = fRemovedPackageHandles.elements(); e.hasMoreElements();) {
+ IPackage pkgHandle = (IPackage) e.nextElement();
+ fNewState.getSourceElementTable().removePackage(pkgHandle);
+ }
+ recomputeSourceEntriesForChangedPackages();
+ checkCancel();
+ fWorkQueue = new WorkQueue();
+
+ /* rebuild the namespaces and issue indictments for changes */
+ computeNamespaceChanges();
+ // 1G220B5 - force compilation of all their dependents as well - only one level deeper
+ for (Enumeration e = fWorkQueue.getElementsToCompile().elements(); e.hasMoreElements();) {
+ markDependentsAsNeedingCompile(e.nextElement());
+ }
+
+ /* find out what has changed at the package element level */
+ fNotifier.subTask(Util.bind("build.analyzingSources"/*nonNLS*/));
+ computeAllClasses();
+ checkCancel();
+
+ /* All dependents of changed zips will need compiling */
+ markDependentsOfChangedZips();
+
+ /* remove old classes and get affected JCUs */
+ removeOldClasses();
+ checkCancel();
+
+ /* flag changed classes and get compilation units to compile */
+ updateChangedClasses();
+ checkCancel();
+
+ /* adding new classes might hide (equivalent to delete) old classes */
+ addNewClasses();
+ checkCancel();
+
+ float amountPerIteration = 0.60f; // Approximation of n + (n/4) + (n/16) + ... = 0.85
+
+ /* keep compiling until there is nothing left to compile */
+ Vector vToCompile = fWorkQueue.getElementsToCompile();
+ while (vToCompile.size() != 0) {
+ fNotifier.setProgressPerCompilationUnit(amountPerIteration / vToCompile.size());
+ compile(vToCompile);
+ vToCompile = fWorkQueue.getElementsToCompile();
+ amountPerIteration *= 0.25f;
+ }
+
+ // not using PrincipalStructureByPackageTable
+ // propagatePrincipalStructureByPackageTable();
+
+ // Force all in build context
+ /*
+ Don't force -- we're not doing lazy builds.
+
+ if (fAddedPackageHandles.size() > 0 || fChangedPackageHandles.size() > 0) {
+ for (int i = 0; i < fAddedPackageHandles.size(); ++i) {
+ IPackage pkg = (IPackage) fAddedPackageHandles.elementAt(i);
+ maybeForce(pkg);
+ }
+ for (int i = 0; i < fChangedPackageHandles.size(); ++i) {
+ IPackage pkg = (IPackage) fChangedPackageHandles.elementAt(i);
+ maybeForce(pkg);
+ }
+ }
+ */
+ /* Update resources in binary output */
+ IResourceDelta projectDelta = (IResourceDelta) deltas.get(fNewProject);
+ if (projectDelta != null) {
+ ProjectResourceCopier copier = new ProjectResourceCopier(fNewState.getJavaProject(), fDC, fNotifier, 0.10f);
+ copier.updateAffectedResources(projectDelta);
+ }
+
+ /* Removals and recompilations can leave unused namespace nodes in the
+ * dependency graph. Clean them up. */
+ cleanupUnusedNamespaceNodes();
+ checkCancel();
+
+ /* Copy resource to binary output */
+ //copyResources(projectDelta, 0.05f);
+
+ fNotifier.done();
+ } finally {
+ cleanUp();
+ }
+}
+/**
+ * Applies the delta to the old state
+ * to build the new state. The old state and new state have been set.
+ * The new state knows its workspace and build context.
+ * This is the method that actually does the incremental build
+ */
+public void applySourceDelta(IResourceDelta projectDelta) {
+ Hashtable deltas = new Hashtable(11);
+ deltas.put(fNewProject, projectDelta);
+ applySourceDelta(deltas);
+}
+/**
+ * The given source element has changed and will be compiled.
+ * Flag the node in the dependency graph, and store all compilation
+ * units that will need compiling as a result of the change.
+ */
+protected void changedSourceElement(SourceEntry newEntry) {
+ PackageElement element = fNewState.packageElementFromSourceEntry(newEntry);
+ if (element.isSource()) {
+ fWorkQueue.add(element);
}
- /**
- * Applies the deltas to the old state to build the new state.
- * The old state and new state have been set.
- * The new state knows its workspace and build context.
- * This is the method that actually does the incremental build
- */
- public void applySourceDelta(Hashtable deltas) {
- fNotifier = new BuildNotifier(fDC, false);
- fNotifier.begin();
- fNotifier.subTask("Preparing for build");
- fSourceDeltas = deltas;
- fNewState = fOldState.copy(fNewProject, fImageContext);
-
- // options might have changed since last builder run, thus refresh them
- fCompilerOptions =
- JavaModelManager.convertConfigurableOptions(JavaCore.getOptions());
- fNewState.setCompilerOptions(fCompilerOptions);
-
- try {
- /* find out what has changed at the package level */
- fNotifier.subTask("Analyzing packages");
- computeAllPackages();
- checkCancel();
-
- /* update the package map */
- updatePackageMap();
- fNewState.canonicalizeBuildContext();
- fNotifier.updateProgressDelta(0.05f);
- checkCancel();
-
- /* Update the source element table and namespace table for the removed and changed packages.
- * The tables are simply deleted. They will be rebuilt lazily for changed packages. */
- for (Enumeration e = fRemovedPackageHandles.elements(); e.hasMoreElements();) {
- IPackage pkgHandle = (IPackage) e.nextElement();
- fNewState.getSourceElementTable().removePackage(pkgHandle);
- }
- recomputeSourceEntriesForChangedPackages();
- checkCancel();
- fWorkQueue = new WorkQueue();
-
- /* rebuild the namespaces and issue indictments for changes */
- computeNamespaceChanges();
- // 1G220B5 - force compilation of all their dependents as well - only one level deeper
- for (Enumeration e = fWorkQueue.getElementsToCompile().elements();
- e.hasMoreElements();
- ) {
- markDependentsAsNeedingCompile(e.nextElement());
- }
-
- /* find out what has changed at the package element level */
- fNotifier.subTask("Analyzing sources");
- computeAllClasses();
- checkCancel();
-
- /* All dependents of changed zips will need compiling */
- markDependentsOfChangedZips();
-
- /* remove old classes and get affected JCUs */
- removeOldClasses();
- checkCancel();
-
- /* flag changed classes and get compilation units to compile */
- updateChangedClasses();
- checkCancel();
-
- /* adding new classes might hide (equivalent to delete) old classes */
- addNewClasses();
- checkCancel();
-
- float amountPerIteration = 0.60f;
- // Approximation of n + (n/4) + (n/16) + ... = 0.85
-
- /* keep compiling until there is nothing left to compile */
- Vector vToCompile = fWorkQueue.getElementsToCompile();
- while (vToCompile.size() != 0) {
- fNotifier.setProgressPerCompilationUnit(amountPerIteration / vToCompile.size());
- compile(vToCompile);
- vToCompile = fWorkQueue.getElementsToCompile();
- amountPerIteration *= 0.25f;
- }
-
- // not using PrincipalStructureByPackageTable
- // propagatePrincipalStructureByPackageTable();
-
- // Force all in build context
- /*
- Don't force -- we're not doing lazy builds.
-
- if (fAddedPackageHandles.size() > 0 || fChangedPackageHandles.size() > 0) {
- for (int i = 0; i < fAddedPackageHandles.size(); ++i) {
- IPackage pkg = (IPackage) fAddedPackageHandles.elementAt(i);
- maybeForce(pkg);
- }
- for (int i = 0; i < fChangedPackageHandles.size(); ++i) {
- IPackage pkg = (IPackage) fChangedPackageHandles.elementAt(i);
- maybeForce(pkg);
- }
- }
- */
- /* Update resources in binary output */
- IResourceDelta projectDelta = (IResourceDelta) deltas.get(fNewProject);
- if (projectDelta != null) {
- ProjectResourceCopier copier =
- new ProjectResourceCopier(fNewState.getJavaProject(), fDC, fNotifier, 0.10f);
- copier.updateAffectedResources(projectDelta);
+ /* remove problems for this source entry */
+ SourceEntry oldEntry = fOldState.getSourceEntry(element);
+ fNewState.getProblemReporter().removeProblems(oldEntry);
+}
+/**
+ * Since the image builder is given as a result, let go of
+ * any unneeded structures.
+ */
+protected void cleanUp() {
+ super.cleanUp();
+ // Don't clear package level information because it's needed to compute the image delta.
+ fSourceDeltas = null;
+ fAddedClasses = fRemovedClasses = fChangedClasses = null;
+}
+/**
+ * Removals and recompilations can leave unused namespace nodes in the
+ * dependency graph. Clean them up.
+ */
+protected void cleanupUnusedNamespaceNodes() {
+ if (fRemovedClasses.size() > 0 || fChangedClasses.size() > 0) {
+ PackageMap packageMap = fNewState.getPackageMap();
+ DependencyGraph graph = fNewState.getInternalDependencyGraph();
+ Vector unused = graph.getUnusedNamespaceNodes();
+ for (Enumeration e = unused.elements(); e.hasMoreElements();) {
+ NamespaceNode node = (NamespaceNode) e.nextElement();
+ IPackage pkg = node.getPackage();
+ if (!packageMap.containsPackage(pkg)) {
+ graph.removePackage(pkg);
}
-
- /* Removals and recompilations can leave unused namespace nodes in the
- * dependency graph. Clean them up. */
- cleanupUnusedNamespaceNodes();
- checkCancel();
-
- /* Copy resource to binary output */
- //copyResources(projectDelta, 0.05f);
-
- fNotifier.done();
- } finally {
- cleanUp();
}
}
-
- /**
- * Applies the delta to the old state
- * to build the new state. The old state and new state have been set.
- * The new state knows its workspace and build context.
- * This is the method that actually does the incremental build
- */
- public void applySourceDelta(IResourceDelta projectDelta) {
- Hashtable deltas = new Hashtable(11);
- deltas.put(fNewProject, projectDelta);
- applySourceDelta(deltas);
+}
+/**
+ * Compare the visibility and gender of the two types.
+ * Returns true if equal, false if not.
+ */
+protected boolean compareVisibilityAndGender(TypeStructureEntry tsEntry, org.eclipse.jdt.core.IType type) throws JavaModelException {
+ try {
+ /* This relies on visibility bits being the same between the image builder and the java model. */
+ IType oldType = (IType) tsEntry.getType().inState(fNewState);
+ final int visVlags = IConstants.AccPublic | IConstants.AccPrivate | IConstants.AccProtected;
+ int oldVis = oldType.getModifiers() & visVlags;
+ int newVis = type.getFlags() & visVlags;
+ return oldVis == newVis && oldType.isInterface() == type.isInterface();
}
-
- /**
- * The given source element has changed and will be compiled.
- * Flag the node in the dependency graph, and store all compilation
- * units that will need compiling as a result of the change.
- */
- protected void changedSourceElement(SourceEntry newEntry) {
- PackageElement element = fNewState.packageElementFromSourceEntry(newEntry);
- if (element.isSource()) {
- fWorkQueue.add(element);
- }
-
- /* remove problems for this source entry */
- SourceEntry oldEntry = fOldState.getSourceEntry(element);
- fNewState.getProblemReporter().removeProblems(oldEntry);
+ catch (NotPresentException e) {
+ // Old state may be missing. See 1FVQGL1: ITPJCORE:WINNT - SEVERE - Error saving java file
+ return false;
}
+}
+/**
+ * A unit is being (re)compiled. Save any previous type structure.
+ */
+protected void compiling(CompilerCompilationUnit unit) {
- /**
- * Since the image builder is given as a result, let go of
- * any unneeded structures.
- */
- protected void cleanUp() {
- super.cleanUp();
- // Don't clear package level information because it's needed to compute the image delta.
- fSourceDeltas = null;
- fAddedClasses = fRemovedClasses = fChangedClasses = null;
+ /* Save old binaries if they exist */
+ SourceEntry sEntry = unit.getSourceEntry();
+ PackageElement element = fNewState.packageElementFromSourceEntry(sEntry);
+ if (fOldState.getSourceEntry(element) != null) {
+ saveBinaryTypes(element);
}
+}
+/**
+ * Computes the added, removed, changed classes for this incremental build.
+ * Vectors contain SourceEntry objects for each source element being added,
+ * removed, or changed.
+ *
+ * Takes into account package fragments, and only yields elements which are visible
+ *
+ * It's important to do this computation using the computed namespaces rather than
+ * directly from the source element tables, since types may be removed during namespace
+ * computation.
+ */
+protected void computeAllClasses() {
+ fAddedClasses = new Vector();
+ fRemovedClasses = new Vector();
+ fChangedClasses = new Vector();
+ fChangedZips = new Vector(1);
- /**
- * Removals and recompilations can leave unused namespace nodes in the
- * dependency graph. Clean them up.
- */
- protected void cleanupUnusedNamespaceNodes() {
- if (fRemovedClasses.size() > 0 || fChangedClasses.size() > 0) {
- PackageMap packageMap = fNewState.getPackageMap();
- DependencyGraph graph = fNewState.getInternalDependencyGraph();
- Vector unused = graph.getUnusedNamespaceNodes();
- for (Enumeration e = unused.elements(); e.hasMoreElements();) {
- NamespaceNode node = (NamespaceNode) e.nextElement();
- IPackage pkg = node.getPackage();
- if (!packageMap.containsPackage(pkg)) {
- graph.removePackage(pkg);
- }
+ /* do for each added builder package */
+ for (Enumeration e = fAddedPackageHandles.elements(); e.hasMoreElements();) {
+ IPackage pkg = (IPackage) e.nextElement();
+ SourceEntry[] entries = fNewState.getSourceEntries(pkg);
+ if (entries != null) {
+ for (int i = 0; i < entries.length; ++i) {
+ fAddedClasses.addElement(entries[i]);
}
}
}
- /**
- * Compare the visibility and gender of the two types.
- * Returns true if equal, false if not.
- */
- protected boolean compareVisibilityAndGender(
- TypeStructureEntry tsEntry,
- org.eclipse.jdt.core.IType type)
- throws JavaModelException {
- try {
- /* This relies on visibility bits being the same between the image builder and the java model. */
- IType oldType = (IType) tsEntry.getType().inState(fNewState);
- final int visVlags =
- IConstants.AccPublic | IConstants.AccPrivate | IConstants.AccProtected;
- int oldVis = oldType.getModifiers() & visVlags;
- int newVis = type.getFlags() & visVlags;
- return oldVis == newVis && oldType.isInterface() == type.isInterface();
- } catch (NotPresentException e) {
- // Old state may be missing. See 1FVQGL1: ITPJCORE:WINNT - SEVERE - Error saving java file
- return false;
+ /* do for each removed builder package */
+ for (Enumeration e = fRemovedPackageHandles.elements(); e.hasMoreElements();) {
+ IPackage pkg = (IPackage) e.nextElement();
+ // Don't force the package's table.
+ // If the package's table was not forced in the old state,
+ // there should be no work to do for its classes.
+ if (fOldState.getSourceElementTable().containsPackage(pkg)) {
+ SourceEntry[] entries = fOldState.getSourceEntries(pkg);
+ if (entries != null) {
+ for (int i = 0; i < entries.length; ++i) {
+ fRemovedClasses.addElement(entries[i]);
+ }
+ }
}
}
- /**
- * A unit is being (re)compiled. Save any previous type structure.
- */
- protected void compiling(CompilerCompilationUnit unit) {
+ /* build table of changed package elements, keyed by package */
+ Hashtable changeTable = new Hashtable(fChangedPkgOrZips.size() * 2 + 1);
+ for (Enumeration e = fChangedPkgOrZips.elements(); e.hasMoreElements();) {
+ IResourceDelta changedPkgOrZip = (IResourceDelta) e.nextElement();
+ IPath path = changedPkgOrZip.getFullPath();
- /* Save old binaries if they exist */
- SourceEntry sEntry = unit.getSourceEntry();
- PackageElement element = fNewState.packageElementFromSourceEntry(sEntry);
- if (fOldState.getSourceEntry(element) != null) {
- saveBinaryTypes(element);
+ // ask the state if it is a ZIP file only if it is present in this state
+ if (fNewState.isZipElement(path)) {
+ /**
+ * Don't do any finer grained change calculation,
+ * all dependents of the zip and its namespaces
+ * will be recompiled
+ */
+ fChangedZips.addElement(path);
+ } else {
+ addChangedFileNamesFromChangedPackage(changedPkgOrZip, changeTable);
}
}
- /**
- * Computes the added, removed, changed classes for this incremental build.
- * Vectors contain SourceEntry objects for each source element being added,
- * removed, or changed.
- *
- * Takes into account package fragments, and only yields elements which are visible
- *
- * It's important to do this computation using the computed namespaces rather than
- * directly from the source element tables, since types may be removed during namespace
- * computation.
- */
- protected void computeAllClasses() {
- fAddedClasses = new Vector();
- fRemovedClasses = new Vector();
- fChangedClasses = new Vector();
- fChangedZips = new Vector(1);
-
- /* do for each added builder package */
- for (Enumeration e = fAddedPackageHandles.elements(); e.hasMoreElements();) {
- IPackage pkg = (IPackage) e.nextElement();
- SourceEntry[] entries = fNewState.getSourceEntries(pkg);
- if (entries != null) {
- for (int i = 0; i < entries.length; ++i) {
- fAddedClasses.addElement(entries[i]);
- }
+ /* do for each changed builder package */
+ for (Enumeration e = fChangedPackageHandles.elements(); e.hasMoreElements();) {
+ IPackage pkg = (IPackage) e.nextElement();
+ Hashtable changesForPkg = (Hashtable) changeTable.get(pkg);
+ Hashtable fileNames = new Hashtable();
+ SourceEntry[] oldEntries = fOldState.getSourceEntries(pkg);
+ if (oldEntries != null) {
+ for (int i = 0; i < oldEntries.length; ++i) {
+ SourceEntry oldEntry = oldEntries[i];
+ fileNames.put(oldEntry.getFileName(), oldEntry);
}
}
-
- /* do for each removed builder package */
- for (Enumeration e = fRemovedPackageHandles.elements(); e.hasMoreElements();) {
- IPackage pkg = (IPackage) e.nextElement();
- // Don't force the package's table.
- // If the package's table was not forced in the old state,
- // there should be no work to do for its classes.
- if (fOldState.getSourceElementTable().containsPackage(pkg)) {
- SourceEntry[] entries = fOldState.getSourceEntries(pkg);
- if (entries != null) {
- for (int i = 0; i < entries.length; ++i) {
- fRemovedClasses.addElement(entries[i]);
+ SourceEntry[] newEntries = fNewState.getSourceEntries(pkg);
+ if (newEntries != null) {
+ for (int i = 0; i < newEntries.length; ++i) {
+ SourceEntry newEntry = newEntries[i];
+ String fileName = newEntry.getFileName();
+ SourceEntry oldEntry = (SourceEntry) fileNames.remove(fileName);
+ if (oldEntry != null) {
+ // Present in old and new. Has it changed?
+ if (!newEntry.equals(oldEntry)) {
+ // It has changed path, so treat it as a removal and an addition
+ fRemovedClasses.addElement(oldEntry);
+ fAddedClasses.addElement(newEntry);
}
+ else if (changesForPkg != null && changesForPkg.containsKey(fileName)) {
+ fChangedClasses.addElement(newEntry);
+ }
+ } else {
+ // Present only in new
+ fAddedClasses.addElement(newEntry);
}
}
}
-
- /* build table of changed package elements, keyed by package */
- Hashtable changeTable = new Hashtable(fChangedPkgOrZips.size() * 2 + 1);
- for (Enumeration e = fChangedPkgOrZips.elements(); e.hasMoreElements();) {
- IResourceDelta changedPkgOrZip = (IResourceDelta) e.nextElement();
- IPath path = changedPkgOrZip.getFullPath();
-
- // ask the state if it is a ZIP file only if it is present in this state
- if (fNewState.isZipElement(path)) {
- /**
- * Don't do any finer grained change calculation,
- * all dependents of the zip and its namespaces
- * will be recompiled
- */
- fChangedZips.addElement(path);
- } else {
- addChangedFileNamesFromChangedPackage(changedPkgOrZip, changeTable);
- }
+ // Remaining ones are removed.
+ for (Enumeration ee = fileNames.elements(); ee.hasMoreElements();) {
+ fRemovedClasses.addElement(ee.nextElement());
}
-
- /* do for each changed builder package */
- for (Enumeration e = fChangedPackageHandles.elements(); e.hasMoreElements();) {
- IPackage pkg = (IPackage) e.nextElement();
- Hashtable changesForPkg = (Hashtable) changeTable.get(pkg);
- Hashtable fileNames = new Hashtable();
- SourceEntry[] oldEntries = fOldState.getSourceEntries(pkg);
- if (oldEntries != null) {
- for (int i = 0; i < oldEntries.length; ++i) {
- SourceEntry oldEntry = oldEntries[i];
- fileNames.put(oldEntry.getFileName(), oldEntry);
+ }
+}
+/**
+ * Computes the added, removed, changed packages and zips
+ * for this incremental build.
+ * Looks only in the union of the old and the new classpaths.
+ * Folders outside this union are ignored.
+ */
+protected void computeAllPackages() {
+ fAddedPkgOrZips = new Vector();
+ fRemovedPkgOrZips = new Vector();
+ fChangedPkgOrZips = new Vector();
+ IPackageFragmentRoot[] oldRoots = fOldState.getPackageFragmentRootsInClassPath();
+ fNewState.readClassPath(); // TBD: Only read it if changed.
+ IPackageFragmentRoot[] newRoots = fNewState.getPackageFragmentRootsInClassPath();
+ for (Enumeration e = fSourceDeltas.elements(); e.hasMoreElements();) {
+ IResourceDelta delta = (IResourceDelta) e.nextElement();
+ computeAllPackages(delta, oldRoots, newRoots);
+ }
+}
+protected void computeAllPackages(IResourceDelta delta, IPackageFragmentRoot[] oldRoots, IPackageFragmentRoot[] newRoots) {
+ int status = delta.getKind();
+ IPath path = delta.getFullPath();
+ IResource rootResource = null;
+ switch (delta.getKind()) {
+ case IResourceDelta.ADDED :
+ /* Look for this package only in the new roots */
+ for (int i = 0; i < newRoots.length; i++) {
+ rootResource = null;
+ try {
+ rootResource = newRoots[i].getUnderlyingResource();
+ } catch (JavaModelException e) {
}
- }
- SourceEntry[] newEntries = fNewState.getSourceEntries(pkg);
- if (newEntries != null) {
- for (int i = 0; i < newEntries.length; ++i) {
- SourceEntry newEntry = newEntries[i];
- String fileName = newEntry.getFileName();
- SourceEntry oldEntry = (SourceEntry) fileNames.remove(fileName);
- if (oldEntry != null) {
- // Present in old and new. Has it changed?
- if (!newEntry.equals(oldEntry)) {
- // It has changed path, so treat it as a removal and an addition
- fRemovedClasses.addElement(oldEntry);
- fAddedClasses.addElement(newEntry);
- } else
- if (changesForPkg != null && changesForPkg.containsKey(fileName)) {
- fChangedClasses.addElement(newEntry);
- }
- } else {
- // Present only in new
- fAddedClasses.addElement(newEntry);
- }
+ if (rootResource != null && rootResource.getFullPath().isPrefixOf(path)) {
+ fAddedPkgOrZips.addElement(path);
+ break;
}
}
- // Remaining ones are removed.
- for (Enumeration ee = fileNames.elements(); ee.hasMoreElements();) {
- fRemovedClasses.addElement(ee.nextElement());
+ break;
+ case IResourceDelta.REMOVED :
+ /* Look for this package only in the old roots */
+ for (int i = 0; i < oldRoots.length; i++) {
+ rootResource = null;
+ try {
+ rootResource = oldRoots[i].getUnderlyingResource();
+ } catch (JavaModelException e) {
+ }
+ if (rootResource != null && rootResource.getFullPath().isPrefixOf(path)) {
+ fRemovedPkgOrZips.addElement(path);
+ break;
+ }
}
- }
- }
-
- /**
- * Computes the added, removed, changed packages and zips
- * for this incremental build.
- * Looks only in the union of the old and the new classpaths.
- * Folders outside this union are ignored.
- */
- protected void computeAllPackages() {
- fAddedPkgOrZips = new Vector();
- fRemovedPkgOrZips = new Vector();
- fChangedPkgOrZips = new Vector();
- IPackageFragmentRoot[] oldRoots =
- fOldState.getPackageFragmentRootsInClassPath();
- fNewState.readClassPath(); // TBD: Only read it if changed.
- IPackageFragmentRoot[] newRoots =
- fNewState.getPackageFragmentRootsInClassPath();
- for (Enumeration e = fSourceDeltas.elements(); e.hasMoreElements();) {
- IResourceDelta delta = (IResourceDelta) e.nextElement();
- computeAllPackages(delta, oldRoots, newRoots);
- }
- }
-
- protected void computeAllPackages(
- IResourceDelta delta,
- IPackageFragmentRoot[] oldRoots,
- IPackageFragmentRoot[] newRoots) {
- int status = delta.getKind();
- IPath path = delta.getFullPath();
- IResource rootResource = null;
- switch (delta.getKind()) {
- case IResourceDelta.ADDED :
- /* Look for this package only in the new roots */
- for (int i = 0; i < newRoots.length; i++) {
- rootResource = null;
- try {
- rootResource = newRoots[i].getUnderlyingResource();
- } catch (JavaModelException e) {
- }
- if (rootResource != null && rootResource.getFullPath().isPrefixOf(path)) {
- fAddedPkgOrZips.addElement(path);
- break;
- }
+ break;
+ case IResourceDelta.CHANGED :
+ /* Look for this package in the union of both sets of roots */
+ boolean found = false;
+ for (int i = 0; i < newRoots.length; i++) {
+ rootResource = null;
+ try {
+ rootResource = newRoots[i].getUnderlyingResource();
+ } catch (JavaModelException e) {
}
- break;
- case IResourceDelta.REMOVED :
- /* Look for this package only in the old roots */
- for (int i = 0; i < oldRoots.length; i++) {
- rootResource = null;
- try {
- rootResource = oldRoots[i].getUnderlyingResource();
- } catch (JavaModelException e) {
- }
- if (rootResource != null && rootResource.getFullPath().isPrefixOf(path)) {
- fRemovedPkgOrZips.addElement(path);
- break;
- }
+ if (rootResource != null && rootResource.getFullPath().isPrefixOf(path)) {
+ found = true;
+ break;
}
- break;
- case IResourceDelta.CHANGED :
- /* Look for this package in the union of both sets of roots */
- boolean found = false;
- for (int i = 0; i < newRoots.length; i++) {
+ }
+ if (!found) {
+ for (int i = 0; i < oldRoots.length; i++) {
rootResource = null;
try {
- rootResource = newRoots[i].getUnderlyingResource();
+ oldRoots[i].getUnderlyingResource();
} catch (JavaModelException e) {
}
if (rootResource != null && rootResource.getFullPath().isPrefixOf(path)) {
@@ -590,355 +568,300 @@ public class IncrementalImageBuilder extends AbstractImageBuilder {
break;
}
}
- if (!found) {
- for (int i = 0; i < oldRoots.length; i++) {
- rootResource = null;
- try {
- oldRoots[i].getUnderlyingResource();
- } catch (JavaModelException e) {
- }
- if (rootResource != null && rootResource.getFullPath().isPrefixOf(path)) {
- found = true;
- break;
- }
- }
- }
- if (found) {
- /* Only include changes if it's not an archive, or if it's an archive and the contents really changed */
- if (!fNewState.isZipElement(path)
- || (delta.getFlags() & IResourceDelta.CONTENT) != 0) {
- fChangedPkgOrZips.addElement(delta);
- }
+ }
+ if (found) {
+ /* Only include changes if it's not an archive, or if it's an archive and the contents really changed */
+ if (!fNewState.isZipElement(path)
+ || (delta.getFlags() & IResourceDelta.CONTENT) != 0) {
+ fChangedPkgOrZips.addElement(delta);
}
- break;
- }
- IResourceDelta[] children = delta.getAffectedChildren();
- for (int i = 0; i < children.length; ++i) {
- String extension = children[i].getFullPath().getFileExtension();
- if (extension == null
- || extension.equalsIgnoreCase("zip")
- || extension.equalsIgnoreCase("jar")) {
- // TBD: Currently rely on empty extension indicating folder
- computeAllPackages(children[i], oldRoots, newRoots);
}
- }
+ break;
}
-
- /**
- * Computes namespace changes for each added, removed and changed class file or JCU.
- * The appropriate namespace node is informed of the changes, and it
- * may invalidate its dependents where necessary. JCUs that need compiling
- * as a result of invalidations are stored by the state.
- * Must process removed types here, even though in most cases there will already
- * be an explicit dependency on the removed type, because it is possible for others
- * to have a namespace dependency but not a type dependency (e.g. in the case of errors).
- */
- protected void computeNamespaceChanges() {
-
- for (Enumeration e = fSourceDeltas.elements(); e.hasMoreElements();) {
- IResourceDelta delta = (IResourceDelta) e.nextElement();
- JavaModelManager.getJavaModelManager().closeAffectedElements(delta);
+ IResourceDelta[] children = delta.getAffectedChildren();
+ for (int i = 0; i < children.length; ++i) {
+ String extension = children[i].getFullPath().getFileExtension();
+ if (extension == null
+ || extension.equalsIgnoreCase("zip"/*nonNLS*/)
+ || extension.equalsIgnoreCase("jar"/*nonNLS*/)) {
+ // TBD: Currently rely on empty extension indicating folder
+ computeAllPackages(children[i], oldRoots, newRoots);
}
+ }
+}
+/**
+ * Computes namespace changes for each added, removed and changed class file or JCU.
+ * The appropriate namespace node is informed of the changes, and it
+ * may invalidate its dependents where necessary. JCUs that need compiling
+ * as a result of invalidations are stored by the state.
+ * Must process removed types here, even though in most cases there will already
+ * be an explicit dependency on the removed type, because it is possible for others
+ * to have a namespace dependency but not a type dependency (e.g. in the case of errors).
+ */
+protected void computeNamespaceChanges() {
- // Should really only process packages in image context here,
- // but in general other packages may depend on namespaces being added,
- // not just those being removed and changed. So for now, process everything.
+ for (Enumeration e = fSourceDeltas.elements(); e.hasMoreElements();) {
+ IResourceDelta delta = (IResourceDelta) e.nextElement();
+ JavaModelManager.getJavaModelManager().closeAffectedElements(delta);
+ }
- // The computations here must be based on the computed namespaces rather than
- // directly off of the namespace contributions of affected source elements
- // since the namespace computation may remove items due to conflicts.
+ // Should really only process packages in image context here,
+ // but in general other packages may depend on namespaces being added,
+ // not just those being removed and changed. So for now, process everything.
- int numPackages =
- fAddedPackageHandles.size()
- + fRemovedPackageHandles.size()
- + fChangedPackageHandles.size();
- if (numPackages == 0) {
- fNotifier.updateProgressDelta(0.10f);
- return;
- }
- float progressDelta = 0.10f / numPackages;
+ // The computations here must be based on the computed namespaces rather than
+ // directly off of the namespace contributions of affected source elements
+ // since the namespace computation may remove items due to conflicts.
- // Process changes in the set of package prefixes
- if (fAddedPackageHandles.size() > 0 || fRemovedPackageHandles.size() > 0) {
- computePackagePrefixChanges();
- }
+ int numPackages = fAddedPackageHandles.size() + fRemovedPackageHandles.size() + fChangedPackageHandles.size();
+ if (numPackages == 0) {
+ fNotifier.updateProgressDelta(0.10f);
+ return;
+ }
+ float progressDelta = 0.10f / numPackages;
- // Process added packages
- for (Enumeration addedPkgs = fAddedPackageHandles.elements();
- addedPkgs.hasMoreElements();
- ) {
- IPackage pkg = (IPackage) addedPkgs.nextElement();
- fNotifier.subTask("Analyzing " + PackageImpl.readableName(pkg));
+ // Process changes in the set of package prefixes
+ if (fAddedPackageHandles.size() > 0 || fRemovedPackageHandles.size() > 0) {
+ computePackagePrefixChanges();
+ }
- // Mark all dependents of missing namespace as needing compile.
- markDependentsAsNeedingCompile(pkg);
+ // Process added packages
+ for (Enumeration addedPkgs = fAddedPackageHandles.elements(); addedPkgs.hasMoreElements();) {
+ IPackage pkg = (IPackage) addedPkgs.nextElement();
+ fNotifier.subTask(Util.bind("build.analyzing"/*nonNLS*/, PackageImpl.readableName(pkg)));
- // If any types currently exist with the same name as this package,
- // they must be recompiled
- markOverlappingTypesAsNeedingCompile(pkg);
- fNotifier.updateProgressDelta(progressDelta);
- fNotifier.checkCancel();
- }
+ // Mark all dependents of missing namespace as needing compile.
+ markDependentsAsNeedingCompile(pkg);
- // Process removed packages
- for (Enumeration removedPkgs = fRemovedPackageHandles.elements();
- removedPkgs.hasMoreElements();
- ) {
- IPackage pkg = (IPackage) removedPkgs.nextElement();
- fNotifier.subTask("Analyzing " + PackageImpl.readableName(pkg));
+ // If any types currently exist with the same name as this package,
+ // they must be recompiled
+ markOverlappingTypesAsNeedingCompile(pkg);
+ fNotifier.updateProgressDelta(progressDelta);
+ fNotifier.checkCancel();
+ }
- // Mark all dependents of namespace as needing compile.
- markDependentsAsNeedingCompile(pkg);
+ // Process removed packages
+ for (Enumeration removedPkgs = fRemovedPackageHandles.elements(); removedPkgs.hasMoreElements();) {
+ IPackage pkg = (IPackage) removedPkgs.nextElement();
+ fNotifier.subTask(Util.bind("build.analyzing"/*nonNLS*/, PackageImpl.readableName(pkg)));
- // If any types currently exist with the same name as this package,
- // they must be recompiled
- markOverlappingTypesAsNeedingCompile(pkg);
- fNotifier.updateProgressDelta(progressDelta);
- fNotifier.checkCancel();
- }
+ // Mark all dependents of namespace as needing compile.
+ markDependentsAsNeedingCompile(pkg);
- // Process changed packages
- for (Enumeration changedPkgs = fChangedPackageHandles.elements();
- changedPkgs.hasMoreElements();
- ) {
- IPackage pkg = (IPackage) changedPkgs.nextElement();
- fNotifier.subTask("Analyzing " + PackageImpl.readableName(pkg));
- computeNamespaceChanges(pkg);
- fNotifier.updateProgressDelta(progressDelta);
- fNotifier.checkCancel();
- }
+ // If any types currently exist with the same name as this package,
+ // they must be recompiled
+ markOverlappingTypesAsNeedingCompile(pkg);
+ fNotifier.updateProgressDelta(progressDelta);
+ fNotifier.checkCancel();
}
- /**
- * Computes the names with namespace changes for the given type.
- */
- protected void computeNamespaceChanges(
- Hashtable oldTSEntries,
- String parentTypeName,
- org.eclipse.jdt.core.IType type,
- Vector vTypeNames)
- throws JavaModelException {
- String typeName = type.getElementName();
- if (parentTypeName != null) {
- int len = parentTypeName.length() + typeName.length() + 1;
- typeName =
- new StringBuffer(len)
- .append(parentTypeName)
- .append("$")
- .append(typeName)
- .toString();
- }
- /* Remove it so that only non-matching ones remain in the table. */
- TypeStructureEntry tsEntry = (TypeStructureEntry) oldTSEntries.remove(typeName);
- if (tsEntry == null || !compareVisibilityAndGender(tsEntry, type)) {
- vTypeNames.addElement(typeName);
- }
- org.eclipse.jdt.core.IType[] memberTypes = type.getTypes();
- for (int i = 0; i < memberTypes.length; ++i) {
- computeNamespaceChanges(oldTSEntries, typeName, memberTypes[i], vTypeNames);
- }
+ // Process changed packages
+ for (Enumeration changedPkgs = fChangedPackageHandles.elements(); changedPkgs.hasMoreElements();) {
+ IPackage pkg = (IPackage) changedPkgs.nextElement();
+ fNotifier.subTask(Util.bind("build.analyzing"/*nonNLS*/, PackageImpl.readableName(pkg)));
+ computeNamespaceChanges(pkg);
+ fNotifier.updateProgressDelta(progressDelta);
+ fNotifier.checkCancel();
}
-
- /**
- * Computes the names with namespace changes for the given element.
- * Handles the cases where the element is added, removed, or changed.
- */
- protected void computeNamespaceChanges(
- PackageElement element,
- Vector vTypeNames) {
- Hashtable oldTSEntries = new Hashtable(5);
- SourceEntry oldSourceEntry = fOldState.getSourceEntry(element);
- if (oldSourceEntry != null) {
- // Ignore entries from zip files, since zip file changes are handled wholesale elsewhere.
- if (oldSourceEntry.getZipEntryName() == null) {
- org.eclipse.jdt.internal.core.builder.IType[] oldTypes =
- fOldState.getInternalDependencyGraph().getTypes(element);
- if (oldTypes != null) {
- for (int i = 0; i < oldTypes.length; ++i) {
- TypeStructureEntry tsEntry =
- fOldState.getTypeStructureEntry(oldTypes[i], false);
- if (tsEntry != null) {
- oldTSEntries.put(tsEntry.getType().getSimpleName(), tsEntry);
- }
+}
+/**
+ * Computes the names with namespace changes for the given type.
+ */
+protected void computeNamespaceChanges(Hashtable oldTSEntries, String parentTypeName, org.eclipse.jdt.core.IType type, Vector vTypeNames) throws JavaModelException {
+ String typeName = type.getElementName();
+ if (parentTypeName != null) {
+ int len = parentTypeName.length() + typeName.length() + 1;
+ typeName = new StringBuffer(len).append(parentTypeName).append("$"/*nonNLS*/).append(typeName).toString();
+ }
+ /* Remove it so that only non-matching ones remain in the table. */
+ TypeStructureEntry tsEntry = (TypeStructureEntry) oldTSEntries.remove(typeName);
+ if (tsEntry == null || !compareVisibilityAndGender(tsEntry, type)) {
+ vTypeNames.addElement(typeName);
+ }
+ org.eclipse.jdt.core.IType[] memberTypes = type.getTypes();
+ for (int i = 0; i < memberTypes.length; ++i) {
+ computeNamespaceChanges(oldTSEntries, typeName, memberTypes[i], vTypeNames);
+ }
+}
+/**
+ * Computes the names with namespace changes for the given element.
+ * Handles the cases where the element is added, removed, or changed.
+ */
+protected void computeNamespaceChanges(PackageElement element, Vector vTypeNames) {
+ Hashtable oldTSEntries = new Hashtable(5);
+ SourceEntry oldSourceEntry = fOldState.getSourceEntry(element);
+ if (oldSourceEntry != null) {
+ // Ignore entries from zip files, since zip file changes are handled wholesale elsewhere.
+ if (oldSourceEntry.getZipEntryName() == null) {
+ org.eclipse.jdt.internal.core.builder.IType[] oldTypes = fOldState.getInternalDependencyGraph().getTypes(element);
+ if (oldTypes != null) {
+ for (int i = 0; i < oldTypes.length; ++i) {
+ TypeStructureEntry tsEntry = fOldState.getTypeStructureEntry(oldTypes[i], false);
+ if (tsEntry != null) {
+ oldTSEntries.put(tsEntry.getType().getSimpleName(), tsEntry);
}
}
}
}
- SourceEntry newSourceEntry = fNewState.getSourceEntry(element);
- if (newSourceEntry != null) {
- // Ignore entries from zip files, since zip file changes are handled wholesale elsewhere.
- if (oldSourceEntry.getZipEntryName() == null) {
- /* use this if JavaModel is broken
- String fileName = element.getFileName();
- fileName = fileName.substring(0, fileName.indexOf('.'));
- FakeType[] types = new FakeType[] {new FakeType(fileName)};
- try {
- computeNamespaceChanges(oldTSEntries, null, types[0], vTypeNames);
- } catch (NotPresentException e) {} // ignore
- */
+ }
+ SourceEntry newSourceEntry = fNewState.getSourceEntry(element);
+ if (newSourceEntry != null) {
+ // Ignore entries from zip files, since zip file changes are handled wholesale elsewhere.
+ if (oldSourceEntry.getZipEntryName() == null) {
+ /* use this if JavaModel is broken
+ String fileName = element.getFileName();
+ fileName = fileName.substring(0, fileName.indexOf('.'));
+ FakeType[] types = new FakeType[] {new FakeType(fileName)};
+ try {
+ computeNamespaceChanges(oldTSEntries, null, types[0], vTypeNames);
+ } catch (NotPresentException e) {} // ignore
+ */
- IJavaElement javaElement = fNewState.getJavaElement(newSourceEntry);
- if (javaElement instanceof ICompilationUnit) {
- ICompilationUnit unit = (ICompilationUnit) javaElement;
+ IJavaElement javaElement = fNewState.getJavaElement(newSourceEntry);
+ if (javaElement instanceof ICompilationUnit) {
+ ICompilationUnit unit = (ICompilationUnit) javaElement;
+ try {
+ org.eclipse.jdt.core.IType[] types = unit.getTypes();
+ for (int i = 0; i < types.length; ++i) {
+ computeNamespaceChanges(oldTSEntries, null, types[i], vTypeNames);
+ }
+ } catch (JavaModelException e) {
+ // TBD: ignore
+ }
+ } else {
+ if (javaElement instanceof IClassFile) {
+ IClassFile classFile = (IClassFile) javaElement;
try {
- org.eclipse.jdt.core.IType[] types = unit.getTypes();
- for (int i = 0; i < types.length; ++i) {
- computeNamespaceChanges(oldTSEntries, null, types[i], vTypeNames);
- }
+ computeNamespaceChanges(oldTSEntries, null, classFile.getType(), vTypeNames);
} catch (JavaModelException e) {
// TBD: ignore
}
- } else {
- if (javaElement instanceof IClassFile) {
- IClassFile classFile = (IClassFile) javaElement;
- try {
- computeNamespaceChanges(oldTSEntries, null, classFile.getType(), vTypeNames);
- } catch (JavaModelException e) {
- // TBD: ignore
- }
- }
}
}
}
- for (Enumeration e = oldTSEntries.keys(); e.hasMoreElements();) {
- String name = (String) e.nextElement();
- vTypeNames.addElement(name);
- }
}
+ for (Enumeration e = oldTSEntries.keys(); e.hasMoreElements();) {
+ String name = (String) e.nextElement();
+ vTypeNames.addElement(name);
+ }
+}
+/**
+ * Computes namespace changes for each added, removed and changed class file or JCU
+ * in an affected package.
+ */
+protected void computeNamespaceChanges(IPackage pkg) {
/**
- * Computes namespace changes for each added, removed and changed class file or JCU
- * in an affected package.
+ * Must remove syntax problems for all source entries in this package
+ * in the old state, regardless of whether they contributed to the old
+ * state's namespace. This must be done before computing the new namespace
+ * because the computation may reveal new errors that we don't want to remove.
*/
- protected void computeNamespaceChanges(IPackage pkg) {
-
- /**
- * Must remove syntax problems for all source entries in this package
- * in the old state, regardless of whether they contributed to the old
- * state's namespace. This must be done before computing the new namespace
- * because the computation may reveal new errors that we don't want to remove.
- */
- Hashtable oldTable = new Hashtable(21);
- SourceEntry[] oldEntries = fOldState.getSourceEntries(pkg);
- if (oldEntries != null) {
- for (int i = 0; i < oldEntries.length; i++) {
- SourceEntry oldEntry = oldEntries[i];
- fNewState.getProblemReporter().removeSyntaxErrors(oldEntry);
- oldTable.put(oldEntry.getFileName(), oldEntry);
- }
+ Hashtable oldTable = new Hashtable(21);
+ SourceEntry[] oldEntries = fOldState.getSourceEntries(pkg);
+ if (oldEntries != null) {
+ for (int i = 0; i < oldEntries.length; i++) {
+ SourceEntry oldEntry = oldEntries[i];
+ fNewState.getProblemReporter().removeSyntaxErrors(oldEntry);
+ oldTable.put(oldEntry.getFileName(), oldEntry);
}
- Vector vTypeNames = new Vector();
- SourceEntry[] newEntries = fNewState.getSourceEntries(pkg);
- if (newEntries != null) {
- Dictionary sourceChanges = getSourceChanges(pkg);
- for (int i = 0; i < newEntries.length; ++i) {
- SourceEntry newEntry = newEntries[i];
- SourceEntry oldEntry = (SourceEntry) oldTable.remove(newEntry.getFileName());
- if (oldEntry == null) {
- /* Added. Issue indictment based only on file name. */
- vTypeNames.addElement(newEntry.getName());
- } else {
- if (!oldEntry.equals(newEntry)
- || sourceChanges.get(newEntry.getPath()) != null) {
- /* Changed. Issue indictments by comparing source types with previously built types. */
- PackageElement element = new PackageElement(pkg, newEntry);
- computeNamespaceChanges(element, vTypeNames);
- }
+ }
+ Vector vTypeNames = new Vector();
+ SourceEntry[] newEntries = fNewState.getSourceEntries(pkg);
+ if (newEntries != null) {
+ Dictionary sourceChanges = getSourceChanges(pkg);
+ for (int i = 0; i < newEntries.length; ++i) {
+ SourceEntry newEntry = newEntries[i];
+ SourceEntry oldEntry = (SourceEntry) oldTable.remove(newEntry.getFileName());
+ if (oldEntry == null) {
+ /* Added. Issue indictment based only on file name. */
+ vTypeNames.addElement(newEntry.getName());
+ } else {
+ if (!oldEntry.equals(newEntry) || sourceChanges.get(newEntry.getPath()) != null) {
+ /* Changed. Issue indictments by comparing source types with previously built types. */
+ PackageElement element = new PackageElement(pkg, newEntry);
+ computeNamespaceChanges(element, vTypeNames);
}
}
}
- /* Only removed source entries should remain in oldTable now. */
- for (Enumeration e = oldTable.elements(); e.hasMoreElements();) {
- SourceEntry oldEntry = (SourceEntry) e.nextElement();
- /* Removed. Issue indictment based only on file name. */
- vTypeNames.addElement(oldEntry.getName());
- }
- if (vTypeNames.isEmpty()) {
- return;
- }
- IndictmentSet indicts = new IndictmentSet();
- Hashtable nestedIndictsTable = null;
- for (Enumeration e = vTypeNames.elements(); e.hasMoreElements();) {
- String name = (String) e.nextElement();
- int lastDollar = name.lastIndexOf('$');
- if (lastDollar == -1) {
- indicts.add(Indictment.createTypeIndictment(name));
- } else {
- // Nested type. Issue indictments as if containing type was a package.
- // Dependencies on missing member types look like namespace dependencies on
- // package with same name as enclosing type.
- String qualification = name.substring(0, lastDollar);
- // Convert qualification from $ separated to . separated.
- // For example if name = "A$B$C", typeName = "C" and qualification = "A.B".
- qualification = qualification.replace('$', '.');
- String typeName = name.substring(lastDollar + 1);
-
- // Issue indictments, not relative to current package.
- // This catches dependencies on missing types in same package (e.g. ref is A.B).
- IPackage nestedPkg = fDC.getImage().getPackageHandle(qualification, false);
- nestedPkg = fNewState.canonicalize(nestedPkg);
+ }
+ /* Only removed source entries should remain in oldTable now. */
+ for (Enumeration e = oldTable.elements(); e.hasMoreElements();) {
+ SourceEntry oldEntry = (SourceEntry) e.nextElement();
+ /* Removed. Issue indictment based only on file name. */
+ vTypeNames.addElement(oldEntry.getName());
+ }
+ if (vTypeNames.isEmpty()) {
+ return;
+ }
+ IndictmentSet indicts = new IndictmentSet();
+ Hashtable nestedIndictsTable = null;
+ for (Enumeration e = vTypeNames.elements(); e.hasMoreElements();) {
+ String name = (String) e.nextElement();
+ int lastDollar = name.lastIndexOf('$');
+ if (lastDollar == -1) {
+ indicts.add(Indictment.createTypeIndictment(name));
+ } else {
+ // Nested type. Issue indictments as if containing type was a package.
+ // Dependencies on missing member types look like namespace dependencies on
+ // package with same name as enclosing type.
+ String qualification = name.substring(0, lastDollar);
+ // Convert qualification from $ separated to . separated.
+ // For example if name = "A$B$C", typeName = "C" and qualification = "A.B".
+ qualification = qualification.replace('$', '.');
+ String typeName = name.substring(lastDollar + 1);
+
+ // Issue indictments, not relative to current package.
+ // This catches dependencies on missing types in same package (e.g. ref is A.B).
+ IPackage nestedPkg = fDC.getImage().getPackageHandle(qualification, false);
+ nestedPkg = fNewState.canonicalize(nestedPkg);
+ if (nestedIndictsTable == null) {
+ nestedIndictsTable = new Hashtable(11);
+ }
+ IndictmentSet nestedIndicts = (IndictmentSet) nestedIndictsTable.get(nestedPkg);
+ if (nestedIndicts == null) {
+ nestedIndicts = new IndictmentSet();
+ nestedIndictsTable.put(nestedPkg, nestedIndicts);
+ }
+ nestedIndicts.add(Indictment.createTypeIndictment(typeName));
+
+ // Issue indictments, relative to current package (only if not unnamed package).
+ // This catches dependencies on missing types in other packages (e.g. ref is some.other.pkg.A.B).
+ if (!pkg.isUnnamed()) {
+ nestedPkg = fDC.getImage().getPackageHandle(pkg.getName() + '.' + qualification, false);
if (nestedIndictsTable == null) {
nestedIndictsTable = new Hashtable(11);
}
- IndictmentSet nestedIndicts = (IndictmentSet) nestedIndictsTable.get(nestedPkg);
+ nestedIndicts = (IndictmentSet) nestedIndictsTable.get(nestedPkg);
if (nestedIndicts == null) {
nestedIndicts = new IndictmentSet();
nestedIndictsTable.put(nestedPkg, nestedIndicts);
}
nestedIndicts.add(Indictment.createTypeIndictment(typeName));
-
- // Issue indictments, relative to current package (only if not unnamed package).
- // This catches dependencies on missing types in other packages (e.g. ref is some.other.pkg.A.B).
- if (!pkg.isUnnamed()) {
- nestedPkg =
- fDC.getImage().getPackageHandle(pkg.getName() + '.' + qualification, false);
- if (nestedIndictsTable == null) {
- nestedIndictsTable = new Hashtable(11);
- }
- nestedIndicts = (IndictmentSet) nestedIndictsTable.get(nestedPkg);
- if (nestedIndicts == null) {
- nestedIndicts = new IndictmentSet();
- nestedIndictsTable.put(nestedPkg, nestedIndicts);
- }
- nestedIndicts.add(Indictment.createTypeIndictment(typeName));
- }
- }
- }
- if (!indicts.isEmpty()) {
- issueIndictments(pkg, indicts, false);
- }
- if (nestedIndictsTable != null) {
- for (Enumeration e = nestedIndictsTable.keys(); e.hasMoreElements();) {
- IPackage nestedPkg = (IPackage) e.nextElement();
- IndictmentSet nestedIndicts = (IndictmentSet) nestedIndictsTable.get(nestedPkg);
- issueIndictments(pkg, nestedIndicts, false);
}
}
}
-
- /**
- * Compute the added and removed package prefixes (not actual packages)
- * and issue the appropriate indictments on the namespaces.
- */
- protected void computePackagePrefixChanges() {
- Hashtable oldTable = computePackagePrefixes(fOldState.getPackageMap());
- Hashtable newTable = computePackagePrefixes(fNewState.getPackageMap());
- for (Enumeration e = oldTable.elements(); e.hasMoreElements();) {
- String name = (String) e.nextElement();
- if (newTable.remove(name) == null) {
- int lastDot = name.lastIndexOf('.');
- if (lastDot != -1) {
- String parentName = name.substring(0, lastDot);
- String simpleName = name.substring(lastDot + 1);
- IPackage parentPkg = fDC.getImage().getPackageHandle(parentName, false);
- IndictmentSet indictments = new IndictmentSet();
- indictments.add(Indictment.createTypeIndictment(simpleName));
- issueIndictments(parentPkg, indictments, false);
- }
- }
+ if (!indicts.isEmpty()) {
+ issueIndictments(pkg, indicts, false);
+ }
+ if (nestedIndictsTable != null) {
+ for (Enumeration e = nestedIndictsTable.keys(); e.hasMoreElements();) {
+ IPackage nestedPkg = (IPackage) e.nextElement();
+ IndictmentSet nestedIndicts = (IndictmentSet) nestedIndictsTable.get(nestedPkg);
+ issueIndictments(pkg, nestedIndicts, false);
}
- for (Enumeration e = newTable.elements(); e.hasMoreElements();) {
- String name = (String) e.nextElement();
+ }
+}
+/**
+ * Compute the added and removed package prefixes (not actual packages)
+ * and issue the appropriate indictments on the namespaces.
+ */
+protected void computePackagePrefixChanges() {
+ Hashtable oldTable = computePackagePrefixes(fOldState.getPackageMap());
+ Hashtable newTable = computePackagePrefixes(fNewState.getPackageMap());
+ for (Enumeration e = oldTable.elements(); e.hasMoreElements();) {
+ String name = (String) e.nextElement();
+ if (newTable.remove(name) == null) {
int lastDot = name.lastIndexOf('.');
if (lastDot != -1) {
String parentName = name.substring(0, lastDot);
@@ -950,1076 +873,1006 @@ public class IncrementalImageBuilder extends AbstractImageBuilder {
}
}
}
-
- /**
- * Returns a set of strings containing the names of all packages
- * in the image, and all their prefixes.
- */
- protected Hashtable computePackagePrefixes(PackageMap packageMap) {
- Hashtable prefixes = new Hashtable(packageMap.size() * 3 + 1);
- for (Enumeration e = packageMap.getAllPackages(); e.hasMoreElements();) {
- IPackage pkg = (IPackage) e.nextElement();
- if (!pkg.isUnnamed()) {
- String name = pkg.getName();
- while (!prefixes.containsKey(name)) {
- prefixes.put(name, name);
- int i = name.lastIndexOf('.');
- if (i == -1)
- break;
- name = name.substring(0, i);
- }
- }
+ for (Enumeration e = newTable.elements(); e.hasMoreElements();) {
+ String name = (String) e.nextElement();
+ int lastDot = name.lastIndexOf('.');
+ if (lastDot != -1) {
+ String parentName = name.substring(0, lastDot);
+ String simpleName = name.substring(lastDot + 1);
+ IPackage parentPkg = fDC.getImage().getPackageHandle(parentName, false);
+ IndictmentSet indictments = new IndictmentSet();
+ indictments.add(Indictment.createTypeIndictment(simpleName));
+ issueIndictments(parentPkg, indictments, false);
}
- return prefixes;
}
-
- /**
- * For debugging only.
- */
- static void dump(IResourceDelta delta) {
- StringBuffer sb = new StringBuffer();
- IPath path = delta.getFullPath();
- for (int i = path.segmentCount(); --i > 0;) {
- sb.append(" ");
- }
- switch (delta.getKind()) {
- case IResourceDelta.ADDED :
- sb.append('+');
- break;
- case IResourceDelta.REMOVED :
- sb.append('-');
- break;
- case IResourceDelta.CHANGED :
- sb.append('*');
- break;
- case IResourceDelta.NO_CHANGE :
- sb.append('=');
- break;
- default :
- sb.append('?');
- break;
- }
- sb.append(path);
- System.out.println(sb.toString());
- IResourceDelta[] children = delta.getAffectedChildren();
- for (int i = 0; i < children.length; ++i) {
- dump(children[i]);
+}
+/**
+ * Returns a set of strings containing the names of all packages
+ * in the image, and all their prefixes.
+ */
+protected Hashtable computePackagePrefixes(PackageMap packageMap) {
+ Hashtable prefixes = new Hashtable(packageMap.size() * 3 + 1);
+ for (Enumeration e = packageMap.getAllPackages(); e.hasMoreElements();) {
+ IPackage pkg = (IPackage) e.nextElement();
+ if (!pkg.isUnnamed()) {
+ String name = pkg.getName();
+ while (!prefixes.containsKey(name)) {
+ prefixes.put(name, name);
+ int i = name.lastIndexOf('.');
+ if (i == -1)
+ break;
+ name = name.substring(0, i);
+ }
}
}
-
- /**
- * Returns an enumeration of the packages that have been affected
- * by the build.
- */
- protected Enumeration getAffectedPackages() {
- return fAffectedPackages.keys();
+ return prefixes;
+}
+/**
+ * For debugging only.
+ */
+static void dump(IResourceDelta delta) {
+ StringBuffer sb = new StringBuffer();
+ IPath path = delta.getFullPath();
+ for (int i = path.segmentCount(); --i > 0;) {
+ sb.append(" "/*nonNLS*/);
}
-
- /**
- * Returns a builder type for the given old and new type structure entries.
- * Either old or new entries may be null (but not both).
- * This method should only be called if there is no associated builder
- * type already in the builder type table.
- */
- protected BuilderType getBuilderType(
- TypeStructureEntry oldEntry,
- TypeStructureEntry newEntry) {
- IType handle = null;
- BuilderType type = null;
- if (oldEntry == null) {
- /* must have been added */
- Assert.isNotNull(newEntry);
- type = new NewBuilderType(this, newEntry);
- handle = newEntry.getType();
+ switch (delta.getKind()) {
+ case IResourceDelta.ADDED:
+ sb.append('+');
+ break;
+ case IResourceDelta.REMOVED:
+ sb.append('-');
+ break;
+ case IResourceDelta.CHANGED:
+ sb.append('*');
+ break;
+ case IResourceDelta.NO_CHANGE:
+ sb.append('=');
+ break;
+ default:
+ sb.append('?');
+ break;
+ }
+ sb.append(path);
+ System.out.println(sb.toString());
+ IResourceDelta[] children = delta.getAffectedChildren();
+ for (int i = 0; i < children.length; ++i) {
+ dump(children[i]);
+ }
+}
+/**
+ * Returns an enumeration of the packages that have been affected
+ * by the build.
+ */
+protected Enumeration getAffectedPackages() {
+ return fAffectedPackages.keys();
+}
+/**
+ * Returns a builder type for the given old and new type structure entries.
+ * Either old or new entries may be null (but not both).
+ * This method should only be called if there is no associated builder
+ * type already in the builder type table.
+ */
+protected BuilderType getBuilderType(TypeStructureEntry oldEntry, TypeStructureEntry newEntry) {
+ IType handle = null;
+ BuilderType type = null;
+ if (oldEntry == null) {
+ /* must have been added */
+ Assert.isNotNull(newEntry);
+ type = new NewBuilderType(this, newEntry);
+ handle = newEntry.getType();
+ } else {
+ if (newEntry == null) {
+ /* must have been deleted */
+ Assert.isNotNull(oldEntry);
+ type = new OldBuilderType(this, oldEntry);
+ handle = oldEntry.getType();
} else {
- if (newEntry == null) {
- /* must have been deleted */
- Assert.isNotNull(oldEntry);
- type = new OldBuilderType(this, oldEntry);
+ if (oldEntry.fSourceEntry.equals(newEntry.fSourceEntry)) {
+ /* unchanged */
+ type = new UnmodifiedBuilderType(this, oldEntry);
handle = oldEntry.getType();
} else {
- if (oldEntry.fSourceEntry.equals(newEntry.fSourceEntry)) {
- /* unchanged */
- type = new UnmodifiedBuilderType(this, oldEntry);
- handle = oldEntry.getType();
- } else {
- /* modified */
- IBinaryType oldBinary = fOldState.getBinaryTypeOrNull(oldEntry);
- type = new ModifiedBuilderType(this, oldEntry, oldBinary);
- handle = oldEntry.getType();
- }
+ /* modified */
+ IBinaryType oldBinary = fOldState.getBinaryTypeOrNull(oldEntry);
+ type = new ModifiedBuilderType(this, oldEntry, oldBinary);
+ handle = oldEntry.getType();
}
}
- fBuilderTypeTable.put(handle, type);
- return type;
}
-
- /**
- * Returns a builder type for the given type.
- */
- protected BuilderType getBuilderType(IType type) {
- BuilderType builderType = (BuilderType) fBuilderTypeTable.get(type);
- if (builderType != null) {
- return builderType;
- }
- return getBuilderType(
- fOldState.getTypeStructureEntry(type, false),
- fNewState.getTypeStructureEntry(type, false));
+ fBuilderTypeTable.put(handle, type);
+ return type;
+}
+/**
+ * Returns a builder type for the given type.
+ */
+protected BuilderType getBuilderType(IType type) {
+ BuilderType builderType = (BuilderType) fBuilderTypeTable.get(type);
+ if (builderType != null) {
+ return builderType;
}
-
- /**
- * Returns an object describing the differences between the old
- * state and the new state, otherwise returns null. The delta is
- * restricted to the given ImageContext. This image delta will
- * include entries for all program elements that are present in:
- * <pre>
- * (oldState UNION newState) INTERSECT imageContext
- *</pre>
- * That is, it will include each program element that is present in one or the other
- * state and also in the given image context.
- * Any delta objects navigated to from the result are restricted
- * to the same ImageContext.
- * Note that there is no necessary relationship between the image context
- * supplied and the build contexts of the old and new states.
- */
- public IDelta getImageDelta(IImageContext imageContext) {
- if (fImageDelta == null
- || !Util.equalOrNull(imageContext, fContextOfLastDelta)) {
- fImageDelta = new DeltaImpl(this, imageContext);
- fContextOfLastDelta = imageContext;
- }
- return fImageDelta;
+ return getBuilderType(fOldState.getTypeStructureEntry(type, false), fNewState.getTypeStructureEntry(type, false));
+}
+/**
+ * Returns an object describing the differences between the old
+ * state and the new state, otherwise returns null. The delta is
+ * restricted to the given ImageContext. This image delta will
+ * include entries for all program elements that are present in:
+ * <pre>
+ * (oldState UNION newState) INTERSECT imageContext
+ *</pre>
+ * That is, it will include each program element that is present in one or the other
+ * state and also in the given image context.
+ * Any delta objects navigated to from the result are restricted
+ * to the same ImageContext.
+ * Note that there is no necessary relationship between the image context
+ * supplied and the build contexts of the old and new states.
+ */
+public IDelta getImageDelta(IImageContext imageContext) {
+ if (fImageDelta == null || !Util.equalOrNull(imageContext, fContextOfLastDelta)) {
+ fImageDelta = new DeltaImpl(this, imageContext);
+ fContextOfLastDelta = imageContext;
}
+ return fImageDelta;
+}
+/**
+ * Returns a set of paths of files which are changing in the given package.
+ */
+protected Dictionary getSourceChanges(IPackage pkgHandle) {
+ Dictionary set = new Hashtable(30);
- /**
- * Returns a set of paths of files which are changing in the given package.
- */
- protected Dictionary getSourceChanges(IPackage pkgHandle) {
- Dictionary set = new Hashtable(30);
-
- /* do for each fragment of this package */
- IPath[] newFrags = fNewState.getPackageMap().getFragments(pkgHandle);
- for (int i = 0; i < newFrags.length; i++) {
- IPath fragPath = newFrags[i];
-
- /* find the JCUs for this package */
- IResourceDelta[] fileDeltas = null;
- for (Enumeration e = fChangedPkgOrZips.elements(); e.hasMoreElements();) {
- IResourceDelta pkgDelta = (IResourceDelta) e.nextElement();
- if (pkgDelta.getFullPath().equals(fragPath)) {
- /* A zip file is changing. Don't bother optimizing this case -- too complex. */
- if (!fNewState.isZipElement(fragPath)) {
- fileDeltas = pkgDelta.getAffectedChildren(IResourceDelta.CHANGED);
- }
- break;
+ /* do for each fragment of this package */
+ IPath[] newFrags = fNewState.getPackageMap().getFragments(pkgHandle);
+ for (int i = 0; i < newFrags.length; i++) {
+ IPath fragPath = newFrags[i];
+
+ /* find the JCUs for this package */
+ IResourceDelta[] fileDeltas = null;
+ for (Enumeration e = fChangedPkgOrZips.elements(); e.hasMoreElements();) {
+ IResourceDelta pkgDelta = (IResourceDelta) e.nextElement();
+ if (pkgDelta.getFullPath().equals(fragPath)) {
+ /* A zip file is changing. Don't bother optimizing this case -- too complex. */
+ if (!fNewState.isZipElement(fragPath)) {
+ fileDeltas = pkgDelta.getAffectedChildren(IResourceDelta.CHANGED);
}
+ break;
}
- if (fileDeltas != null) {
- /* do for each changed file in this fragment */
- for (int j = 0; j < fileDeltas.length; j++) {
- IResourceDelta fileDelta = fileDeltas[j];
- // See 1FVSC75: ITPJCORE:ALL - SCENARIO B1 - Builder should check F_CONTENT on changed files
- if (fileDelta.getKind() == IResourceDelta.CHANGED
- && (fileDelta.getFlags() & IResourceDelta.CONTENT) != 0) {
- IPath path = fileDelta.getFullPath();
-
- /* skip non-java resources */
- String extension = path.getFileExtension();
- if (extension != null
- && (extension.equalsIgnoreCase("java") || extension.equalsIgnoreCase("class"))) {
- set.put(path, path);
- }
+ }
+ if (fileDeltas != null) {
+ /* do for each changed file in this fragment */
+ for (int j = 0; j < fileDeltas.length; j++) {
+ IResourceDelta fileDelta = fileDeltas[j];
+ // See 1FVSC75: ITPJCORE:ALL - SCENARIO B1 - Builder should check F_CONTENT on changed files
+ if (fileDelta.getKind() == IResourceDelta.CHANGED && (fileDelta.getFlags() & IResourceDelta.CONTENT) != 0) {
+ IPath path = fileDelta.getFullPath();
+
+ /* skip non-java resources */
+ String extension = path.getFileExtension();
+ if (extension != null && (extension.equalsIgnoreCase("java"/*nonNLS*/) || extension.equalsIgnoreCase("class"/*nonNLS*/))) {
+ set.put(path, path);
}
}
}
}
- return set;
+ }
+ return set;
+}
+protected boolean hasPackageMapChanges() {
+ if (!Util.equalArraysOrNull(fOldState.getPackageFragmentRootsInClassPath(), fNewState.getPackageFragmentRootsInClassPath())) {
+ return true;
}
- protected boolean hasPackageMapChanges() {
- if (!Util
- .equalArraysOrNull(
- fOldState.getPackageFragmentRootsInClassPath(),
- fNewState.getPackageFragmentRootsInClassPath())) {
- return true;
- }
+ /* Has package or zip been added / removed ? */
+ if (fRemovedPkgOrZips.size() > 0 || fAddedPkgOrZips.size() > 0) {
+ return true;
+ }
- /* Has package or zip been added / removed ? */
- if (fRemovedPkgOrZips.size() > 0 || fAddedPkgOrZips.size() > 0) {
- return true;
+ /* if there is a changed zip file, assume package map changes */
+ for (Enumeration e = fChangedPkgOrZips.elements(); e.hasMoreElements();) {
+ IResourceDelta changed = (IResourceDelta) e.nextElement();
+ String extension = changed.getFullPath().getFileExtension();
+ if (extension != null) {
+ if (extension.equalsIgnoreCase("zip"/*nonNLS*/) || extension.equalsIgnoreCase("jar"/*nonNLS*/)) {
+ return true;
+ }
}
+ }
+ return false;
+}
+/**
+ * Returns true if there is a change to the list of source entries in this package, false
+ * otherwise. This is meant to be a fast optimization, to determine
+ * whether the source entries for this package need to be recomputed. This
+ * method works solely against the source workspace delta. When in doubt,
+ * it is always okay to return true here.
+ */
+protected boolean hasSourceEntryChanges(IPackage pkgHandle) {
+ IPath[] oldFrags = fOldState.getPackageMap().getFragments(pkgHandle);
+ IPath[] newFrags = fNewState.getPackageMap().getFragments(pkgHandle);
+ if (!Util.equalArraysOrNull(oldFrags, newFrags)) {
+ /* The set of package fragments has changed. Don't bother optimizing this case -- too complex. */
+ return true;
+ }
+
+ /* do for each fragment of this package */
+ for (int i = 0; i < newFrags.length; i++) {
+ IPath fragPath = newFrags[i];
- /* if there is a changed zip file, assume package map changes */
+ /* find the JCUs for this package */
+ IResourceDelta[] fileDeltas = null;
for (Enumeration e = fChangedPkgOrZips.elements(); e.hasMoreElements();) {
- IResourceDelta changed = (IResourceDelta) e.nextElement();
- String extension = changed.getFullPath().getFileExtension();
- if (extension != null) {
- if (extension.equalsIgnoreCase("zip") || extension.equalsIgnoreCase("jar")) {
+ IResourceDelta pkgDelta = (IResourceDelta) e.nextElement();
+ if (pkgDelta.getFullPath().equals(fragPath)) {
+ /* A zip file is changing. Don't bother optimizing this case -- too complex. */
+ if (fNewState.isZipElement(fragPath)) {
return true;
}
+ fileDeltas = pkgDelta.getAffectedChildren();
+ break;
}
}
- return false;
- }
-
- /**
- * Returns true if there is a change to the list of source entries in this package, false
- * otherwise. This is meant to be a fast optimization, to determine
- * whether the source entries for this package need to be recomputed. This
- * method works solely against the source workspace delta. When in doubt,
- * it is always okay to return true here.
- */
- protected boolean hasSourceEntryChanges(IPackage pkgHandle) {
- IPath[] oldFrags = fOldState.getPackageMap().getFragments(pkgHandle);
- IPath[] newFrags = fNewState.getPackageMap().getFragments(pkgHandle);
- if (!Util.equalArraysOrNull(oldFrags, newFrags)) {
- /* The set of package fragments has changed. Don't bother optimizing this case -- too complex. */
+ if (fileDeltas == null) {
+ /**
+ * It's a more complex interaction between zips, for example
+ * the package may be added in one zip and removed from another.
+ * Don't bother optimizing this case -- too complex.
+ */
return true;
}
- /* do for each fragment of this package */
- for (int i = 0; i < newFrags.length; i++) {
- IPath fragPath = newFrags[i];
+ /* do for each file in this fragment in the new workspace */
+ for (int j = 0; j < fileDeltas.length; j++) {
+ IPath path = fileDeltas[j].getFullPath();
- /* find the JCUs for this package */
- IResourceDelta[] fileDeltas = null;
- for (Enumeration e = fChangedPkgOrZips.elements(); e.hasMoreElements();) {
- IResourceDelta pkgDelta = (IResourceDelta) e.nextElement();
- if (pkgDelta.getFullPath().equals(fragPath)) {
- /* A zip file is changing. Don't bother optimizing this case -- too complex. */
- if (fNewState.isZipElement(fragPath)) {
+ /* skip java resources */
+ String extension = path.getFileExtension();
+ if (extension != null) {
+ if ((extension.equalsIgnoreCase("java"/*nonNLS*/) || extension.equalsIgnoreCase("class"/*nonNLS*/))) {
+ /* if there is an added or removed jcu or binary, the source entries have changed */
+ int status = fileDeltas[j].getKind();
+ if (status == IResourceDelta.ADDED || status == IResourceDelta.REMOVED) {
return true;
}
- fileDeltas = pkgDelta.getAffectedChildren();
- break;
- }
- }
- if (fileDeltas == null) {
- /**
- * It's a more complex interaction between zips, for example
- * the package may be added in one zip and removed from another.
- * Don't bother optimizing this case -- too complex.
- */
- return true;
- }
-
- /* do for each file in this fragment in the new workspace */
- for (int j = 0; j < fileDeltas.length; j++) {
- IPath path = fileDeltas[j].getFullPath();
-
- /* skip java resources */
- String extension = path.getFileExtension();
- if (extension != null) {
- if ((extension.equalsIgnoreCase("java")
- || extension.equalsIgnoreCase("class"))) {
- /* if there is an added or removed jcu or binary, the source entries have changed */
- int status = fileDeltas[j].getKind();
- if (status == IResourceDelta.ADDED || status == IResourceDelta.REMOVED) {
- return true;
- }
- /* it's a change, but it may be changing local status */
- if (fileDeltas[j].getResource().isLocal(IResource.DEPTH_ZERO)
- != fOldState.contains(new SourceEntry(path, null, null))) {
- return true;
- }
+ /* it's a change, but it may be changing local status */
+ if (fileDeltas[j].getResource().isLocal(IResource.DEPTH_ZERO) != fOldState.contains(new SourceEntry(path, null, null))) {
+ return true;
}
}
}
}
- return false;
}
+ return false;
+}
+/**
+ * Issues indictments to the dependents of the specified element.
+ * If transitive is true, they are issued to all dependents transitively,
+ * otherwise they are issued only to immediate dependents.
+ * The trial process is run as the indictments are issued.
+ * Any newly-convicted compilation units are added to the to-be-compiled list.
+ */
+protected void issueIndictments(Object element, IndictmentSet indicts, boolean transitive) {
+ DependencyGraph graph = fNewState.getInternalDependencyGraph();
+ Object[] dependents = graph.getDependents(element);
+ if (dependents.length > 0) {
+ Hashtable seen = new Hashtable(11);
+ seen.put(element, element); // Don't visit the given element
- /**
- * Issues indictments to the dependents of the specified element.
- * If transitive is true, they are issued to all dependents transitively,
- * otherwise they are issued only to immediate dependents.
- * The trial process is run as the indictments are issued.
- * Any newly-convicted compilation units are added to the to-be-compiled list.
- */
- protected void issueIndictments(
- Object element,
- IndictmentSet indicts,
- boolean transitive) {
- DependencyGraph graph = fNewState.getInternalDependencyGraph();
- Object[] dependents = graph.getDependents(element);
- if (dependents.length > 0) {
- Hashtable seen = new Hashtable(11);
- seen.put(element, element); // Don't visit the given element
-
- for (int i = 0; i < dependents.length; ++i) {
- issueIndictments(graph, dependents[i], indicts, transitive, seen);
- }
+ for (int i = 0; i < dependents.length; ++i) {
+ issueIndictments(graph, dependents[i], indicts, transitive, seen);
}
}
-
- /**
- * Issues indictments to the specified element.
- * If transitive is true, they are issued to all dependents transitively,
- * otherwise they are issued only to this element.
- * The trial process is run as the indictments are issued.
- * Any newly-convicted compilation units are added to the to-be-compiled list.
- */
- protected void issueIndictments(
- DependencyGraph graph,
- Object element,
- IndictmentSet indicts,
- boolean transitive,
- Hashtable seen) {
- // Only issue indictments to compilation units.
- if (element instanceof PackageElement) {
- PackageElement pkgElement = (PackageElement) element;
- if (pkgElement.isSource()) {
- // Have we already seen this one?
- if (!seen.containsKey(element)) {
- seen.put(element, element);
- // Is it already in the queue?
- if (!fWorkQueue.contains(pkgElement)) {
- // If it's not being removed, conduct the trial.
- if (fNewState.getSourceEntry(pkgElement) != null) {
- if (tryUnit(pkgElement, indicts)) {
- fWorkQueue.add(pkgElement);
- }
+}
+/**
+ * Issues indictments to the specified element.
+ * If transitive is true, they are issued to all dependents transitively,
+ * otherwise they are issued only to this element.
+ * The trial process is run as the indictments are issued.
+ * Any newly-convicted compilation units are added to the to-be-compiled list.
+ */
+protected void issueIndictments(DependencyGraph graph, Object element, IndictmentSet indicts, boolean transitive, Hashtable seen) {
+ // Only issue indictments to compilation units.
+ if (element instanceof PackageElement) {
+ PackageElement pkgElement = (PackageElement) element;
+ if (pkgElement.isSource()) {
+ // Have we already seen this one?
+ if (!seen.containsKey(element)) {
+ seen.put(element, element);
+ // Is it already in the queue?
+ if (!fWorkQueue.contains(pkgElement)) {
+ // If it's not being removed, conduct the trial.
+ if (fNewState.getSourceEntry(pkgElement) != null) {
+ if (tryUnit(pkgElement, indicts)) {
+ fWorkQueue.add(pkgElement);
}
}
+ }
- // Recurse if transitive
- if (transitive) {
- Object[] dependents = graph.getDependents(element);
- for (int i = 0; i < dependents.length; ++i) {
- issueIndictments(graph, dependents[i], indicts, transitive, seen);
- }
+ // Recurse if transitive
+ if (transitive) {
+ Object[] dependents = graph.getDependents(element);
+ for (int i = 0; i < dependents.length; ++i) {
+ issueIndictments(graph, dependents[i], indicts, transitive, seen);
}
}
}
}
}
-
- /**
- * Mark the immediate dependents of the given element
- * as needing to be compiled (if not marked so already),
- * and add any newly marked ones to the list.
- */
- protected void markDependentsAsNeedingCompile(Object element) {
- DependencyGraph graph = fNewState.getInternalDependencyGraph();
- Object[] deps = graph.getDependents(element);
- for (int i = 0; i < deps.length; ++i) {
- if (deps[i] instanceof PackageElement) {
- PackageElement pkgElement = (PackageElement) deps[i];
- if (pkgElement.isSource()) {
- if (!fWorkQueue.contains(pkgElement)) {
- // Mark it, if it's not being removed.
- if (fNewState.getSourceEntry(pkgElement) != null) {
- fWorkQueue.add(pkgElement);
- }
+}
+/**
+ * Mark the immediate dependents of the given element
+ * as needing to be compiled (if not marked so already),
+ * and add any newly marked ones to the list.
+ */
+protected void markDependentsAsNeedingCompile(Object element) {
+ DependencyGraph graph = fNewState.getInternalDependencyGraph();
+ Object[] deps = graph.getDependents(element);
+ for (int i = 0; i < deps.length; ++i) {
+ if (deps[i] instanceof PackageElement) {
+ PackageElement pkgElement = (PackageElement) deps[i];
+ if (pkgElement.isSource()) {
+ if (!fWorkQueue.contains(pkgElement)) {
+ // Mark it, if it's not being removed.
+ if (fNewState.getSourceEntry(pkgElement) != null) {
+ fWorkQueue.add(pkgElement);
}
}
}
}
}
+}
+/**
+ * All elements that refer to changed zips, or packages
+ * referred to by changed zips, must be recompiled.
+ * This is conservative, but since the old zip structure
+ * is not available, we can't do much better.
+ */
+protected void markDependentsOfChangedZips() {
- /**
- * All elements that refer to changed zips, or packages
- * referred to by changed zips, must be recompiled.
- * This is conservative, but since the old zip structure
- * is not available, we can't do much better.
- */
- protected void markDependentsOfChangedZips() {
+ PathMap oldPathMap = fOldState.getPathMap();
+ PathMap newPathMap = fNewState.getPathMap();
+
+ /* do for each changed zip */
+ for (Enumeration e = fChangedZips.elements(); e.hasMoreElements();) {
+ IPath zip = (IPath) e.nextElement();
- PathMap oldPathMap = fOldState.getPathMap();
- PathMap newPathMap = fNewState.getPathMap();
+ /* mark dependents of packages in old zip */
+ IPackage[] pkgs = oldPathMap.packageHandlesFromPath(zip);
+ for (int i = 0; i < pkgs.length; i++) {
+ markDependentsAsNeedingCompile(pkgs[i]);
+ }
- /* do for each changed zip */
- for (Enumeration e = fChangedZips.elements(); e.hasMoreElements();) {
- IPath zip = (IPath) e.nextElement();
+ /* mark dependents of packages in new zip */
+ pkgs = newPathMap.packageHandlesFromPath(zip);
+ for (int i = 0; i < pkgs.length; i++) {
+ markDependentsAsNeedingCompile(pkgs[i]);
+ }
+
+ /* mark dependents of the zip itself */
+ markDependentsAsNeedingCompile(zip);
+ }
+
+ /* also handle zips which were removed from class path */
+ IPath[] paths = oldPathMap.getPaths();
+ for (int i = 0; i < paths.length; ++i) {
+ IPath zip = paths[i];
+ if (fOldState.isZipElement(zip) && !newPathMap.hasPath(zip)) {
/* mark dependents of packages in old zip */
IPackage[] pkgs = oldPathMap.packageHandlesFromPath(zip);
- for (int i = 0; i < pkgs.length; i++) {
- markDependentsAsNeedingCompile(pkgs[i]);
- }
-
- /* mark dependents of packages in new zip */
- pkgs = newPathMap.packageHandlesFromPath(zip);
- for (int i = 0; i < pkgs.length; i++) {
- markDependentsAsNeedingCompile(pkgs[i]);
+ for (int j = 0; j < pkgs.length; j++) {
+ markDependentsAsNeedingCompile(pkgs[j]);
}
-
+
/* mark dependents of the zip itself */
markDependentsAsNeedingCompile(zip);
}
-
- /* also handle zips which were removed from class path */
- IPath[] paths = oldPathMap.getPaths();
- for (int i = 0; i < paths.length; ++i) {
- IPath zip = paths[i];
- if (fOldState.isZipElement(zip) && !newPathMap.hasPath(zip)) {
-
- /* mark dependents of packages in old zip */
- IPackage[] pkgs = oldPathMap.packageHandlesFromPath(zip);
- for (int j = 0; j < pkgs.length; j++) {
- markDependentsAsNeedingCompile(pkgs[j]);
- }
-
- /* mark dependents of the zip itself */
- markDependentsAsNeedingCompile(zip);
- }
- }
}
-
- /**
- * The given package is being added or removed. Make sure that no types
- * exist with the same name as this package. If any such types
- * exist, mark them as needing compilation and add them to the
- * compile vector.
- */
- protected void markOverlappingTypesAsNeedingCompile(IPackage pkg) {
- String pkgName = pkg.getName();
- int lastDot;
- while ((lastDot = pkgName.lastIndexOf('.')) > 0) {
-
- /* try to get a compilation unit for this package name */
- PackageElement element =
- fNewState.getCompilationUnitFromName(
- pkgName,
- fNewState.defaultPackageForProject());
- if (element != null) {
- fWorkQueue.add(element);
- }
-
- /* strip off a package level */
- pkgName = pkgName.substring(0, lastDot);
+}
+/**
+ * The given package is being added or removed. Make sure that no types
+ * exist with the same name as this package. If any such types
+ * exist, mark them as needing compilation and add them to the
+ * compile vector.
+ */
+protected void markOverlappingTypesAsNeedingCompile(IPackage pkg) {
+ String pkgName = pkg.getName();
+ int lastDot;
+ while ((lastDot = pkgName.lastIndexOf('.')) > 0) {
+
+ /* try to get a compilation unit for this package name */
+ PackageElement element = fNewState.getCompilationUnitFromName(pkgName, fNewState.defaultPackageForProject());
+ if (element != null) {
+ fWorkQueue.add(element);
}
- }
- /**
- * Force compilation of everything in the given package (non-state-specific handle),
- * if indicated by the build context.
- */
- protected void maybeForce(IPackage pkg) {
- ImageContextImpl imageContext = (ImageContextImpl) fNewState.getBuildContext();
- if (imageContext == null
- ? pkg.inState(fNewState).isPresent()
- : imageContext.containsPackage(pkg)) {
- // fNotifier.subTask("Forcing " + pkg.getName());
- fNewState.getAllTypesForPackage(pkg);
- checkCancel();
- }
+ /* strip off a package level */
+ pkgName = pkgName.substring(0, lastDot);
}
-
- /**
- * Propagate the principal structure by package table,
- * being sure to exclude any affected packages.
- */
- protected void propagatePrincipalStructureByPackageTable() {
- Hashtable newTable =
- (Hashtable) fOldState.getPrincipalStructureByPackageTable().clone();
- for (Enumeration e = fAffectedPackages.keys(); e.hasMoreElements();) {
- IPackage pkg = (IPackage) e.nextElement();
- newTable.remove(pkg);
- }
- fNewState.setPrincipalStructureByPackageTable(newTable);
+}
+/**
+ * Force compilation of everything in the given package (non-state-specific handle),
+ * if indicated by the build context.
+ */
+protected void maybeForce(IPackage pkg) {
+ ImageContextImpl imageContext = (ImageContextImpl) fNewState.getBuildContext();
+ if (imageContext == null ? pkg.inState(fNewState).isPresent() : imageContext.containsPackage(pkg)) {
+ // fNotifier.subTask("Forcing " + pkg.getName());
+ fNewState.getAllTypesForPackage(pkg);
+ checkCancel();
}
-
- /**
- * Recomputes the source entries for changed packages. As an optimization,
- * only recompute the source entries for packages that may actually have
- * changes to their source entries.
- */
- protected void recomputeSourceEntriesForChangedPackages() {
- for (Enumeration e = fChangedPackageHandles.elements(); e.hasMoreElements();) {
- IPackage pkg = (IPackage) e.nextElement();
- if (hasSourceEntryChanges(pkg)) {
- fNewState.getSourceElementTable().removePackage(pkg);
- // Now force it.
- fNewState.getSourceEntries(pkg);
- }
- }
+}
+/**
+ * Propagate the principal structure by package table,
+ * being sure to exclude any affected packages.
+ */
+protected void propagatePrincipalStructureByPackageTable() {
+ Hashtable newTable = (Hashtable) fOldState.getPrincipalStructureByPackageTable().clone();
+ for (Enumeration e = fAffectedPackages.keys(); e.hasMoreElements();) {
+ IPackage pkg = (IPackage) e.nextElement();
+ newTable.remove(pkg);
}
-
- /**
- * Remove all types and compilation units from the new state
- * that do not exist in the new workspace. Keep track of any
- * types that will need to be compiled as a result of the change.
- */
- protected void removeOldClasses() {
- for (Enumeration e = fRemovedClasses.elements(); e.hasMoreElements();) {
- SourceEntry entry = (SourceEntry) e.nextElement();
- removeSourceElement(entry);
+ fNewState.setPrincipalStructureByPackageTable(newTable);
+}
+/**
+ * Recomputes the source entries for changed packages. As an optimization,
+ * only recompute the source entries for packages that may actually have
+ * changes to their source entries.
+ */
+protected void recomputeSourceEntriesForChangedPackages() {
+ for (Enumeration e = fChangedPackageHandles.elements(); e.hasMoreElements();) {
+ IPackage pkg = (IPackage) e.nextElement();
+ if (hasSourceEntryChanges(pkg)) {
+ fNewState.getSourceElementTable().removePackage(pkg);
+ // Now force it.
+ fNewState.getSourceEntries(pkg);
}
}
+}
+/**
+ * Remove all types and compilation units from the new state
+ * that do not exist in the new workspace. Keep track of any
+ * types that will need to be compiled as a result of the change.
+ */
+protected void removeOldClasses() {
+ for (Enumeration e = fRemovedClasses.elements(); e.hasMoreElements();) {
+ SourceEntry entry = (SourceEntry) e.nextElement();
+ removeSourceElement(entry);
+ }
+}
+/**
+ * Removes the given source element from the new state's tables
+ * and dependency graph. Marks all JCUs that depend on the removed element.
+ */
+protected void removeSourceElement(SourceEntry entry) {
+ PackageElement element = fOldState.packageElementFromSourceEntry(entry);
+ SourceEntry oldEntry = fOldState.getSourceEntry(element);
+ if (oldEntry == null) {
+ // It didn't exist in the old state (strange).
+ return;
+ }
- /**
- * Removes the given source element from the new state's tables
- * and dependency graph. Marks all JCUs that depend on the removed element.
- */
- protected void removeSourceElement(SourceEntry entry) {
- PackageElement element = fOldState.packageElementFromSourceEntry(entry);
- SourceEntry oldEntry = fOldState.getSourceEntry(element);
- if (oldEntry == null) {
- // It didn't exist in the old state (strange).
- return;
- }
-
- // delete problems for this entry
- // only delete non-syntax problems, since new syntax problems may have already
- // been generated during namespace computations
- fNewState.getProblemReporter().removeNonSyntaxErrors(oldEntry);
+ // delete problems for this entry
+ // only delete non-syntax problems, since new syntax problems may have already
+ // been generated during namespace computations
+ fNewState.getProblemReporter().removeNonSyntaxErrors(oldEntry);
- /* remove type descriptor for types that belong to this source element */
- DependencyGraph graph = fNewState.getInternalDependencyGraph();
- Hashtable structureTable = fNewState.getPrincipalStructureTable();
- IType[] types = graph.getTypes(element);
- if (types != null) {
- for (int i = 0; i < types.length; ++i) {
- IType type = types[i];
- structureTable.remove(type);
- if (!element.isBinary()) {
- fNewState.getBinaryOutput().deleteBinary(type);
- }
+ /* remove type descriptor for types that belong to this source element */
+ DependencyGraph graph = fNewState.getInternalDependencyGraph();
+ Hashtable structureTable = fNewState.getPrincipalStructureTable();
+ IType[] types = graph.getTypes(element);
+ if (types != null) {
+ for (int i = 0; i < types.length; ++i) {
+ IType type = types[i];
+ structureTable.remove(type);
+ if (!element.isBinary()) {
+ fNewState.getBinaryOutput().deleteBinary(type);
}
}
- markDependentsAsNeedingCompile(element);
- graph.remove(element);
-
- // The element has already been removed from the source element table.
- // So don't do any source element table or fragment logic here.
-
- // Don't delete the namespace for the package here, because it cannot be rebuilt lazily
- // since the package may be in process of being removed.
}
+ markDependentsAsNeedingCompile(element);
+ graph.remove(element);
- /**
- * Hang onto the binary types for this source, because it will be compiled
- */
- protected void saveBinaryTypes(PackageElement element) {
- DependencyGraph graph = fOldState.getInternalDependencyGraph();
- IType[] types = graph.getTypes(element);
- for (int i = 0; i < types.length; i++) {
- IType type = types[i];
- BuilderType builderType = (BuilderType) fBuilderTypeTable.get(type);
+ // The element has already been removed from the source element table.
+ // So don't do any source element table or fragment logic here.
- if (builderType == null || !builderType.isAffected()) {
- TypeStructureEntry oldEntry = fOldState.getTypeStructureEntry(type, false);
- Assert.isNotNull(oldEntry);
+ // Don't delete the namespace for the package here, because it cannot be rebuilt lazily
+ // since the package may be in process of being removed.
+}
+/**
+ * Hang onto the binary types for this source, because it will be compiled
+ */
+protected void saveBinaryTypes(PackageElement element) {
+ DependencyGraph graph = fOldState.getInternalDependencyGraph();
+ IType[] types = graph.getTypes(element);
+ for (int i = 0; i < types.length; i++) {
+ IType type = types[i];
+ BuilderType builderType = (BuilderType) fBuilderTypeTable.get(type);
- /* create and store the builder type */
- // Allow it to be missing. See 1FW1S0Y: ITPJCORE:ALL - Java builder builds when non-Java files affected
- IBinaryType oldBinary = fOldState.getBinaryTypeOrNull(oldEntry);
- builderType = new ModifiedBuilderType(this, oldEntry, oldBinary);
- fBuilderTypeTable.put(type, builderType);
+ if (builderType == null || !builderType.isAffected()) {
+ TypeStructureEntry oldEntry = fOldState.getTypeStructureEntry(type, false);
+ Assert.isNotNull(oldEntry);
- /* remove the principal structure entry in the new state */
- fNewState.getPrincipalStructureTable().remove(type);
+ /* create and store the builder type */
+ // Allow it to be missing. See 1FW1S0Y: ITPJCORE:ALL - Java builder builds when non-Java files affected
+ IBinaryType oldBinary = fOldState.getBinaryTypeOrNull(oldEntry);
+ builderType = new ModifiedBuilderType(this, oldEntry, oldBinary);
+ fBuilderTypeTable.put(type, builderType);
- /* nuke the binary because it will soon be stale */
- fNewState.getBinaryOutput().deleteBinary(type);
- }
- }
- }
+ /* remove the principal structure entry in the new state */
+ fNewState.getPrincipalStructureTable().remove(type);
- /**
- * Sort the compilation units by topological order.
- */
- protected void sort(PackageElement[] compileArray) {
- DependencyGraph graph = fNewState.getInternalDependencyGraph();
- int len = compileArray.length;
- int[] sortOrder = new int[len];
- for (int i = 0; i < len; ++i) {
- sortOrder[i] = graph.getOrder(compileArray[i]);
+ /* nuke the binary because it will soon be stale */
+ fNewState.getBinaryOutput().deleteBinary(type);
}
- Util.sort(compileArray, sortOrder);
}
-
- /**
- * Returns a string describe the builder
- * @see IImageBuilder
- */
- public String toString() {
- return "incremental image builder for:\n"
- + "\tnew state: "
- + getNewState()
- + "\n"
- + "\told state: "
- + getOldState();
+}
+/**
+ * Sort the compilation units by topological order.
+ */
+protected void sort(PackageElement[] compileArray) {
+ DependencyGraph graph = fNewState.getInternalDependencyGraph();
+ int len = compileArray.length;
+ int[] sortOrder = new int[len];
+ for (int i = 0; i < len; ++i) {
+ sortOrder[i] = graph.getOrder(compileArray[i]);
}
-
- /**
- * If this type is a subtype is the originator of an abstract method
- * indictment, it must be compiled
- */
- protected boolean tryAbstractMethodIndictments(
- PackageElement unit,
- IndictmentSet indictments) {
- final boolean GUILTY = true, INNOCENT = false;
- IType[] trialTypes = indictments.getAbstractMethodOriginators();
- if (trialTypes.length == 0) {
- return false;
- }
- /* if problems were detected, some innerclasses might not have been generated,
- thus the state would not reflect their presence, and even if guilty could not
- be convicted (also see 1GA6CV7) */
- Vector problemVector =
- fOldState.getProblemReporter().getProblemVector(fOldState.getSourceEntry(unit));
- if (problemVector != null) {
- Enumeration problems = problemVector.elements();
- while (problems.hasMoreElements()) {
- IProblemDetail problem = (IProblemDetail) problems.nextElement();
- if ((problem.getSeverity() & IProblemDetail.S_ERROR) != 0)
- return GUILTY;
- }
- }
-
- /* do for each type in this package element */
- IType[] types = fOldState.getInternalDependencyGraph().getTypes(unit);
- for (int i = 0, imax = types.length; i < imax; i++) {
- IType type = types[i];
- TypeStructureEntry tsEntry = fOldState.getTypeStructureEntry(type, false);
-
- /* shouldn't happen, but trust nobody! */
- if (tsEntry == null) {
- continue;
- }
- IType oldType = (IType) type.inState(fOldState);
- int flags = oldType.getModifiers();
-
- /* interfaces aren't affected by method additions/removals in super interfaces,
- other than for compatibility checking, which is handled elsewhere */
- if (oldType.isInterface()) {
- continue;
- }
-
- /* only check superclasses if this class is not abstract, */
- /* because abstract classes aren't affected by abstract method additions/removals */
- /* on their superclasses, only on their superinterfaces */
- boolean checkSuperclasses = (flags & IConstants.AccAbstract) == 0;
-
- /* do for each abstract method originator */
- BuilderType builderType = getBuilderType(type);
- for (int j = 0, jmax = trialTypes.length; j < jmax; ++j) {
- IType trialType = trialTypes[j];
- if (checkSuperclasses) {
- if (builderType.hasSuperclass(trialType)) {
- return GUILTY;
- }
- }
- if (builderType.hasSuperInterface(trialType)) {
+ Util.sort(compileArray, sortOrder);
+}
+/**
+ * Returns a string describe the builder
+ * @see IImageBuilder
+ */
+public String toString() {
+ return "incremental image builder for:\n"/*nonNLS*/ + "\tnew state: "/*nonNLS*/ + getNewState() + "\n"/*nonNLS*/ + "\told state: "/*nonNLS*/ + getOldState();
+}
+/**
+ * If this type is a subtype is the originator of an abstract method
+ * indictment, it must be compiled
+ */
+protected boolean tryAbstractMethodIndictments(PackageElement unit, IndictmentSet indictments) {
+ final boolean GUILTY = true, INNOCENT = false;
+ IType[] trialTypes = indictments.getAbstractMethodOriginators();
+ if (trialTypes.length == 0) {
+ return false;
+ }
+ /* if problems were detected, some innerclasses might not have been generated,
+ thus the state would not reflect their presence, and even if guilty could not
+ be convicted (also see 1GA6CV7) */
+ Vector problemVector = fOldState.getProblemReporter().getProblemVector(fOldState.getSourceEntry(unit));
+ if (problemVector != null){
+ Enumeration problems = problemVector.elements();
+ while (problems.hasMoreElements()){
+ IProblemDetail problem = (IProblemDetail) problems.nextElement();
+ if ((problem.getSeverity() & IProblemDetail.S_ERROR) != 0) return GUILTY;
+ }
+ }
+
+ /* do for each type in this package element */
+ IType[] types = fOldState.getInternalDependencyGraph().getTypes(unit);
+ for (int i = 0, imax = types.length; i < imax; i++) {
+ IType type = types[i];
+ TypeStructureEntry tsEntry = fOldState.getTypeStructureEntry(type, false);
+
+ /* shouldn't happen, but trust nobody! */
+ if (tsEntry == null) {
+ continue;
+ }
+ IType oldType = (IType) type.inState(fOldState);
+ int flags = oldType.getModifiers();
+
+ /* interfaces aren't affected by method additions/removals in super interfaces,
+ other than for compatibility checking, which is handled elsewhere */
+ if (oldType.isInterface()) {
+ continue;
+ }
+
+ /* only check superclasses if this class is not abstract, */
+ /* because abstract classes aren't affected by abstract method additions/removals */
+ /* on their superclasses, only on their superinterfaces */
+ boolean checkSuperclasses = (flags & IConstants.AccAbstract) == 0;
+
+ /* do for each abstract method originator */
+ BuilderType builderType = getBuilderType(type);
+ for (int j = 0, jmax = trialTypes.length; j < jmax; ++j) {
+ IType trialType = trialTypes[j];
+ if (checkSuperclasses) {
+ if (builderType.hasSuperclass(trialType)) {
return GUILTY;
}
}
+ if (builderType.hasSuperInterface(trialType)) {
+ return GUILTY;
+ }
}
-
- /* no supertypes convicted this package element, so it must be innocent */
- return INNOCENT;
}
- /**
- * If a subtype of the originator of a method indictment redefines
- * the method for which there is an indictment, it must be recompiled.
- * This is also true if any superinterfaces of the subtype defines
- * an indicted method.
- */
- protected boolean tryMethodDeclarations(
- BuilderType builderType,
- IndictmentSet indictments) {
- final boolean GUILTY = true, INNOCENT = false;
-
- /* try the methods of this type */
- IBinaryType oldBinary = builderType.getOldBinaryType();
- if (oldBinary == null)
- return GUILTY;
-
- IBinaryMethod[] methods = oldBinary.getMethods();
- if (methods != null) {
- for (int k = 0; k < methods.length; k++) {
- if (indictments.tryMethodDeclaration(methods[k])) {
- return GUILTY;
- }
+ /* no supertypes convicted this package element, so it must be innocent */
+ return INNOCENT;
+}
+/**
+ * If a subtype of the originator of a method indictment redefines
+ * the method for which there is an indictment, it must be recompiled.
+ * This is also true if any superinterfaces of the subtype defines
+ * an indicted method.
+ */
+protected boolean tryMethodDeclarations(BuilderType builderType, IndictmentSet indictments) {
+ final boolean GUILTY = true, INNOCENT = false;
+
+ /* try the methods of this type */
+ IBinaryType oldBinary = builderType.getOldBinaryType();
+ if (oldBinary == null) return GUILTY;
+
+ IBinaryMethod[] methods = oldBinary.getMethods();
+ if (methods != null) {
+ for (int k = 0; k < methods.length; k++) {
+ if (indictments.tryMethodDeclaration(methods[k])) {
+ return GUILTY;
}
}
+ }
- /* recurse on superinterfaces */
- char[][] interfaces = oldBinary.getInterfaceNames();
- if (interfaces != null) {
- for (int i = 0; i < interfaces.length; i++) {
- BuilderType supr =
- getBuilderType(
- BinaryStructure.getType(
- builderType.getNewState(),
- builderType.getNewTypeStructureEntry(),
- interfaces[i]));
- if (tryMethodDeclarations(supr, indictments)) {
- return GUILTY;
- }
+ /* recurse on superinterfaces */
+ char[][] interfaces = oldBinary.getInterfaceNames();
+ if (interfaces != null) {
+ for (int i = 0; i < interfaces.length; i++) {
+ BuilderType supr = getBuilderType(BinaryStructure.getType(builderType.getNewState(), builderType.getNewTypeStructureEntry(), interfaces[i]));
+ if (tryMethodDeclarations(supr, indictments)) {
+ return GUILTY;
}
}
+ }
+ return INNOCENT;
+}
+/**
+ * If a subtype of the originator of a method indictment redefines
+ * the method for which there is an indictment, it must be recompiled.
+ */
+protected boolean tryMethodDeclarations(PackageElement unit, IndictmentSet indictments) {
+ final boolean GUILTY = true, INNOCENT = false;
+ IType[] methodIndictmentOwners = indictments.getMethodIndictmentOwners();
+ if (methodIndictmentOwners.length == 0) {
return INNOCENT;
}
-
- /**
- * If a subtype of the originator of a method indictment redefines
- * the method for which there is an indictment, it must be recompiled.
- */
- protected boolean tryMethodDeclarations(
- PackageElement unit,
- IndictmentSet indictments) {
- final boolean GUILTY = true, INNOCENT = false;
- IType[] methodIndictmentOwners = indictments.getMethodIndictmentOwners();
- if (methodIndictmentOwners.length == 0) {
- return INNOCENT;
- }
- /* if problems were detected, some innerclasses might not have been generated,
- thus the state would not reflect their presence, and even if guilty could not
- be convicted (also see 1GA6CV7) */
- Vector problemVector =
- fOldState.getProblemReporter().getProblemVector(fOldState.getSourceEntry(unit));
- if (problemVector != null) {
- Enumeration problems = problemVector.elements();
- while (problems.hasMoreElements()) {
- IProblemDetail problem = (IProblemDetail) problems.nextElement();
- if ((problem.getSeverity() & IProblemDetail.S_ERROR) != 0)
- return GUILTY;
+ /* if problems were detected, some innerclasses might not have been generated,
+ thus the state would not reflect their presence, and even if guilty could not
+ be convicted (also see 1GA6CV7) */
+ Vector problemVector = fOldState.getProblemReporter().getProblemVector(fOldState.getSourceEntry(unit));
+ if (problemVector != null){
+ Enumeration problems = problemVector.elements();
+ while (problems.hasMoreElements()){
+ IProblemDetail problem = (IProblemDetail) problems.nextElement();
+ if ((problem.getSeverity() & IProblemDetail.S_ERROR) != 0) return GUILTY;
+ }
+ }
+ IType[] types = fOldState.getInternalDependencyGraph().getTypes(unit);
+ for (int i = 0; i < types.length; ++i) {
+ boolean found = false;
+ BuilderType trialType = getBuilderType(types[i]);
+ for (int j = 0, len = methodIndictmentOwners.length; j < len; ++j) {
+ //note this is conservative because owners are not matched to their methods
+ if (trialType.hasSuperType(methodIndictmentOwners[j])) {
+ found = true;
+ break;
}
}
- IType[] types = fOldState.getInternalDependencyGraph().getTypes(unit);
- for (int i = 0; i < types.length; ++i) {
- boolean found = false;
- BuilderType trialType = getBuilderType(types[i]);
- for (int j = 0, len = methodIndictmentOwners.length; j < len; ++j) {
- //note this is conservative because owners are not matched to their methods
- if (trialType.hasSuperType(methodIndictmentOwners[j])) {
- found = true;
- break;
- }
- }
- if (found) {
- if (tryMethodDeclarations(trialType, indictments)) {
- return GUILTY;
- }
+ if (found) {
+ if (tryMethodDeclarations(trialType, indictments)){
+ return GUILTY;
}
}
- return INNOCENT;
}
+ return INNOCENT;
+}
+/**
+ * Conducts a trial on a single compilation unit. Returns true if the unit
+ * is guilty. The sentence is compilation without possibility of parole.
+ */
+protected boolean tryUnit(PackageElement unit, IndictmentSet indictments) {
- /**
- * Conducts a trial on a single compilation unit. Returns true if the unit
- * is guilty. The sentence is compilation without possibility of parole.
- */
- protected boolean tryUnit(PackageElement unit, IndictmentSet indictments) {
-
- /* innocent unless proven guilty */
- final boolean GUILTY = true, INNOCENT = false;
-
- /* quick test to see if there's no indictments */
- if (indictments.isEmpty()) {
- return INNOCENT;
- }
-
- /* automatically guilty if there is an upstream hierarchy change */
- if (indictments.hasHierarchyIndictment()) {
- return GUILTY;
- }
-
- /* gather the evidence */
- ReferenceInfo evidence = fNewState.getReferencesForPackageElement(unit);
-
- /* Unable to index unit, convict and let compiler try it */
- if (evidence == null) {
- return GUILTY;
- }
- if (indictments.tryAllEvidence(evidence)) {
- return GUILTY;
- }
+ /* innocent unless proven guilty */
+ final boolean GUILTY = true, INNOCENT = false;
- /**
- * If a subtype of the originator of a method indictment redefines
- * the method for which there is an indictment, it must be recompiled.
- */
- if (tryMethodDeclarations(unit, indictments)) {
- return GUILTY;
- }
+ /* quick test to see if there's no indictments */
+ if (indictments.isEmpty()) {
+ return INNOCENT;
+ }
- /**
- * If this type is a subtype of the originator of an abstract method
- * indictment, it may need to be recompiled.
- */
- if (tryAbstractMethodIndictments(unit, indictments)) {
- return GUILTY;
- }
+ /* automatically guilty if there is an upstream hierarchy change */
+ if (indictments.hasHierarchyIndictment()) {
+ return GUILTY;
+ }
- /**
- * If there have been changes to constructors in the direct superclass,
- * it must be recompiled.
- */
- if (tryZeroArgConstructorInSuperclass(unit, indictments)) {
- return GUILTY;
- }
+ /* gather the evidence */
+ ReferenceInfo evidence = fNewState.getReferencesForPackageElement(unit);
- /* evidence is exhausted and unit has not been convicted */
- return INNOCENT;
+ /* Unable to index unit, convict and let compiler try it */
+ if (evidence == null) {
+ return GUILTY;
+ }
+ if (indictments.tryAllEvidence(evidence)) {
+ return GUILTY;
}
/**
- * If there have been changes to the zero-arg constructor in the superclass of any types in the CU,
- * the CU must be recompiled. This handles refs by default constructors and implicit super invocations in
- * constructors, which aren't covered by the normal method indictments since they
- * generate no evidence of refs to the super constructor.
+ * If a subtype of the originator of a method indictment redefines
+ * the method for which there is an indictment, it must be recompiled.
*/
- protected boolean tryZeroArgConstructorInSuperclass(
- PackageElement unit,
- IndictmentSet indictments) {
- if (!indictments.hasConstructorIndictments()) {
- return false;
- }
- IType[] types = fOldState.getInternalDependencyGraph().getTypes(unit);
- for (int i = 0; i < types.length; ++i) {
- IType superclass = getBuilderType(types[i]).getSuperclass();
- if (superclass != null) {
- String key = '<' + superclass.getDeclaredName() + ">/0";
- if (indictments.tryMethodEvidence(key.toCharArray())) {
- return true;
- }
- }
- }
- return false;
+ if (tryMethodDeclarations(unit, indictments)) {
+ return GUILTY;
}
/**
- * Processes changed classes in the state. Stores compilation
- * units that need to be compiled as a result of the changes.
+ * If this type is a subtype of the originator of an abstract method
+ * indictment, it may need to be recompiled.
*/
- protected void updateChangedClasses() {
- for (Enumeration e = fChangedClasses.elements(); e.hasMoreElements();) {
- SourceEntry entry = (SourceEntry) e.nextElement();
- changedSourceElement(entry);
- }
+ if (tryAbstractMethodIndictments(unit, indictments)) {
+ return GUILTY;
}
/**
- * Updates or rebuilds the package map with the affected package fragments.
- * After, the added/removed/changed builder packages are known.
+ * If there have been changes to constructors in the direct superclass,
+ * it must be recompiled.
*/
- protected void updatePackageMap() {
- // Simply rebuild if adding or removing packages, rather than trying to do this
- // incrementally, which is tricky. E.g. a package should not really be added if its
- // project does not appear in the class path.
- boolean rebuild = hasPackageMapChanges();
- if (rebuild) {
- fNewState.buildInitialPackageMap();
- }
-
- /* Set of affected package handles */
- Vector affected = new Vector();
+ if (tryZeroArgConstructorInSuperclass(unit, indictments)) {
+ return GUILTY;
+ }
- /* Process changed package fragments (package map not affected). *
- * Due to changing class paths, a package which is changing in the source *
- * may actually be added / removed rather than changed. Figure out which. */
- for (Enumeration e = fChangedPkgOrZips.elements(); e.hasMoreElements();) {
- IResourceDelta delta = (IResourceDelta) e.nextElement();
- IPackage[] pkgHandles = null;
-
- /* Look in the new state only if the package has not been removed */
- if (delta.getKind() != IResourceDelta.REMOVED) {
- pkgHandles = fNewState.getPathMap().packageHandlesFromPath(delta.getFullPath());
- for (int i = 0; i < pkgHandles.length; i++) {
- if (!affected.contains(pkgHandles[i])) {
- affected.addElement(pkgHandles[i]);
- }
- }
- }
- /* Look in the old state only if the package has not been added */
- if (delta.getKind() != IResourceDelta.ADDED) {
- pkgHandles = fOldState.getPathMap().packageHandlesFromPath(delta.getFullPath());
- for (int i = 0; i < pkgHandles.length; i++) {
- if (!affected.contains(pkgHandles[i])) {
- affected.addElement(pkgHandles[i]);
- }
- }
+ /* evidence is exhausted and unit has not been convicted */
+ return INNOCENT;
+}
+/**
+ * If there have been changes to the zero-arg constructor in the superclass of any types in the CU,
+ * the CU must be recompiled. This handles refs by default constructors and implicit super invocations in
+ * constructors, which aren't covered by the normal method indictments since they
+ * generate no evidence of refs to the super constructor.
+ */
+protected boolean tryZeroArgConstructorInSuperclass(PackageElement unit, IndictmentSet indictments) {
+ if (!indictments.hasConstructorIndictments()) {
+ return false;
+ }
+ IType[] types = fOldState.getInternalDependencyGraph().getTypes(unit);
+ for (int i = 0; i < types.length; ++i) {
+ IType superclass = getBuilderType(types[i]).getSuperclass();
+ if (superclass != null) {
+ String key = '<' + superclass.getDeclaredName() + ">/0"/*nonNLS*/;
+ if (indictments.tryMethodEvidence(key.toCharArray())) {
+ return true;
}
}
+ }
+ return false;
+}
+/**
+ * Processes changed classes in the state. Stores compilation
+ * units that need to be compiled as a result of the changes.
+ */
+protected void updateChangedClasses() {
+ for (Enumeration e = fChangedClasses.elements(); e.hasMoreElements();) {
+ SourceEntry entry = (SourceEntry) e.nextElement();
+ changedSourceElement(entry);
+ }
+}
+/**
+ * Updates or rebuilds the package map with the affected package fragments.
+ * After, the added/removed/changed builder packages are known.
+ */
+protected void updatePackageMap() {
+ // Simply rebuild if adding or removing packages, rather than trying to do this
+ // incrementally, which is tricky. E.g. a package should not really be added if its
+ // project does not appear in the class path.
+ boolean rebuild = hasPackageMapChanges();
+ if (rebuild) {
+ fNewState.buildInitialPackageMap();
+ }
- /* Partition affected packages into added/removed/changed */
- fAddedPackageHandles = new Vector();
- fRemovedPackageHandles = new Vector();
- fChangedPackageHandles = new Vector();
- PackageMap oldMap = fOldState.getPackageMap();
- PackageMap newMap = fNewState.getPackageMap();
- for (Enumeration e = affected.elements(); e.hasMoreElements();) {
- IPackage pkg = (IPackage) e.nextElement();
- if (oldMap.containsPackage(pkg)) {
- if (newMap.containsPackage(pkg)) {
- fChangedPackageHandles.addElement(pkg);
- } else {
- fRemovedPackageHandles.addElement(pkg);
+ /* Set of affected package handles */
+ Vector affected = new Vector();
+
+ /* Process changed package fragments (package map not affected). *
+ * Due to changing class paths, a package which is changing in the source *
+ * may actually be added / removed rather than changed. Figure out which. */
+ for (Enumeration e = fChangedPkgOrZips.elements(); e.hasMoreElements();) {
+ IResourceDelta delta = (IResourceDelta) e.nextElement();
+ IPackage[] pkgHandles = null;
+
+ /* Look in the new state only if the package has not been removed */
+ if (delta.getKind() != IResourceDelta.REMOVED) {
+ pkgHandles = fNewState.getPathMap().packageHandlesFromPath(delta.getFullPath());
+ for (int i = 0; i < pkgHandles.length; i++) {
+ if (!affected.contains(pkgHandles[i])) {
+ affected.addElement(pkgHandles[i]);
}
- } else {
- if (newMap.containsPackage(pkg)) {
- fAddedPackageHandles.addElement(pkg);
- } else {
- // This can occur if there are changes to a package
- // which does not appear in either the old or new class path.
- // Ignore it.
+ }
+ }
+ /* Look in the old state only if the package has not been added */
+ if (delta.getKind() != IResourceDelta.ADDED) {
+ pkgHandles = fOldState.getPathMap().packageHandlesFromPath(delta.getFullPath());
+ for (int i = 0; i < pkgHandles.length; i++) {
+ if (!affected.contains(pkgHandles[i])) {
+ affected.addElement(pkgHandles[i]);
}
}
}
+ }
- /* Check for added/removed/changed packages due to added/removed fragments and/or class path changes */
- if (rebuild) {
- for (Enumeration e = oldMap.getAllPackages(); e.hasMoreElements();) {
- IPackage pkg = (IPackage) e.nextElement();
- IPath[] newFragments = newMap.getFragments(pkg);
- if (newFragments == null) {
- // package has been removed due to class path change;
- // may also have been removed due to source change
- if (!fRemovedPackageHandles.contains(pkg)) {
- fRemovedPackageHandles.addElement(pkg);
- }
- } else
- if (!Util.equalArraysOrNull(oldMap.getFragments(pkg), newFragments)) {
- // package has changed package fragments due to class path change;
- // may also have source change
- if (!fChangedPackageHandles.contains(pkg)) {
- fChangedPackageHandles.addElement(pkg);
- }
- }
+ /* Partition affected packages into added/removed/changed */
+ fAddedPackageHandles = new Vector();
+ fRemovedPackageHandles = new Vector();
+ fChangedPackageHandles = new Vector();
+ PackageMap oldMap = fOldState.getPackageMap();
+ PackageMap newMap = fNewState.getPackageMap();
+ for (Enumeration e = affected.elements(); e.hasMoreElements();) {
+ IPackage pkg = (IPackage) e.nextElement();
+ if (oldMap.containsPackage(pkg)) {
+ if (newMap.containsPackage(pkg)) {
+ fChangedPackageHandles.addElement(pkg);
+ } else {
+ fRemovedPackageHandles.addElement(pkg);
}
- for (Enumeration e = newMap.getAllPackages(); e.hasMoreElements();) {
- IPackage pkg = (IPackage) e.nextElement();
- if (!oldMap.containsPackage(pkg)) {
- // package has been added due to class path change;
- // may also have been added due to source change
- if (!fAddedPackageHandles.contains(pkg)) {
- fAddedPackageHandles.addElement(pkg);
- }
- }
+ } else {
+ if (newMap.containsPackage(pkg)) {
+ fAddedPackageHandles.addElement(pkg);
+ } else {
+ // This can occur if there are changes to a package
+ // which does not appear in either the old or new class path.
+ // Ignore it.
}
}
+ }
- /* Add all affected packages to fAffectedPackages. */
- fAffectedPackages = new Hashtable(11);
- for (Enumeration e = fAddedPackageHandles.elements(); e.hasMoreElements();) {
- IPackage pkg = (IPackage) e.nextElement();
- fAffectedPackages.put(pkg, pkg);
- }
- for (Enumeration e = fRemovedPackageHandles.elements(); e.hasMoreElements();) {
+ /* Check for added/removed/changed packages due to added/removed fragments and/or class path changes */
+ if (rebuild) {
+ for (Enumeration e = oldMap.getAllPackages(); e.hasMoreElements();) {
IPackage pkg = (IPackage) e.nextElement();
- fAffectedPackages.put(pkg, pkg);
+ IPath[] newFragments = newMap.getFragments(pkg);
+ if (newFragments == null) {
+ // package has been removed due to class path change;
+ // may also have been removed due to source change
+ if (!fRemovedPackageHandles.contains(pkg)) {
+ fRemovedPackageHandles.addElement(pkg);
+ }
+ } else
+ if (!Util.equalArraysOrNull(oldMap.getFragments(pkg), newFragments)) {
+ // package has changed package fragments due to class path change;
+ // may also have source change
+ if (!fChangedPackageHandles.contains(pkg)) {
+ fChangedPackageHandles.addElement(pkg);
+ }
+ }
}
- for (Enumeration e = fChangedPackageHandles.elements(); e.hasMoreElements();) {
+ for (Enumeration e = newMap.getAllPackages(); e.hasMoreElements();) {
IPackage pkg = (IPackage) e.nextElement();
- fAffectedPackages.put(pkg, pkg);
+ if (!oldMap.containsPackage(pkg)) {
+ // package has been added due to class path change;
+ // may also have been added due to source change
+ if (!fAddedPackageHandles.contains(pkg)) {
+ fAddedPackageHandles.addElement(pkg);
+ }
+ }
}
}
- /**
- * Stores the results of a compilation in the appropriate state tables.
- * Keeps track of what compilation units need to be compiled as a result
- * of the changes.
- */
- protected void updateState(ConvertedCompilationResult[] results) {
- int n = results.length;
- PackageElement[] oldUnits = new PackageElement[n];
- PackageElement[] newUnits = new PackageElement[n];
- IType[][] oldTypeList = new IType[n][];
-
- // Preparation
- DependencyGraph oldGraph = fOldState.getInternalDependencyGraph();
- DependencyGraph newGraph = fNewState.getInternalDependencyGraph();
-
- for (int i = 0; i < n; i++) {
- PackageElement element = results[i].getPackageElement();
-
- // Be sure the package is in the set of affected packages.
- // It may not be if this unit was recompiled in a package
- // other than the ones which have direct changes.
- IPackage pkg = element.getPackage();
- fAffectedPackages.put(pkg, pkg);
-
- // Be sure to look up the source entries in the old and new state,
- // since they may be different.
- SourceEntry oldSourceEntry = fOldState.getSourceEntry(element);
- oldUnits[i] =
- (oldSourceEntry == null
- ? null
- : fOldState.packageElementFromSourceEntry(oldSourceEntry));
- SourceEntry newSourceEntry = fNewState.getSourceEntry(element);
- newUnits[i] = fNewState.packageElementFromSourceEntry(newSourceEntry);
- if (oldUnits[i] != null) {
- oldTypeList[i] = oldGraph.getTypes(oldUnits[i]);
- }
+ /* Add all affected packages to fAffectedPackages. */
+ fAffectedPackages = new Hashtable(11);
+ for (Enumeration e = fAddedPackageHandles.elements(); e.hasMoreElements();) {
+ IPackage pkg = (IPackage) e.nextElement();
+ fAffectedPackages.put(pkg, pkg);
+ }
+ for (Enumeration e = fRemovedPackageHandles.elements(); e.hasMoreElements();) {
+ IPackage pkg = (IPackage) e.nextElement();
+ fAffectedPackages.put(pkg, pkg);
+ }
+ for (Enumeration e = fChangedPackageHandles.elements(); e.hasMoreElements();) {
+ IPackage pkg = (IPackage) e.nextElement();
+ fAffectedPackages.put(pkg, pkg);
+ }
+}
+/**
+ * Stores the results of a compilation in the appropriate state tables.
+ * Keeps track of what compilation units need to be compiled as a result
+ * of the changes.
+ */
+protected void updateState(ConvertedCompilationResult[] results) {
+ int n = results.length;
+ PackageElement[] oldUnits = new PackageElement[n];
+ PackageElement[] newUnits = new PackageElement[n];
+ IType[][] oldTypeList = new IType[n][];
+
+ // Preparation
+ DependencyGraph oldGraph = fOldState.getInternalDependencyGraph();
+ DependencyGraph newGraph = fNewState.getInternalDependencyGraph();
+
+ for (int i = 0; i < n; i++) {
+ PackageElement element = results[i].getPackageElement();
+
+ // Be sure the package is in the set of affected packages.
+ // It may not be if this unit was recompiled in a package
+ // other than the ones which have direct changes.
+ IPackage pkg = element.getPackage();
+ fAffectedPackages.put(pkg, pkg);
+
+ // Be sure to look up the source entries in the old and new state,
+ // since they may be different.
+ SourceEntry oldSourceEntry = fOldState.getSourceEntry(element);
+ oldUnits[i] = (oldSourceEntry == null ? null : fOldState.packageElementFromSourceEntry(oldSourceEntry));
+ SourceEntry newSourceEntry = fNewState.getSourceEntry(element);
+ newUnits[i] = fNewState.packageElementFromSourceEntry(newSourceEntry);
+ if (oldUnits[i] != null) {
+ oldTypeList[i] = oldGraph.getTypes(oldUnits[i]);
}
+ }
- // Remove old problems and principal structure from new state before
- // storing new results.
- for (int i = 0; i < n; i++) {
- if (oldUnits[i] != null) {
- SourceEntry sEntry = fOldState.getSourceEntry(oldUnits[i]);
- fNewState.getProblemReporter().removeNonSyntaxErrors(sEntry);
- }
- if (oldTypeList[i] != null) {
- IType[] oldTypes = oldTypeList[i];
- for (int j = 0; j < oldTypes.length; ++j) {
- fNewState.getPrincipalStructureTable().remove(oldTypes[j]);
- }
- }
+ // Remove old problems and principal structure from new state before
+ // storing new results.
+ for (int i = 0; i < n; i++) {
+ if (oldUnits[i] != null) {
+ SourceEntry sEntry = fOldState.getSourceEntry(oldUnits[i]);
+ fNewState.getProblemReporter().removeNonSyntaxErrors(sEntry);
}
-
- super.updateState(results);
-
- // now calculate the changes
- for (int i = 0; i < n; i++) {
- PackageElement unit = newUnits[i];
- if (unit == null) {
- // Unit isn't visible. Shouldn't have gotten this far. Skip it.
- continue;
+ if (oldTypeList[i] != null) {
+ IType[] oldTypes = oldTypeList[i];
+ for (int j = 0; j < oldTypes.length; ++j) {
+ fNewState.getPrincipalStructureTable().remove(oldTypes[j]);
}
+ }
+ }
+
+ super.updateState(results);
- /**
- * Assumption: namespace changes have been dealt with before
- * compilation. Compilation units that were removed have already generated
- * type collaborator indictments. Here, we are only concerned
- * with changes within each compilation unit.
- */
+ // now calculate the changes
+ for (int i = 0; i < n; i++) {
+ PackageElement unit = newUnits[i];
+ if (unit == null) {
+ // Unit isn't visible. Shouldn't have gotten this far. Skip it.
+ continue;
+ }
- TypeStructureEntry[] newTSEntries = results[i].getTypes();
- IndictmentSet indictments = new IndictmentSet();
+ /**
+ * Assumption: namespace changes have been dealt with before
+ * compilation. Compilation units that were removed have already generated
+ * type collaborator indictments. Here, we are only concerned
+ * with changes within each compilation unit.
+ */
- /* do for each type generated by unit in old state */
- IType[] oldTypes = oldTypeList[i];
- if (oldTypes != null) {
- for (int j = 0; j < oldTypes.length; ++j) {
- IType oldType = oldTypes[j];
- boolean found = false;
- for (int k = 0; k < newTSEntries.length; ++k) {
- if (newTSEntries[k] != null && newTSEntries[k].getType().equals(oldType)) {
- found = true;
- break;
- }
- }
- if (!found) {
- getBuilderType(oldType).computeIndictments(indictments);
+ TypeStructureEntry[] newTSEntries = results[i].getTypes();
+ IndictmentSet indictments = new IndictmentSet();
+
+ /* do for each type generated by unit in old state */
+ IType[] oldTypes = oldTypeList[i];
+ if (oldTypes != null) {
+ for (int j = 0; j < oldTypes.length; ++j) {
+ IType oldType = oldTypes[j];
+ boolean found = false;
+ for (int k = 0; k < newTSEntries.length; ++k) {
+ if (newTSEntries[k] != null && newTSEntries[k].getType().equals(oldType)) {
+ found = true;
+ break;
}
}
+ if (!found) {
+ getBuilderType(oldType).computeIndictments(indictments);
+ }
}
+ }
+
+ /* do for each type in result */
+ for (int j = 0; j < newTSEntries.length; j++) {
+ TypeStructureEntry newTSEntry = newTSEntries[j];
+ if (newTSEntry != null) {
+ /* compute the indictments for this type */
+ IType type = newTSEntry.getType();
+ BuilderType bType = getBuilderType(type);
- /* do for each type in result */
- for (int j = 0; j < newTSEntries.length; j++) {
- TypeStructureEntry newTSEntry = newTSEntries[j];
- if (newTSEntry != null) {
- /* compute the indictments for this type */
- IType type = newTSEntry.getType();
- BuilderType bType = getBuilderType(type);
-
- /* the new tsEntry wasn't known at compilation time */
- if (bType.getNewTypeStructureEntry() == null) {
- bType.setNewTypeStructureEntry(newTSEntry);
- }
- bType.computeIndictments(indictments);
+ /* the new tsEntry wasn't known at compilation time */
+ if (bType.getNewTypeStructureEntry() == null) {
+ bType.setNewTypeStructureEntry(newTSEntry);
}
+ bType.computeIndictments(indictments);
}
- if (!indictments.isEmpty()) {
- issueIndictments(unit, indictments, false);
- }
+ }
+ if (!indictments.isEmpty()) {
+ issueIndictments(unit, indictments, false);
}
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/Indictment.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/Indictment.java
index ff906db81c..a7aa0b7a0d 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/Indictment.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/Indictment.java
@@ -30,7 +30,6 @@ public abstract class Indictment {
protected Indictment(char[] name) {
fName = name;
}
-
/**
* Creates and returns an indictment.
* @param type the originating type of the added or removed abstract
@@ -39,45 +38,37 @@ public abstract class Indictment {
public static Indictment createAbstractMethodIndictment(IType type) {
return new AbstractMethodCollaboratorIndictment(type);
}
-
/**
* Creates and returns an indictment.
*/
public static Indictment createFieldIndictment(IBinaryField field) {
return new FieldCollaboratorIndictment(field.getName());
}
-
- /**
- * Creates and returns an indictment.
- */
- public static Indictment createHierarchyIndictment(IBinaryType type) {
- return new TypeHierarchyIndictment(BinaryStructure.getDeclaredName(type));
- }
-
+/**
+ * Creates and returns an indictment.
+ */
+public static Indictment createHierarchyIndictment(IBinaryType type) {
+ return new TypeHierarchyIndictment(BinaryStructure.getDeclaredName(type));
+}
/**
* Creates and returns a method indictment.
* Returns null if no indictment should be issued for the method.
*/
- public static Indictment createMethodIndictment(
- IType owner,
- IBinaryType type,
- IBinaryMethod method) {
+ public static Indictment createMethodIndictment(IType owner, IBinaryType type, IBinaryMethod method) {
/* Is it a clinit? */
- if (method.getSelector().length > 0
- && method.getSelector()[0] == '<'
- && !method.isConstructor()) {
+ if (method.getSelector().length > 0 && method.getSelector()[0] == '<' && !method.isConstructor()) {
return null;
}
int parmCount = Util.getParameterCount(method.getMethodDescriptor());
char[] name;
if (method.isConstructor()) {
name = CharOperation.concat('<', BinaryStructure.getDeclaredName(type), '>');
- } else {
+ }
+ else {
name = method.getSelector();
}
return new MethodCollaboratorIndictment(owner, name, parmCount);
}
-
/**
* Creates and returns an indictment.
* If the binary type is known, use createTypeIndictment(IBinaryType) instead.
@@ -85,58 +76,49 @@ public abstract class Indictment {
* The name must be a top level, unqualified name.
*/
public static Indictment createTypeIndictment(String name) {
- Assert.isTrue(name.indexOf('.') == -1);
+ //Assert.isTrue(name.indexOf('.') == -1);
return new TypeCollaboratorIndictment(name.toCharArray());
}
-
/**
* Creates and returns an indictment.
*/
public static Indictment createTypeIndictment(IBinaryNestedType type) {
return new TypeCollaboratorIndictment(BinaryStructure.getDeclaredName(type));
}
-
/**
* Creates and returns an indictment.
*/
public static Indictment createTypeIndictment(IBinaryType type) {
return new TypeCollaboratorIndictment(BinaryStructure.getDeclaredName(type));
}
-
/**
* Returns true if indictments are equal, false otherwise
*/
public boolean equals(Object o) {
- if (this == o)
- return true;
- if (o == null)
- return false;
- if (!this.getClass().equals(o.getClass()))
- return false;
+ if (this == o) return true;
+ if (o == null) return false;
+ if (!this.getClass().equals(o.getClass())) return false;
- Indictment i = (Indictment) o;
+ Indictment i = (Indictment)o;
return this.fName.equals(i.fName);
}
-
/**
* Returns the key used by IndictmentSet to organize indictments.
*/
char[] getKey() {
return fName;
}
-
/**
* Returns what kind of indictment this is
*/
public abstract int getKind();
- /**
- * Returns the key to use for method indictments, where the method has the given
- * name and parameter count.
- */
- static char[] getMethodIndictmentKey(char[] methodName, int parmCount) {
- return (Util.toString(methodName) + '/' + parmCount).toCharArray();
- }
-
+/**
+ * Returns the key to use for method indictments, where the method has the given
+ * name and parameter count.
+ */
+static char[] getMethodIndictmentKey(char[] methodName, int parmCount) {
+ return (Util.toString(methodName) + '/' + parmCount).toCharArray();
+}
/**
* Returns the indictment name. Either the name of a field, method,
* type or interface. All type names are unqualified.
@@ -144,12 +126,10 @@ public abstract class Indictment {
public String getName() {
return new String(fName);
}
-
/**
* Returns a hashcode for the indictment
*/
public int hashCode() {
return getKind() * 10 + fName.hashCode();
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/IndictmentSet.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/IndictmentSet.java
index 2c587f1d81..53852daff5 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/IndictmentSet.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/IndictmentSet.java
@@ -15,6 +15,7 @@ import org.eclipse.jdt.internal.core.Util;
import java.util.Enumeration;
import java.util.Hashtable;
+
/**
* Represents a set of indictments that reside on a node
* in the dependency graph. The keys are strings of the form:
@@ -31,59 +32,57 @@ public class IndictmentSet {
protected Hashtable fAbstractMethodTable;
protected Hashtable fMethodOwners;
protected boolean fHasConstructorIndictments;
-
+
/* whether there is an upstream hierarchy change */
private boolean fHierarchyChange = false;
public void add(Indictment i) {
// allow null, since certain methods are not indicted (class initializers)
if (i != null) {
switch (i.getKind()) {
- case Indictment.K_HIERARCHY :
+ case Indictment.K_HIERARCHY:
fHierarchyChange = true;
break;
- case Indictment.K_TYPE :
- if (fTypesTable == null)
+ case Indictment.K_TYPE:
+ if (fTypesTable == null)
fTypesTable = new HashtableOfObject(11);
fTypesTable.put(i.getKey(), i);
break;
- case Indictment.K_METHOD :
- if (fMethodsTable == null)
+ case Indictment.K_METHOD:
+ if (fMethodsTable == null)
fMethodsTable = new HashtableOfObject(11);
fMethodsTable.put(i.getKey(), i);
IType owner = ((MethodCollaboratorIndictment) i).getOwner();
- if (fMethodOwners == null)
+ if (fMethodOwners == null)
fMethodOwners = new Hashtable(11);
fMethodOwners.put(owner, owner);
fMethodOwnersArray = null;
- if (i.getName().startsWith("<")) {
+ if (i.getName().startsWith("<"/*nonNLS*/)) {
fHasConstructorIndictments = true;
}
break;
- case Indictment.K_FIELD :
- if (fFieldsTable == null)
+ case Indictment.K_FIELD:
+ if (fFieldsTable == null)
fFieldsTable = new HashtableOfObject(11);
fFieldsTable.put(i.getKey(), i);
break;
- case Indictment.K_ABSTRACT_METHOD :
- if (fAbstractMethodTable == null)
+ case Indictment.K_ABSTRACT_METHOD:
+ if (fAbstractMethodTable == null)
fAbstractMethodTable = new Hashtable(11);
fAbstractMethodTable.put(i.getKey(), i);
break;
- default :
- Assert.isTrue(false, "Unexpected kind of indictment");
+ default:
+ Assert.isTrue(false, Util.bind("build.unknownIndictment"/*nonNLS*/));
break;
}
}
}
-
- /**
- * Maximum conservatism. Convict all dependents.
- */
- public void convictAll() {
- // TBD: Should have separate flag for this.
- fHierarchyChange = true;
- }
-
+/**
+ * Maximum conservatism. Convict all dependents.
+ */
+public void convictAll() {
+ // TBD: Should have separate flag for this.
+ fHierarchyChange = true;
+}
/**
* Returns the originators of all abstract method indictments.
* If any of these returned types are direct supertypes of the
@@ -99,16 +98,12 @@ public class IndictmentSet {
}
IType[] toReturn = new IType[length];
int i = 0;
- for (Enumeration e = fAbstractMethodTable.elements();
- e.hasMoreElements();
- i++) {
- toReturn[i] =
- ((AbstractMethodCollaboratorIndictment) e.nextElement()).getType();
+ for (Enumeration e = fAbstractMethodTable.elements(); e.hasMoreElements(); i++) {
+ toReturn[i] = ((AbstractMethodCollaboratorIndictment) e.nextElement()).getType();
}
return toReturn;
}
-
/**
* Returns the types for which method indictments were issued.
*/
@@ -116,7 +111,8 @@ public class IndictmentSet {
if (fMethodOwnersArray == null) {
if (fMethodsTable == null) {
fMethodOwnersArray = new IType[0];
- } else {
+ }
+ else {
fMethodOwnersArray = new IType[fMethodOwners.size()];
int count = 0;
for (Enumeration e = fMethodOwners.elements(); e.hasMoreElements();) {
@@ -126,32 +122,29 @@ public class IndictmentSet {
}
return fMethodOwnersArray;
}
-
/**
* Returns true if there are any constructor indictments, false otherwise.
*/
public boolean hasConstructorIndictments() {
return fHasConstructorIndictments;
}
-
/**
* Returns true if there is a type hierarchy indictment, false otherwise.
*/
public boolean hasHierarchyIndictment() {
return fHierarchyChange;
}
-
/**
* Returns true if the indictment set has no indictments, false otherwise.
*/
public boolean isEmpty() {
- return fMethodsTable == null
- && fFieldsTable == null
- && fTypesTable == null
- && fAbstractMethodTable == null
- && !fHierarchyChange;
+ return
+ fMethodsTable == null
+ && fFieldsTable == null
+ && fTypesTable == null
+ && fAbstractMethodTable == null
+ && !fHierarchyChange;
}
-
/**
* Resets the contents of the indictment set. Allows re-use of objects
* and saves on garbage.
@@ -163,67 +156,60 @@ public class IndictmentSet {
fAbstractMethodTable = null;
fHierarchyChange = false;
}
-
/**
* Returns a string representation of the instance.
*/
public String toString() {
- return "IndictmentSet("
- + "\n hierarchyChange: "
- + fHierarchyChange
- + "\n types:\n"
- + fTypesTable
- + "\n interfaces:\n"
- + fAbstractMethodTable
- + "\n methods:\n"
- + fMethodsTable
- + "\n fields:\n"
- + fFieldsTable
- + "\n)";
-
+ return
+ "IndictmentSet("/*nonNLS*/
+ + "\n hierarchyChange: "/*nonNLS*/ + fHierarchyChange
+ + "\n types:\n"/*nonNLS*/ + fTypesTable
+ + "\n interfaces:\n"/*nonNLS*/ + fAbstractMethodTable
+ + "\n methods:\n"/*nonNLS*/ + fMethodsTable
+ + "\n fields:\n"/*nonNLS*/ + fFieldsTable
+ + "\n)"/*nonNLS*/;
+
}
+/**
+ * Tries all the evidence in the given set of references against the indictments.
+ * Returns true if any evidence matches an indictment, and false otherwise.
+ */
+public boolean tryAllEvidence(ReferenceInfo references) {
+ char[][] names = references.getNames();
+ byte[] kinds = references.getKinds();
+ int numRefs = names.length;
- /**
- * Tries all the evidence in the given set of references against the indictments.
- * Returns true if any evidence matches an indictment, and false otherwise.
- */
- public boolean tryAllEvidence(ReferenceInfo references) {
- char[][] names = references.getNames();
- byte[] kinds = references.getKinds();
- int numRefs = names.length;
-
- /* try all references */
- for (int i = 0; i < numRefs; i++) {
- switch (kinds[i]) {
- case ReferenceInfo.REFTYPE_unknown :
- case ReferenceInfo.REFTYPE_class :
- case ReferenceInfo.REFTYPE_type :
- /* try type indictments */
- if (fTypesTable != null && fTypesTable.containsKey(names[i])) {
- return true;
- }
- if (kinds[i] != ReferenceInfo.REFTYPE_unknown)
- break;
- case ReferenceInfo.REFTYPE_var :
- /* try field indictments */
- if (fFieldsTable != null && fFieldsTable.containsKey(names[i])) {
- return true;
- }
- if (kinds[i] != ReferenceInfo.REFTYPE_unknown)
- break;
- case ReferenceInfo.REFTYPE_call :
- /* try method indictments */
- if (fMethodsTable != null && fMethodsTable.containsKey(names[i])) {
- return true;
- }
- if (kinds[i] != ReferenceInfo.REFTYPE_unknown)
- break;
- }
+ /* try all references */
+ for (int i = 0; i < numRefs; i++) {
+ switch (kinds[i]) {
+ case ReferenceInfo.REFTYPE_unknown:
+ case ReferenceInfo.REFTYPE_class:
+ case ReferenceInfo.REFTYPE_type:
+ /* try type indictments */
+ if (fTypesTable != null && fTypesTable.containsKey(names[i])) {
+ return true;
+ }
+ if (kinds[i] != ReferenceInfo.REFTYPE_unknown)
+ break;
+ case ReferenceInfo.REFTYPE_var:
+ /* try field indictments */
+ if (fFieldsTable != null && fFieldsTable.containsKey(names[i])) {
+ return true;
+ }
+ if (kinds[i] != ReferenceInfo.REFTYPE_unknown)
+ break;
+ case ReferenceInfo.REFTYPE_call:
+ /* try method indictments */
+ if (fMethodsTable != null && fMethodsTable.containsKey(names[i])) {
+ return true;
+ }
+ if (kinds[i] != ReferenceInfo.REFTYPE_unknown)
+ break;
}
-
- return false;
}
+ return false;
+}
/**
* Tries an ambiguous name against the set of available indictments. Returns
* true if there is a match (guilty), and false if there is no match (not
@@ -233,7 +219,7 @@ public class IndictmentSet {
if (fFieldsTable == null && fTypesTable == null) {
return false;
}
-
+
// Try all segments of name
int i = 0;
int j = CharOperation.indexOf('.', name);
@@ -243,12 +229,11 @@ public class IndictmentSet {
return true;
}
i = j + 1;
- j = CharOperation.indexOf('.', name, i);
+ j = CharOperation.indexOf('.', name, i);
}
- char[] segment = CharOperation.subarray(name, i, name.length - 1);
+ char[] segment = CharOperation.subarray(name, i, name.length-1);
return tryFieldEvidence(segment) || tryTypeEvidence(segment);
}
-
/**
* Tries a field name against the set of available indictments. Returns
* true if there is a match (guilty), and false if there is no match (not
@@ -257,25 +242,20 @@ public class IndictmentSet {
public boolean tryFieldEvidence(char[] name) {
return fFieldsTable != null && fFieldsTable.containsKey(name);
}
-
- /**
- * Tries a method declaration against the set of available indictments.
- * Returns true if there is a match (guilty), and false if there is no match
- * (not guilty).
- */
- public boolean tryMethodDeclaration(IBinaryMethod method) {
- if (fMethodsTable != null) {
- char[] key =
- Indictment.getMethodIndictmentKey(
- method.getSelector(),
- Util.getParameterCount(method.getMethodDescriptor()));
- if (fMethodsTable.get(key) != null) {
- return true;
- }
+/**
+ * Tries a method declaration against the set of available indictments.
+ * Returns true if there is a match (guilty), and false if there is no match
+ * (not guilty).
+ */
+public boolean tryMethodDeclaration(IBinaryMethod method) {
+ if (fMethodsTable != null) {
+ char[] key = Indictment.getMethodIndictmentKey(method.getSelector(), Util.getParameterCount(method.getMethodDescriptor()));
+ if (fMethodsTable.get(key) != null) {
+ return true;
}
- return false;
}
-
+ return false;
+}
/**
* Tries a method name against the set of available indictments. Returns
* true if there is a match (guilty), and false if there is no match (not
@@ -284,10 +264,9 @@ public class IndictmentSet {
* constructor: "<" + NameOfType + ">/" + NumberOfParameters
* method: NameOfMethod + "/" + NumberOfParameters
*/
- public boolean tryMethodEvidence(char[] name) {
+ public boolean tryMethodEvidence(char[] name) {
return fMethodsTable != null && fMethodsTable.containsKey(name);
}
-
/**
* Tries a type name against the set of available indictments. Returns
* true if there is a match (guilty), and false if there is no match (not
@@ -302,7 +281,7 @@ public class IndictmentSet {
/* it may be a qualified name */
int lastDot = CharOperation.lastIndexOf('.', name);
if (lastDot != -1) {
- char[] key = CharOperation.subarray(name, lastDot + 1, name.length - 1);
+ char[] key = CharOperation.subarray(name, lastDot+1, name.length-1);
if (fTypesTable.containsKey(key)) {
return true;
}
@@ -310,5 +289,4 @@ public class IndictmentSet {
}
return false;
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JCUNode.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JCUNode.java
index cf188968d1..56b0d58445 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JCUNode.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JCUNode.java
@@ -20,18 +20,16 @@ public class JCUNode extends AbstractNode {
/* empty types list */
protected static final IType[] fgNoTypes = new IType[0];
- public JCUNode(PackageElement unit) {
+ public JCUNode (PackageElement unit) {
fUnit = unit;
fTypes = fgNoTypes;
}
-
- public JCUNode(PackageElement unit, IType[] types) {
+ public JCUNode (PackageElement unit, IType[] types) {
fUnit = unit;
/* never let types be null */
fTypes = types == null ? fgNoTypes : types;
}
-
/**
* Returns a copy of this node, without copying dependencies. Used
* by DependencyGraph.copy().
@@ -39,14 +37,12 @@ public class JCUNode extends AbstractNode {
public AbstractNode copy() {
return new JCUNode(fUnit, fTypes);
}
-
/**
* Returns the element which this node represents.
*/
public Object getElement() {
return fUnit;
}
-
/**
* Returns the number of bytes that this node uses.
* For debugging and profiling purposes only.
@@ -63,25 +59,21 @@ public class JCUNode extends AbstractNode {
}
return size;
}
-
/**
* Returns what kind of node this is.
*/
public int getKind() {
return JCU_NODE;
}
-
public PackageElement getPackageElement() {
return fUnit;
}
-
/**
* Returns the types that belong to this compilation unit
*/
public IType[] getTypes() {
return fTypes;
}
-
/**
* Sets the types that belong to this compilation unit
*/
@@ -89,7 +81,6 @@ public class JCUNode extends AbstractNode {
/* never let types be null */
fTypes = types == null ? fgNoTypes : types;
}
-
/**
* Prints a string representation of the node. This method is for debugging
* purposes only.
@@ -97,5 +88,4 @@ public class JCUNode extends AbstractNode {
public String toString() {
return "JCUNode(" + fUnit.getFileName() + ")";
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JavaBuilder.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JavaBuilder.java
index 78a151854f..99b50b52d8 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JavaBuilder.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JavaBuilder.java
@@ -24,34 +24,33 @@ public class JavaBuilder extends IncrementalProjectBuilder {
/**
* Flag indicating whether to persist built states between sessions.
*/
- public static final boolean SAVE_ENABLED = true;
- /**
- * Constructs a new Java Builder.
- */
- public JavaBuilder() {
- }
-
+ public static final boolean SAVE_ENABLED = true;
+/**
+ * Constructs a new Java Builder.
+ */
+public JavaBuilder() {
+}
/**
* Run the Java Image Builder.
*/
- protected IProject[] build(int kind, Map map, IProgressMonitor monitor)
- throws CoreException {
+ protected IProject[] build(int kind, Map map, IProgressMonitor monitor) throws CoreException {
- if (!this.getProject().exists())
- return new IProject[0];
+ if (!this.getProject().exists()) return new IProject[0];
//if (!((JavaProject)getJavaProject()).hasSource()) return new IProject[0];
-
+
JavaDevelopmentContextImpl dc = getDevelopmentContext();
dc.setProgressMonitor(monitor);
boolean ok = false;
try {
if (kind == FULL_BUILD) {
fullBuild(dc, monitor);
- } else {
+ }
+ else {
Hashtable deltas = checkIncrementalBuild(monitor);
if (deltas == null) {
fullBuild(dc, monitor);
- } else {
+ }
+ else {
incrementalBuild(dc, deltas, monitor);
}
}
@@ -61,8 +60,7 @@ public class JavaBuilder extends IncrementalProjectBuilder {
if (e.getThrowable() instanceof CoreException) {
throw (CoreException) e.getThrowable();
} else {
- throw new CoreException(
- new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, "Java Builder", e));
+ throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, -1, Util.bind("build.builderName"/*nonNLS*/), e));
}
} catch (OperationCanceledException e) {
// Do nothing for now, and avoid propagating the exception.
@@ -76,20 +74,17 @@ public class JavaBuilder extends IncrementalProjectBuilder {
// forcing a full build next time.
setLastBuiltState(null);
}
- if (monitor != null)
- monitor.subTask("Java build completed");
+ if (monitor != null) monitor.subTask(Util.bind("build.completed"/*nonNLS*/));
}
return getRequiredProjects(getLastBuiltState(monitor));
}
-
/**
* Checks whether we can do an incremental build.
* Returns a hashtable containing all the required deltas if yes, null if no.
*
* @return hashtable mapping from IProject to IResourceDelta for all required project deltas, or null
*/
- protected Hashtable checkIncrementalBuild(IProgressMonitor monitor)
- throws CoreException {
+ protected Hashtable checkIncrementalBuild(IProgressMonitor monitor) throws CoreException {
IState oldState = getLastBuiltState(monitor);
if (oldState == null) {
//System.out.println("No previous built state for: "+getProject().getName());
@@ -98,115 +93,85 @@ public class JavaBuilder extends IncrementalProjectBuilder {
Hashtable deltas = new Hashtable(11);
IProject project = getProject();
- if (monitor != null)
- monitor.subTask(
- "Reading resource change information for :" + project.getName());
+ if (monitor != null) monitor.subTask(Util.bind("build.readingDelta"/*nonNLS*/, project.getName()));
IResourceDelta delta = getDelta(project);
- if (delta == null) {
+ if (delta == null){
//System.out.println("Missing delta for: "+ project.getName());
- if (monitor != null)
- monitor.subTask("");
+ if (monitor != null) monitor.subTask(""/*nonNLS*/);
return null;
} else {
deltas.put(project, delta);
}
IProject[] prereqs = getRequiredProjects(oldState);
for (int i = 0; i < prereqs.length; ++i) {
- if (monitor != null)
- monitor.subTask(
- "Reading resource change information for :" + prereqs[i].getName());
+ if (monitor != null) monitor.subTask(Util.bind("build.readingDelta"/*nonNLS*/, prereqs[i].getName()));
delta = getDelta(prereqs[i]);
- if (delta == null) {
+ if (delta == null){
//System.out.println("Missing delta for: "+ prereqs[i].getName());
- if (monitor != null)
- monitor.subTask("");
+ if (monitor != null) monitor.subTask(""/*nonNLS*/);
return null;
} else {
deltas.put(prereqs[i], delta);
}
}
- if (monitor != null)
- monitor.subTask("");
+ if (monitor != null) monitor.subTask(""/*nonNLS*/);
return deltas;
}
-
- /**
- * Returns true if the class path has changed since the last built state.
- */
- protected boolean classpathChanged(IState lastBuiltState)
- throws CoreException {
- try {
- IPackageFragmentRoot[] oldRoots =
- ((StateImpl) lastBuiltState).getPackageFragmentRootsInClassPath();
- IPackageFragmentRoot[] newRoots =
- ((JavaProject) getJavaProject()).getBuilderRoots(null);
- return !Util.equalArraysOrNull(oldRoots, newRoots);
- } catch (JavaModelException e) {
- throw new CoreException(
- new Status(
- IStatus.ERROR,
- JavaCore.PLUGIN_ID,
- Platform.PLUGIN_ERROR,
- "Project " + getProject().getFullPath() + " not present",
- e));
- }
+/**
+ * Returns true if the class path has changed since the last built state.
+ */
+protected boolean classpathChanged(IState lastBuiltState) throws CoreException {
+ try {
+ IPackageFragmentRoot[] oldRoots = ((StateImpl) lastBuiltState).getPackageFragmentRootsInClassPath();
+ IPackageFragmentRoot[] newRoots = ((JavaProject) getJavaProject()).getBuilderRoots(null);
+ return !Util.equalArraysOrNull(oldRoots, newRoots);
+ } catch (JavaModelException e) {
+ throw new CoreException(
+ new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Util.bind("element.projectDoesNotExist"/*nonNLS*/, getProject().getFullPath().toString()), e));
}
-
+}
/**
* Runs a full build.
*/
- protected void fullBuild(
- JavaDevelopmentContextImpl dc,
- IProgressMonitor monitor)
- throws CoreException {
+ protected void fullBuild(JavaDevelopmentContextImpl dc, IProgressMonitor monitor) throws CoreException {
IProject project = getProject();
//System.out.println("FULL build of: "+project.getName());
/* create problem reporter and clear all problems */
- IProblemReporter problemReporter = new MarkerProblemReporter(project, dc);
+ IProblemReporter problemReporter= new MarkerProblemReporter(project, dc);
problemReporter.removeProblems(project);
/* create and invoke the batch builder */
// Pass the compiler options, needed for 1FVXS80: ITPJCORE:ALL - .class files are missing their LocalVariableTable
- ConfigurableOption[] options =
- JavaModelManager.convertConfigurableOptions(JavaCore.getOptions());
+ ConfigurableOption[] options = JavaModelManager.convertConfigurableOptions(JavaCore.getOptions());
setLastBuiltState(null); // free possible existing state
IImageBuilder builder = dc.createState(project, null, problemReporter, options);
setLastBuiltState(builder.getNewState());
}
-
- /**
- * Returns the development context to use for this builder.
- */
- protected JavaDevelopmentContextImpl getDevelopmentContext() {
- return (JavaDevelopmentContextImpl) JavaModelManager
- .getJavaModelManager()
- .getDevelopmentContext(getProject());
- }
-
- /**
- * Returns the Java view of the project.
- */
- protected IJavaProject getJavaProject() {
- return JavaCore.create(getProject());
- }
-
- /**
- * Returns the last built state for this builder.
- */
- protected IState getLastBuiltState(IProgressMonitor monitor) {
- return JavaModelManager.getJavaModelManager().getLastBuiltState(
- getProject(),
- monitor);
- }
-
- /**
- * Returns a problem factory for the given locale.
- */
- public IProblemFactory getProblemFactory(Locale locale) {
- return ProblemFactory.getProblemFactory(locale);
- }
-
+/**
+ * Returns the development context to use for this builder.
+ */
+protected JavaDevelopmentContextImpl getDevelopmentContext() {
+ return (JavaDevelopmentContextImpl) JavaModelManager.getJavaModelManager().getDevelopmentContext(getProject());
+}
+/**
+ * Returns the Java view of the project.
+ */
+protected IJavaProject getJavaProject() {
+ return JavaCore.create(getProject());
+}
+/**
+ * Returns the last built state for this builder.
+ */
+protected IState getLastBuiltState(IProgressMonitor monitor) {
+ return JavaModelManager.getJavaModelManager().getLastBuiltState(getProject(), monitor);
+}
+/**
+ * Returns a problem factory for the given locale.
+ */
+public IProblemFactory getProblemFactory(Locale locale) {
+ return ProblemFactory.getProblemFactory(locale);
+}
/**
* Returns the prerequisite projects for the given built state.
* Returns an empty array if state is null.
@@ -231,33 +196,26 @@ public class JavaBuilder extends IncrementalProjectBuilder {
v.copyInto(result);
return result;
}
-
/**
* Runs an incremental build.
*
* @param deltas maps from IProject to IResourceDelta for this builder's project and all prerequisite projects
*/
- protected void incrementalBuild(
- JavaDevelopmentContextImpl dc,
- Hashtable deltas,
- IProgressMonitor monitor)
- throws CoreException {
+ protected void incrementalBuild(JavaDevelopmentContextImpl dc, Hashtable deltas, IProgressMonitor monitor) throws CoreException {
IProject project = getProject();
//System.out.println("INCREMENTAL build of: "+project.getName());
StateImpl oldState = (StateImpl) getLastBuiltState(monitor);
if (needIncrementalBuild(oldState, deltas)) {
- IncrementalImageBuilder builder =
- new IncrementalImageBuilder(oldState, project, null);
+ IncrementalImageBuilder builder = new IncrementalImageBuilder(oldState, project, null);
builder.applySourceDelta(deltas);
setLastBuiltState(builder.getNewState());
- } else {
+ }
+ else {
/* Still update resources in binary output */
- BuildNotifier notifier =
- new BuildNotifier((JavaDevelopmentContextImpl) dc, false);
+ BuildNotifier notifier = new BuildNotifier((JavaDevelopmentContextImpl) dc, false);
notifier.begin();
try {
- ProjectResourceCopier copier =
- new ProjectResourceCopier(getJavaProject(), dc, notifier, 1.0f);
+ ProjectResourceCopier copier = new ProjectResourceCopier(getJavaProject(), dc, notifier, 1.0f);
IResourceDelta change = (IResourceDelta) deltas.get(project);
copier.updateAffectedResources(change);
} finally {
@@ -265,59 +223,51 @@ public class JavaBuilder extends IncrementalProjectBuilder {
}
}
}
-
- /**
- * Checks whether this is an empty delta as far as the builder is concerned.
- */
- protected boolean isEmpty(IResourceDelta change) {
- // Made checks more selective for 1FW1S0Y: ITPJCORE:ALL - Java builder builds when non-Java files affected
- if (change == null)
- return true;
- int kind = change.getKind();
- boolean isAdded = kind == IResourceDelta.ADDED;
- boolean isRemoved = kind == IResourceDelta.REMOVED;
- boolean isChanged = kind == IResourceDelta.CHANGED;
- int flags = change.getFlags();
- boolean contentChanged = isChanged && (flags & IResourceDelta.CONTENT) != 0;
- String extension = change.getFullPath().getFileExtension();
- boolean isJavaOrClassFile =
- extension != null
- && (extension.equalsIgnoreCase("java") || extension.equalsIgnoreCase("class"));
- boolean isArchive =
- extension != null
- && (extension.equalsIgnoreCase("zip") || extension.equalsIgnoreCase("jar"));
-
- // care about added, removed and modified (content actually modified) .java and .class files
- if (isJavaOrClassFile && (isAdded || isRemoved || contentChanged))
+/**
+ * Checks whether this is an empty delta as far as the builder is concerned.
+ */
+protected boolean isEmpty(IResourceDelta change) {
+ // Made checks more selective for 1FW1S0Y: ITPJCORE:ALL - Java builder builds when non-Java files affected
+ if (change == null)
+ return true;
+ int kind = change.getKind();
+ boolean isAdded = kind == IResourceDelta.ADDED;
+ boolean isRemoved = kind == IResourceDelta.REMOVED;
+ boolean isChanged = kind == IResourceDelta.CHANGED;
+ int flags = change.getFlags();
+ boolean contentChanged = isChanged && (flags & IResourceDelta.CONTENT) != 0;
+ String extension = change.getFullPath().getFileExtension();
+ boolean isJavaOrClassFile = extension != null && (extension.equalsIgnoreCase("java"/*nonNLS*/) || extension.equalsIgnoreCase("class"/*nonNLS*/));
+ boolean isArchive = extension != null && (extension.equalsIgnoreCase("zip"/*nonNLS*/) || extension.equalsIgnoreCase("jar"/*nonNLS*/));
+
+ // care about added, removed and modified (content actually modified) .java and .class files
+ if (isJavaOrClassFile && (isAdded || isRemoved || contentChanged))
+ return false;
+ // care about added, removed and modified (content actually modified) .jar and .zip files
+ if (isArchive && (isAdded || isRemoved || contentChanged))
+ return false;
+
+ // care about all folder additions and removals since they may represent package fragments
+ IResource resource = change.getResource();
+ if (resource != null){
+ int type = resource.getType();
+ // may have been a container previously if its type is changing
+ boolean isFolder = (flags & IResourceDelta.TYPE) != 0 || type == IResource.FOLDER;
+ if (isFolder && (isAdded || isRemoved))
return false;
- // care about added, removed and modified (content actually modified) .jar and .zip files
- if (isArchive && (isAdded || isRemoved || contentChanged))
+ }
+ // recurse on children
+ IResourceDelta[] children = change.getAffectedChildren();
+ for (int i = 0; i < children.length; ++i) {
+ if (!isEmpty(children[i]))
return false;
-
- // care about all folder additions and removals since they may represent package fragments
- IResource resource = change.getResource();
- if (resource != null) {
- int type = resource.getType();
- // may have been a container previously if its type is changing
- boolean isFolder =
- (flags & IResourceDelta.TYPE) != 0 || type == IResource.FOLDER;
- if (isFolder && (isAdded || isRemoved))
- return false;
- }
- // recurse on children
- IResourceDelta[] children = change.getAffectedChildren();
- for (int i = 0; i < children.length; ++i) {
- if (!isEmpty(children[i]))
- return false;
- }
- return true;
}
-
+ return true;
+}
/**
* Checks whether an incremental build is really necessary.
*/
- protected boolean needIncrementalBuild(StateImpl oldState, Hashtable deltas)
- throws CoreException {
+ protected boolean needIncrementalBuild(StateImpl oldState, Hashtable deltas) throws CoreException {
if (classpathChanged(oldState)) {
return true;
}
@@ -329,41 +279,30 @@ public class JavaBuilder extends IncrementalProjectBuilder {
}
return false;
}
-
- /**
- * Returns true if the output location has changed since the last built state.
- */
- protected boolean outputLocationChanged(IState lastBuiltState)
- throws CoreException {
- try {
- IPath oldOutputLocation = ((StateImpl) lastBuiltState).getOutputLocation();
- IPath newOutputLocation = getJavaProject().getOutputLocation();
- return !oldOutputLocation.equals(newOutputLocation);
- } catch (JavaModelException e) {
- throw new CoreException(
- new Status(
- IStatus.ERROR,
- JavaCore.PLUGIN_ID,
- Platform.PLUGIN_ERROR,
- "Project " + getProject().getFullPath() + " not present",
- e));
- }
- }
-
- protected void setLastBuiltState(IState state) {
- JavaModelManager.getJavaModelManager().setLastBuiltState(getProject(), state);
+/**
+ * Returns true if the output location has changed since the last built state.
+ */
+protected boolean outputLocationChanged(IState lastBuiltState) throws CoreException {
+ try {
+ IPath oldOutputLocation = ((StateImpl) lastBuiltState).getOutputLocation();
+ IPath newOutputLocation = getJavaProject().getOutputLocation();
+ return !oldOutputLocation.equals(newOutputLocation);
+ } catch (JavaModelException e) {
+ throw new CoreException(new Status(IStatus.ERROR, JavaCore.PLUGIN_ID, Platform.PLUGIN_ERROR, Util.bind("element.projectDoesNotExist", getProject().getFullPath().toString()), e));
}
-
- /**
- * String representation for debugging purposes
- */
- public String toString() {
- IState lastBuiltState = getLastBuiltState(null);
- if (lastBuiltState == null) {
- return "JavaBuilder(no built state)";
- } else {
- return "JavaBuilder(" + lastBuiltState + ")";
- }
+}
+protected void setLastBuiltState(IState state) {
+ JavaModelManager.getJavaModelManager().setLastBuiltState(getProject(), state);
+}
+/**
+ * String representation for debugging purposes
+ */
+public String toString() {
+ IState lastBuiltState = getLastBuiltState(null);
+ if (lastBuiltState == null) {
+ return "JavaBuilder(no built state)"/*nonNLS*/;
+ } else {
+ return "JavaBuilder("/*nonNLS*/ + lastBuiltState + ")"/*nonNLS*/;
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JavaDevelopmentContextImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JavaDevelopmentContextImpl.java
index 8f04c48dcd..2f4dcc4374 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JavaDevelopmentContextImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/JavaDevelopmentContextImpl.java
@@ -15,6 +15,8 @@ import org.eclipse.jdt.internal.core.util.IProgressListener;
import org.eclipse.jdt.internal.compiler.ConfigurableOption;
import org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
+import org.eclipse.core.runtime.IPath;
+
public class JavaDevelopmentContextImpl implements IDevelopmentContext {
/**
@@ -51,8 +53,7 @@ public class JavaDevelopmentContextImpl implements IDevelopmentContext {
/**
* The default package.
*/
- private final IPackage fDefaultPackage =
- fImage.getPackageHandle("java.lang", false);
+ private final IPackage fDefaultPackage = fImage.getPackageHandle("java.lang", false);
/**
* The root class handle
@@ -75,357 +76,311 @@ public class JavaDevelopmentContextImpl implements IDevelopmentContext {
/**
* Whether the compiler is in the call stack.
*/
- boolean inCompiler;
- /**
- * Create a new Java DC.
- */
- public JavaDevelopmentContextImpl() {
- }
-
+ boolean inCompiler;
+/**
+ * Create a new Java DC.
+ */
+public JavaDevelopmentContextImpl() {
+}
/**
* @see IDevelopmentContext
*/
public void addBuildListener(IBuildListener buildListener) {
fBuildListeners.addElement(buildListener);
}
-
- /**
- * Returns a class type handle corresponding to the given
- * (fully qualified) class type name.
- */
- protected IType classTypeFromName(final String name) {
-
- /* strip off the leading "L" and trailing ";" */
- String localName = name.substring(1, name.length() - 1);
- int lastDot = localName.lastIndexOf('.');
- IPackage pkg;
- if (lastDot == -1) {
- pkg = getImage().getPackageHandle(IPackageFragment.DEFAULT_PACKAGE_NAME, true);
- } else {
- pkg = this.packageHandleFromSignature(localName.substring(0, lastDot));
- }
- return pkg.getClassHandle(localName.substring(lastDot + 1, localName.length()));
- }
-
- /**
- * @see IDevelopmentContext
- */
- public IImageBuilder createState(
- IProject project,
- IImageContext buildContext) {
- return createState(project, buildContext, (IProblemReporter) null);
- }
-
- /**
- * @see IDevelopmentContext
- */
- public IImageBuilder createState(
- IProject project,
- IImageContext buildContext,
- IProblemReporter problemReporter) {
- return createState(
- project,
- buildContext,
- problemReporter,
- getDefaultCompilerOptions());
- }
-
- /**
- * @see IDevelopmentContext
- */
- public IImageBuilder createState(
- IProject project,
- IImageContext buildContext,
- IProblemReporter problemReporter,
- ConfigurableOption[] compilerOptions) {
- StateImpl state = new StateImpl(this, project, buildContext);
- BatchImageBuilder builder = new BatchImageBuilder(state, compilerOptions);
- if (problemReporter != null) {
- state.setProblemReporter(problemReporter);
- }
- builder.build();
- return builder;
- }
-
- /**
- * @see IDevelopmentContext
- */
- public void garbageCollect(IState[] statesInUse) {
- getBinaryOutput().garbageCollect(statesInUse);
- }
-
- /**
- * Returns the binary broker for this development context.
- * Returns null if none has been assigned to the DC.
- */
- public IBinaryBroker getBinaryBroker() {
- if (fBinaryBrokerOutput == null)
- return null;
- else
- return fBinaryBrokerOutput.getBinaryBroker();
- }
-
- /**
- * Workaround for 1GAMR1K: ITPCORE:Platform should be more fault tolerant
- */
- byte[] getBinaryFromFileSystem(org.eclipse.core.resources.IFile file) {
- try {
- String osPath = file.getLocation().toOSString();
- InputStream input = new java.io.FileInputStream(osPath);
- return org.eclipse.jdt.internal.core.Util.readContentsAsBytes(input);
- } catch (IOException e) {
- return new byte[0];
- }
- }
-
- /**
- * Returns the binary output for this development context.
- */
- public BinaryOutput getBinaryOutput() {
- return fBinaryBrokerOutput;
- }
-
- /**
- * Returns the vector of build listeners.
- */
- protected Vector getBuildListeners() {
- return fBuildListeners;
+/**
+ * Returns a class type handle corresponding to the given
+ * (fully qualified) class type name.
+ */
+protected IType classTypeFromName(final String name) {
+
+ /* strip off the leading "L" and trailing ";" */
+ String localName = name.substring(1, name.length() - 1);
+ int lastDot = localName.lastIndexOf('.');
+ IPackage pkg;
+ if (lastDot == -1) {
+ pkg = getImage().getPackageHandle(IPackageFragment.DEFAULT_PACKAGE_NAME, true);
+ } else {
+ pkg = this.packageHandleFromSignature(localName.substring(0, lastDot));
+ }
+ return pkg.getClassHandle(localName.substring(lastDot + 1, localName.length()));
+}
+/**
+ * @see IDevelopmentContext
+ */
+public IImageBuilder createState(IProject project, IImageContext buildContext) {
+ return createState(project, buildContext, (IProblemReporter)null);
+}
+/**
+ * @see IDevelopmentContext
+ */
+public IImageBuilder createState(IProject project, IImageContext buildContext, IProblemReporter problemReporter) {
+ return createState(project, buildContext, problemReporter, getDefaultCompilerOptions());
+}
+/**
+ * @see IDevelopmentContext
+ */
+public IImageBuilder createState(IProject project, IImageContext buildContext, IProblemReporter problemReporter, ConfigurableOption[] compilerOptions) {
+ StateImpl state = new StateImpl(this, project, buildContext);
+ BatchImageBuilder builder = new BatchImageBuilder(state, compilerOptions);
+ if (problemReporter != null) {
+ state.setProblemReporter(problemReporter);
+ }
+ builder.build();
+ return builder;
+}
+/**
+ * @see IDevelopmentContext
+ */
+public void garbageCollect(IState[] statesInUse) {
+ getBinaryOutput().garbageCollect(statesInUse);
+}
+/**
+ * Returns the binary broker for this development context.
+ * Returns null if none has been assigned to the DC.
+ */
+public IBinaryBroker getBinaryBroker() {
+ if (fBinaryBrokerOutput == null)
+ return null;
+ else
+ return fBinaryBrokerOutput.getBinaryBroker();
+}
+/**
+ * Workaround for 1GAMR1K: ITPCORE:Platform should be more fault tolerant
+ */
+byte[] getBinaryFromFileSystem(org.eclipse.core.resources.IFile file) {
+ try {
+ IPath location = file.getLocation();
+ if (location == null) return new byte[0];
+ InputStream input = new java.io.FileInputStream(location.toOSString());
+ return org.eclipse.jdt.internal.core.Util.readContentsAsBytes(input);
+ } catch (IOException e) {
+ return new byte[0];
}
-
+}
+/**
+ * Returns the binary output for this development context.
+ */
+public BinaryOutput getBinaryOutput() {
+ return fBinaryBrokerOutput;
+}
+/**
+ * Returns the vector of build listeners.
+ */
+protected Vector getBuildListeners() {
+ return fBuildListeners;
+}
/**
* Returns the build monitor.
*/
public IBuildMonitor getBuildMonitor() {
return fBuildMonitor;
}
-
- public IState getCurrentState() throws NotPresentException {
- if (fCurrentState == null) {
- throw new NotPresentException("no current state");
- }
- return fCurrentState;
- }
-
- /**
- * Reads the default compiler options.
- */
- protected static ConfigurableOption[] getDefaultCompilerOptions() {
- ConfigurableOption[] options = Compiler.getDefaultOptions(Locale.getDefault());
-
- /**
- * Ugly because this requires knowledge of the compiler's
- * internal problem representation.
- */
- setCompilerOption(options, 11, 1);
- setCompilerOption(options, 12, 1);
- return options;
- }
-
- /**
- * Returns the default package handle (java.lang).
- */
- protected IPackage getDefaultPackage() {
- return fDefaultPackage;
+public IState getCurrentState() throws NotPresentException {
+ if (fCurrentState == null) {
+ throw new NotPresentException("no current state");
}
+ return fCurrentState;
+}
+/**
+ * Reads the default compiler options.
+ */
+protected static ConfigurableOption[] getDefaultCompilerOptions() {
+ ConfigurableOption[] options = Compiler.getDefaultOptions(Locale.getDefault());
/**
- * Returns the image handle
+ * Ugly because this requires knowledge of the compiler's
+ * internal problem representation.
*/
- public IImage getImage() {
- return fImage;
- }
-
+ setCompilerOption(options, 11, 1);
+ setCompilerOption(options, 12, 1);
+ return options;
+}
+/**
+ * Returns the default package handle (java.lang).
+ */
+protected IPackage getDefaultPackage() {
+ return fDefaultPackage;
+}
+/**
+ * Returns the image handle
+ */
+public IImage getImage() {
+ return fImage;
+}
/**
* Returns the progress monitor. Returns null if one hasn't been set.
*/
public IProgressMonitor getProgressMonitor() {
return fProgressMonitor;
}
-
- protected IType getRootClassHandle() {
- return fRootClass;
- }
-
- /**
- * Process an internal exception: if we're being called by the compiler, throw an AbortCompilation
- * otherwise throw an internal image builder exception.
- */
- protected RuntimeException internalException(String message) {
- ImageBuilderInternalException imageBuilderException =
- new ImageBuilderInternalException(message);
- if (this.inCompiler) {
- return new AbortCompilation(true, imageBuilderException);
- } else {
- return imageBuilderException;
- }
+protected IType getRootClassHandle() {
+ return fRootClass;
+}
+/**
+ * Process an internal exception: if we're being called by the compiler, throw an AbortCompilation
+ * otherwise throw an internal image builder exception.
+ */
+protected RuntimeException internalException(String message) {
+ ImageBuilderInternalException imageBuilderException =
+ new ImageBuilderInternalException(message);
+ if (this.inCompiler) {
+ return new AbortCompilation(true, imageBuilderException);
+ } else {
+ return imageBuilderException;
}
-
- /**
- * Process an internal exception: if we're being called by the compiler, throw an AbortCompilation
- * otherwise throw an internal image builder exception.
- */
- protected RuntimeException internalException(Throwable t) {
- ImageBuilderInternalException imageBuilderException =
- new ImageBuilderInternalException(t);
- if (this.inCompiler) {
- return new AbortCompilation(true, imageBuilderException);
- } else {
- return imageBuilderException;
- }
+}
+/**
+ * Process an internal exception: if we're being called by the compiler, throw an AbortCompilation
+ * otherwise throw an internal image builder exception.
+ */
+protected RuntimeException internalException(Throwable t) {
+ ImageBuilderInternalException imageBuilderException =
+ new ImageBuilderInternalException(t);
+ if (this.inCompiler) {
+ return new AbortCompilation(true, imageBuilderException);
+ } else {
+ return imageBuilderException;
}
-
+}
/**
* Returns a new package handle for the given signature.
*/
- public IPackage packageHandleFromSignature(String signature) {
+ public IPackage packageHandleFromSignature (String signature) {
return new PackageImpl(this, signature, false);
}
+/**
+ * Returns the parameter type handles, extracted from the given method
+ * or constructor signature. Parameter names can either be fully
+ * qualified VM type names, or DC API source signature names. The
+ * class java.lang.String would be represented as either:
+ * VM name: Ljava.lang.String;
+ * DC name: QString;
+ */
+protected IType[] parameterTypesFromSignature(final String signature) {
+ Vector typeVector = new Vector();
- /**
- * Returns the parameter type handles, extracted from the given method
- * or constructor signature. Parameter names can either be fully
- * qualified VM type names, or DC API source signature names. The
- * class java.lang.String would be represented as either:
- * VM name: Ljava.lang.String;
- * DC name: QString;
+ /* The signature looks like this:
+ * name(<parm1><parm2><parm3>...)<return type>
*/
- protected IType[] parameterTypesFromSignature(final String signature) {
- Vector typeVector = new Vector();
- /* The signature looks like this:
- * name(<parm1><parm2><parm3>...)<return type>
- */
-
- /* extract parameters from signature */
- String localSig =
- signature.substring(signature.indexOf('(') + 1, signature.lastIndexOf(')'));
-
- /* parse each parameter */
- while (localSig.length() > 0) {
+ /* extract parameters from signature */
+ String localSig = signature.substring(signature.indexOf('(') + 1, signature.lastIndexOf(')'));
- /*
- * Each parameter can be defined by the following productions:
- * parameter: arrayType
- * arrayType: [arrayType OR type
- * type: L<classname>; OR <single character for base type>
- */
+ /* parse each parameter */
+ while (localSig.length() > 0) {
- /* skip array characters */
- int position = 0;
- while (localSig.charAt(position) == '[') {
- position++;
- }
- IType parmType;
- char c = localSig.charAt(position);
- if (c == 'L' || c == 'Q') {
- /* its a class type */
- int endIndex = localSig.indexOf(";") + 1;
- parmType = classTypeFromName(localSig.substring(position, endIndex));
- localSig = localSig.substring(endIndex);
- } else {
- /* its a base type */
- parmType = primitiveTypeFromTypeCode(localSig.charAt(position));
- localSig = localSig.substring(position + 1);
- }
+ /*
+ * Each parameter can be defined by the following productions:
+ * parameter: arrayType
+ * arrayType: [arrayType OR type
+ * type: L<classname>; OR <single character for base type>
+ */
- /* if its an array type */
- if (position != 0) {
- parmType = new ArrayTypeHandleImpl((TypeImpl) parmType, position);
- }
- typeVector.addElement(parmType);
+ /* skip array characters */
+ int position = 0;
+ while (localSig.charAt(position) == '[') {
+ position++;
+ }
+ IType parmType;
+ char c = localSig.charAt(position);
+ if (c == 'L' || c == 'Q') {
+ /* its a class type */
+ int endIndex = localSig.indexOf(";") + 1;
+ parmType = classTypeFromName(localSig.substring(position, endIndex));
+ localSig = localSig.substring(endIndex);
+ } else {
+ /* its a base type */
+ parmType = primitiveTypeFromTypeCode(localSig.charAt(position));
+ localSig = localSig.substring(position + 1);
}
- /* convert results vector to an array */
- IType[] results = new IType[typeVector.size()];
- typeVector.copyInto(results);
- return results;
- }
-
- /**
- * Returns a primitive type handle corresponding to the given type code char.
- * Returns nulll if type code is not a valid primitive type code.
- */
- protected IType primitiveTypeFromTypeCode(char typeCode) {
- switch (typeCode) {
- case 'V' :
- return fVoidType;
- case 'I' :
- return fIntType;
- case 'B' :
- return fByteType;
- case 'C' :
- return fCharType;
- case 'D' :
- return fDoubleType;
- case 'F' :
- return fFloatType;
- case 'J' :
- return fLongType;
- case 'S' :
- return fShortType;
- case 'Z' :
- return fBooleanType;
- default :
- return null;
+ /* if its an array type */
+ if (position != 0) {
+ parmType = new ArrayTypeHandleImpl((TypeImpl) parmType, position);
}
+ typeVector.addElement(parmType);
}
+ /* convert results vector to an array */
+ IType[] results = new IType[typeVector.size()];
+ typeVector.copyInto(results);
+ return results;
+}
+/**
+ * Returns a primitive type handle corresponding to the given type code char.
+ * Returns nulll if type code is not a valid primitive type code.
+ */
+protected IType primitiveTypeFromTypeCode(char typeCode) {
+ switch (typeCode) {
+ case 'V': return fVoidType;
+ case 'I': return fIntType;
+ case 'B': return fByteType;
+ case 'C': return fCharType;
+ case 'D': return fDoubleType;
+ case 'F': return fFloatType;
+ case 'J': return fLongType;
+ case 'S': return fShortType;
+ case 'Z': return fBooleanType;
+ default: return null;
+ }
+}
/**
* @see IDevelopmentContext
*/
public void removeBuildListener(IBuildListener buildListener) {
fBuildListeners.removeElement(buildListener);
}
-
- /**
- * @see IDevelopmentContext.
- */
- public IState restoreState(IProject project, DataInputStream in)
- throws IOException {
- try {
- return new StateSnap().read(this, project, in);
- } catch (RuntimeException e) {
- System.out.println("RuntimeException restoring state:");
- e.printStackTrace();
- throw e;
- } catch (Error e) {
- System.out.println("Error restoring state:");
- e.printStackTrace();
- throw e;
- }
+/**
+ * @see IDevelopmentContext.
+ */
+public IState restoreState(IProject project, DataInputStream in) throws IOException {
+ try {
+ return new StateSnap().read(this, project, in);
}
-
- /**
- * @see IDevelopmentContext.
- */
- public void saveState(IState state, DataOutputStream out) throws IOException {
- try {
- new StateSnap().save((StateImpl) state, out);
- } catch (IOException e) {
- System.out.println("IOException saving state: ");
- e.printStackTrace();
- throw e;
- } catch (RuntimeException e) {
- System.out.println("RuntimeException saving state: ");
- e.printStackTrace();
- throw e;
- } catch (Error e) {
- System.out.println("Error saving state:");
- e.printStackTrace();
- throw e;
- }
+ catch (RuntimeException e) {
+ System.out.println("RuntimeException restoring state:");
+ e.printStackTrace();
+ throw e;
}
-
- /**
- * Sets the binary broker for this developent context
- */
- public void setBinaryBroker(IBinaryBroker broker) {
- if (broker == null)
- fBinaryBrokerOutput = null;
- else
- fBinaryBrokerOutput = new BinaryBrokerOutput(broker);
+ catch (Error e) {
+ System.out.println("Error restoring state:");
+ e.printStackTrace();
+ throw e;
}
-
+}
+/**
+ * @see IDevelopmentContext.
+ */
+public void saveState(IState state, DataOutputStream out) throws IOException {
+ try {
+ new StateSnap().save((StateImpl) state, out);
+ }
+ catch (IOException e) {
+ System.out.println("IOException saving state: ");
+ e.printStackTrace();
+ throw e;
+ }
+ catch (RuntimeException e) {
+ System.out.println("RuntimeException saving state: ");
+ e.printStackTrace();
+ throw e;
+ }
+ catch (Error e) {
+ System.out.println("Error saving state:");
+ e.printStackTrace();
+ throw e;
+ }
+}
+/**
+ * Sets the binary broker for this developent context
+ */
+public void setBinaryBroker(IBinaryBroker broker) {
+ if (broker == null)
+ fBinaryBrokerOutput = null;
+ else
+ fBinaryBrokerOutput = new BinaryBrokerOutput(broker);
+}
/**
* Sets the build monitor. The build monitor is a hook used
* by the test suites to test the image builder's efficiency.
@@ -433,44 +388,35 @@ public class JavaDevelopmentContextImpl implements IDevelopmentContext {
public void setBuildMonitor(IBuildMonitor monitor) {
fBuildMonitor = monitor;
}
-
- /**
- * Sets the build progress listener for this development context
- */
- public void setBuildProgressListener(IProgressListener listener) {
- }
-
- /**
- * Sets a compiler option. This seems awkward.
- */
- protected static void setCompilerOption(
- ConfigurableOption[] options,
- int optionID,
- int valueIndex) {
- for (int i = 0; i < options.length; i++) {
- if (options[i].getID() == optionID) {
- options[i].setValueIndex(valueIndex);
- return;
- }
+/**
+ * Sets the build progress listener for this development context
+ */
+public void setBuildProgressListener(IProgressListener listener) {
+}
+/**
+ * Sets a compiler option. This seems awkward.
+ */
+protected static void setCompilerOption(ConfigurableOption[] options, int optionID, int valueIndex) {
+ for (int i = 0; i < options.length; i++) {
+ if (options[i].getID() == optionID) {
+ options[i].setValueIndex(valueIndex);
+ return;
}
}
-
- /**
- * setCurrentState method comment.
- */
- public void setCurrentState(IState state) {
- fCurrentState = (StateImpl) state;
- }
-
+}
+/**
+ * setCurrentState method comment.
+ */
+public void setCurrentState(IState state) {
+ fCurrentState = (StateImpl)state;
+}
/**
* Sets the progress monitor for all build activities.
*/
public void setProgressMonitor(IProgressMonitor monitor) {
fProgressMonitor = monitor;
}
-
public String toString() {
return "a JavaDevelopmentContextImpl(" + fCurrentState + ")";
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/MarkerProblemReporter.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/MarkerProblemReporter.java
index 39ac0f483c..1077ffebf6 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/MarkerProblemReporter.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/MarkerProblemReporter.java
@@ -13,6 +13,7 @@ import org.eclipse.jdt.core.*;
import java.util.*;
+
/**
* An <code>IProblemReporter</code> that reports problems using the <code>IMarker</code> API.
* It keeps the problems backed in a ProblemTable as well, since the marker manager only
@@ -24,276 +25,237 @@ public class MarkerProblemReporter implements IProblemReporter {
protected IProject fProject;
protected ProblemTable fProblemTable = new ProblemTable();
private IDevelopmentContext dc;
- /**
- * Creates a new MarkerProblemReporter that is not initialized.
- * Used only during deserialization.
- */
- public MarkerProblemReporter() {
- }
-
- /**
- * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
- */
- public IProblemReporter copy() {
- /* The copy still reports to the same marker manager, since there's only one,
- * but the backing problem table is copied. */
- MarkerProblemReporter copy = new MarkerProblemReporter(fProject, this.dc);
- copy.fProblemTable = (ProblemTable) fProblemTable.copy();
- return copy;
- }
-
- /**
- * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
- */
- public Enumeration getAllProblems() {
- return fProblemTable.getAllProblems();
- }
-
- /**
- * Returns the extra flags for the given marker.
- */
- protected int getFlags(IMarker marker) throws CoreException {
- if (!marker.exists())
- return 0;
- Integer flags = (Integer) marker.getAttribute(IJavaModelMarker.FLAGS);
- return flags == null ? 0 : flags.intValue();
- }
-
- /**
- * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
- */
- public Enumeration getImageProblems() {
- return fProblemTable.getImageProblems();
- }
-
- /**
- * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
- */
- public Enumeration getProblemKeys() {
- return fProblemTable.getProblemKeys();
- }
-
- /**
- * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
- */
- public Enumeration getProblems(Object sourceID) {
- return fProblemTable.getProblems(sourceID);
- }
-
- /**
- * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
- */
- public Vector getProblemVector(Object sourceID) {
- return fProblemTable.getProblemVector(sourceID);
+/**
+ * Creates a new MarkerProblemReporter that is not initialized.
+ * Used only during deserialization.
+ */
+public MarkerProblemReporter() {
+}
+/**
+ * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
+ */
+public IProblemReporter copy() {
+ /* The copy still reports to the same marker manager, since there's only one,
+ * but the backing problem table is copied. */
+ MarkerProblemReporter copy = new MarkerProblemReporter(fProject, this.dc);
+ copy.fProblemTable = (ProblemTable) fProblemTable.copy();
+ return copy;
+}
+/**
+ * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
+ */
+public Enumeration getAllProblems() {
+ return fProblemTable.getAllProblems();
+}
+/**
+ * Returns the extra flags for the given marker.
+ */
+protected int getFlags(IMarker marker) throws CoreException {
+ if (!marker.exists()) return 0;
+ Integer flags = (Integer) marker.getAttribute(IJavaModelMarker.FLAGS);
+ return flags == null ? 0 : flags.intValue();
+}
+/**
+ * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
+ */
+public Enumeration getImageProblems() {
+ return fProblemTable.getImageProblems();
+}
+/**
+ * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
+ */
+public Enumeration getProblemKeys() {
+ return fProblemTable.getProblemKeys();
+}
+/**
+ * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
+ */
+public Enumeration getProblems(Object sourceID) {
+ return fProblemTable.getProblems(sourceID);
+}
+/**
+ * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
+ */
+public Vector getProblemVector(Object sourceID) {
+ return fProblemTable.getProblemVector(sourceID);
+}
+/**
+ * Returns the resource for the given source ID.
+ * Returns null if the source ID is not a SourceEntry or resource,
+ * or if the resource could not be found.
+ */
+protected IResource getResource(Object sourceID) {
+ if (sourceID instanceof IResource) {
+ return (IResource) sourceID;
}
-
- /**
- * Returns the resource for the given source ID.
- * Returns null if the source ID is not a SourceEntry or resource,
- * or if the resource could not be found.
- */
- protected IResource getResource(Object sourceID) {
- if (sourceID instanceof IResource) {
- return (IResource) sourceID;
- }
- if (!(sourceID instanceof SourceEntry))
- return null;
- SourceEntry entry = (SourceEntry) sourceID;
- IPath path = entry.getPath();
- if (path.isAbsolute()) {
- if (fProject.getFullPath().isPrefixOf(path)) {
- return fProject.getWorkspace().getRoot().getFile(path);
- }
- } else {
- return fProject.getFile(path);
- }
+ if (!(sourceID instanceof SourceEntry))
return null;
+ SourceEntry entry = (SourceEntry) sourceID;
+ IPath path = entry.getPath();
+ if (path.isAbsolute()) {
+ if (fProject.getFullPath().isPrefixOf(path)) {
+ return fProject.getWorkspace().getRoot().getFile(path);
+ }
+ } else {
+ return fProject.getFile(path);
}
-
- /**
- * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
- */
- public boolean hasProblems(Object sourceID) {
- return fProblemTable.hasProblems(sourceID);
+ return null;
+}
+/**
+ * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
+ */
+public boolean hasProblems(Object sourceID) {
+ return fProblemTable.hasProblems(sourceID);
+}
+/**
+ * Creates a marker from the given problem detail and add it to the resource.
+ * The marker is as follows:
+ * - its type is T_PROBLEM
+ * - its plugin ID is the JavaBuilder's plugin ID
+ * - its message is the problem's message
+ * - its priority reflects the severity of the problem
+ * - its range is the problem's range
+ * - it has an extra attribute "ID" which holds the problem's id
+ */
+protected void markerFromProblemDetail(IResource resource, IProblemDetail problem) throws CoreException {
+
+ IMarker marker = resource.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER);
+
+ marker.setAttribute(IMarker.MESSAGE, problem.getMessage());
+
+ int sev = problem.getSeverity();
+ marker.setAttribute(IMarker.SEVERITY , ((sev & IProblemDetail.S_ERROR) != 0 ? IMarker.SEVERITY_ERROR : IMarker.SEVERITY_WARNING));
+ if ((sev & ProblemDetailImpl.S_SYNTAX_ERROR) != 0) {
+ setFlags(marker, ProblemDetailImpl.S_SYNTAX_ERROR);
}
-
- /**
- * Creates a marker from the given problem detail and add it to the resource.
- * The marker is as follows:
- * - its type is T_PROBLEM
- * - its plugin ID is the JavaBuilder's plugin ID
- * - its message is the problem's message
- * - its priority reflects the severity of the problem
- * - its range is the problem's range
- * - it has an extra attribute "ID" which holds the problem's id
- */
- protected void markerFromProblemDetail(
- IResource resource,
- IProblemDetail problem)
- throws CoreException {
-
- IMarker marker =
- resource.createMarker(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER);
-
- marker.setAttribute(IMarker.MESSAGE, problem.getMessage());
-
- int sev = problem.getSeverity();
- marker.setAttribute(
- IMarker.SEVERITY,
- ((sev & IProblemDetail.S_ERROR) != 0
- ? IMarker.SEVERITY_ERROR
- : IMarker.SEVERITY_WARNING));
- if ((sev & ProblemDetailImpl.S_SYNTAX_ERROR) != 0) {
- setFlags(marker, ProblemDetailImpl.S_SYNTAX_ERROR);
- }
- marker.setAttribute("ID", new Integer(problem.getID()));
-
- int start = problem.getStartPos();
- marker.setAttribute(IMarker.CHAR_START, new Integer(start));
- marker.setAttribute(IMarker.CHAR_END, new Integer(problem.getEndPos() + 1));
- marker.setAttribute(IMarker.LINE_NUMBER, new Integer(problem.getLineNumber()));
-
- // compute a user-friendly location
- IJavaElement element = JavaCore.create(resource);
- if (element instanceof ICompilationUnit) {
- // try to find a finer grain element
- ICompilationUnit unit = (ICompilationUnit) element;
- IJavaElement fragment = unit.getElementAt(start);
- if (fragment != null)
- element = fragment;
- }
- String location = null;
- if (element instanceof org.eclipse.jdt.internal.core.JavaElement) {
- location = ((org.eclipse.jdt.internal.core.JavaElement) element).readableName();
- }
- if (location != null)
- marker.setAttribute(IMarker.LOCATION, location);
+ marker.setAttribute("ID", new Integer(problem.getID()));
+
+ int start = problem.getStartPos();
+ marker.setAttribute(IMarker.CHAR_START, new Integer(start));
+ marker.setAttribute(IMarker.CHAR_END, new Integer(problem.getEndPos() + 1));
+ marker.setAttribute(IMarker.LINE_NUMBER, new Integer(problem.getLineNumber()));
+
+ // compute a user-friendly location
+ IJavaElement element = JavaCore.create(resource);
+ if (element instanceof ICompilationUnit){ // try to find a finer grain element
+ ICompilationUnit unit = (ICompilationUnit) element;
+ IJavaElement fragment = unit.getElementAt(start);
+ if (fragment != null) element = fragment;
}
-
- /**
- * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
- */
- public void putProblem(Object sourceID, IProblemDetail problem) {
- /* Delegate first to the backing problem table. */
- fProblemTable.putProblem(sourceID, problem);
-
- /* Now update the markers. */
- IResource resource = getResource(sourceID);
- if (resource != null) {
- try {
- markerFromProblemDetail(resource, problem);
- } catch (CoreException e) {
- throw ((JavaDevelopmentContextImpl) this.dc).internalException(e);
- }
+ String location = null;
+ if (element instanceof org.eclipse.jdt.internal.core.JavaElement){
+ location = ((org.eclipse.jdt.internal.core.JavaElement)element).readableName();
+ }
+ if (location != null) marker.setAttribute(IMarker.LOCATION, location);
+}
+/**
+ * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
+ */
+public void putProblem(Object sourceID, IProblemDetail problem) {
+ /* Delegate first to the backing problem table. */
+ fProblemTable.putProblem(sourceID, problem);
+
+ /* Now update the markers. */
+ IResource resource = getResource(sourceID);
+ if (resource != null) {
+ try {
+ markerFromProblemDetail(resource, problem);
+ } catch (CoreException e) {
+ throw ((JavaDevelopmentContextImpl)this.dc).internalException(e);
}
}
-
- /**
- * Remove problem markers for the given element. If removeSyntaxErrors is true, remove only syntax errors,
- * otherwise remove only non-syntax errors.
- */
- protected void removeMarkers(Object sourceID, boolean removeSyntaxErrors) {
- IResource resource = getResource(sourceID);
- if (resource != null && resource.exists()) {
- try {
- IMarker[] markers =
- resource.findMarkers(
- IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER,
- false,
- IResource.DEPTH_INFINITE);
- if (markers.length > 0) {
- Vector toRemove = new Vector(markers.length);
- for (int i = 0; i < markers.length; i++) {
- IMarker marker = markers[i];
- try {
- boolean isSyntaxError =
- (getFlags(marker) & ProblemDetailImpl.S_SYNTAX_ERROR) != 0;
- if (isSyntaxError == removeSyntaxErrors) {
- toRemove.addElement(marker);
- }
- } catch (CoreException e) { // marker state cannot be accessed - ignore it
+}
+/**
+ * Remove problem markers for the given element. If removeSyntaxErrors is true, remove only syntax errors,
+ * otherwise remove only non-syntax errors.
+ */
+protected void removeMarkers(Object sourceID, boolean removeSyntaxErrors) {
+ IResource resource = getResource(sourceID);
+ if (resource != null && resource.exists()) {
+ try {
+ IMarker[] markers = resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_INFINITE);
+ if (markers.length > 0) {
+ Vector toRemove = new Vector(markers.length);
+ for (int i = 0; i < markers.length; i++) {
+ IMarker marker = markers[i];
+ try {
+ boolean isSyntaxError = (getFlags(marker) & ProblemDetailImpl.S_SYNTAX_ERROR) != 0;
+ if (isSyntaxError == removeSyntaxErrors) {
+ toRemove.addElement(marker);
}
+ } catch(CoreException e){ // marker state cannot be accessed - ignore it
}
- if (toRemove.size() > 0) {
- IMarker[] markersToRemove = new IMarker[toRemove.size()];
- toRemove.copyInto(markersToRemove);
- resource.getWorkspace().deleteMarkers(markersToRemove);
- }
}
- } catch (CoreException e) { // silently absorb CoreException during marker deletion
+ if (toRemove.size() > 0) {
+ IMarker[] markersToRemove = new IMarker[toRemove.size()];
+ toRemove.copyInto(markersToRemove);
+ resource.getWorkspace().deleteMarkers(markersToRemove);
+ }
}
+ } catch (CoreException e) { // silently absorb CoreException during marker deletion
}
}
-
- /**
- * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
- */
- public void removeNonSyntaxErrors(Object sourceID) {
- /* Delegate first to the backing problem table. */
- fProblemTable.removeNonSyntaxErrors(sourceID);
-
- removeMarkers(sourceID, false);
- }
-
- /**
- * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
- */
- public void removeProblems(Object sourceID) {
- /* Delegate first to the backing problem table. */
- fProblemTable.removeProblems(sourceID);
-
- /* Now update the markers. */
- IResource resource = getResource(sourceID);
- if (resource != null) {
- try {
- // See PR 1G2NPUH
- // If the resource doesn't exist, we don't want to try to remove markers for it.
- // Simply ignore. This test is done to prevent from having an exception.
- if (resource.exists())
- resource.deleteMarkers(
- IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER,
- false,
- IResource.DEPTH_INFINITE);
- } catch (CoreException e) {
- throw ((JavaDevelopmentContextImpl) this.dc).internalException(e);
- }
+}
+/**
+ * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
+ */
+public void removeNonSyntaxErrors(Object sourceID) {
+ /* Delegate first to the backing problem table. */
+ fProblemTable.removeNonSyntaxErrors(sourceID);
+
+ removeMarkers(sourceID, false);
+}
+/**
+ * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
+ */
+public void removeProblems(Object sourceID) {
+ /* Delegate first to the backing problem table. */
+ fProblemTable.removeProblems(sourceID);
+
+ /* Now update the markers. */
+ IResource resource = getResource(sourceID);
+ if (resource != null) {
+ try {
+ // See PR 1G2NPUH
+ // If the resource doesn't exist, we don't want to try to remove markers for it.
+ // Simply ignore. This test is done to prevent from having an exception.
+ if (resource.exists())
+ resource.deleteMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_INFINITE);
+ } catch (CoreException e) {
+ throw ((JavaDevelopmentContextImpl)this.dc).internalException(e);
}
}
+}
+/**
+ * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
+ */
+public void removeSyntaxErrors(Object sourceID) {
+ /* Delegate first to the backing problem table. */
+ fProblemTable.removeSyntaxErrors(sourceID);
+
+ removeMarkers(sourceID, true);
+}
+/**
+ * Sets the extra flags for the given marker.
+ */
+protected void setFlags(IMarker marker, int flags) throws CoreException {
+ // Don't take space if no extra flags.
+ marker.setAttribute(IJavaModelMarker.FLAGS, flags == 0 ? null : new Integer(flags));
+}
- /**
- * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
- */
- public void removeSyntaxErrors(Object sourceID) {
- /* Delegate first to the backing problem table. */
- fProblemTable.removeSyntaxErrors(sourceID);
-
- removeMarkers(sourceID, true);
- }
-
- /**
- * Sets the extra flags for the given marker.
- */
- protected void setFlags(IMarker marker, int flags) throws CoreException {
- // Don't take space if no extra flags.
- marker.setAttribute(
- IJavaModelMarker.FLAGS,
- flags == 0 ? null : new Integer(flags));
- }
-
- /**
- * Creates a new MarkerProblemReporter that reports problems as markers
- * against the given project.
- */
- public MarkerProblemReporter(IProject project, IDevelopmentContext dc) {
- initialize(project, dc);
- }
-
- /**
- * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
- */
- public void initialize(IProject project, IDevelopmentContext dc) {
- this.fProject = project;
- this.dc = dc;
- }
+/**
+ * Creates a new MarkerProblemReporter that reports problems as markers
+ * against the given project.
+ */
+public MarkerProblemReporter(IProject project, IDevelopmentContext dc) {
+ initialize(project, dc);
+}
+/**
+ * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
+ */
+public void initialize(IProject project, IDevelopmentContext dc) {
+ this.fProject = project;
+ this.dc = dc;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/MethodCollaboratorIndictment.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/MethodCollaboratorIndictment.java
index 8bb2b8a97b..38374557e9 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/MethodCollaboratorIndictment.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/MethodCollaboratorIndictment.java
@@ -9,61 +9,49 @@ import org.eclipse.jdt.internal.core.builder.IType;
class MethodCollaboratorIndictment extends Indictment {
protected IType fOwner;
protected int fParmCount;
- /**
- * Creates a new MethodCollaboratorIndictment.
- */
- protected MethodCollaboratorIndictment(
- IType owner,
- char[] name,
- int parmCount) {
- super(getMethodIndictmentKey(name, parmCount));
- fOwner = owner;
- fParmCount = parmCount;
- }
-
+/**
+ * Creates a new MethodCollaboratorIndictment.
+ */
+protected MethodCollaboratorIndictment(IType owner, char[] name, int parmCount) {
+ super(getMethodIndictmentKey(name, parmCount));
+ fOwner = owner;
+ fParmCount = parmCount;
+}
/**
* Returns true if indictments are equal, false otherwise
*/
public boolean equals(Object o) {
- if (this == o)
- return true;
- if (o == null)
- return false;
- if (!this.getClass().equals(o.getClass()))
- return false;
+ if (this == o) return true;
+ if (o == null) return false;
+ if (!this.getClass().equals(o.getClass())) return false;
- MethodCollaboratorIndictment f = (MethodCollaboratorIndictment) o;
+ MethodCollaboratorIndictment f = (MethodCollaboratorIndictment)o;
return (this.fName.equals(f.fName)) && (this.fParmCount == f.fParmCount);
}
-
/**
* Returns what kind of indictment this is
*/
public int getKind() {
return K_METHOD;
}
-
/**
* Returns the owning type of the method.
*/
public IType getOwner() {
return fOwner;
}
-
/**
* Returns the number of parameters to the method.
*/
public int getParmCount() {
return fParmCount;
}
-
/**
* Returns a hashcode for the indictment
*/
public int hashCode() {
return super.hashCode() + fParmCount;
}
-
/**
* Returns a string representation of this class. For debugging purposes
* only (NON-NLS).
@@ -76,5 +64,4 @@ class MethodCollaboratorIndictment extends Indictment {
buf.append(')');
return buf.toString();
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/MethodImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/MethodImpl.java
index 98c4631c2d..a42e18f76d 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/MethodImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/MethodImpl.java
@@ -11,12 +11,10 @@ public class MethodImpl extends AbstractMemberHandle implements IMethod {
fOwner = owner;
fSignature = signature;
}
-
MethodImpl(ClassOrInterfaceHandleImpl owner, String name, IType[] paramTypes) {
fOwner = owner;
fSignature = computeSignature(name, paramTypes);
}
-
/**
* Returns an array of Type objects that represent the types of
* the checked exceptions thrown by the method
@@ -28,9 +26,8 @@ public class MethodImpl extends AbstractMemberHandle implements IMethod {
* The resulting Types are in no particular order.
*/
public IType[] getExceptionTypes() {
- return nonStateSpecific(((IMethod) inCurrentState()).getExceptionTypes());
+ return nonStateSpecific(((IMethod)inCurrentState()).getExceptionTypes());
}
-
/**
* Returns the simple name of the member represented by this object.
* If this Member represents a constructor, this returns
@@ -41,7 +38,6 @@ public class MethodImpl extends AbstractMemberHandle implements IMethod {
String sig = getSignature();
return sig.substring(0, sig.indexOf('('));
}
-
/**
* Returns an array of Type objects that represent the formal
* parameter types, in declaration order, of the method
@@ -52,16 +48,14 @@ public class MethodImpl extends AbstractMemberHandle implements IMethod {
public IType[] getParameterTypes() {
return getInternalDC().parameterTypesFromSignature(getSignature());
}
-
/**
* Returns a Type object that represents the formal return type
* of the method represented by this Method object.
*/
public IType getReturnType() {
- IType wrapped = ((IMethod) inCurrentState()).getReturnType();
+ IType wrapped = ((IMethod)inCurrentState()).getReturnType();
return (IType) wrapped.nonStateSpecific();
}
-
/**
* Returns a string representing the constructor's parameters in the
* unqualified source signature format.
@@ -77,38 +71,33 @@ public class MethodImpl extends AbstractMemberHandle implements IMethod {
sourceSig += ")";
return sourceSig;
}
-
- /**
- * Returns a state specific version of this handle in the given state.
- */
- public IHandle inState(IState s)
- throws org.eclipse.jdt.internal.core.builder.StateSpecificException {
-
- return new MethodImplSWH((StateImpl) s, this);
- }
-
+/**
+ * Returns a state specific version of this handle in the given state.
+ */
+public IHandle inState(IState s) throws org.eclipse.jdt.internal.core.builder.StateSpecificException {
+
+ return new MethodImplSWH((StateImpl) s, this);
+}
/**
* Returns a constant indicating what kind of handle this is.
*/
public int kind() {
return K_JAVA_METHOD;
}
-
- /**
- * toString method comment.
- */
- public String toString() {
- StringBuffer sb = new StringBuffer(getDeclaringClass().getName());
- sb.append('.').append(getName()).append('(');
- IType[] paramTypes = getParameterTypes();
- for (int i = 0; i < paramTypes.length; ++i) {
- if (i != 0) {
- sb.append(',');
- }
- sb.append(paramTypes[i].getName());
+/**
+ * toString method comment.
+ */
+public String toString() {
+ StringBuffer sb = new StringBuffer(getDeclaringClass().getName());
+ sb.append('.').append(getName()).append('(');
+ IType[] paramTypes = getParameterTypes();
+ for (int i = 0; i < paramTypes.length; ++i) {
+ if (i != 0) {
+ sb.append(',');
}
- sb.append(')');
- return sb.toString();
+ sb.append(paramTypes[i].getName());
}
-
+ sb.append(')');
+ return sb.toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/MethodImplSWH.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/MethodImplSWH.java
index 951ce780f7..2bffc0905e 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/MethodImplSWH.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/MethodImplSWH.java
@@ -19,75 +19,64 @@ public class MethodImplSWH extends AbstractMemberHandleSWH implements IMethod {
fState = state;
fHandle = handle;
}
-
- /**
- * Internal - Returns the IBinaryMethod for this method.
- */
- protected IBinaryMethod getBinaryMethod() throws NotPresentException {
- return getBinaryMethod(getTypeStructureEntry());
- }
-
- /**
- * Internal - Returns the IBinaryMethod for this method.
- */
- protected IBinaryMethod getBinaryMethod(TypeStructureEntry tsEntry)
- throws NotPresentException {
- IBinaryType t = fState.getBinaryType(getTypeStructureEntry());
- IBinaryMethod m = BinaryStructure.getMethod(t, fHandle.fSignature);
- if (m == null) {
- throw new NotPresentException();
- } else {
- return m;
- }
+/**
+ * Internal - Returns the IBinaryMethod for this method.
+ */
+protected IBinaryMethod getBinaryMethod() throws NotPresentException {
+ return getBinaryMethod(getTypeStructureEntry());
+}
+/**
+ * Internal - Returns the IBinaryMethod for this method.
+ */
+protected IBinaryMethod getBinaryMethod(TypeStructureEntry tsEntry) throws NotPresentException {
+ IBinaryType t = fState.getBinaryType(getTypeStructureEntry());
+ IBinaryMethod m = BinaryStructure.getMethod(t, fHandle.fSignature);
+ if (m == null) {
+ throw new NotPresentException();
+ } else {
+ return m;
}
-
- /**
- * Returns an array of Type objects that represent the types of
- * the checked exceptions thrown by the underlying method
- * represented by this Method object.
- * Unchecked exceptions are not included in the result, even if
- * they are declared in the source.
- * Returns an array of length 0 if the constructor throws no checked
- * exceptions.
- * The resulting Types are in no particular order.
- */
- public IType[] getExceptionTypes() {
- TypeStructureEntry tsEntry = getTypeStructureEntry();
- char[][] exceptions = getBinaryMethod(tsEntry).getExceptionTypeNames();
- PackageImpl pkg = fHandle.fOwner.fOwner;
- int len = exceptions.length;
- IType[] results = new IType[len];
- for (int i = 0; i < len; i++) {
- results[i] =
- (IType) fState
- .typeNameToHandle(tsEntry, Util.convertTypeSignature(exceptions[i]))
- .inState(fState);
- }
- return results;
+}
+/**
+ * Returns an array of Type objects that represent the types of
+ * the checked exceptions thrown by the underlying method
+ * represented by this Method object.
+ * Unchecked exceptions are not included in the result, even if
+ * they are declared in the source.
+ * Returns an array of length 0 if the constructor throws no checked
+ * exceptions.
+ * The resulting Types are in no particular order.
+ */
+public IType[] getExceptionTypes() {
+ TypeStructureEntry tsEntry = getTypeStructureEntry();
+ char[][] exceptions = getBinaryMethod(tsEntry).getExceptionTypeNames();
+ PackageImpl pkg = fHandle.fOwner.fOwner;
+ int len = exceptions.length;
+ IType[] results = new IType[len];
+ for (int i = 0; i < len; i++) {
+ results[i] = (IType) fState.typeNameToHandle(tsEntry, Util.convertTypeSignature(exceptions[i])).inState(fState);
}
-
+ return results;
+}
/**
* Internal - Returns the non state specific handle
*/
- IMember getHandle() {
- return fHandle;
- }
-
- /**
- * Returns the Java language modifiers for the member
- * represented by this object, as an integer.
- */
- public int getModifiers() {
- return getBinaryMethod().getModifiers() & 0xFFFF;
- }
-
+ IMember getHandle() {
+ return fHandle;
+ }
+/**
+ * Returns the Java language modifiers for the member
+ * represented by this object, as an integer.
+ */
+public int getModifiers() {
+ return getBinaryMethod().getModifiers() & 0xFFFF;
+}
/**
* Returns the name of the method.
*/
public String getName() {
return fHandle.getName();
}
-
/**
* Returns an array of Type objects that represent the formal
* parameter types, in declaration order, of the method
@@ -103,68 +92,59 @@ public class MethodImplSWH extends AbstractMemberHandleSWH implements IMethod {
}
return results;
}
-
- /**
- * Returns a Type object that represents the formal return type
- * of the method represented by this Method object.
- */
- public IType getReturnType() {
- TypeStructureEntry tsEntry = getTypeStructureEntry();
- char[] sig = getBinaryMethod(tsEntry).getMethodDescriptor();
- int i = CharOperation.lastIndexOf(')', sig);
- if (i == -1) {
- // should not happen
- return getDevelopmentContext().getImage().voidType();
- }
- sig = CharOperation.subarray(sig, i + 1, sig.length);
- return (IType) fState
- .typeSignatureToHandle(tsEntry, Util.convertTypeSignature(sig))
- .inState(fState);
- }
-
- /**
- * Returns true if the member represented by this object is
- * deprecated, false otherwise. A deprecated object is one that
- * has a @ deprecated tag in its doc comment.
- */
- public boolean isDeprecated() {
- return (getBinaryMethod().getModifiers() & IConstants.AccDeprecated) != 0;
- }
-
- /**
- * Returns true if the object represented by the receiver is present
- * in the development context, false otherwise. If the receiver is
- * state-specific, checks whether it is present in this object's state,
- * otherwise checks whether it is present in the current state of the
- * development context.
- */
- public boolean isPresent() {
- TypeStructureEntry entry =
- fState.getTypeStructureEntry(fHandle.getDeclaringClass(), true);
- if (entry == null) {
- return false;
- }
- IBinaryType t = fState.getBinaryType(entry);
- IBinaryMethod m = BinaryStructure.getMethod(t, fHandle.fSignature);
- return m != null;
+/**
+ * Returns a Type object that represents the formal return type
+ * of the method represented by this Method object.
+ */
+public IType getReturnType() {
+ TypeStructureEntry tsEntry = getTypeStructureEntry();
+ char[] sig = getBinaryMethod(tsEntry).getMethodDescriptor();
+ int i = CharOperation.lastIndexOf(')', sig);
+ if (i == -1) {
+ // should not happen
+ return getDevelopmentContext().getImage().voidType();
}
-
- /**
- * Returns true if the member represented by this object is
- * synthetic, false otherwise. A synthetic object is one that
- * was invented by the compiler, but was not declared in the source.
- * See <em>The Inner Classes Specification</em>.
- * A synthetic object is not the same as a fictitious object.
- */
- public boolean isSynthetic() throws NotPresentException {
- return (getBinaryMethod().getModifiers() & IConstants.AccSynthetic) != 0;
+ sig = CharOperation.subarray(sig, i + 1, sig.length);
+ return (IType) fState.typeSignatureToHandle(tsEntry, Util.convertTypeSignature(sig)).inState(fState);
+}
+/**
+ * Returns true if the member represented by this object is
+ * deprecated, false otherwise. A deprecated object is one that
+ * has a @ deprecated tag in its doc comment.
+ */
+public boolean isDeprecated() {
+ return (getBinaryMethod().getModifiers() & IConstants.AccDeprecated) != 0;
+}
+/**
+ * Returns true if the object represented by the receiver is present
+ * in the development context, false otherwise. If the receiver is
+ * state-specific, checks whether it is present in this object's state,
+ * otherwise checks whether it is present in the current state of the
+ * development context.
+ */
+public boolean isPresent() {
+ TypeStructureEntry entry = fState.getTypeStructureEntry(fHandle.getDeclaringClass(), true);
+ if (entry == null) {
+ return false;
}
-
+ IBinaryType t = fState.getBinaryType(entry);
+ IBinaryMethod m = BinaryStructure.getMethod(t, fHandle.fSignature);
+ return m != null;
+}
+/**
+ * Returns true if the member represented by this object is
+ * synthetic, false otherwise. A synthetic object is one that
+ * was invented by the compiler, but was not declared in the source.
+ * See <em>The Inner Classes Specification</em>.
+ * A synthetic object is not the same as a fictitious object.
+ */
+public boolean isSynthetic() throws NotPresentException {
+ return (getBinaryMethod().getModifiers() & IConstants.AccSynthetic) != 0;
+}
/**
* Returns the non state specific handle
*/
- public IHandle nonStateSpecific() {
- return fHandle;
- }
-
+ public IHandle nonStateSpecific() {
+ return fHandle;
+ }
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ModifiedBuilderType.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ModifiedBuilderType.java
index 661c3a6fd2..49e92da647 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ModifiedBuilderType.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ModifiedBuilderType.java
@@ -25,259 +25,231 @@ public class ModifiedBuilderType extends BuilderType {
/**
* The tsEntry for this type in the old state
*/
- protected TypeStructureEntry fOldTSEntry;
+ protected TypeStructureEntry fOldTSEntry;
/**
* The structure of this type in the old state
*/
- protected IBinaryType fOldStructure;
- /**
- * Creates a new ModifiedBuilderType. The new tsEntry is not
- * yet known because the type hasn't yet been compiled.
- */
- public ModifiedBuilderType(
- IncrementalImageBuilder builder,
- TypeStructureEntry oldEntry,
- IBinaryType oldBinary) {
- super(builder, false, false);
- fOldTSEntry = oldEntry;
- fOldStructure = oldBinary;
- }
-
- /**
- * Adds the indictments for the descriptor's type, methods,
- * and fields. Usually used when a type has been added or removed.
- */
- public void computeAllIndictments(IndictmentSet set) {
+ protected IBinaryType fOldStructure;
+/**
+ * Creates a new ModifiedBuilderType. The new tsEntry is not
+ * yet known because the type hasn't yet been compiled.
+ */
+public ModifiedBuilderType(IncrementalImageBuilder builder, TypeStructureEntry oldEntry, IBinaryType oldBinary) {
+ super(builder, false, false);
+ fOldTSEntry = oldEntry;
+ fOldStructure = oldBinary;
+}
+/**
+ * Adds the indictments for the descriptor's type, methods,
+ * and fields. Usually used when a type has been added or removed.
+ */
+public void computeAllIndictments(IndictmentSet set) {
- /* indictment for the type */
- IType type = fOldTSEntry.getType();
- set.add(Indictment.createTypeIndictment(fOldStructure));
+ /* indictment for the type */
+ IType type = fOldTSEntry.getType();
+ set.add(Indictment.createTypeIndictment(fOldStructure));
- /* indictments for all fields */
- IBinaryField[] fields = fOldStructure.getFields();
- if (fields != null) {
- for (int i = 0; i < fields.length; i++) {
- set.add(Indictment.createFieldIndictment(fields[i]));
- }
+ /* indictments for all fields */
+ IBinaryField[] fields = fOldStructure.getFields();
+ if (fields != null) {
+ for (int i = 0; i < fields.length; i++) {
+ set.add(Indictment.createFieldIndictment(fields[i]));
}
+ }
- /* indictments for all methods */
- IBinaryMethod[] methods = fOldStructure.getMethods();
- if (methods != null) {
- for (int i = 0; i < methods.length; i++) {
- set.add(Indictment.createMethodIndictment(type, fOldStructure, methods[i]));
- }
+ /* indictments for all methods */
+ IBinaryMethod[] methods = fOldStructure.getMethods();
+ if (methods != null) {
+ for (int i = 0; i < methods.length; i++) {
+ set.add(Indictment.createMethodIndictment(type, fOldStructure, methods[i]));
}
}
-
- /**
- * Computes the indictments for the fields of this type
- */
- public void computeFieldIndictments(
- IndictmentSet indictments,
- IBinaryType newType,
- IType typeHandle) {
-
- /* create a set of all old fields */
- HashtableOfObject oldFieldsTable = new HashtableOfObject(11);
- IBinaryField[] oldFields = fOldStructure.getFields();
- if (oldFields != null) {
- for (int i = 0; i < oldFields.length; i++) {
- oldFieldsTable.put(oldFields[i].getName(), oldFields[i]);
- }
+}
+/**
+ * Computes the indictments for the fields of this type
+ */
+public void computeFieldIndictments(IndictmentSet indictments, IBinaryType newType, IType typeHandle) {
+
+ /* create a set of all old fields */
+ HashtableOfObject oldFieldsTable = new HashtableOfObject(11);
+ IBinaryField[] oldFields = fOldStructure.getFields();
+ if (oldFields != null) {
+ for (int i = 0; i < oldFields.length; i++) {
+ oldFieldsTable.put(oldFields[i].getName(), oldFields[i]);
}
+ }
- /* check if each new field was in old field list */
- IBinaryField[] newFields = newType.getFields();
- if (newFields != null) {
- for (int i = 0; i < newFields.length; i++) {
- IBinaryField newField = newFields[i];
- IBinaryField oldField = (IBinaryField) oldFieldsTable.get(newField.getName());
- if (oldField == null) {
- /* it's a new field -- create a indictment */
- indictments.add(Indictment.createFieldIndictment(newField));
- } else {
- /* if it has it changed, issue an indictment */
- oldFieldsTable.put(oldField.getName(), null);
- // TBD: there is no remove on HashtableOfObject
- if (!BinaryStructure.compare(oldField, newField)) {
- indictments.add(Indictment.createFieldIndictment(oldField));
- }
+ /* check if each new field was in old field list */
+ IBinaryField[] newFields = newType.getFields();
+ if (newFields != null) {
+ for (int i = 0; i < newFields.length; i++) {
+ IBinaryField newField = newFields[i];
+ IBinaryField oldField = (IBinaryField) oldFieldsTable.get(newField.getName());
+ if (oldField == null) {
+ /* it's a new field -- create a indictment */
+ indictments.add(Indictment.createFieldIndictment(newField));
+ } else {
+ /* if it has it changed, issue an indictment */
+ oldFieldsTable.put(oldField.getName(), null); // TBD: there is no remove on HashtableOfObject
+ if (!BinaryStructure.compare(oldField, newField)) {
+ indictments.add(Indictment.createFieldIndictment(oldField));
}
}
}
-
- /* remaining old fields have been deleted -- create indictments */
- Object[] remaining = oldFieldsTable.valueTable;
- for (int i = remaining.length; i-- > 0;) {
- if (remaining[i] != null) {
- IBinaryField oldField = (IBinaryField) remaining[i];
- indictments.add(Indictment.createFieldIndictment(oldField));
- }
- }
}
- /**
- * Computes the indictments for this type
- */
- public void computeIndictments(IndictmentSet indictments) {
- if (getOldBinaryType() == null) {
- // Don't know old structure. Must convict all dependents.
- // Needed for 1FVQGL1: ITPJCORE:WINNT - SEVERE - Error saving java file
- indictments.convictAll();
- return;
- }
-
- if (fNewTSEntry == null) {
- /* a new type could not be generated */
- computeAllIndictments(indictments);
- return;
- }
-
- IBinaryType newType = getNewState().getBinaryType(fNewTSEntry);
- IType typeHandle = (IType) fOldTSEntry.getType();
-
- /* see if there's a change to supertype hierarchy */
- boolean hierarchyChange = detectHierarchyChange();
-
- /* add the hierarchy indictment if there were any changes */
- if (hierarchyChange) {
- indictments.add(Indictment.createHierarchyIndictment(newType));
- }
-
- /* if type modifiers (including deprecated flag) have changed */
- if (fOldStructure.getModifiers() != newType.getModifiers()) {
- /* issue a type collaborator indictment */
- indictments.add(Indictment.createTypeIndictment(newType));
+ /* remaining old fields have been deleted -- create indictments */
+ Object[] remaining = oldFieldsTable.valueTable;
+ for (int i = remaining.length; i-- > 0;) {
+ if (remaining[i] != null) {
+ IBinaryField oldField = (IBinaryField) remaining[i];
+ indictments.add(Indictment.createFieldIndictment(oldField));
}
+ }
+}
+/**
+ * Computes the indictments for this type
+ */
+public void computeIndictments(IndictmentSet indictments) {
+ if (getOldBinaryType() == null) {
+ // Don't know old structure. Must convict all dependents.
+ // Needed for 1FVQGL1: ITPJCORE:WINNT - SEVERE - Error saving java file
+ indictments.convictAll();
+ return;
+ }
+
+ if (fNewTSEntry == null) {
+ /* a new type could not be generated */
+ computeAllIndictments(indictments);
+ return;
+ }
+
+ IBinaryType newType = getNewState().getBinaryType(fNewTSEntry);
+ IType typeHandle = (IType)fOldTSEntry.getType();
+
+ /* see if there's a change to supertype hierarchy */
+ boolean hierarchyChange = detectHierarchyChange();
+
+ /* add the hierarchy indictment if there were any changes */
+ if (hierarchyChange) {
+ indictments.add(Indictment.createHierarchyIndictment(newType));
+ }
- /* compute indictments for members */
- computeMethodIndictments(indictments, newType, typeHandle);
- computeFieldIndictments(indictments, newType, typeHandle);
+ /* if type modifiers (including deprecated flag) have changed */
+ if (fOldStructure.getModifiers() != newType.getModifiers()) {
+ /* issue a type collaborator indictment */
+ indictments.add(Indictment.createTypeIndictment(newType));
}
- /**
- * Computes the method indictments for this type
- */
- public void computeMethodIndictments(
- IndictmentSet indictments,
- IBinaryType newType,
- IType typeHandle) {
+ /* compute indictments for members */
+ computeMethodIndictments(indictments, newType, typeHandle);
+ computeFieldIndictments(indictments, newType, typeHandle);
+}
+/**
+ * Computes the method indictments for this type
+ */
+public void computeMethodIndictments(IndictmentSet indictments, IBinaryType newType, IType typeHandle) {
- boolean issueAbstractMethodIndictment = false;
- if ((fOldStructure.getModifiers() & IConstants.AccAbstract)
- != (newType.getModifiers() & IConstants.AccAbstract)) {
- issueAbstractMethodIndictment = true;
- }
+ boolean issueAbstractMethodIndictment = false;
+ if ((fOldStructure.getModifiers() & IConstants.AccAbstract) !=
+ (newType.getModifiers() & IConstants.AccAbstract)) {
+ issueAbstractMethodIndictment = true;
+ }
- /* create a set of all old methods */
- HashtableOfObject oldMethodsTable = new HashtableOfObject(21);
- IBinaryMethod[] oldMethods = fOldStructure.getMethods();
- if (oldMethods != null) {
- for (int i = 0; i < oldMethods.length; i++) {
- IBinaryMethod oldMethod = oldMethods[i];
- char[] sig =
- CharOperation.concat(oldMethod.getSelector(), oldMethod.getMethodDescriptor());
- oldMethodsTable.put(sig, oldMethod);
- }
+ /* create a set of all old methods */
+ HashtableOfObject oldMethodsTable = new HashtableOfObject(21);
+ IBinaryMethod[] oldMethods = fOldStructure.getMethods();
+ if (oldMethods != null) {
+ for (int i = 0; i < oldMethods.length; i++) {
+ IBinaryMethod oldMethod = oldMethods[i];
+ char[] sig = CharOperation.concat(oldMethod.getSelector(), oldMethod.getMethodDescriptor());
+ oldMethodsTable.put(sig, oldMethod);
}
+ }
- /* check if each new method was in old method list */
- IBinaryMethod[] newMethods = newType.getMethods();
- if (newMethods != null) {
- for (int i = 0; i < newMethods.length; i++) {
- IBinaryMethod newMethod = (IBinaryMethod) newMethods[i];
- char[] sig =
- CharOperation.concat(newMethod.getSelector(), newMethod.getMethodDescriptor());
- IBinaryMethod oldMethod = (IBinaryMethod) oldMethodsTable.get(sig);
- if (oldMethod == null) {
- /* it's a new method -- issue an indictment */
- indictments.add(
- Indictment.createMethodIndictment(typeHandle, newType, newMethod));
-
- /* if the new method is abstract, issue an abstract method indictment too */
- if ((newMethod.getModifiers() & IConstants.AccAbstract) != 0) {
- issueAbstractMethodIndictment = true;
- }
- } else {
- /* if it has it changed, issue an indictment */
- oldMethodsTable.put(sig, null);
- // TBD: there is no remove on HashtableOfObject
- if (!BinaryStructure.compare(oldMethod, newMethod)) {
- indictments.add(
- Indictment.createMethodIndictment(typeHandle, fOldStructure, oldMethod));
- }
- /* if an existing method changes its abstract state, issue an abstract method indictment too */
- if ((oldMethod.getModifiers() & IConstants.AccAbstract)
- != (newMethod.getModifiers() & IConstants.AccAbstract)) {
- issueAbstractMethodIndictment = true;
- }
+ /* check if each new method was in old method list */
+ IBinaryMethod[] newMethods = newType.getMethods();
+ if (newMethods != null) {
+ for (int i = 0; i < newMethods.length; i++) {
+ IBinaryMethod newMethod = (IBinaryMethod) newMethods[i];
+ char[] sig = CharOperation.concat(newMethod.getSelector(), newMethod.getMethodDescriptor());
+ IBinaryMethod oldMethod = (IBinaryMethod) oldMethodsTable.get(sig);
+ if (oldMethod == null) {
+ /* it's a new method -- issue an indictment */
+ indictments.add(Indictment.createMethodIndictment(typeHandle, newType, newMethod));
+
+ /* if the new method is abstract, issue an abstract method indictment too */
+ if ((newMethod.getModifiers() & IConstants.AccAbstract) != 0) {
+ issueAbstractMethodIndictment = true;
}
- }
- }
-
- /* remaining old methods have been deleted -- issue indictments */
- Object[] remaining = oldMethodsTable.valueTable;
- for (int i = remaining.length; i-- > 0;) {
- if (remaining[i] != null) {
- IBinaryMethod oldMethod = (IBinaryMethod) remaining[i];
- indictments.add(
- Indictment.createMethodIndictment(typeHandle, fOldStructure, oldMethod));
-
- /* if old method is abstract, issue an abstract method indictment too */
- if ((oldMethod.getModifiers() & IConstants.AccAbstract) != 0) {
+ } else {
+ /* if it has it changed, issue an indictment */
+ oldMethodsTable.put(sig, null); // TBD: there is no remove on HashtableOfObject
+ if (!BinaryStructure.compare(oldMethod, newMethod)) {
+ indictments.add(Indictment.createMethodIndictment(typeHandle, fOldStructure, oldMethod));
+ }
+ /* if an existing method changes its abstract state, issue an abstract method indictment too */
+ if ((oldMethod.getModifiers() & IConstants.AccAbstract) != (newMethod.getModifiers() & IConstants.AccAbstract)) {
issueAbstractMethodIndictment = true;
}
}
}
-
- /* issue abstract method indictment now, if need be */
- if (issueAbstractMethodIndictment) {
- indictments.add(Indictment.createAbstractMethodIndictment(typeHandle));
- }
}
- /**
- * Returns the tsEntry in the new state
- */
- public TypeStructureEntry getNewTypeStructureEntry() {
- if (fNewTSEntry == null) {
- if (fOldTSEntry != null) {
- fNewTSEntry =
- fBuilder.fNewState.getTypeStructureEntry(fOldTSEntry.getType(), false);
+ /* remaining old methods have been deleted -- issue indictments */
+ Object[] remaining = oldMethodsTable.valueTable;
+ for (int i = remaining.length; i-- > 0;) {
+ if (remaining[i] != null) {
+ IBinaryMethod oldMethod = (IBinaryMethod) remaining[i];
+ indictments.add(Indictment.createMethodIndictment(typeHandle, fOldStructure, oldMethod));
+
+ /* if old method is abstract, issue an abstract method indictment too */
+ if ((oldMethod.getModifiers() & IConstants.AccAbstract) != 0) {
+ issueAbstractMethodIndictment = true;
}
}
- return fNewTSEntry;
- }
-
- /**
- * Returns the binary type in the old state
- */
- public IBinaryType getOldBinaryType() {
- return fOldStructure;
}
- /**
- * Returns the old tsEntry
- */
- public TypeStructureEntry getOldTypeStructureEntry() {
- return fOldTSEntry;
+ /* issue abstract method indictment now, if need be */
+ if (issueAbstractMethodIndictment) {
+ indictments.add(Indictment.createAbstractMethodIndictment(typeHandle));
}
-
- /**
- * Sets the tsEntry in the new state
- */
- public void setNewTypeStructureEntry(TypeStructureEntry newEntry) {
- fNewTSEntry = newEntry;
- }
-
- /**
- * For debugging only
- */
- public String toString() {
- StringBuffer buf = new StringBuffer("ModifiedBuilderType(");
- return buf.append(fOldTSEntry.getType().getName()).append(")").toString();
+}
+/**
+ * Returns the tsEntry in the new state
+ */
+public TypeStructureEntry getNewTypeStructureEntry() {
+ if (fNewTSEntry == null) {
+ if (fOldTSEntry != null) {
+ fNewTSEntry = fBuilder.fNewState.getTypeStructureEntry(fOldTSEntry.getType(), false);
+ }
}
-
+ return fNewTSEntry;
+}
+/**
+ * Returns the binary type in the old state
+ */
+public IBinaryType getOldBinaryType() {
+ return fOldStructure;
+}
+/**
+ * Returns the old tsEntry
+ */
+public TypeStructureEntry getOldTypeStructureEntry() {
+ return fOldTSEntry;
+}
+/**
+ * Sets the tsEntry in the new state
+ */
+public void setNewTypeStructureEntry(TypeStructureEntry newEntry) {
+ fNewTSEntry = newEntry;
+}
+/**
+ * For debugging only
+ */
+public String toString() {
+ StringBuffer buf = new StringBuffer("ModifiedBuilderType(");
+ return buf.append(fOldTSEntry.getType().getName()).append(")").toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/NamespaceNode.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/NamespaceNode.java
index c6d30b30d4..b05e970808 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/NamespaceNode.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/NamespaceNode.java
@@ -15,17 +15,15 @@ public class NamespaceNode extends AbstractNode {
/**
* Creates a new namespace node for the given package
*/
- public NamespaceNode(IPackage pkg) {
+ public NamespaceNode (IPackage pkg) {
fPackage = pkg;
}
-
/**
* Adds a node that this node depends on. Backwards link is added automatically
*/
public void addDependency(INode nodeThatIDependOn) {
Assert.isTrue(false, "namespaces cannot have dependencies");
}
-
/**
* Returns a copy of this node, without copying dependencies. Used
* by DependencyGraph.copy().
@@ -33,14 +31,12 @@ public class NamespaceNode extends AbstractNode {
public AbstractNode copy() {
return new NamespaceNode(fPackage);
}
-
/**
* Returns the element which this node represents.
*/
public Object getElement() {
return fPackage;
}
-
/**
* Returns the number of bytes that this node uses.
* For debugging and profiling purposes only.
@@ -49,18 +45,15 @@ public class NamespaceNode extends AbstractNode {
/* one slot for package */
return super.getFootprint() + 4;
}
-
/**
* Returns what kind of node this is.
*/
public int getKind() {
return NAMESPACE_NODE;
}
-
public IPackage getPackage() {
return fPackage;
}
-
/**
* Prints a string representation of the node. This method is for debugging
* purposes only.
@@ -68,5 +61,4 @@ public class NamespaceNode extends AbstractNode {
public String toString() {
return "NamespaceNode(" + fPackage.getName() + ")";
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/NewBuilderType.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/NewBuilderType.java
index f067b3361d..04dbed8581 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/NewBuilderType.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/NewBuilderType.java
@@ -5,49 +5,41 @@ public class NewBuilderType extends BuilderType {
* The tsEntry in the new state
*/
protected TypeStructureEntry fNewTSEntry;
- /**
- * NewBuilderType constructor comment.
- */
- public NewBuilderType(
- IncrementalImageBuilder builder,
- TypeStructureEntry newEntry) {
- /* this is a new type, which is a hierarchy change */
- super(builder, true, true);
- fNewTSEntry = newEntry;
- }
-
- /**
- * No indictments for a new type.
- */
- public void computeIndictments(IndictmentSet indictments) {
- }
-
- /**
- * Returns the new tsEntry
- */
- public TypeStructureEntry getNewTypeStructureEntry() {
- return fNewTSEntry;
- }
-
- /**
- * Added types do not have an entry in the old state.
- */
- public TypeStructureEntry getOldTypeStructureEntry() {
- return null;
- }
-
- /**
- * Sets the tsEntry in the new state
- */
- public void setNewTypeStructureEntry(TypeStructureEntry newEntry) {
- fNewTSEntry = newEntry;
- }
-
- /**
- * For debugging only
- */
- public String toString() {
- return "NewBuilderType(" + fNewTSEntry.getType().getName() + ")";
- }
-
+/**
+ * NewBuilderType constructor comment.
+ */
+public NewBuilderType(IncrementalImageBuilder builder, TypeStructureEntry newEntry) {
+ /* this is a new type, which is a hierarchy change */
+ super(builder, true, true);
+ fNewTSEntry = newEntry;
+}
+/**
+ * No indictments for a new type.
+ */
+public void computeIndictments(IndictmentSet indictments) {
+}
+/**
+ * Returns the new tsEntry
+ */
+public TypeStructureEntry getNewTypeStructureEntry() {
+ return fNewTSEntry;
+}
+/**
+ * Added types do not have an entry in the old state.
+ */
+public TypeStructureEntry getOldTypeStructureEntry() {
+ return null;
+}
+/**
+ * Sets the tsEntry in the new state
+ */
+public void setNewTypeStructureEntry(TypeStructureEntry newEntry) {
+ fNewTSEntry = newEntry;
+}
+/**
+ * For debugging only
+ */
+public String toString() {
+ return "NewBuilderType(" + fNewTSEntry.getType().getName() + ")";
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/NonStateSpecificHandleImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/NonStateSpecificHandleImpl.java
index bfc2517266..9d73832fe6 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/NonStateSpecificHandleImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/NonStateSpecificHandleImpl.java
@@ -8,20 +8,17 @@ import org.eclipse.jdt.internal.core.Assert;
import org.eclipse.jdt.internal.core.builder.*;
public abstract class NonStateSpecificHandleImpl implements IHandle {
- public boolean equals(Object obj) {
- Assert.isTrue(false, "TBD");
- return false;
- }
-
+public boolean equals(Object obj) {
+ Assert.isTrue(false, "TBD");
+ return false;
+}
public IDevelopmentContext getDevelopmentContext() {
return getInternalDC();
}
-
abstract JavaDevelopmentContextImpl getInternalDC();
- public IState getState() {
- throw new org.eclipse.jdt.internal.core.builder.StateSpecificException();
- }
-
+public IState getState() {
+ throw new org.eclipse.jdt.internal.core.builder.StateSpecificException();
+}
/**
* Returns a consistent hash code for this object
*/
@@ -32,102 +29,85 @@ public abstract class NonStateSpecificHandleImpl implements IHandle {
protected IHandle inCurrentState() {
return inState(getDevelopmentContext().getCurrentState());
}
-
/**
* Returns a state-specific version of this handle in the given state
*/
- public abstract IHandle inState(IState s)
- throws org.eclipse.jdt.internal.core.builder.StateSpecificException;
- public boolean isFictional() {
- return inCurrentState().isFictional();
- }
-
- public boolean isPresent() {
- return inCurrentState().isPresent();
- }
-
- public boolean isStateSpecific() {
- return false;
- }
-
- public abstract int kind();
- public IHandle nonStateSpecific() {
- throw new org.eclipse.jdt.internal.core.builder.StateSpecificException();
- }
-
- /**
- * Converts an array of state-specific constructors to non-state-specific constructors.
- */
- static IConstructor[] nonStateSpecific(IConstructor[] stateSpecific) {
- int len = stateSpecific.length;
- if (len == 0)
- return stateSpecific;
- IConstructor[] result = new IConstructor[len];
- for (int i = 0; i < len; ++i) {
- result[i] = (IConstructor) stateSpecific[i].nonStateSpecific();
- }
- return result;
- }
-
- /**
- * Converts an array of state-specific fields to non-state-specific fields.
- */
- static IField[] nonStateSpecific(IField[] stateSpecific) {
- int len = stateSpecific.length;
- if (len == 0)
- return stateSpecific;
- IField[] result = new IField[len];
- for (int i = 0; i < len; ++i) {
- result[i] = (IField) stateSpecific[i].nonStateSpecific();
- }
- return result;
- }
-
- /**
- * Converts an array of state-specific methods to non-state-specific methods.
- */
- static IMethod[] nonStateSpecific(IMethod[] stateSpecific) {
- int len = stateSpecific.length;
- if (len == 0)
- return stateSpecific;
- IMethod[] result = new IMethod[len];
- for (int i = 0; i < len; ++i) {
- result[i] = (IMethod) stateSpecific[i].nonStateSpecific();
- }
- return result;
- }
-
- /**
- * Converts an array of state-specific packages to non-state-specific packages.
- */
- static IPackage[] nonStateSpecific(IPackage[] stateSpecific) {
- int len = stateSpecific.length;
- if (len == 0)
- return stateSpecific;
- IPackage[] result = new IPackage[len];
- for (int i = 0; i < len; ++i) {
- result[i] = (IPackage) stateSpecific[i].nonStateSpecific();
- }
- return result;
- }
-
- /**
- * Converts an array of state-specific types to non-state-specific types.
- */
- static IType[] nonStateSpecific(IType[] stateSpecific) {
- int len = stateSpecific.length;
- if (len == 0)
- return stateSpecific;
- IType[] result = new IType[len];
- for (int i = 0; i < len; ++i) {
- result[i] = (IType) stateSpecific[i].nonStateSpecific();
- }
- return result;
- }
-
- public String toString() {
- Assert.isTrue(false, "TBD");
- return null;
- }
-
+ public abstract IHandle inState(IState s) throws org.eclipse.jdt.internal.core.builder.StateSpecificException;
+public boolean isFictional() {
+ return inCurrentState().isFictional();
+}
+public boolean isPresent() {
+ return inCurrentState().isPresent();
+}
+public boolean isStateSpecific() {
+ return false;
+}
+public abstract int kind();
+public IHandle nonStateSpecific() {
+ throw new org.eclipse.jdt.internal.core.builder.StateSpecificException();
+}
+/**
+ * Converts an array of state-specific constructors to non-state-specific constructors.
+ */
+static IConstructor[] nonStateSpecific(IConstructor[] stateSpecific) {
+ int len = stateSpecific.length;
+ if (len == 0) return stateSpecific;
+ IConstructor[] result = new IConstructor[len];
+ for (int i = 0; i < len; ++i) {
+ result[i] = (IConstructor) stateSpecific[i].nonStateSpecific();
+ }
+ return result;
+}
+/**
+ * Converts an array of state-specific fields to non-state-specific fields.
+ */
+static IField[] nonStateSpecific(IField[] stateSpecific) {
+ int len = stateSpecific.length;
+ if (len == 0) return stateSpecific;
+ IField[] result = new IField[len];
+ for (int i = 0; i < len; ++i) {
+ result[i] = (IField) stateSpecific[i].nonStateSpecific();
+ }
+ return result;
+}
+/**
+ * Converts an array of state-specific methods to non-state-specific methods.
+ */
+static IMethod[] nonStateSpecific(IMethod[] stateSpecific) {
+ int len = stateSpecific.length;
+ if (len == 0) return stateSpecific;
+ IMethod[] result = new IMethod[len];
+ for (int i = 0; i < len; ++i) {
+ result[i] = (IMethod) stateSpecific[i].nonStateSpecific();
+ }
+ return result;
+}
+/**
+ * Converts an array of state-specific packages to non-state-specific packages.
+ */
+static IPackage[] nonStateSpecific(IPackage[] stateSpecific) {
+ int len = stateSpecific.length;
+ if (len == 0) return stateSpecific;
+ IPackage[] result = new IPackage[len];
+ for (int i = 0; i < len; ++i) {
+ result[i] = (IPackage) stateSpecific[i].nonStateSpecific();
+ }
+ return result;
+}
+/**
+ * Converts an array of state-specific types to non-state-specific types.
+ */
+static IType[] nonStateSpecific(IType[] stateSpecific) {
+ int len = stateSpecific.length;
+ if (len == 0) return stateSpecific;
+ IType[] result = new IType[len];
+ for (int i = 0; i < len; ++i) {
+ result[i] = (IType) stateSpecific[i].nonStateSpecific();
+ }
+ return result;
+}
+public String toString() {
+ Assert.isTrue(false, "TBD");
+ return null;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/OldBuilderType.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/OldBuilderType.java
index d7abdfc1d5..9f4fac066f 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/OldBuilderType.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/OldBuilderType.java
@@ -16,52 +16,46 @@ public class OldBuilderType extends BuilderType {
* The tsEntry for this type in the old state
*/
protected TypeStructureEntry fOldTSEntry;
+
- /**
- * Creates a new OldBuilderType
- */
- public OldBuilderType(
- IncrementalImageBuilder builder,
- TypeStructureEntry oldEntry) {
- /* this is a deleted type, which is a hierarchy change */
- super(builder, true, true);
- fOldTSEntry = oldEntry;
- }
-
- /**
- * Adds the indictments for the descriptor's type, methods,
- * and fields. Usually used when a type has been added or removed.
- */
- public void computeIndictments(IndictmentSet set) {
- /* dependents should already have been compiled */
- }
-
- /**
- * Old builder types don't necessarily exist in the new state.
- */
- public TypeStructureEntry getNewTypeStructureEntry() {
- return null;
- }
-
- /**
- * Returns the old tsEntry
- */
- public TypeStructureEntry getOldTypeStructureEntry() {
- return fOldTSEntry;
- }
-
- /**
- * Sets the tsEntry in the new state
- */
- public void setNewTypeStructureEntry(TypeStructureEntry newEntry) {
- Assert.isTrue(false);
- }
-
- /**
- * For debugging only
- */
- public String toString() {
- return "OldBuilderType(" + fOldTSEntry.getType().getName() + ")";
- }
+/**
+ * Creates a new OldBuilderType
+ */
+public OldBuilderType(IncrementalImageBuilder builder, TypeStructureEntry oldEntry) {
+ /* this is a deleted type, which is a hierarchy change */
+ super(builder, true, true);
+ fOldTSEntry = oldEntry;
+}
+/**
+ * Adds the indictments for the descriptor's type, methods,
+ * and fields. Usually used when a type has been added or removed.
+ */
+public void computeIndictments(IndictmentSet set) {
+ /* dependents should already have been compiled */
+}
+/**
+ * Old builder types don't necessarily exist in the new state.
+ */
+public TypeStructureEntry getNewTypeStructureEntry() {
+ return null;
+}
+/**
+ * Returns the old tsEntry
+ */
+public TypeStructureEntry getOldTypeStructureEntry() {
+ return fOldTSEntry;
+}
+/**
+ * Sets the tsEntry in the new state
+ */
+public void setNewTypeStructureEntry(TypeStructureEntry newEntry) {
+ Assert.isTrue(false);
+}
+/**
+ * For debugging only
+ */
+public String toString() {
+ return "OldBuilderType(" + fOldTSEntry.getType().getName() + ")";
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/OrderedSet.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/OrderedSet.java
index 2e9f369833..d2d155b886 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/OrderedSet.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/OrderedSet.java
@@ -2,240 +2,221 @@ package org.eclipse.jdt.internal.core.builder.impl;
public class OrderedSet {
protected int elementCount;
- protected Object[] elementKeys;
- protected int[] elementIndexes;
- protected Object[] orderedList;
+ protected Object [] elementKeys;
+ protected int [] elementIndexes;
+ protected Object [] orderedList;
protected float loadFactor;
private static final int DEFAULT_SIZE = 101;
- /**
- * Constructs a new OrderedSet using the default capacity
- * and load factor.
- */
- public OrderedSet() {
- this(DEFAULT_SIZE);
+/**
+ * Constructs a new OrderedSet using the default capacity
+ * and load factor.
+ */
+public OrderedSet() {
+ this (DEFAULT_SIZE);
+}
+/**
+ * Constructs a new OrderedSet using the specified capacity
+ * and the default load factor.
+ *
+ * @param capacity the initial capacity
+ */
+public OrderedSet (int capacity) {
+ this(capacity, 0.75f);
+}
+/**
+ * Constructs a new OrderedSet using the specified capacity
+ * and load factor.
+ *
+ * @param loadFactor the initial load factor
+ */
+public OrderedSet (int capacity, float loadFactor) {
+ if (capacity <= 0) throw new IllegalArgumentException();
+ elementCount = 0;
+ elementKeys = new Object [capacity];
+ int[] indexes = new int [capacity];
+ for (int i = capacity; --i >= 0; ) {
+ indexes[i] = -1;
}
-
- /**
- * Constructs a new OrderedSet using the specified capacity
- * and the default load factor.
- *
- * @param capacity the initial capacity
- */
- public OrderedSet(int capacity) {
- this(capacity, 0.75f);
+ elementIndexes = indexes;
+ orderedList = new Object[capacity];
+ this.loadFactor = loadFactor;
+}
+private int findIndex (Object object, Object [] array) {
+ Object key;
+ int length = array.length;
+ int index = (object.hashCode() & 0x7FFFFFFF) % length;
+ for (int i=index; i<length; i++) {
+ if (((key = array [i]) == null) || (key == object)) return i;
+ if (key.equals (object)) return i;
}
-
- /**
- * Constructs a new OrderedSet using the specified capacity
- * and load factor.
- *
- * @param loadFactor the initial load factor
- */
- public OrderedSet(int capacity, float loadFactor) {
- if (capacity <= 0)
- throw new IllegalArgumentException();
- elementCount = 0;
- elementKeys = new Object[capacity];
- int[] indexes = new int[capacity];
- for (int i = capacity; --i >= 0;) {
- indexes[i] = -1;
- }
- elementIndexes = indexes;
- orderedList = new Object[capacity];
- this.loadFactor = loadFactor;
+ for (int i=0; i<index; i++) {
+ if (((key = array [i]) == null) || (key == object)) return i;
+ if (key.equals (object)) return i;
}
-
- private int findIndex(Object object, Object[] array) {
- Object key;
- int length = array.length;
- int index = (object.hashCode() & 0x7FFFFFFF) % length;
- for (int i = index; i < length; i++) {
- if (((key = array[i]) == null) || (key == object))
- return i;
- if (key.equals(object))
- return i;
- }
- for (int i = 0; i < index; i++) {
- if (((key = array[i]) == null) || (key == object))
- return i;
- if (key.equals(object))
- return i;
- }
- return -1; // unreacheable
+ return -1; // unreacheable
+}
+/**
+ * Answers the object associated with the specified index in
+ * this OrderedSet.
+ *
+ * @param index the index to use
+ * @return the object associated with the specified index
+ * @throws ArrayIndexOutOfBoundsException if the index is out of range
+ *
+ * @see #put
+ */
+public Object get(int index) {
+ if (index >= elementCount) {
+ throw new ArrayIndexOutOfBoundsException();
}
-
- /**
- * Answers the object associated with the specified index in
- * this OrderedSet.
- *
- * @param index the index to use
- * @return the object associated with the specified index
- * @throws ArrayIndexOutOfBoundsException if the index is out of range
- *
- * @see #put
- */
- public Object get(int index) {
- if (index >= elementCount) {
- throw new ArrayIndexOutOfBoundsException();
- }
- return orderedList[index];
+ return orderedList[index];
+}
+/**
+ * Answers whether the specified object is in
+ * this OrderedSet.
+ *
+ * @param obj the object, which must not be null
+ * @return true if the object is in the set, false otherwise
+ *
+ * @see #put
+ */
+public boolean includes(Object obj) {
+ if (obj == null) {
+ throw new NullPointerException();
}
-
- /**
- * Answers whether the specified object is in
- * this OrderedSet.
- *
- * @param obj the object, which must not be null
- * @return true if the object is in the set, false otherwise
- *
- * @see #put
- */
- public boolean includes(Object obj) {
- if (obj == null) {
- throw new NullPointerException();
- }
- int index = elementIndexes[findIndex(obj, elementKeys)];
- return index != -1;
+ int index = elementIndexes[findIndex (obj, elementKeys)];
+ return index != -1;
+}
+/**
+ * Answers the index associated with the specified object in
+ * this OrderedSet.
+ *
+ * @param obj the object, which must not be null
+ * @return the index associated with the object
+ * @throws IllegalArgumentException if the key is not in the pool
+ *
+ * @see #put
+ */
+public int index(Object obj) {
+ if (obj == null) {
+ throw new NullPointerException();
}
-
- /**
- * Answers the index associated with the specified object in
- * this OrderedSet.
- *
- * @param obj the object, which must not be null
- * @return the index associated with the object
- * @throws IllegalArgumentException if the key is not in the pool
- *
- * @see #put
- */
- public int index(Object obj) {
- if (obj == null) {
- throw new NullPointerException();
- }
- int findIndex = findIndex(obj, elementKeys);
- int index = elementIndexes[findIndex];
- if (index == -1) {
- throw new IllegalArgumentException();
- }
- return index;
+ int findIndex = findIndex (obj, elementKeys);
+ int index = elementIndexes[findIndex];
+ if (index == -1) {
+ throw new IllegalArgumentException();
}
-
- /**
- * Associate the given object with the given index in this OrderedSet.
- * The object's index is not retrievable using index(Object).
- * But the object is retrievable using get(int index).
- * The index must not yet have been assigned.
- *
- * @param index the index of the object
- * @param obj the object to add
- *
- * @see #get
- * @see java.lang.Object#equals
- */
- public void put(int index, Object obj) {
- if (obj == null)
- throw new NullPointerException();
- if (orderedList.length <= index) {
- int[] newOrderedList = new int[orderedList.length * 2];
- System.arraycopy(orderedList, 0, newOrderedList, 0, elementCount);
- }
- if (orderedList[index] != null) {
- throw new IllegalArgumentException();
- }
- orderedList[index] = obj;
- if (index >= elementCount) {
- elementCount = index + 1;
- }
+ return index;
+}
+/**
+ * Associate the given object with the given index in this OrderedSet.
+ * The object's index is not retrievable using index(Object).
+ * But the object is retrievable using get(int index).
+ * The index must not yet have been assigned.
+ *
+ * @param index the index of the object
+ * @param obj the object to add
+ *
+ * @see #get
+ * @see java.lang.Object#equals
+ */
+public void put(int index, Object obj) {
+ if (obj == null) throw new NullPointerException ();
+ if (orderedList.length <= index) {
+ int[] newOrderedList = new int[orderedList.length*2];
+ System.arraycopy(orderedList, 0, newOrderedList, 0, elementCount);
}
-
- /**
- * Associate the given object with the next index in this OrderedSet.
- * If the object is already present, its index is unchanged. The object cannot be null.
- *
- * @param obj the object to add
- * @return the index associated with the specified obj
- *
- * @see #index
- * @see java.lang.Object#equals
- */
- public int put(Object obj) {
- if (obj == null)
- throw new NullPointerException();
- int index = findIndex(obj, elementKeys);
- int resultIndex = elementIndexes[index];
- if (resultIndex == -1) {
- int size = (int) (elementKeys.length * loadFactor + 1);
- if ((elementCount + 1) >= size) {
- rehash();
- index = findIndex(obj, elementKeys);
- }
- orderedList[elementCount] = elementKeys[index] = obj;
- return elementIndexes[index] = elementCount++;
- } else {
- return resultIndex;
- }
+ if (orderedList[index] != null) {
+ throw new IllegalArgumentException();
}
-
- /**
- * Increases the capacity of this OrderedSet. This method is sent when
- * the size of this OrderedSet exceeds the load factor.
- */
- protected void rehash() {
- Object key;
- int index, length = elementKeys.length << 1;
- Object[] newKeys = new Object[length];
- int[] newIndexes = new int[length];
- for (int i = length; --i >= 0;) {
- newIndexes[i] = -1;
- }
- for (int i = 0; i < elementKeys.length; i++) {
- if ((key = elementKeys[i]) != null) {
- index = findIndex(key, newKeys);
- newKeys[index] = key;
- newIndexes[index] = elementIndexes[i];
- }
+ orderedList[index] = obj;
+ if (index >= elementCount) {
+ elementCount = index + 1;
+ }
+}
+/**
+ * Associate the given object with the next index in this OrderedSet.
+ * If the object is already present, its index is unchanged. The object cannot be null.
+ *
+ * @param obj the object to add
+ * @return the index associated with the specified obj
+ *
+ * @see #index
+ * @see java.lang.Object#equals
+ */
+public int put (Object obj) {
+ if (obj == null) throw new NullPointerException ();
+ int index = findIndex (obj, elementKeys);
+ int resultIndex = elementIndexes [index];
+ if (resultIndex == -1) {
+ int size = (int)(elementKeys.length * loadFactor + 1);
+ if ((elementCount + 1) >= size) {
+ rehash ();
+ index = findIndex (obj, elementKeys);
}
- Object[] newOrdered = new Object[length];
- System.arraycopy(orderedList, 0, newOrdered, 0, elementCount);
- elementKeys = newKeys;
- elementIndexes = newIndexes;
- orderedList = newOrdered;
+ orderedList [elementCount] = elementKeys [index] = obj;
+ return elementIndexes [index] = elementCount++;
}
-
- /**
- * Answers the number of objects in this OrderedSet.
- *
- * @return the number of objects in this OrderedSet
- */
- public int size() {
- return elementCount;
+ else {
+ return resultIndex;
}
-
- /**
- * Answers the string representation of this OrderedSet.
- *
- * @return the string representation of this OrderedSet
- */
- public String toString() {
- Object key;
- StringBuffer buffer = new StringBuffer();
- buffer.append('{');
- for (int i = 0; i < elementCount; i++) {
- if (i != 0)
- buffer.append(',');
- if (buffer.length() > 1000) {
- buffer.append("...");
- break;
- }
- buffer.append(orderedList[i]);
- buffer.append('=');
- buffer.append(i);
+}
+/**
+ * Increases the capacity of this OrderedSet. This method is sent when
+ * the size of this OrderedSet exceeds the load factor.
+ */
+protected void rehash () {
+ Object key;
+ int index, length = elementKeys.length<<1;
+ Object [] newKeys = new Object [length];
+ int [] newIndexes = new int [length];
+ for (int i = length; --i >= 0; ) {
+ newIndexes[i] = -1;
+ }
+ for (int i=0; i<elementKeys.length; i++) {
+ if ((key = elementKeys [i]) != null) {
+ index = findIndex (key, newKeys);
+ newKeys [index] = key;
+ newIndexes [index] = elementIndexes [i];
}
- buffer.append('}');
- return buffer.toString();
}
-
+ Object [] newOrdered = new Object[length];
+ System.arraycopy(orderedList, 0, newOrdered, 0, elementCount);
+ elementKeys = newKeys;
+ elementIndexes = newIndexes;
+ orderedList = newOrdered;
+}
+/**
+ * Answers the number of objects in this OrderedSet.
+ *
+ * @return the number of objects in this OrderedSet
+ */
+public int size () {
+ return elementCount;
+}
+/**
+ * Answers the string representation of this OrderedSet.
+ *
+ * @return the string representation of this OrderedSet
+ */
+public String toString () {
+ Object key;
+ StringBuffer buffer = new StringBuffer ();
+ buffer.append ('{');
+ for (int i=0; i<elementCount; i++) {
+ if (i != 0) buffer.append (',');
+ if (buffer.length() > 1000) {
+ buffer.append("...");
+ break;
+ }
+ buffer.append (orderedList[i]);
+ buffer.append ('=');
+ buffer.append (i);
+ }
+ buffer.append ('}');
+ return buffer.toString ();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageElement.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageElement.java
index ad33830657..dc6fc5895e 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageElement.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageElement.java
@@ -15,48 +15,40 @@ public class PackageElement {
IPackage fPackage;
String fFileName;
boolean fIsSource;
- PackageElement(IPackage pkg, String fileName, boolean isSource) {
- fPackage = pkg;
- fFileName = fileName;
- fIsSource = isSource;
- }
-
+PackageElement(IPackage pkg, String fileName, boolean isSource) {
+ fPackage = pkg;
+ fFileName = fileName;
+ fIsSource = isSource;
+}
PackageElement(IPackage pkg, SourceEntry entry) {
fPackage = pkg;
fFileName = entry.getFileName();
fIsSource = entry.isSource();
}
-
public boolean equals(Object o) {
- if (this == o)
- return true;
- if (!(o instanceof PackageElement))
- return false;
+ if (this == o) return true;
+ if (!(o instanceof PackageElement)) return false;
PackageElement e = (PackageElement) o;
/* If filenames are equal, so is isSource flag.
*/
return this.fFileName.equals(e.fFileName) && fPackage.equals(e.fPackage);
}
-
/**
* Returns the 'file name'.
*/
public String getFileName() {
return fFileName;
}
-
/**
* Returns the package containing the package element.
*/
public IPackage getPackage() {
return fPackage;
}
-
public int hashCode() {
return fPackage.hashCode() * 17 + fFileName.hashCode();
}
-
/**
* Returns true if the source entry comes from a class file, otherwise
* returns false.
@@ -64,7 +56,6 @@ public class PackageElement {
public boolean isBinary() {
return !fIsSource;
}
-
/**
* Returns true if the source entry comes from a compilation unit, otherwise
* returns false.
@@ -72,9 +63,7 @@ public class PackageElement {
public boolean isSource() {
return fIsSource;
}
-
- public String toString() {
- return fPackage.isUnnamed() ? fFileName : fPackage.getName() + '/' + fFileName;
- }
-
+public String toString() {
+ return fPackage.isUnnamed() ? fFileName : fPackage.getName() + '/' + fFileName;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageImpl.java
index eac92556fe..176c8bf757 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageImpl.java
@@ -6,25 +6,22 @@ package org.eclipse.jdt.internal.core.builder.impl;
*/
import org.eclipse.jdt.internal.core.builder.*;
-public class PackageImpl
- extends NonStateSpecificHandleImpl
- implements IPackage {
+public class PackageImpl extends NonStateSpecificHandleImpl implements IPackage {
JavaDevelopmentContextImpl fDevelopmentContext;
String fName;
boolean fIsUnnamed;
public static final String DEFAULT_PACKAGE_PREFIX = "Default-";
- /**
- * Creates a new package
- * @param name of package
- * @param isUnnamed whether the package is unnamed
- */
- PackageImpl(JavaDevelopmentContextImpl ctx, String name, boolean isUnnamed) {
- fName = name;
- fIsUnnamed = isUnnamed;
- fDevelopmentContext = ctx;
- }
-
+/**
+ * Creates a new package
+ * @param name of package
+ * @param isUnnamed whether the package is unnamed
+ */
+PackageImpl(JavaDevelopmentContextImpl ctx, String name, boolean isUnnamed) {
+ fName = name;
+ fIsUnnamed = isUnnamed;
+ fDevelopmentContext = ctx;
+}
/**
* Appends the signature for this package to the given StringBuffer.
* If includeUnnamed is true, then the identifiers for unnamed packages
@@ -35,40 +32,36 @@ public class PackageImpl
if (includeUnnamed || !fIsUnnamed) {
sb.append(fName);
return true;
- } else {
+ }
+ else {
return false;
}
}
-
/**
* Compares this object against the specified object.
* Returns true if the objects are the same.
*/
public boolean equals(Object o) {
- if (this == o)
- return true;
- if (!(o instanceof PackageImpl))
- return false;
+ if (this == o) return true;
+ if (!(o instanceof PackageImpl)) return false;
PackageImpl pkg = (PackageImpl) o;
- return fName.equals(pkg.fName)
- && fIsUnnamed == pkg.fIsUnnamed
- && fDevelopmentContext.equals(pkg.fDevelopmentContext);
- }
-
- /**
- * Returns an array containing Type objects representing all
- * classes and interfaces in the package represented by this object.
- * This includes public and default (package) access top-level
- * classes, inner classes, and local inner classes.
- * Returns an array of length 0 if this package has no
- * classes or interfaces.
- * The Types are in no particular order.
- */
- public IType[] getAllClasses() throws NotPresentException {
- return nonStateSpecific(inCurrentState0().getAllClasses());
- }
-
+ return fName.equals(pkg.fName)
+ && fIsUnnamed == pkg.fIsUnnamed
+ && fDevelopmentContext.equals(pkg.fDevelopmentContext);
+ }
+/**
+ * Returns an array containing Type objects representing all
+ * classes and interfaces in the package represented by this object.
+ * This includes public and default (package) access top-level
+ * classes, inner classes, and local inner classes.
+ * Returns an array of length 0 if this package has no
+ * classes or interfaces.
+ * The Types are in no particular order.
+ */
+public IType[] getAllClasses() throws NotPresentException {
+ return nonStateSpecific(inCurrentState0().getAllClasses());
+}
/**
* Returns a handle representing the class or interface
* with the given name. The name is the VM class name,
@@ -81,157 +74,142 @@ public class PackageImpl
public IType getClassHandle(String name) {
return new ClassOrInterfaceHandleImpl(name, this);
}
-
- /**
- * Returns an array of Type objects representing all the classes
- * and interfaces declared as members of the package represented by
- * this object. This includes public and default (package) access
- * classes and interfaces declared as members of the package.
- * This does not include inner classes and interfaces.
- * Returns an array of length 0 if this package declares no classes
- * or interfaces as members.
- * The Types are in no particular order.
- */
- public IType[] getDeclaredClasses() throws NotPresentException {
- return nonStateSpecific(inCurrentState0().getDeclaredClasses());
- }
-
- /**
- * Return the internal representation of the development context that owns this object
- */
- JavaDevelopmentContextImpl getInternalDC() {
- return fDevelopmentContext;
- }
-
- /**
- * Returns the fully-qualified name of the package represented
- * by this object, as a String.
- * If the package is unnamed, returns the internal identifier
- * string of this unnamed packaged.
- * This is a handle-only method.
- */
- public String getName() {
- return fName;
- }
-
- /**
- * Returns an array of Package objects representing all other
- * packages which this package directly references.
- * This is the union of all packages directly referenced by all
- * classes and interfaces in this package, including packages
- * mentioned in import declarations.
- * <p>
- * A direct reference in source code is a use of a package's
- * name other than as a prefix of another package name.
- * For example, 'java.lang.Object' contains a direct reference
- * to the package 'java.lang', but not to the package 'java'.
- * Also note that every package that declares at least one type
- * contains a direct reference to java.lang in virtue of the
- * automatic import of java.lang.*.
- * The result does not include this package (so contrary to the note
- * above, the result for package java.lang does not include java.lang).
- * In other words, the result is non-reflexive and typically
- * non-transitive.
- * <p>
- * The resulting packages may or may not be present in the image,
- * since the classes and interfaces in this package may refer to missing
- * packages.
- * The resulting packages are in no particular order.
- */
- public IPackage[] getReferencedPackages() throws NotPresentException {
- return nonStateSpecific(inCurrentState0().getReferencedPackages());
- }
-
- /**
- * Returns an array of Package objects representing all packages
- * in the given image context which directly reference this package.
- * The result does not include this package.
- * In other words, the result is non-transitive and non-reflexive.
- * <p>
- * The intersection of all packages in the image and those in the
- * image context are considered, so the resulting packages are
- * guaranteed to be present in the image.
- * The resulting packages are in no particular order.
- */
- public IPackage[] getReferencingPackages(IImageContext context)
- throws NotPresentException {
- return nonStateSpecific(inCurrentState0().getReferencingPackages(context));
- }
-
- /**
- * Returns an array of SourceFragments describing the source package
- * fragments from which this built package is derived.
- * Returns an empty array if this package is not derived directly from source
- * (e.g. package com.oti.requiem.fictional).
- * The source coordinates in the results are set to #(1 0).
- */
- public ISourceFragment[] getSourceFragments() throws NotPresentException {
- return inCurrentState0().getSourceFragments();
- }
-
+/**
+ * Returns an array of Type objects representing all the classes
+ * and interfaces declared as members of the package represented by
+ * this object. This includes public and default (package) access
+ * classes and interfaces declared as members of the package.
+ * This does not include inner classes and interfaces.
+ * Returns an array of length 0 if this package declares no classes
+ * or interfaces as members.
+ * The Types are in no particular order.
+ */
+public IType[] getDeclaredClasses() throws NotPresentException {
+ return nonStateSpecific(inCurrentState0().getDeclaredClasses());
+}
+/**
+ * Return the internal representation of the development context that owns this object
+ */
+JavaDevelopmentContextImpl getInternalDC() {
+ return fDevelopmentContext;
+}
+/**
+ * Returns the fully-qualified name of the package represented
+ * by this object, as a String.
+ * If the package is unnamed, returns the internal identifier
+ * string of this unnamed packaged.
+ * This is a handle-only method.
+ */
+public String getName() {
+ return fName;
+}
+/**
+ * Returns an array of Package objects representing all other
+ * packages which this package directly references.
+ * This is the union of all packages directly referenced by all
+ * classes and interfaces in this package, including packages
+ * mentioned in import declarations.
+ * <p>
+ * A direct reference in source code is a use of a package's
+ * name other than as a prefix of another package name.
+ * For example, 'java.lang.Object' contains a direct reference
+ * to the package 'java.lang', but not to the package 'java'.
+ * Also note that every package that declares at least one type
+ * contains a direct reference to java.lang in virtue of the
+ * automatic import of java.lang.*.
+ * The result does not include this package (so contrary to the note
+ * above, the result for package java.lang does not include java.lang).
+ * In other words, the result is non-reflexive and typically
+ * non-transitive.
+ * <p>
+ * The resulting packages may or may not be present in the image,
+ * since the classes and interfaces in this package may refer to missing
+ * packages.
+ * The resulting packages are in no particular order.
+ */
+public IPackage[] getReferencedPackages() throws NotPresentException {
+ return nonStateSpecific(inCurrentState0().getReferencedPackages());
+}
+/**
+ * Returns an array of Package objects representing all packages
+ * in the given image context which directly reference this package.
+ * The result does not include this package.
+ * In other words, the result is non-transitive and non-reflexive.
+ * <p>
+ * The intersection of all packages in the image and those in the
+ * image context are considered, so the resulting packages are
+ * guaranteed to be present in the image.
+ * The resulting packages are in no particular order.
+ */
+public IPackage[] getReferencingPackages(IImageContext context) throws NotPresentException
+{
+ return nonStateSpecific(inCurrentState0().getReferencingPackages(context));
+}
+/**
+ * Returns an array of SourceFragments describing the source package
+ * fragments from which this built package is derived.
+ * Returns an empty array if this package is not derived directly from source
+ * (e.g. package com.oti.requiem.fictional).
+ * The source coordinates in the results are set to #(1 0).
+ */
+public ISourceFragment[] getSourceFragments() throws NotPresentException {
+ return inCurrentState0().getSourceFragments();
+}
/**
* Returns a consistent hash code for this object
*/
public int hashCode() {
return fName.hashCode();
}
-
/**
* Returns a state-specific version of this handle in the current state
*/
private PackageImplSWH inCurrentState0() {
return new PackageImplSWH(fDevelopmentContext.fCurrentState, this);
}
-
/**
* Returns a state specific version of this handle in the given state.
*/
- public IHandle inState(IState s)
- throws org.eclipse.jdt.internal.core.builder.StateSpecificException {
+ public IHandle inState(IState s) throws org.eclipse.jdt.internal.core.builder.StateSpecificException {
return new PackageImplSWH((StateImpl) s, this);
}
-
- /**
- * Returns true if this package is an unnamed package, false
- * otherwise. See <em>The Java Language Specification</em>,
- * sections 7.4.1 and 7.4.2, for details.
- * This is a handle-only method.
- */
- public boolean isUnnamed() {
- return fIsUnnamed;
- }
-
+/**
+ * Returns true if this package is an unnamed package, false
+ * otherwise. See <em>The Java Language Specification</em>,
+ * sections 7.4.1 and 7.4.2, for details.
+ * This is a handle-only method.
+ */
+public boolean isUnnamed() {
+ return fIsUnnamed;
+}
/**
* Returns a constant indicating what kind of handle this is.
*/
public int kind() {
return K_JAVA_PACKAGE;
}
-
- /**
- * Returns the readable name for the given package,
- * suitable for use in progress messages.
- */
- public static String readableName(IPackage pkg) {
- String name = pkg.getName();
- if (pkg.isUnnamed()) {
- return "default package for " + name.substring(DEFAULT_PACKAGE_PREFIX.length());
- } else {
- return "package " + name;
- }
+/**
+ * Returns the readable name for the given package,
+ * suitable for use in progress messages.
+ */
+public static String readableName(IPackage pkg) {
+ String name = pkg.getName();
+ if (pkg.isUnnamed()) {
+ return "default package for " + name.substring(DEFAULT_PACKAGE_PREFIX.length());
+ } else {
+ return "package " + name;
}
-
+}
/**
* Returns a string representation of the package. For debugging purposes
* only (NON-NLS).
*/
public String toString() {
String result = "package ";
- if (isUnnamed())
+ if (isUnnamed())
result += "{unnamed, id=" + getName() + "}";
else
result += getName();
return result;
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageImplSWH.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageImplSWH.java
index 730634e451..79dc190a12 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageImplSWH.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageImplSWH.java
@@ -10,21 +10,16 @@ import org.eclipse.jdt.internal.core.builder.*;
import java.util.*;
-public class PackageImplSWH
- extends StateSpecificHandleImpl
- implements IPackage {
+public class PackageImplSWH extends StateSpecificHandleImpl implements IPackage {
PackageImpl fHandle;
/**
* Internal - Create a new Package
*/
- PackageImplSWH(StateImpl state, PackageImpl handle)
- throws NotPresentException {
- if (state == null)
- throw new NotPresentException();
+ PackageImplSWH(StateImpl state, PackageImpl handle) throws NotPresentException {
+ if (state == null) throw new NotPresentException();
fState = state;
fHandle = handle;
}
-
/**
* Returns an array containing Type objects representing all
* classes and interfaces in the package represented by this object.
@@ -43,102 +38,97 @@ public class PackageImplSWH
}
IType[] results = new IType[entries.length];
for (int i = 0, num = entries.length; i < num; ++i) {
- results[i] = (IType) entries[i].getType().inState(fState);
+ results[i] = (IType)entries[i].getType().inState(fState);
}
return results;
}
-
- /**
- * getClassHandle method comment.
- * Returns a handle representing the class or interface
- * with the given name. The name is the VM class name,
- * not including the package name.
- * For inner classes, the name is as described in the
- * <em>Inner Classes Specification</em>.
- * This is a handle-only method; the specified class
- * may or may not actually be present in the image.
- */
- public IType getClassHandle(String name) {
- return (IType) fHandle.getClassHandle(name).inState(fState);
+/**
+ * getClassHandle method comment.
+ * Returns a handle representing the class or interface
+ * with the given name. The name is the VM class name,
+ * not including the package name.
+ * For inner classes, the name is as described in the
+ * <em>Inner Classes Specification</em>.
+ * This is a handle-only method; the specified class
+ * may or may not actually be present in the image.
+ */
+public IType getClassHandle(String name) {
+ return (IType)fHandle.getClassHandle(name).inState(fState);
+}
+/**
+ * Returns an array of Type objects representing all the classes
+ * and interfaces declared as members of the package represented by
+ * this object. This includes public and default (package) access
+ * classes and interfaces declared as members of the package.
+ * This does not include inner classes and interfaces.
+ * Returns an array of length 0 if this package declares no classes
+ * or interfaces as members.
+ * The Types are in no particular order.
+ */
+public IType[] getDeclaredClasses() throws NotPresentException {
+ TypeStructureEntry[] entries = fState.getAllTypesForPackage(fHandle);
+ if (entries == null) {
+ throw new NotPresentException();
}
-
- /**
- * Returns an array of Type objects representing all the classes
- * and interfaces declared as members of the package represented by
- * this object. This includes public and default (package) access
- * classes and interfaces declared as members of the package.
- * This does not include inner classes and interfaces.
- * Returns an array of length 0 if this package declares no classes
- * or interfaces as members.
- * The Types are in no particular order.
- */
- public IType[] getDeclaredClasses() throws NotPresentException {
- TypeStructureEntry[] entries = fState.getAllTypesForPackage(fHandle);
- if (entries == null) {
- throw new NotPresentException();
- }
- int num = entries.length;
- IType[] results = new IType[num];
- int count = 0;
- for (int i = 0; i < num; ++i) {
- if (BinaryStructure.isPackageMember(fState.getBinaryType(entries[i]))) {
- results[count++] = (IType) entries[i].getType().inState(fState);
- }
+ int num = entries.length;
+ IType[] results = new IType[num];
+ int count = 0;
+ for (int i = 0; i < num; ++i) {
+ if (BinaryStructure.isPackageMember(fState.getBinaryType(entries[i]))) {
+ results[count++] = (IType) entries[i].getType().inState(fState);
}
- if (count < num) {
- System.arraycopy(results, 0, results = new IType[count], 0, count);
- }
- return results;
}
-
- /**
- * Returns the fully-qualified name of the package represented
- * by this object, as a String.
- * If the package is unnamed, returns the internal identifier
- * string of this unnamed packaged.
- * This is a handle-only method.
- */
- public String getName() {
- return fHandle.getName();
+ if (count < num) {
+ System.arraycopy(results, 0, results = new IType[count], 0, count);
}
-
- /**
- * Returns an array of Package objects representing all other
- * packages which this package directly references.
- * This is the union of all packages directly referenced by all
- * classes and interfaces in this package, including packages
- * mentioned in import declarations.
- * <p>
- * A direct reference in source code is a use of a package's
- * name other than as a prefix of another package name.
- * For example, 'java.lang.Object' contains a direct reference
- * to the package 'java.lang', but not to the package 'java'.
- * Also note that every package that declares at least one type
- * contains a direct reference to java.lang in virtue of the
- * automatic import of java.lang.*.
- * The result does not include this package (so contrary to the note
- * above, the result for package java.lang does not include java.lang).
- * In other words, the result is non-reflexive and typically
- * non-transitive.
- * <p>
- * The resulting packages may or may not be present in the image,
- * since the classes and interfaces in this package may refer to missing
- * packages.
- * The resulting packages are in no particular order.
- */
- public IPackage[] getReferencedPackages() throws NotPresentException {
- if (!isPresent())
- throw new NotPresentException();
- IPackage[] pkgs = fState.getReferencedPackages((IPackage) nonStateSpecific());
-
- /* wrapped returned packages in state handles */
- for (int i = 0; i < pkgs.length; i++) {
- pkgs[i] = (IPackage) pkgs[i].inState(fState);
- }
- return pkgs;
-
+ return results;
+}
+/**
+ * Returns the fully-qualified name of the package represented
+ * by this object, as a String.
+ * If the package is unnamed, returns the internal identifier
+ * string of this unnamed packaged.
+ * This is a handle-only method.
+ */
+public String getName() {
+ return fHandle.getName();
+}
+/**
+ * Returns an array of Package objects representing all other
+ * packages which this package directly references.
+ * This is the union of all packages directly referenced by all
+ * classes and interfaces in this package, including packages
+ * mentioned in import declarations.
+ * <p>
+ * A direct reference in source code is a use of a package's
+ * name other than as a prefix of another package name.
+ * For example, 'java.lang.Object' contains a direct reference
+ * to the package 'java.lang', but not to the package 'java'.
+ * Also note that every package that declares at least one type
+ * contains a direct reference to java.lang in virtue of the
+ * automatic import of java.lang.*.
+ * The result does not include this package (so contrary to the note
+ * above, the result for package java.lang does not include java.lang).
+ * In other words, the result is non-reflexive and typically
+ * non-transitive.
+ * <p>
+ * The resulting packages may or may not be present in the image,
+ * since the classes and interfaces in this package may refer to missing
+ * packages.
+ * The resulting packages are in no particular order.
+ */
+public IPackage[] getReferencedPackages() throws NotPresentException {
+ if (!isPresent())
+ throw new NotPresentException();
+ IPackage[] pkgs = fState.getReferencedPackages((IPackage)nonStateSpecific());
+
+ /* wrapped returned packages in state handles */
+ for (int i = 0; i < pkgs.length; i++) {
+ pkgs[i] = (IPackage) pkgs[i].inState(fState);
}
-
+ return pkgs;
+
+}
/**
* Returns an array of Package objects representing all packages
* in the given image context which directly reference this package.
@@ -150,8 +140,8 @@ public class PackageImplSWH
* guaranteed to be present in the image.
* The resulting packages are in no particular order.
*/
- public IPackage[] getReferencingPackages(IImageContext context)
- throws NotPresentException {
+ public IPackage[] getReferencingPackages(IImageContext context)
+ throws NotPresentException {
if (!isPresent())
throw new NotPresentException("Not present");
@@ -159,56 +149,51 @@ public class PackageImplSWH
/* wrap packages in state */
for (int i = 0; i < pkgs.length; i++) {
- pkgs[i] = (IPackage) pkgs[i].inState(fState);
+ pkgs[i] = (IPackage)pkgs[i].inState(fState);
}
return pkgs;
}
+/**
+ * Returns an array of SourceFragments describing the source package
+ * fragments from which this built package is derived.
+ * Returns an empty array if this package is not derived directly from source
+ * The source coordinates in the results are set to #(-1, -1).
+ *
+ * If this is a default package, we must resolve the project name from the
+ * internal identifier
+ */
+public ISourceFragment[] getSourceFragments() throws NotPresentException {
- /**
- * Returns an array of SourceFragments describing the source package
- * fragments from which this built package is derived.
- * Returns an empty array if this package is not derived directly from source
- * The source coordinates in the results are set to #(-1, -1).
- *
- * If this is a default package, we must resolve the project name from the
- * internal identifier
- */
- public ISourceFragment[] getSourceFragments() throws NotPresentException {
-
- IPath[] paths = fState.getPackageMap().getFragments(fHandle);
- if (paths == null) {
- throw new NotPresentException();
- }
- int max = paths.length;
- ISourceFragment[] frags = new ISourceFragment[max];
- for (int i = 0; i < max; i++) {
- frags[i] = new SourceFragmentImpl(-1, -1, paths[i]);
- }
- return frags;
- }
-
- /**
- * isPresent method comment.
- */
- public boolean isPresent() {
- return fState.getPackageMap().containsPackage(fHandle);
+ IPath[] paths = fState.getPackageMap().getFragments(fHandle);
+ if (paths == null) {
+ throw new NotPresentException();
}
-
- /**
- * Returns true if this package is an unnamed package, false
- * otherwise. See <em>The Java Language Specification</em>,
- * sections 7.4.1 and 7.4.2, for details.
- * This is a handle-only method.
- */
- public boolean isUnnamed() {
- return fHandle.isUnnamed();
+ int max = paths.length;
+ ISourceFragment[] frags = new ISourceFragment[max];
+ for (int i = 0; i < max; i++) {
+ frags[i] = new SourceFragmentImpl(-1, -1, paths[i]);
}
-
+ return frags;
+}
+/**
+ * isPresent method comment.
+ */
+public boolean isPresent() {
+ return fState.getPackageMap().containsPackage(fHandle);
+}
+/**
+ * Returns true if this package is an unnamed package, false
+ * otherwise. See <em>The Java Language Specification</em>,
+ * sections 7.4.1 and 7.4.2, for details.
+ * This is a handle-only method.
+ */
+public boolean isUnnamed() {
+ return fHandle.isUnnamed();
+}
/**
* Returns the non state specific handle
*/
- public IHandle nonStateSpecific() {
- return fHandle;
- }
-
+ public IHandle nonStateSpecific() {
+ return fHandle;
+ }
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageMap.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageMap.java
index c7623428d8..47d23f4e63 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageMap.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageMap.java
@@ -19,7 +19,6 @@ public class PackageMap extends StateTables {
PackageMap() {
fTable = new Hashtable(23);
}
-
/**
* Returns true if the package exists in the state, otherwise
* returns false
@@ -27,7 +26,6 @@ public class PackageMap extends StateTables {
boolean containsPackage(IPackage pkg) {
return fTable.containsKey(pkg);
}
-
/**
* Creates a copy of the package map.
*/
@@ -36,12 +34,12 @@ public class PackageMap extends StateTables {
PackageMap copy = (PackageMap) super.clone();
copy.fTable = (Hashtable) fTable.clone();
return copy;
- } catch (CloneNotSupportedException e) {
+ }
+ catch (CloneNotSupportedException e) {
// Should not happen.
throw new Error();
}
}
-
/**
* Returns an enumeration of all packages in the state. The enumeration
* is of non state-specific package handles.
@@ -49,7 +47,6 @@ public class PackageMap extends StateTables {
public Enumeration getAllPackages() {
return fTable.keys();
}
-
/**
* Returns all packages in the state. The result is an array
* of non state-specific package handles.
@@ -62,58 +59,52 @@ public class PackageMap extends StateTables {
}
return pkgs;
}
-
/**
* Returns the package map entry for a given package.
* Returns null if the package is not present.
*/
PackageMapEntry getEntry(IPackage pkg) {
- return (PackageMapEntry) fTable.get(pkg);
+ return (PackageMapEntry)fTable.get(pkg);
}
-
/**
* Returns the package fragments for a given package. The returned
* fragments are sorted according to the class path.
* Returns null if the package is not present.
*/
IPath[] getFragments(IPackage pkg) {
- PackageMapEntry entry = (PackageMapEntry) fTable.get(pkg);
+ PackageMapEntry entry = (PackageMapEntry)fTable.get(pkg);
return entry == null ? null : entry.getFragments();
}
-
/**
* Adds a fragment entry for the given package.
* Mutable operation, should only be used when recreating package map.
*/
void putFragment(IPackage pkg, IPath frag) {
- PackageMapEntry entry = (PackageMapEntry) fTable.get(pkg);
+ PackageMapEntry entry = (PackageMapEntry)fTable.get(pkg);
if (entry == null) {
entry = new PackageMapEntry(pkg);
fTable.put(pkg, entry);
}
entry.addFragment(frag);
}
-
/**
* Adds an array of fragments for the given package. Assumes that the
* given array of fragments are in classpath order.
*/
void putFragments(IPackage pkg, IPath[] frags) {
- PackageMapEntry entry = (PackageMapEntry) fTable.get(pkg);
+ PackageMapEntry entry = (PackageMapEntry)fTable.get(pkg);
if (entry == null) {
entry = new PackageMapEntry(pkg);
fTable.put(pkg, entry);
}
entry.addFragments(frags);
}
-
/**
* Returns the number of packages in the state.
*/
int size() {
return fTable.size();
}
-
/**
* For debugging only.
*/
@@ -126,13 +117,11 @@ public class PackageMap extends StateTables {
sb.append(" " + pkgs[i].getName() + ": ");
IPath[] fragments = getFragments(pkgs[i]);
for (int j = 0; j < fragments.length; ++j) {
- if (j != 0)
- sb.append(", ");
+ if (j != 0) sb.append(", ");
sb.append(fragments[j]);
}
sb.append("\n");
}
return sb.toString();
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageMapEntry.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageMapEntry.java
index 231d5177e0..8c5fdbb0b1 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageMapEntry.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PackageMapEntry.java
@@ -23,29 +23,25 @@ class PackageMapEntry extends StateTables {
fPkg = pkg;
fFragments = null;
}
-
- /**
- * Adds a new package fragment to the entry.
- */
- void addFragment(IPath fragment) {
- if (fFragments == null) {
- fFragments = new IPath[] { fragment };
- } else {
- for (int i = 0; i < fFragments.length; ++i) {
- if (fFragments[i].equals(fragment)) {
- System.out.println(
- "Warning: internal error: attempt to add duplicate package fragment in image builder: "
- + fragment);
- return;
- }
+/**
+ * Adds a new package fragment to the entry.
+ */
+void addFragment(IPath fragment) {
+ if (fFragments == null) {
+ fFragments = new IPath[] {fragment};
+ } else {
+ for (int i = 0; i < fFragments.length; ++i) {
+ if (fFragments[i].equals(fragment)) {
+ System.out.println("Warning: internal error: attempt to add duplicate package fragment in image builder: " + fragment);
+ return;
}
- IPath[] newFragments = new IPath[fFragments.length + 1];
- System.arraycopy(fFragments, 0, newFragments, 0, fFragments.length);
- newFragments[fFragments.length] = fragment;
- fFragments = newFragments;
}
+ IPath[] newFragments = new IPath[fFragments.length + 1];
+ System.arraycopy(fFragments, 0, newFragments, 0, fFragments.length);
+ newFragments[fFragments.length] = fragment;
+ fFragments = newFragments;
}
-
+}
/**
* Adds a new package fragment to the entry.
*/
@@ -53,33 +49,26 @@ class PackageMapEntry extends StateTables {
if (fFragments == null) {
fFragments = new IPath[fragments.length];
System.arraycopy(fragments, 0, fFragments, 0, fragments.length);
- } else {
+ }
+ else {
IPath[] newFragments = new IPath[fFragments.length + fragments.length];
System.arraycopy(fFragments, 0, newFragments, 0, fFragments.length);
- System.arraycopy(
- fragments,
- 0,
- newFragments,
- fFragments.length,
- fragments.length);
+ System.arraycopy(fragments, 0, newFragments, fFragments.length, fragments.length);
fFragments = newFragments;
}
}
-
/**
* Returns an the fragments in the package
*/
IPath[] getFragments() {
return fFragments;
}
-
/**
* Returns the package for which this is the entry.
*/
IPackage getPackage() {
return fPkg;
}
-
/**
* Returns a String that represents the value of this object.
* This method is for debugging purposes only.
@@ -90,5 +79,4 @@ class PackageMapEntry extends StateTables {
buf.append(")");
return buf.toString();
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PathMap.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PathMap.java
index d309b57536..6959bd807b 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PathMap.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PathMap.java
@@ -30,49 +30,44 @@ class PathMap extends StateTables {
PathMap(PackageMap pkgMap) {
fTable = packageMapToPathMap(pkgMap);
}
-
- /**
- * Returns the paths which are the keys in the path map.
- */
- IPath[] getPaths() {
- IPath[] paths = new IPath[fTable.size()];
- int count = 0;
- for (Enumeration e = fTable.keys(); e.hasMoreElements();) {
- paths[count++] = (IPath) e.nextElement();
- }
- return paths;
- }
-
- /**
- * Returns whether the path map contains the given path as a key.
- */
- boolean hasPath(IPath path) {
- return fTable.get(path) != null;
+/**
+ * Returns the paths which are the keys in the path map.
+ */
+IPath[] getPaths() {
+ IPath[] paths = new IPath[fTable.size()];
+ int count = 0;
+ for (Enumeration e = fTable.keys(); e.hasMoreElements();) {
+ paths[count++] = (IPath) e.nextElement();
}
-
- /**
- * Returns the package handle for the given package resource.
- * Throws an internal error if the path was inappropriate.
- */
- IPackage packageHandleFromPath(IPath path) {
- IPackage[] pkgs = (IPackage[]) fTable.get(path);
- if (pkgs == null) {
- throw new Error("Attempt to access packages for non-existent path:" + path);
- }
- if (pkgs.length != 1) {
- throw new Error("Didn't get exactly one package for " + path);
- }
- return pkgs[0];
+ return paths;
+}
+/**
+ * Returns whether the path map contains the given path as a key.
+ */
+boolean hasPath(IPath path) {
+ return fTable.get(path) != null;
+}
+/**
+ * Returns the package handle for the given package resource.
+ * Throws an internal error if the path was inappropriate.
+ */
+IPackage packageHandleFromPath(IPath path) {
+ IPackage[] pkgs = (IPackage[])fTable.get(path);
+ if (pkgs == null) {
+ throw new Error("Attempt to access packages for non-existent path:" + path);
}
-
- /**
- * Returns the package handles for the given package resource.
- */
- IPackage[] packageHandlesFromPath(IPath path) {
- IPackage[] pkgs = (IPackage[]) fTable.get(path);
- return pkgs != null ? pkgs : new IPackage[0];
+ if (pkgs.length != 1) {
+ throw new Error("Didn't get exactly one package for " + path);
}
-
+ return pkgs[0];
+}
+/**
+ * Returns the package handles for the given package resource.
+ */
+IPackage[] packageHandlesFromPath(IPath path) {
+ IPackage[] pkgs = (IPackage[]) fTable.get(path);
+ return pkgs != null ? pkgs : new IPackage[0];
+}
/**
* Creates and returns new path map given a package map. The package map is
* from IPackage -> IPath[]. The new path map is from IPath -> IPackage[]
@@ -82,12 +77,12 @@ class PathMap extends StateTables {
/* first generate a path map using vectors */
for (Enumeration e = pkgMap.getAllPackages(); e.hasMoreElements();) {
- IPackage pkg = (IPackage) e.nextElement();
+ IPackage pkg = (IPackage)e.nextElement();
IPath[] paths = pkgMap.getFragments(pkg);
/* add entries in the path map for each fragment */
for (int i = 0; i < paths.length; i++) {
- Vector v = (Vector) table.get(paths[i]);
+ Vector v = (Vector)table.get(paths[i]);
if (v == null) {
/* most common case is one path per package */
v = new Vector(1);
@@ -99,15 +94,14 @@ class PathMap extends StateTables {
/* convert vectors to arrays */
for (Enumeration e = table.keys(); e.hasMoreElements();) {
- IPath path = (IPath) e.nextElement();
- Vector v = (Vector) table.get(path);
+ IPath path = (IPath)e.nextElement();
+ Vector v = (Vector)table.get(path);
IPackage[] pkgs = new IPackage[v.size()];
v.copyInto(pkgs);
table.put(path, pkgs);
}
return table;
}
-
/**
* For debugging only.
*/
@@ -126,7 +120,8 @@ class PathMap extends StateTables {
IPackage[] pkgs = packageHandlesFromPath(path);
if (pkgs.length == 1) {
sb.append(pkgs[0].getName());
- } else {
+ }
+ else {
Arrays.sort(pkgs, StateImpl.getPackageComparator());
sb.append("(" + pkgs.length + " packages)");
for (int j = 0; j < pkgs.length; ++j) {
@@ -138,5 +133,4 @@ class PathMap extends StateTables {
}
return sb.toString();
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PrimitiveTypeHandleImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PrimitiveTypeHandleImpl.java
index aedc255e67..d388f182cb 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PrimitiveTypeHandleImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PrimitiveTypeHandleImpl.java
@@ -16,213 +16,198 @@ public class PrimitiveTypeHandleImpl extends TypeImpl implements IType {
/*
* Type codes
*/
- static final int TC_BOOLEAN = 0;
- static final int TC_BYTE = 1;
- static final int TC_CHAR = 2;
- static final int TC_SHORT = 3;
- static final int TC_INT = 4;
- static final int TC_LONG = 5;
- static final int TC_FLOAT = 6;
- static final int TC_DOUBLE = 7;
- static final int TC_ARRAY = 9;
- static final int TC_CLASS = 10;
- static final int TC_VOID = 11;
- /**
- * Creates a new primitive type with the given type code
- */
- PrimitiveTypeHandleImpl(JavaDevelopmentContextImpl dc, char typeCode) {
- fDevelopmentContext = dc;
- switch (typeCode) {
- case 'I' :
- fTypeCode = TC_INT;
- break;
- case 'F' :
- fTypeCode = TC_FLOAT;
- break;
- case 'V' :
- fTypeCode = TC_VOID;
- break;
- case 'Z' :
- fTypeCode = TC_BOOLEAN;
- break;
- case 'B' :
- fTypeCode = TC_BYTE;
- break;
- case 'S' :
- fTypeCode = TC_SHORT;
- break;
- case 'C' :
- fTypeCode = TC_CHAR;
- break;
- case 'J' :
- fTypeCode = TC_LONG;
- break;
- case 'D' :
- fTypeCode = TC_DOUBLE;
- break;
- }
+ static final int TC_BOOLEAN = 0;
+ static final int TC_BYTE = 1;
+ static final int TC_CHAR = 2;
+ static final int TC_SHORT = 3;
+ static final int TC_INT = 4;
+ static final int TC_LONG = 5;
+ static final int TC_FLOAT = 6;
+ static final int TC_DOUBLE = 7;
+ static final int TC_ARRAY = 9;
+ static final int TC_CLASS = 10;
+ static final int TC_VOID = 11;
+/**
+ * Creates a new primitive type with the given type code
+ */
+PrimitiveTypeHandleImpl(JavaDevelopmentContextImpl dc, char typeCode) {
+ fDevelopmentContext = dc;
+ switch (typeCode) {
+ case 'I' :
+ fTypeCode = TC_INT;
+ break;
+ case 'F' :
+ fTypeCode = TC_FLOAT;
+ break;
+ case 'V' :
+ fTypeCode = TC_VOID;
+ break;
+ case 'Z' :
+ fTypeCode = TC_BOOLEAN;
+ break;
+ case 'B' :
+ fTypeCode = TC_BYTE;
+ break;
+ case 'S' :
+ fTypeCode = TC_SHORT;
+ break;
+ case 'C' :
+ fTypeCode = TC_CHAR;
+ break;
+ case 'J' :
+ fTypeCode = TC_LONG;
+ break;
+ case 'D' :
+ fTypeCode = TC_DOUBLE;
+ break;
}
-
- /**
- * Appends the signature for this type to the StringBuffer
- * If includeUnnamed is true, then the identifiers for unnamed packages
- * are included, preceded by '$'. Otherwise, they are excluded.
- */
- void appendSignature(StringBuffer sb, boolean includeUnnamed) {
- char sig;
- switch (fTypeCode) {
- case TC_BOOLEAN :
- sig = 'Z';
- break;
- case TC_BYTE :
- sig = 'B';
- break;
- case TC_CHAR :
- sig = 'C';
- break;
- case TC_DOUBLE :
- sig = 'D';
- break;
- case TC_FLOAT :
- sig = 'F';
- break;
- case TC_INT :
- sig = 'I';
- break;
- case TC_LONG :
- sig = 'J';
- break;
- case TC_SHORT :
- sig = 'S';
- break;
- case TC_VOID :
- sig = 'V';
- break;
- default :
- Assert.isTrue(false, "invalid type code");
- sig = ' ';
- }
- sb.append(sig);
+}
+/**
+ * Appends the signature for this type to the StringBuffer
+ * If includeUnnamed is true, then the identifiers for unnamed packages
+ * are included, preceded by '$'. Otherwise, they are excluded.
+ */
+void appendSignature(StringBuffer sb, boolean includeUnnamed) {
+ char sig;
+ switch (fTypeCode) {
+ case TC_BOOLEAN :
+ sig = 'Z';
+ break;
+ case TC_BYTE :
+ sig = 'B';
+ break;
+ case TC_CHAR :
+ sig = 'C';
+ break;
+ case TC_DOUBLE :
+ sig = 'D';
+ break;
+ case TC_FLOAT :
+ sig = 'F';
+ break;
+ case TC_INT :
+ sig = 'I';
+ break;
+ case TC_LONG :
+ sig = 'J';
+ break;
+ case TC_SHORT :
+ sig = 'S';
+ break;
+ case TC_VOID :
+ sig = 'V';
+ break;
+ default :
+ Assert.isTrue(false, "invalid type code");
+ sig = ' ';
}
-
+ sb.append(sig);
+}
/**
* Appends the VM signature of the type to the StringBuffer.
*/
void appendVMSignature(StringBuffer sb) {
sb.append(typeSignature(fTypeCode));
}
-
/**
* Compares this object against the specified object.
* Returns true if the objects are the same.
*/
public boolean equals(Object o) {
- if (this == o)
- return true;
- if (!(o instanceof PrimitiveTypeHandleImpl))
- return false;
+ if (this == o) return true;
+ if (!(o instanceof PrimitiveTypeHandleImpl)) return false;
PrimitiveTypeHandleImpl prim = (PrimitiveTypeHandleImpl) o;
- return fTypeCode == prim.fTypeCode
- && fDevelopmentContext.equals(prim.fDevelopmentContext);
- }
-
- public JavaDevelopmentContextImpl getInternalDC() {
- return fDevelopmentContext;
- }
-
- /**
- * Returns the fully-qualified name of the type (class, interface,
- * array, or primitive) represented by this object, as a String.
- * For classes and interfaces, the name is the VM class name,
- * including the package name.
- * For inner classes, the name is as described in the
- * <em>Inner Classes Specification</em>.
- * For array types, the name is the name of the component type, followed by '[]'.
- * For primitive types, the name is the keyword for the primitive type.
- * This is a handle-only method.
- */
- public String getName() {
- return getSimpleName();
+ return fTypeCode == prim.fTypeCode &&
+ fDevelopmentContext.equals(prim.fDevelopmentContext);
}
-
- /**
- * Returns the simple name of the type (class, interface, array,
- * or primitive) represented by this object, as a String.
- * For classes and interfaces, this is the VM class name,
- * excluding the package name.
- * For array types, this is the simple name of the component type, followed by '[]'.
- * For primitive types, this is the keyword for the primitive type.
- * This is a handle-only method.
- */
- public String getSimpleName() {
- switch (fTypeCode) {
- case TC_BOOLEAN :
- return "boolean";
- case TC_BYTE :
- return "byte";
- case TC_CHAR :
- return "char";
- case TC_DOUBLE :
- return "double";
- case TC_FLOAT :
- return "float";
- case TC_INT :
- return "int";
- case TC_LONG :
- return "long";
- case TC_SHORT :
- return "short";
- case TC_VOID :
- return "void";
- default :
- Assert.isTrue(false, "invalid type code");
- }
- return null;
+public JavaDevelopmentContextImpl getInternalDC() {
+ return fDevelopmentContext;
+}
+/**
+ * Returns the fully-qualified name of the type (class, interface,
+ * array, or primitive) represented by this object, as a String.
+ * For classes and interfaces, the name is the VM class name,
+ * including the package name.
+ * For inner classes, the name is as described in the
+ * <em>Inner Classes Specification</em>.
+ * For array types, the name is the name of the component type, followed by '[]'.
+ * For primitive types, the name is the keyword for the primitive type.
+ * This is a handle-only method.
+ */
+public String getName() {
+ return getSimpleName();
+}
+/**
+ * Returns the simple name of the type (class, interface, array,
+ * or primitive) represented by this object, as a String.
+ * For classes and interfaces, this is the VM class name,
+ * excluding the package name.
+ * For array types, this is the simple name of the component type, followed by '[]'.
+ * For primitive types, this is the keyword for the primitive type.
+ * This is a handle-only method.
+ */
+public String getSimpleName() {
+ switch (fTypeCode) {
+ case TC_BOOLEAN :
+ return "boolean";
+ case TC_BYTE :
+ return "byte";
+ case TC_CHAR :
+ return "char";
+ case TC_DOUBLE :
+ return "double";
+ case TC_FLOAT :
+ return "float";
+ case TC_INT :
+ return "int";
+ case TC_LONG :
+ return "long";
+ case TC_SHORT :
+ return "short";
+ case TC_VOID :
+ return "void";
+ default :
+ Assert.isTrue(false, "invalid type code");
}
-
+ return null;
+}
int getTypeCode() {
return fTypeCode;
}
-
/**
* Returns the VM signature of the type.
*/
String getVMSignature() {
return typeSignature(fTypeCode);
}
-
/**
* Returns a consistent hash code for this object
*/
public int hashCode() {
return fTypeCode;
}
-
- /**
- * Returns a state specific version of this handle in the given state.
- */
- public IHandle inState(IState s)
- throws org.eclipse.jdt.internal.core.builder.StateSpecificException {
-
- return new PrimitiveTypeHandleImplSWH((StateImpl) s, this);
- }
-
- /**
- * Determines if the specified Type object represents a primitive Java
- * type.
- * This is a handle-only method.
- *
- * <p>There are nine predefined Type objects to represent the eight
- * primitive Java types and void. These are created by the Java
- * Virtual Machine, and have the same names as the primitive types
- * that they represent, namely boolean, byte, char, short, int,
- * long, float, and double, and void.
- */
- public boolean isPrimitive() {
- return true;
- }
-
+/**
+ * Returns a state specific version of this handle in the given state.
+ */
+public IHandle inState(IState s) throws org.eclipse.jdt.internal.core.builder.StateSpecificException {
+
+ return new PrimitiveTypeHandleImplSWH((StateImpl) s, this);
+}
+/**
+ * Determines if the specified Type object represents a primitive Java
+ * type.
+ * This is a handle-only method.
+ *
+ * <p>There are nine predefined Type objects to represent the eight
+ * primitive Java types and void. These are created by the Java
+ * Virtual Machine, and have the same names as the primitive types
+ * that they represent, namely boolean, byte, char, short, int,
+ * long, float, and double, and void.
+ */
+public boolean isPrimitive() {
+ return true;
+}
/**
* Returns a string representation of the package. For debugging purposes
* only (NON-NLS).
@@ -230,33 +215,31 @@ public class PrimitiveTypeHandleImpl extends TypeImpl implements IType {
public String toString() {
return getName();
}
-
- /**
- * Convert a base type code to the VM naming format
- */
- protected static String typeSignature(int typeCode) {
- switch (typeCode) {
- case TC_VOID :
- return "V";
- case TC_BOOLEAN :
- return "Z";
- case TC_BYTE :
- return "B";
- case TC_CHAR :
- return "C";
- case TC_SHORT :
- return "S";
- case TC_INT :
- return "I";
- case TC_LONG :
- return "J";
- case TC_FLOAT :
- return "F";
- case TC_DOUBLE :
- return "D";
- default :
- return "unknown";
- }
+/**
+ * Convert a base type code to the VM naming format
+ */
+protected static String typeSignature(int typeCode) {
+ switch (typeCode) {
+ case TC_VOID :
+ return "V";
+ case TC_BOOLEAN :
+ return "Z";
+ case TC_BYTE :
+ return "B";
+ case TC_CHAR :
+ return "C";
+ case TC_SHORT :
+ return "S";
+ case TC_INT :
+ return "I";
+ case TC_LONG :
+ return "J";
+ case TC_FLOAT :
+ return "F";
+ case TC_DOUBLE :
+ return "D";
+ default :
+ return "unknown";
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PrimitiveTypeHandleImplSWH.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PrimitiveTypeHandleImplSWH.java
index e745c9a053..2d4b99163d 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PrimitiveTypeHandleImplSWH.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/PrimitiveTypeHandleImplSWH.java
@@ -14,26 +14,23 @@ public class PrimitiveTypeHandleImplSWH extends TypeImplSWH {
PrimitiveTypeHandleImplSWH(StateImpl state, IType handle) {
fState = state;
try {
- fHandle = (PrimitiveTypeHandleImpl) handle;
+ fHandle = (PrimitiveTypeHandleImpl)handle;
} catch (ClassCastException e) {
throw new StateSpecificException();
}
}
-
/**
* Returns the non state specific handle
*/
protected TypeImpl getHandle() {
return fHandle;
}
-
/**
* Primitive types are always present.
*/
public boolean isPresent() {
return true;
}
-
/**
* Determines if the specified Type object represents a primitive Java
* type.
@@ -48,5 +45,4 @@ public class PrimitiveTypeHandleImplSWH extends TypeImplSWH {
public boolean isPrimitive() {
return true;
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProblemDetailImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProblemDetailImpl.java
index 56698e2eb5..12d9a9f5b9 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProblemDetailImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProblemDetailImpl.java
@@ -29,209 +29,174 @@ public class ProblemDetailImpl implements IProblemDetail, IProblem {
* Severity flag indicating a syntax error (also covers namespace errors such as duplicates).
*/
protected static final int S_SYNTAX_ERROR = 2;
- /**
- * Creates a problem detail.
- */
- public ProblemDetailImpl(
- String msg,
- int id,
- int severity,
- SourceEntry sourceEntry,
- int startPos,
- int endPos,
- int lineNumber) {
- fMessage = msg;
- fID = id;
- fSeverity = severity;
- fSourceEntry = sourceEntry;
- fStartPos = startPos;
- fEndPos = endPos;
- fLineNumber = lineNumber;
- }
-
- /**
- * Creates a problem detail.
- */
- public ProblemDetailImpl(String msg, SourceEntry sourceEntry) {
- this(msg, 0, S_ERROR, sourceEntry, -1, -1, -1);
- }
-
- public boolean equals(Object o) {
- if (this == o)
- return true;
- if (!(this instanceof ProblemDetailImpl))
- return false;
- return equals((ProblemDetailImpl) o, false);
- }
-
- public boolean equals(ProblemDetailImpl pb, boolean ignorePositions) {
- return fMessage.equals(pb.fMessage)
+/**
+ * Creates a problem detail.
+ */
+public ProblemDetailImpl(String msg, int id, int severity, SourceEntry sourceEntry, int startPos, int endPos, int lineNumber) {
+ fMessage = msg;
+ fID = id;
+ fSeverity = severity;
+ fSourceEntry = sourceEntry;
+ fStartPos = startPos;
+ fEndPos = endPos;
+ fLineNumber = lineNumber;
+}
+/**
+ * Creates a problem detail.
+ */
+public ProblemDetailImpl(String msg, SourceEntry sourceEntry) {
+ this(msg, 0, S_ERROR, sourceEntry, -1, -1, -1);
+}
+public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(this instanceof ProblemDetailImpl)) return false;
+ return equals((ProblemDetailImpl) o, false);
+}
+public boolean equals(ProblemDetailImpl pb, boolean ignorePositions) {
+ return
+ fMessage.equals(pb.fMessage)
&& Util.equalOrNull(fSourceEntry, pb.fSourceEntry)
&& fSeverity == pb.fSeverity
- && (ignorePositions || (fStartPos == pb.fStartPos && fEndPos == pb.fEndPos));
- }
-
- /**
- * @see IProblem
- */
- public String[] getArguments() {
- return null; // not kept
- }
-
- /**
- * Returns the end pos.
- */
- public int getEndPos() {
- return fEndPos;
- }
-
- /**
- * @see IProblemDetail
- */
- public int getID() {
- return fID;
- }
-
- /**
- * @see IProblemDetail
- */
- public int getKind() {
- return IProblemDetail.K_COMPILATION_PROBLEM;
- }
-
- /**
- * @see IProblemDetail
- */
- public int getLineNumber() {
- return fLineNumber;
- }
-
- /**
- * @see IProblemDetail
- */
- public String getMessage() {
- return fMessage;
- }
-
- /**
- * getOriginatingFileName method comment.
- */
- public char[] getOriginatingFileName() {
- return fSourceEntry.getPathWithZipEntryName().toCharArray();
- }
-
- /**
- * Returns the path of the source entry.
- */
- IPath getPath() {
- return fSourceEntry == null ? null : fSourceEntry.getPath();
- }
-
- /**
- * @see IProblemDetail
- */
- public int getSeverity() {
- return fSeverity;
- }
-
- /**
- * @see IProblem
- */
- public int getSourceEnd() {
- return fEndPos;
- }
-
- /**
- * Returns the source entry
- */
- SourceEntry getSourceEntry() {
- return fSourceEntry;
- }
-
- /**
- * @see ICompilationProblem
- */
- public ISourceFragment getSourceFragment() {
- if (fSourceEntry == null) {
- return null;
- }
- return new SourceFragmentImpl(fStartPos, fEndPos, fSourceEntry);
- }
-
- /**
- * @see IProblem
- */
- public int getSourceLineNumber() {
- return fLineNumber;
- }
-
- /**
- * @see IProblem
- */
- public int getSourceStart() {
- return fStartPos;
- }
-
- /**
- * Returns the start pos.
- */
- public int getStartPos() {
- return fStartPos;
- }
-
- public int hashCode() {
- return fMessage.hashCode() * 17
- + (fSourceEntry == null ? 0 : fSourceEntry.hashCode());
- }
-
- /**
- * @see IProblem
- */
- public boolean isError() {
- return (fSeverity & S_ERROR) != 0;
- }
-
- /**
- * @see IProblem
- */
- public boolean isWarning() {
- return (fSeverity & S_ERROR) == 0;
- }
-
- /**
- * @see IProblem
- */
- public void setSourceEnd(int sourceEnd) {
- fEndPos = sourceEnd;
- }
-
- /**
- * Internal - Set the source entry.
- */
- public void setSourceEntry(SourceEntry sourceEntry) {
- fSourceEntry = sourceEntry;
- }
-
- /**
- * @see IProblem
- */
- public void setSourceLineNumber(int lineNumber) {
- fLineNumber = lineNumber;
- }
-
- /**
- * @see IProblem
- */
- public void setSourceStart(int sourceStart) {
- fStartPos = sourceStart;
- }
-
- /**
- * Returns a readable representation of the class. This method is for debugging
- * purposes only. Non-NLS.
- */
- public String toString() {
- return "ProblemDetail(" + getMessage() + ")";
+ && (ignorePositions ||
+ (fStartPos == pb.fStartPos && fEndPos == pb.fEndPos));
+}
+/**
+ * @see IProblem
+ */
+public String[] getArguments() {
+ return null; // not kept
+}
+/**
+ * Returns the end pos.
+ */
+public int getEndPos() {
+ return fEndPos;
+}
+/**
+ * @see IProblemDetail
+ */
+public int getID() {
+ return fID;
+}
+/**
+ * @see IProblemDetail
+ */
+public int getKind() {
+ return IProblemDetail.K_COMPILATION_PROBLEM;
+}
+/**
+ * @see IProblemDetail
+ */
+public int getLineNumber() {
+ return fLineNumber;
+}
+/**
+ * @see IProblemDetail
+ */
+public String getMessage() {
+ return fMessage;
+}
+/**
+ * getOriginatingFileName method comment.
+ */
+public char[] getOriginatingFileName() {
+ return fSourceEntry.getPathWithZipEntryName().toCharArray();
+}
+/**
+ * Returns the path of the source entry.
+ */
+IPath getPath() {
+ return fSourceEntry == null ? null : fSourceEntry.getPath();
+}
+/**
+ * @see IProblemDetail
+ */
+public int getSeverity() {
+ return fSeverity;
+}
+/**
+ * @see IProblem
+ */
+public int getSourceEnd() {
+ return fEndPos;
+}
+/**
+ * Returns the source entry
+ */
+SourceEntry getSourceEntry() {
+ return fSourceEntry;
+}
+/**
+ * @see ICompilationProblem
+ */
+public ISourceFragment getSourceFragment() {
+ if (fSourceEntry == null) {
+ return null;
}
-
+ return new SourceFragmentImpl(fStartPos, fEndPos, fSourceEntry);
+}
+/**
+ * @see IProblem
+ */
+public int getSourceLineNumber() {
+ return fLineNumber;
+}
+/**
+ * @see IProblem
+ */
+public int getSourceStart() {
+ return fStartPos;
+}
+/**
+ * Returns the start pos.
+ */
+public int getStartPos() {
+ return fStartPos;
+}
+public int hashCode() {
+ return fMessage.hashCode() * 17 + (fSourceEntry == null ? 0 : fSourceEntry.hashCode());
+}
+/**
+ * @see IProblem
+ */
+public boolean isError() {
+ return (fSeverity & S_ERROR) != 0;
+}
+/**
+ * @see IProblem
+ */
+public boolean isWarning() {
+ return (fSeverity & S_ERROR) == 0;
+}
+/**
+ * @see IProblem
+ */
+public void setSourceEnd(int sourceEnd) {
+ fEndPos = sourceEnd;
+}
+/**
+ * Internal - Set the source entry.
+ */
+public void setSourceEntry(SourceEntry sourceEntry) {
+ fSourceEntry = sourceEntry;
+}
+/**
+ * @see IProblem
+ */
+public void setSourceLineNumber(int lineNumber) {
+ fLineNumber = lineNumber;
+}
+/**
+ * @see IProblem
+ */
+public void setSourceStart(int sourceStart) {
+ fStartPos = sourceStart;
+}
+/**
+ * Returns a readable representation of the class. This method is for debugging
+ * purposes only. Non-NLS.
+ */
+public String toString() {
+ return "ProblemDetail(" + getMessage() + ")";
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProblemFactory.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProblemFactory.java
index d9971f5282..3a373ccdbb 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProblemFactory.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProblemFactory.java
@@ -20,118 +20,87 @@ public class ProblemFactory implements IProblemFactory {
protected String[] fMessageTemplates;
protected static Hashtable fgFactories = new Hashtable(5);
- /**
- * Creates a problem factory for the given locale.
- */
- private ProblemFactory(Locale locale) {
- fLocale = locale;
- fCompilerResources =
- ResourceBundle.getBundle(
- "org.eclipse.jdt.internal.compiler.problem.Messages",
- locale);
- //$NON-NLS-1$
- initializeMessageTemplates();
- }
-
- /**
- * @see IProblemFactory
- */
- public IProblem createProblem(
- char[] originatingFileName,
- int problemId,
- String[] arguments,
- int severity,
- int startPosition,
- int endPosition,
- int lineNumber) {
- String message = getLocalizedMessage(problemId, arguments);
- int sev = (severity & IProblem.Error) != 0 ? IProblemDetail.S_ERROR : 0;
- // SourceEntry is filled in later when problem is actually recorded.
- SourceEntry sEntry = null;
- if (lineNumber == 0)
- lineNumber = -1;
- return new ProblemDetailImpl(
- message,
- problemId,
- sev,
- sEntry,
- startPosition,
- endPosition,
- lineNumber);
- }
-
- /**
- * @see IProblemFactory
- */
- public Locale getLocale() {
- return fLocale;
+/**
+ * Creates a problem factory for the given locale.
+ */
+private ProblemFactory(Locale locale) {
+ fLocale = locale;
+ fCompilerResources = ResourceBundle.getBundle("org.eclipse.jdt.internal.compiler.problem.Messages", locale); //$NON-NLS-1$
+ initializeMessageTemplates();
+}
+/**
+ * @see IProblemFactory
+ */
+public IProblem createProblem(char[] originatingFileName, int problemId, String[] arguments, int severity, int startPosition, int endPosition, int lineNumber) {
+ String message = getLocalizedMessage(problemId, arguments);
+ int sev = (severity & IProblem.Error) != 0 ? IProblemDetail.S_ERROR : 0;
+ // SourceEntry is filled in later when problem is actually recorded.
+ SourceEntry sEntry = null;
+ if (lineNumber == 0)
+ lineNumber = -1;
+ return new ProblemDetailImpl(message, problemId, sev, sEntry, startPosition, endPosition, lineNumber);
+}
+/**
+ * @see IProblemFactory
+ */
+public Locale getLocale() {
+ return fLocale;
+}
+/**
+ * @see IProblemFactory
+ */
+public String getLocalizedMessage(int id, String[] problemArguments) {
+ StringBuffer output = new StringBuffer(80);
+ String message = fMessageTemplates[ (id & ProblemIrritants.IgnoreCategoriesMask)];
+ if (message == null) {
+ return "Unable to retrieve the error message for problem id: " + id + ". Check compiler resources.";
}
-
- /**
- * @see IProblemFactory
- */
- public String getLocalizedMessage(int id, String[] problemArguments) {
- StringBuffer output = new StringBuffer(80);
- String message =
- fMessageTemplates[(id & ProblemIrritants.IgnoreCategoriesMask)];
- if (message == null) {
- return "Unable to retrieve the error message for problem id: "
- + id
- + ". Check compiler resources.";
- }
- int length = message.length();
- int start = -1, end = length;
- while (true) {
- if ((end = message.indexOf('{', start)) > -1) {
- output.append(message.substring(start + 1, end));
- if ((start = message.indexOf('}', end)) > -1) {
- try {
- output.append(
- problemArguments[Integer.parseInt(message.substring(end + 1, start))]);
- } catch (NumberFormatException nfe) {
- output.append(message.substring(end + 1, start + 1));
- } catch (ArrayIndexOutOfBoundsException e) {
- return "Corrupted compiler resources for problem id: "
- + (id & ProblemIrritants.IgnoreCategoriesMask)
- + ". Check compiler resources.";
- }
- } else {
- output.append(message.substring(end, length));
- break;
+ int length = message.length();
+ int start = -1, end = length;
+ while (true) {
+ if ((end = message.indexOf('{', start)) > -1) {
+ output.append(message.substring(start + 1, end));
+ if ((start = message.indexOf('}', end)) > -1) {
+ try {
+ output.append(problemArguments[Integer.parseInt(message.substring(end + 1, start))]);
+ } catch (NumberFormatException nfe) {
+ output.append(message.substring(end + 1, start + 1));
+ } catch (ArrayIndexOutOfBoundsException e) {
+ return "Corrupted compiler resources for problem id: " + (id & ProblemIrritants.IgnoreCategoriesMask) + ". Check compiler resources.";
}
} else {
- output.append(message.substring(start + 1, length));
+ output.append(message.substring(end, length));
break;
}
+ } else {
+ output.append(message.substring(start + 1, length));
+ break;
}
- return output.toString();
}
-
- /**
- * Returns the problem factory for the given locale.
- */
- public static ProblemFactory getProblemFactory(Locale locale) {
- ProblemFactory factory = (ProblemFactory) fgFactories.get(locale);
- if (factory == null) {
- factory = new ProblemFactory(locale);
- fgFactories.put(locale, factory);
- }
- return factory;
+ return output.toString();
+}
+/**
+ * Returns the problem factory for the given locale.
+ */
+public static ProblemFactory getProblemFactory(Locale locale) {
+ ProblemFactory factory = (ProblemFactory) fgFactories.get(locale);
+ if (factory == null) {
+ factory = new ProblemFactory(locale);
+ fgFactories.put(locale, factory);
}
-
- /**
- * This method initializes the messageTemplates variable according
- * to the current Locale.
- */
- protected void initializeMessageTemplates() {
- fMessageTemplates = new String[500];
- for (int i = 0; i < fMessageTemplates.length; i++) {
- try {
- fMessageTemplates[i] = fCompilerResources.getString(String.valueOf(i));
- //$NON-NLS-1$
- } catch (MissingResourceException e) {
- }
+ return factory;
+}
+/**
+ * This method initializes the messageTemplates variable according
+ * to the current Locale.
+ */
+protected void initializeMessageTemplates() {
+ fMessageTemplates = new String[500];
+ for (int i = 0; i < fMessageTemplates.length; i++) {
+ try {
+ fMessageTemplates[i] = fCompilerResources.getString(String.valueOf(i)); //$NON-NLS-1$
+ } catch (MissingResourceException e) {
}
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProblemTable.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProblemTable.java
index a1d2cff1d8..289b47417f 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProblemTable.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProblemTable.java
@@ -19,165 +19,152 @@ import org.eclipse.jdt.internal.core.builder.IDevelopmentContext;
public class ProblemTable extends StateTables implements IProblemReporter {
Hashtable fTable = new Hashtable(20);
Vector fImageProblems = new Vector(11);
- /**
- * Creates a copy of the table.
- */
- public IProblemReporter copy() {
- try {
- ProblemTable copy = (ProblemTable) super.clone();
- copy.fTable = new Hashtable(fTable.size() * 2 + 1);
- for (Enumeration e = fTable.keys(); e.hasMoreElements();) {
- SourceEntry sEntry = (SourceEntry) e.nextElement();
- Vector v = (Vector) fTable.get(sEntry);
- copy.fTable.put(sEntry, v.clone());
- }
- return copy;
- } catch (CloneNotSupportedException e) {
- // Should not happen.
- throw new Error();
- }
- }
-
- /**
- * Returns an enumeration of all problems with elements of the image,
- * but not with the image itself.
- */
- public Enumeration getAllProblems() {
-
- /* this is a very slow way of doing it.. is there a faster way? */
- Vector allProblems = new Vector();
- for (Enumeration e = fTable.elements(); e.hasMoreElements();) {
- Vector problemVector = (Vector) e.nextElement();
- for (Enumeration ee = problemVector.elements(); ee.hasMoreElements();) {
- allProblems.addElement(ee.nextElement());
- }
+/**
+ * Creates a copy of the table.
+ */
+public IProblemReporter copy() {
+ try {
+ ProblemTable copy = (ProblemTable) super.clone();
+ copy.fTable = new Hashtable(fTable.size() * 2 + 1);
+ for (Enumeration e = fTable.keys(); e.hasMoreElements();) {
+ SourceEntry sEntry = (SourceEntry) e.nextElement();
+ Vector v = (Vector) fTable.get(sEntry);
+ copy.fTable.put(sEntry, v.clone());
}
- return allProblems.elements();
- }
-
- /**
- * Returns the problems with the image itself. Returns null if no
- * problems exist for the image. An example of such a problem is
- * duplicate types in a package.
- */
- public Enumeration getImageProblems() {
- return fImageProblems.elements();
+ return copy;
+ } catch (CloneNotSupportedException e) {
+ // Should not happen.
+ throw new Error();
}
-
- /**
- * Returns an enumeration of problem table keys (SourceEntry objects)
- */
- public Enumeration getProblemKeys() {
- return fTable.keys();
- }
-
- /**
- * Returns an enumeration of problems for a given source entry.
- */
- public Enumeration getProblems(Object entry) {
- Vector vProblems = (Vector) fTable.get(entry);
- if (vProblems == null) {
- return new Vector().elements();
+}
+/**
+ * Returns an enumeration of all problems with elements of the image,
+ * but not with the image itself.
+ */
+public Enumeration getAllProblems() {
+
+ /* this is a very slow way of doing it.. is there a faster way? */
+ Vector allProblems = new Vector();
+ for (Enumeration e = fTable.elements(); e.hasMoreElements();) {
+ Vector problemVector = (Vector) e.nextElement();
+ for (Enumeration ee = problemVector.elements(); ee.hasMoreElements();) {
+ allProblems.addElement(ee.nextElement());
}
- return vProblems.elements();
}
-
- /**
- * Returns a vector of problems for a given source entry,
- * or null if no problems.
- */
- public Vector getProblemVector(Object entry) {
- return (Vector) fTable.get(entry);
+ return allProblems.elements();
+}
+/**
+ * Returns the problems with the image itself. Returns null if no
+ * problems exist for the image. An example of such a problem is
+ * duplicate types in a package.
+ */
+public Enumeration getImageProblems() {
+ return fImageProblems.elements();
+}
+/**
+ * Returns an enumeration of problem table keys (SourceEntry objects)
+ */
+public Enumeration getProblemKeys() {
+ return fTable.keys();
+}
+/**
+ * Returns an enumeration of problems for a given source entry.
+ */
+public Enumeration getProblems(Object entry) {
+ Vector vProblems = (Vector) fTable.get(entry);
+ if (vProblems == null) {
+ return new Vector().elements();
}
-
- /**
- * Returns whether the given entry has any problems.
- */
- public boolean hasProblems(Object entry) {
- return fTable.get(entry) != null;
+ return vProblems.elements();
+}
+/**
+ * Returns a vector of problems for a given source entry,
+ * or null if no problems.
+ */
+public Vector getProblemVector(Object entry) {
+ return (Vector) fTable.get(entry);
+}
+/**
+ * Returns whether the given entry has any problems.
+ */
+public boolean hasProblems(Object entry) {
+ return fTable.get(entry) != null;
+}
+/**
+ * Adds a problem to the problem table. If the problem is a duplicate, it is
+ * not added and an error message is generated.
+ */
+public void putProblem(Object entry, IProblemDetail problem) {
+ Vector problems = (Vector) fTable.get(entry);
+ if (problems == null) {
+ problems = new Vector();
+ fTable.put(entry, problems);
}
-
- /**
- * Adds a problem to the problem table. If the problem is a duplicate, it is
- * not added and an error message is generated.
- */
- public void putProblem(Object entry, IProblemDetail problem) {
- Vector problems = (Vector) fTable.get(entry);
- if (problems == null) {
- problems = new Vector();
- fTable.put(entry, problems);
+/* for (int i = 0; i < problems.size(); ++i) {
+ if (problem.equals(problems.elementAt(i))) {
+ System.err.println("DBG: Same error reported twice for " + entry + ": " + problem);
+ return;
}
- /* for (int i = 0; i < problems.size(); ++i) {
- if (problem.equals(problems.elementAt(i))) {
- System.err.println("DBG: Same error reported twice for " + entry + ": " + problem);
- return;
- }
- }
- */
- problems.addElement(problem);
}
-
- /**
- * Removes all problems except syntax errors for the given source entry.
- */
- public void removeNonSyntaxErrors(Object entry) {
- Vector problems = (Vector) fTable.get(entry);
- if (problems != null) {
- int i = 0;
- while (i < problems.size()) {
- IProblemDetail problem = (IProblemDetail) problems.elementAt(i);
- if ((problem.getSeverity() & ProblemDetailImpl.S_SYNTAX_ERROR) == 0) {
- problems.removeElementAt(i);
- } else {
- i++;
- }
- }
- if (problems.isEmpty()) {
- fTable.remove(entry);
+*/ problems.addElement(problem);
+}
+/**
+ * Removes all problems except syntax errors for the given source entry.
+ */
+public void removeNonSyntaxErrors(Object entry) {
+ Vector problems = (Vector) fTable.get(entry);
+ if (problems != null) {
+ int i = 0;
+ while (i < problems.size()) {
+ IProblemDetail problem = (IProblemDetail) problems.elementAt(i);
+ if ((problem.getSeverity() & ProblemDetailImpl.S_SYNTAX_ERROR) == 0) {
+ problems.removeElementAt(i);
+ } else {
+ i++;
}
}
+ if (problems.isEmpty()) {
+ fTable.remove(entry);
+ }
}
-
- /**
- * Removes all problems for the given source entry
- */
- public void removeProblems(Object entry) {
- fTable.remove(entry);
- }
-
- /**
- * Removes all syntax errors for the given source entry.
- */
- public void removeSyntaxErrors(Object entry) {
- Vector problems = (Vector) fTable.get(entry);
- if (problems != null) {
- int i = 0;
- while (i < problems.size()) {
- IProblemDetail problem = (IProblemDetail) problems.elementAt(i);
- if ((problem.getSeverity() & ProblemDetailImpl.S_SYNTAX_ERROR) != 0) {
- problems.removeElementAt(i);
- } else {
- i++;
- }
- }
- if (problems.isEmpty()) {
- fTable.remove(entry);
+}
+/**
+ * Removes all problems for the given source entry
+ */
+public void removeProblems(Object entry) {
+ fTable.remove(entry);
+}
+/**
+ * Removes all syntax errors for the given source entry.
+ */
+public void removeSyntaxErrors(Object entry) {
+ Vector problems = (Vector) fTable.get(entry);
+ if (problems != null) {
+ int i = 0;
+ while (i < problems.size()) {
+ IProblemDetail problem = (IProblemDetail) problems.elementAt(i);
+ if ((problem.getSeverity() & ProblemDetailImpl.S_SYNTAX_ERROR) != 0) {
+ problems.removeElementAt(i);
+ } else {
+ i++;
}
}
+ if (problems.isEmpty()) {
+ fTable.remove(entry);
+ }
}
-
+}
/**
* Returns the total number of problems in the table.
*/
int size() {
int size = fImageProblems.size();
- for (Enumeration e = fTable.elements(); e.hasMoreElements();) {
- Vector v = (Vector) e.nextElement();
+ for (Enumeration e = fTable.elements(); e.hasMoreElements(); ) {
+ Vector v = (Vector)e.nextElement();
size += v.size();
}
return size;
}
-
/**
* Returns a String that represents the value of this object.
* @return a string representation of the receiver
@@ -192,10 +179,9 @@ public class ProblemTable extends StateTables implements IProblemReporter {
return buf.toString();
}
- /**
- * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
- */
- public void initialize(IProject project, IDevelopmentContext dc) {
- }
-
+/**
+ * @see org.eclipse.jdt.internal.core.builder.IProblemReporter
+ */
+public void initialize(IProject project, IDevelopmentContext dc) {
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProjectBinaryOutput.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProjectBinaryOutput.java
index 1fd2228263..817ead2866 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProjectBinaryOutput.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProjectBinaryOutput.java
@@ -32,223 +32,203 @@ public class ProjectBinaryOutput extends BinaryOutput {
public final static String ADDED = "ADDED";
public final static String MODIFIED = "MODIFIED";
public final static String DELETED = "DELETED";
-
- /**
- * Creates a new ProjectBinaryOutput for the given project and output path
- * in this project.
- */
- public ProjectBinaryOutput(
- IProject project,
- IPath outputPath,
- JavaDevelopmentContextImpl dc) {
- this.project = project;
- this.outputPath = outputPath;
- this.dc = dc;
-
- /* create the output folder is it doesn't exist */
- if (!project.getFullPath().equals(outputPath)) {
- this.makeContainersIfNecessary(outputPath);
- }
+
+/**
+ * Creates a new ProjectBinaryOutput for the given project and output path
+ * in this project.
+ */
+public ProjectBinaryOutput(IProject project, IPath outputPath, JavaDevelopmentContextImpl dc) {
+ this.project = project;
+ this.outputPath = outputPath;
+ this.dc = dc;
+
+ /* create the output folder is it doesn't exist */
+ if (!project.getFullPath().equals(outputPath)) {
+ this.makeContainersIfNecessary(outputPath);
}
-
- /**
- * @see BinaryOutput
- */
- protected void basicPutBinary(
- TypeStructureEntry tsEntry,
- byte[] binary,
- int crc) {
-
- IType type;
- IPath path = getPathForBinary(type = tsEntry.getType());
- deleteBinary(type);
-
- IContainer container = makeContainersIfNecessary(path.removeLastSegments(1));
-
- PackageElement element =
- new PackageElement(type.getPackage(), new SourceEntry(path, null, null));
- IFile file = container.getFile(new Path(path.lastSegment()));
-
- try {
- ByteArrayInputStream stream = new ByteArrayInputStream(binary);
- file.create(stream, true, null);
- } catch (CoreException e) {
- throw this.dc.internalException(e);
- }
+}
+/**
+ * @see BinaryOutput
+ */
+protected void basicPutBinary(TypeStructureEntry tsEntry, byte[] binary, int crc) {
+
+ IType type;
+ IPath path = getPathForBinary(type = tsEntry.getType());
+ deleteBinary(type);
+
+ IContainer container = makeContainersIfNecessary(path.removeLastSegments(1));
+
+ PackageElement element = new PackageElement(type.getPackage(), new SourceEntry(path, null, null));
+ IFile file = container.getFile(new Path(path.lastSegment()));
+
+ try {
+ ByteArrayInputStream stream = new ByteArrayInputStream(binary);
+ file.create(stream, true, null);
+ } catch (CoreException e) {
+ throw this.dc.internalException(e);
}
-
- /**
- * Deletes everything in the given container.
- */
- private void deleteAllInContainer(IContainer container) {
- try {
- if (!container.exists())
- return;
- IResource[] members = container.members();
- for (int i = 0, max = members.length; i < max; i++) {
- IResource resource = (IResource) members[i];
- resource.delete(true, null);
- }
- } catch (CoreException e) {
- throw this.dc.internalException(e);
+}
+/**
+ * Deletes everything in the given container.
+ */
+private void deleteAllInContainer(IContainer container) {
+ try {
+ if (!container.exists())
+ return;
+ IResource[] members = container.members();
+ for (int i = 0, max = members.length; i < max;i++) {
+ IResource resource = (IResource) members[i];
+ resource.delete(true, null);
}
+ } catch (CoreException e) {
}
-
- /**
- * @see BinaryOutput
- */
- public void deleteBinary(IType type) {
- IPath path = getPathForBinary(type);
- IFile file = getFile(path);
- try {
- file.delete(true, null);
- } catch (CoreException e) {
- throw this.dc.internalException(e);
- }
+}
+/**
+ * @see BinaryOutput
+ */
+public void deleteBinary(IType type) {
+ IPath path = getPathForBinary(type);
+ IFile file = getFile(path);
+ try {
+ file.delete(true, null);
+ } catch (CoreException e) {
}
-
- /**
- * Deletes the classes in the given container, recursively.
- * Delete any folders which become empty.
- */
- private void deleteClassesInContainer(IContainer container) {
- try {
- if (!container.exists())
- return;
- IResource[] members = container.members();
- for (int i = 0, max = members.length; i < max; i++) {
- IResource resource = (IResource) members[i];
- switch (resource.getType()) {
- case IResource.FILE :
- if (resource.getName().toLowerCase().endsWith(".class")) {
- resource.delete(true, null);
- }
- break;
- case IResource.PROJECT :
- case IResource.FOLDER :
- deleteClassesInContainer((IContainer) resource);
- break;
- }
+}
+/**
+ * Deletes the classes in the given container, recursively.
+ * Delete any folders which become empty.
+ */
+private void deleteClassesInContainer(IContainer container) {
+ try {
+ if (!container.exists())
+ return;
+ IResource[] members = container.members();
+ for (int i = 0, max = members.length; i < max;i++) {
+ IResource resource = (IResource) members[i];
+ switch (resource.getType()) {
+ case IResource.FILE :
+ if (resource.getName().toLowerCase().endsWith(".class")) {
+ resource.delete(true, null);
+ }
+ break;
+ case IResource.PROJECT :
+ case IResource.FOLDER :
+ deleteClassesInContainer((IContainer) resource);
+ break;
}
- //
- // Don't delete empty folders, since the output may overlap with the source, and
- // we don't want to delete empty folders which the user may have created.
- //
- // if (container.getType() == IResource.FOLDER && !container.members().hasMoreElements()) {
- // container.delete(true, null);
- // }
- } catch (CoreException e) {
- throw this.dc.internalException(e);
}
+//
+// Don't delete empty folders, since the output may overlap with the source, and
+// we don't want to delete empty folders which the user may have created.
+//
+// if (container.getType() == IResource.FOLDER && !container.members().hasMoreElements()) {
+// container.delete(true, null);
+// }
+ } catch (CoreException e) {
}
-
- /**
- * @see BinaryOutput
- */
- public void garbageCollect(IState[] statesInUse) {
- // Nothing to do for a Project binary output
- }
-
- /**
- * @see BinaryOutput
- */
- public byte[] getBinary(TypeStructureEntry tsEntry, IType type) {
- IPath path = getPathForBinary(type);
- IFile file = getFile(path);
- try {
- InputStream input = file.getContents(true);
- return Util.readContentsAsBytes(input);
- } catch (IOException e) {
- throw this.dc.internalException(e);
- } catch (CoreException e) {
- return this.dc.getBinaryFromFileSystem(file);
- }
- }
-
- /**
- * Returns the container for a path.
- */
- private IContainer getContainer(IPath path) {
- if (path.isAbsolute()) {
- if (this.project.getFullPath().equals(path)) {
- return this.project;
- } else {
- return this.project.getWorkspace().getRoot().getFolder(path);
- }
+}
+/**
+ * @see BinaryOutput
+ */
+public void garbageCollect(IState[] statesInUse) {
+ // Nothing to do for a Project binary output
+}
+/**
+ * @see BinaryOutput
+ */
+public byte[] getBinary(TypeStructureEntry tsEntry, IType type) {
+ IPath path = getPathForBinary(type);
+ IFile file = getFile(path);
+ try {
+ InputStream input = file.getContents(true);
+ return Util.readContentsAsBytes(input);
+ } catch (IOException e) {
+ return new byte[0];
+ } catch (CoreException e) {
+ return new byte[0]; }
+}
+/**
+ * Returns the container for a path.
+ */
+private IContainer getContainer(IPath path) {
+ if (path.isAbsolute()){
+ if (this.project.getFullPath().equals(path)){
+ return this.project;
+ } else {
+ return this.project.getWorkspace().getRoot().getFolder(path);
}
- return this.project.getFolder(path);
- }
-
- /**
- * Returns the file for a path.
- */
- private IFile getFile(IPath path) {
- if (path.isAbsolute()) {
+ }
+ return this.project.getFolder(path);
+}
+/**
+ * Returns the file for a path.
+ */
+private IFile getFile(IPath path) {
+ if (path.isAbsolute()){
return this.project.getWorkspace().getRoot().getFile(path);
- }
- return this.project.getFile(path);
- }
-
- /**
- * Returns the path for the output package fragment root.
- */
- IPath getOutputPath() {
- return this.outputPath;
- }
-
- /**
- * Returns the path in the output folder for the given type.
- */
- private IPath getPathForBinary(IType type) {
- return getOutputPath().append(type.getName().replace('.', '/') + ".class");
- }
-
- /**
- * Returns the container at the given path, creating it and any parent folders if necessary.
- */
- IContainer makeContainersIfNecessary(IPath path) {
- try {
- IContainer container = getContainer(path);
- if (container.exists())
- return container;
- Assert.isTrue(container instanceof IFolder);
- makeContainersIfNecessary(path.removeLastSegments(1));
- ((IFolder) container).create(true, true, null);
+ }
+ return this.project.getFile(path);
+}
+/**
+ * Returns the path for the output package fragment root.
+ */
+IPath getOutputPath() {
+ return this.outputPath;
+}
+/**
+ * Returns the path in the output folder for the given type.
+ */
+private IPath getPathForBinary(IType type) {
+ return getOutputPath().append(type.getName().replace('.', '/') + ".class");
+}
+/**
+ * Returns the container at the given path, creating it and any parent folders if necessary.
+ */
+IContainer makeContainersIfNecessary(IPath path) {
+ try {
+ IContainer container = getContainer(path);
+ if (container.exists())
return container;
- } catch (CoreException e) {
- throw this.dc.internalException(e);
- }
+ Assert.isTrue(container instanceof IFolder);
+ makeContainersIfNecessary(path.removeLastSegments(1));
+ ((IFolder) container).create(true, true, null);
+ return container;
+ } catch (CoreException e) {
+ throw this.dc.internalException(e);
+ }
+}
+/**
+ * @see BinaryOutput
+ */
+public void scrubOutput() {
+
+ IJavaProject projectElement = JavaCore.create(this.project);
+ IClasspathEntry[] entries;
+ try {
+ entries = projectElement.getResolvedClasspath(true);
+ } catch(JavaModelException e){
+ throw this.dc.internalException(e);
}
- /**
- * @see BinaryOutput
- */
- public void scrubOutput() {
-
- IJavaProject projectElement = JavaCore.create(this.project);
- IClasspathEntry[] entries;
- try {
- entries = projectElement.getResolvedClasspath(true);
- } catch (JavaModelException e) {
- throw this.dc.internalException(e);
- }
-
- /* detect whether the binary ouput coincidates with source folder */
- boolean flushAllOutput = false;
- for (int i = 0, length = entries.length; i < length; i++) {
- IClasspathEntry entry = entries[i];
- if ((entry.getEntryKind() == IClasspathEntry.CPE_SOURCE)) {
- if (!this.outputPath.equals(entry.getPath())) {
- flushAllOutput = true; // output is distinct - flush all
- break;
- }
+ /* detect whether the binary ouput coincidates with source folder */
+ boolean flushAllOutput = true;
+ boolean hasSource = false;
+ for (int i = 0, length = entries.length; i < length; i++) {
+ IClasspathEntry entry = entries[i];
+ if ((entry.getEntryKind() == IClasspathEntry.CPE_SOURCE)) {
+ hasSource = true;
+ if (this.outputPath.equals(entry.getPath())){
+ flushAllOutput = false; // output coincidates, cannot flush
+ break;
}
}
- if (flushAllOutput) {
+ }
+ if (hasSource) {
+ if (flushAllOutput){
deleteAllInContainer(getContainer(this.outputPath));
} else {
deleteClassesInContainer(getContainer(this.outputPath));
}
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProjectResourceCopier.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProjectResourceCopier.java
index 0d2c48adfb..6180ae05d3 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProjectResourceCopier.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ProjectResourceCopier.java
@@ -24,241 +24,208 @@ public class ProjectResourceCopier implements IResourceVisitor {
private final BuildNotifier notifier;
private final float totalAvailableProgress;
private IResource[] sourceFolders;
- public ProjectResourceCopier(
- IJavaProject project,
- JavaDevelopmentContextImpl devContext,
- BuildNotifier notifier,
- float totalAvailableProgress) {
-
- this.project = project;
- this.devContext = devContext;
- this.projectRsc = this.project.getProject();
- this.workspace = this.projectRsc.getWorkspace();
- this.root = this.workspace.getRoot();
- try {
- this.outputLocation = this.project.getOutputLocation();
- IClasspathEntry[] entries = this.project.getResolvedClasspath(true);
- this.sourceFolders = new IResource[entries.length];
- for (int i = 0, length = entries.length; i < length; i++) {
- IClasspathEntry entry = entries[i];
- if ((entry.getEntryKind() == IClasspathEntry.CPE_SOURCE)) {
- this.sourceFolders[i] = this.root.findMember(entry.getPath());
- }
+public ProjectResourceCopier(IJavaProject project, JavaDevelopmentContextImpl devContext, BuildNotifier notifier, float totalAvailableProgress){
+
+ this.project = project;
+ this.devContext = devContext;
+ this.projectRsc = this.project.getProject();
+ this.workspace = this.projectRsc.getWorkspace();
+ this.root = this.workspace.getRoot();
+ try {
+ this.outputLocation = this.project.getOutputLocation();
+ IClasspathEntry[] entries = this.project.getResolvedClasspath(true);
+ this.sourceFolders = new IResource[entries.length];
+ for (int i = 0, length = entries.length; i < length; i++) {
+ IClasspathEntry entry = entries[i];
+ if ((entry.getEntryKind() == IClasspathEntry.CPE_SOURCE)) {
+ this.sourceFolders[i] = this.root.findMember(entry.getPath());
}
- } catch (JavaModelException e) {
- throw new ImageBuilderInternalException(e);
}
- this.notifier = notifier;
- this.totalAvailableProgress = totalAvailableProgress;
+ } catch(JavaModelException e){
+ throw new ImageBuilderInternalException(e);
}
+ this.notifier = notifier;
+ this.totalAvailableProgress = totalAvailableProgress;
+}
+public void copyAllResourcesOnClasspath(){
- public void copyAllResourcesOnClasspath() {
-
- boolean hasNotified = false;
- try {
- for (int i = 0, length = this.sourceFolders.length; i < length; i++) {
- if (sourceFolders[i] != null) {
- if (this.outputLocation.equals(this.sourceFolders[i].getFullPath()))
- continue; // do nothing if output is same as source folder
- if (!hasNotified) {
- hasNotified = true;
- if (notifier != null)
- notifier.subTask("Copying all resources on the classpath");
- }
- this.sourceFolders[i].accept(this);
+ boolean hasNotified = false;
+ try {
+ for (int i = 0, length = this.sourceFolders.length; i < length; i++) {
+ if (sourceFolders[i] != null){
+ if (this.outputLocation.equals(this.sourceFolders[i].getFullPath())) continue; // do nothing if output is same as source folder
+ if (!hasNotified){
+ hasNotified = true;
+ if (notifier != null) notifier.subTask("Copying all resources on the classpath");
}
- if (notifier != null)
- notifier.updateProgressDelta(totalAvailableProgress / length);
+ this.sourceFolders[i].accept(this);
}
- } catch (CoreException e) {
- throw this.devContext.internalException(e);
+ if (notifier != null) notifier.updateProgressDelta(totalAvailableProgress / length);
}
+ } catch(CoreException e){
+ //throw this.devContext.internalException(e);
}
-
- /**
- * Copy a given resource into the output folder (if non java source file)
- */
- private boolean copyToOutput(IResource resource) {
-
- if (!resource.exists())
- return false;
- IPath sourceFolderPath = getSourceFolderPath(resource);
- IPath resourcePath = resource.getFullPath();
-
- switch (resource.getType()) {
- case IResource.FILE :
- if (sourceFolderPath == null)
- return false; // resource is not inside the classpath
- if (!"java".equals(resource.getFileExtension())) { // ignore source files
-
- IFile currentFile = (IFile) resource;
- IPath pathSuffix =
- resourcePath.removeFirstSegments(sourceFolderPath.segmentCount());
- IPath targetPath = this.outputLocation.append(pathSuffix);
- try {
- IFile previousFile = this.root.getFile(targetPath);
- if (previousFile.exists())
- previousFile.delete(true, false, null);
- currentFile.copy(targetPath, true, null);
- } catch (CoreException e) {
- throw this.devContext.internalException(e);
- }
- }
- break;
- case IResource.PROJECT :
- if (resourcePath.equals(this.outputLocation))
- return false; // do not visit the binary output
- if (resourcePath.equals(sourceFolderPath))
- return true; // skip source folder itself
- break;
- case IResource.FOLDER :
- if (resourcePath.equals(this.outputLocation))
- return false; // do not visit the binary output
- if (sourceFolderPath == null)
- return true;
- // continue inside folder (source folder might be one of its children)
- if (resourcePath.equals(sourceFolderPath))
- return true; // skip source folder itself
- IContainer currentFolder = (IFolder) resource;
-
- IPath pathSuffix =
- resourcePath.removeFirstSegments(sourceFolderPath.segmentCount());
+}
+/**
+ * Copy a given resource into the output folder (if non java source file)
+ */
+private boolean copyToOutput(IResource resource) {
+
+ if (!resource.exists()) return false;
+ IPath sourceFolderPath = getSourceFolderPath(resource);
+ IPath resourcePath = resource.getFullPath();
+
+ switch (resource.getType()){
+ case IResource.FILE :
+ if (sourceFolderPath == null) return false; // resource is not inside the classpath
+ if (!"java".equals(resource.getFileExtension())){ // ignore source files
+
+ IFile currentFile = (IFile) resource;
+ IPath pathSuffix = resourcePath.removeFirstSegments(sourceFolderPath.segmentCount());
IPath targetPath = this.outputLocation.append(pathSuffix);
- IFolder targetFolder = this.root.getFolder(targetPath);
- if (!targetFolder.exists()) {
- try {
- targetFolder.create(true, true, null);
- } catch (CoreException e) {
- throw this.devContext.internalException(e);
- }
+ try {
+ IFile previousFile = this.root.getFile(targetPath);
+ if (previousFile.exists()) previousFile.delete(true, false, null);
+ currentFile.copy(targetPath, true, null);
+ } catch(CoreException e){
+ //throw this.devContext.internalException(e);
}
- break;
- }
- return true;
- }
-
- /**
- * Delete the corresponding resource from the output folder
- */
- private boolean deleteResourceCopyFromOutput(IResource resource) {
-
- IPath sourceFolderPath = getSourceFolderPath(resource);
- if (sourceFolderPath == null)
- return false; // resource is not inside the classpath
-
- IPath resourcePath = resource.getFullPath();
- if (resourcePath.equals(sourceFolderPath))
- return true; // skip source folder itself
- if (resourcePath.equals(this.outputLocation))
- return false; // do not visit the binary output
- IPath pathSuffix, targetPath;
-
- switch (resource.getType()) {
- case IResource.FILE :
- if (!"java".equals(resource.getFileExtension())) { // ignore source files
-
- IFile currentFile = (IFile) resource;
- pathSuffix = resourcePath.removeFirstSegments(sourceFolderPath.segmentCount());
- targetPath = this.outputLocation.append(pathSuffix);
- try {
- IFile previousFile = this.root.getFile(targetPath);
- if (previousFile.exists())
- previousFile.delete(true, true, null);
- } catch (CoreException e) {
- throw this.devContext.internalException(e);
- }
+ }
+ break;
+ case IResource.PROJECT :
+ if (resourcePath.equals(this.outputLocation)) return false; // do not visit the binary output
+ if (resourcePath.equals(sourceFolderPath)) return true; // skip source folder itself
+ break;
+ case IResource.FOLDER :
+ if (resourcePath.equals(this.outputLocation)) return false; // do not visit the binary output
+ if (sourceFolderPath == null) return true; // continue inside folder (source folder might be one of its children)
+ if (resourcePath.equals(sourceFolderPath)) return true; // skip source folder itself
+ IContainer currentFolder = (IFolder) resource;
+
+ IPath pathSuffix = resourcePath.removeFirstSegments(sourceFolderPath.segmentCount());
+ IPath targetPath = this.outputLocation.append(pathSuffix);
+ IFolder targetFolder = this.root.getFolder(targetPath);
+ if (!targetFolder.exists()){
+ try {
+ targetFolder.create(true, true, null);
+ } catch(CoreException e){
+ //throw this.devContext.internalException(e);
}
- break;
- case IResource.FOLDER :
- IContainer currentFolder = (IFolder) resource;
+ }
+ break;
+ }
+ return true;
+}
+/**
+ * Delete the corresponding resource from the output folder
+ */
+private boolean deleteResourceCopyFromOutput(IResource resource) {
+
+ IPath sourceFolderPath = getSourceFolderPath(resource);
+ if (sourceFolderPath == null) return false; // resource is not inside the classpath
+
+ IPath resourcePath = resource.getFullPath();
+ if (resourcePath.equals(sourceFolderPath)) return true; // skip source folder itself
+ if (resourcePath.equals(this.outputLocation)) return false; // do not visit the binary output
+ IPath pathSuffix, targetPath;
+
+ switch (resource.getType()){
+ case IResource.FILE :
+ if (!"java".equals(resource.getFileExtension())){ // ignore source files
+
+ IFile currentFile = (IFile) resource;
pathSuffix = resourcePath.removeFirstSegments(sourceFolderPath.segmentCount());
targetPath = this.outputLocation.append(pathSuffix);
- IFolder targetFolder = this.root.getFolder(targetPath);
- if (targetFolder.exists()) {
- try {
- targetFolder.delete(true, false, null);
- } catch (CoreException e) {
- throw this.devContext.internalException(e);
- }
+ try {
+ IFile previousFile = this.root.getFile(targetPath);
+ if (previousFile.exists()) previousFile.delete(true, true, null);
+ } catch(CoreException e){
+ //throw this.devContext.internalException(e);
}
- break;
- }
- return false;
- }
-
- /**
- * Answer the path of the classpath source folder entry enclosing a given resource (if the resource is on the classpath)
- */
- private IPath getSourceFolderPath(IResource resource) {
-
- IPath resourcePath = resource.getFullPath();
- for (int i = 0, length = this.sourceFolders.length; i < length; i++) {
- if (this.sourceFolders[i] != null) {
- IPath sourceFolderPath = this.sourceFolders[i].getFullPath();
- if (sourceFolderPath.isPrefixOf(resourcePath)) {
- return sourceFolderPath;
+ }
+ break;
+ case IResource.FOLDER :
+ IContainer currentFolder = (IFolder) resource;
+ pathSuffix = resourcePath.removeFirstSegments(sourceFolderPath.segmentCount());
+ targetPath = this.outputLocation.append(pathSuffix);
+ IFolder targetFolder = this.root.getFolder(targetPath);
+ if (targetFolder.exists()){
+ try {
+ targetFolder.delete(true, false, null);
+ } catch(CoreException e){
+ //throw this.devContext.internalException(e);
}
}
- }
- return null;
+ break;
}
-
- /**
- * Traverse an existing delta and update the affected resources in the binary output
- */
- public void updateAffectedResources(IResourceDelta delta) {
-
- // check that there is anything to do (if any source folder is not coincidating with the binary output)
- boolean hasNotified = false;
- for (int i = 0, length = this.sourceFolders.length; i < length; i++) {
- if (sourceFolders[i] != null) {
- if (this.outputLocation.equals(this.sourceFolders[i].getFullPath()))
- continue; // do nothing if output is same as source folder
- if (!hasNotified) {
- hasNotified = true;
- if (notifier != null)
- notifier.subTask("Updating resources on the classpath");
- }
+ return false;
+}
+/**
+ * Answer the path of the classpath source folder entry enclosing a given resource (if the resource is on the classpath)
+ */
+private IPath getSourceFolderPath(IResource resource) {
+
+ IPath resourcePath = resource.getFullPath();
+ for (int i = 0, length = this.sourceFolders.length; i < length; i++){
+ if (this.sourceFolders[i] != null){
+ IPath sourceFolderPath = this.sourceFolders[i].getFullPath();
+ if (sourceFolderPath.isPrefixOf(resourcePath)){
+ return sourceFolderPath;
}
}
- if (hasNotified)
- updateAffectedResources0(delta);
}
-
- /**
- * Traverse an existing delta and update the affected resources in the binary output
- */
- private void updateAffectedResources0(IResourceDelta delta) {
-
- IResource affectedResource = delta.getResource();
- boolean processChildren = true;
- switch (delta.getKind()) {
- case IResourceDelta.ADDED :
- case IResourceDelta.CHANGED :
- processChildren = copyToOutput(affectedResource);
- break;
- case IResourceDelta.REMOVED :
- processChildren = deleteResourceCopyFromOutput(affectedResource);
- }
- if (processChildren) {
- IResourceDelta[] children = delta.getAffectedChildren();
- for (int i = 0; i < children.length; i++) {
- updateAffectedResources0(children[i]);
+ return null;
+}
+/**
+ * Traverse an existing delta and update the affected resources in the binary output
+ */
+ public void updateAffectedResources(IResourceDelta delta){
+
+ // check that there is anything to do (if any source folder is not coincidating with the binary output)
+ boolean hasNotified = false;
+ for (int i = 0, length = this.sourceFolders.length; i < length; i++) {
+ if (sourceFolders[i] != null){
+ if (this.outputLocation.equals(this.sourceFolders[i].getFullPath())) continue; // do nothing if output is same as source folder
+ if (!hasNotified){
+ hasNotified = true;
+ if (notifier != null) notifier.subTask("Updating resources on the classpath");
}
}
}
-
- /** Visits the given resource.
- *
- * @param resource the resource to visit
- * @return <code>true</code> if the resource's members should
- * be visited; <code>false</code> if they should be skipped
- * @exception CoreException if the visit fails for some reason.
- */
- public boolean visit(IResource resource) throws CoreException {
-
- return copyToOutput(resource);
- // binary output should be empty, just copy current resources
+ if (hasNotified)
+ updateAffectedResources0(delta);
+}
+/**
+ * Traverse an existing delta and update the affected resources in the binary output
+ */
+ private void updateAffectedResources0(IResourceDelta delta){
+
+ IResource affectedResource = delta.getResource();
+ boolean processChildren = true;
+ switch (delta.getKind()) {
+ case IResourceDelta.ADDED:
+ case IResourceDelta.CHANGED:
+ processChildren = copyToOutput(affectedResource);
+ break;
+ case IResourceDelta.REMOVED:
+ processChildren = deleteResourceCopyFromOutput(affectedResource);
+ }
+ if (processChildren){
+ IResourceDelta[] children = delta.getAffectedChildren();
+ for (int i = 0; i < children.length; i++) {
+ updateAffectedResources0(children[i]);
+ }
}
+}
+/** Visits the given resource.
+ *
+ * @param resource the resource to visit
+ * @return <code>true</code> if the resource's members should
+ * be visited; <code>false</code> if they should be skipped
+ * @exception CoreException if the visit fails for some reason.
+ */
+public boolean visit(IResource resource) throws CoreException {
+ return copyToOutput(resource); // binary output should be empty, just copy current resources
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ReportCardImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ReportCardImpl.java
index fb3d175c88..f2728f8a56 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ReportCardImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ReportCardImpl.java
@@ -14,159 +14,138 @@ import java.util.*;
public class ReportCardImpl implements IReportCard {
private StateImpl fState;
private ImageContextImpl fImageContext;
- public ReportCardImpl(StateImpl state, IImageContext context) {
- fState = state;
- fImageContext = (ImageContextImpl) context;
- }
-
- public IPath[] changedPaths(IReportCard previous) {
- Hashtable myProblemTable = problemTableFrom(getLeafProblemsFor(null));
- Hashtable prevProblemTable =
- problemTableFrom(previous.getLeafProblemsFor(null));
- Hashtable changed = new Hashtable();
-
- /* do for all problems in the new table */
- for (Enumeration e = myProblemTable.keys(); e.hasMoreElements();) {
- IPath path = (IPath) e.nextElement();
- Hashtable myProblems = (Hashtable) myProblemTable.get(path);
- Hashtable prevProblems = (Hashtable) prevProblemTable.remove(path);
- if (prevProblems == null || !setCompare(myProblems, prevProblems)) {
- changed.put(path, path);
- }
- }
-
- /* pick up all problems that are only in the old table */
- for (Enumeration e = prevProblemTable.keys(); e.hasMoreElements();) {
- IPath path = (IPath) e.nextElement();
+public ReportCardImpl(StateImpl state, IImageContext context) {
+ fState = state;
+ fImageContext = (ImageContextImpl)context;
+}
+public IPath[] changedPaths(IReportCard previous) {
+ Hashtable myProblemTable = problemTableFrom(getLeafProblemsFor(null));
+ Hashtable prevProblemTable = problemTableFrom(previous.getLeafProblemsFor(null));
+ Hashtable changed = new Hashtable();
+
+ /* do for all problems in the new table */
+ for (Enumeration e = myProblemTable.keys(); e.hasMoreElements();) {
+ IPath path = (IPath) e.nextElement();
+ Hashtable myProblems = (Hashtable) myProblemTable.get(path);
+ Hashtable prevProblems = (Hashtable) prevProblemTable.remove(path);
+ if (prevProblems == null || !setCompare(myProblems, prevProblems)) {
changed.put(path, path);
- }
+ }
+ }
- /* convert results to array */
- IPath[] results = new IPath[changed.size()];
- int i = 0;
- for (Enumeration e = changed.keys(); e.hasMoreElements(); i++) {
- results[i] = (IPath) e.nextElement();
- }
- return results;
+ /* pick up all problems that are only in the old table */
+ for (Enumeration e = prevProblemTable.keys(); e.hasMoreElements();) {
+ IPath path = (IPath) e.nextElement();
+ changed.put(path, path);
}
+ /* convert results to array */
+ IPath[] results = new IPath[changed.size()];
+ int i = 0;
+ for (Enumeration e = changed.keys(); e.hasMoreElements();i++) {
+ results[i] = (IPath) e.nextElement();
+ }
+ return results;
+}
/**
* Returns all the problems for this state
*/
private void getAllProblems(Vector results) {
/* iterate through problems in the problem table */
- for (Enumeration e = fState.getProblemReporter().getAllProblems();
- e.hasMoreElements();
- ) {
+ for (Enumeration e = fState.getProblemReporter().getAllProblems(); e.hasMoreElements();) {
results.addElement(e.nextElement());
}
-
+
/* go through all problems attached to the image itself */
for (Enumeration e = fState.getProblems(); e.hasMoreElements();) {
results.addElement(e.nextElement());
}
}
+public IImageContext getImageContext() {
+ return fImageContext;
+}
+public IProblemDetail[] getLeafProblemsFor(IPath path) {
+ Vector vResults = new Vector();
- public IImageContext getImageContext() {
- return fImageContext;
+ /* if we want all problems */
+ if (path == null) {
+ getAllProblems(vResults);
}
-
- public IProblemDetail[] getLeafProblemsFor(IPath path) {
- Vector vResults = new Vector();
-
- /* if we want all problems */
- if (path == null) {
- getAllProblems(vResults);
- } else {
- getProblemsForPath(path, vResults);
- }
- /* convert to array */
- IProblemDetail[] results = new IProblemDetail[vResults.size()];
- vResults.copyInto(results);
- return results;
+ else {
+ getProblemsForPath(path, vResults);
}
-
- public IPath[] getProblemPaths(IPath path) {
- Hashtable set = new Hashtable();
-
- /* build set of all element IDs */
- IProblemDetail[] problems = getLeafProblemsFor(path);
- for (int i = 0; i < problems.length; i++) {
- IPath problemPath =
- ((ProblemDetailImpl) problems[i]).getSourceEntry().getPath();
- set.put(problemPath, problemPath);
- }
-
- /* convert set to array */
- IPath[] results = new IPath[set.size()];
- int i = 0;
- for (Enumeration e = set.keys(); e.hasMoreElements();) {
- results[i++] = (IPath) e.nextElement();
- }
- return results;
+ /* convert to array */
+ IProblemDetail[] results = new IProblemDetail[vResults.size()];
+ vResults.copyInto(results);
+ return results;
+}
+public IPath[] getProblemPaths(IPath path) {
+ Hashtable set = new Hashtable();
+
+ /* build set of all element IDs */
+ IProblemDetail[] problems = getLeafProblemsFor(path);
+ for (int i = 0; i < problems.length; i++) {
+ IPath problemPath = ((ProblemDetailImpl) problems[i]).getSourceEntry().getPath();
+ set.put(problemPath, problemPath);
}
- private void getProblemsForPath(IPath path, Vector vResults) {
- for (Enumeration e = fState.getProblemReporter().getProblemKeys();
- e.hasMoreElements();
- ) {
- SourceEntry sEntry = (SourceEntry) e.nextElement();
- IPath sEntryPath = sEntry.getPath();
- if (path.isPrefixOf(sEntryPath)) {
- String extension = sEntryPath.getFileExtension();
- // test most frequent cases first
- if (extension != null
- && (extension.toLowerCase().equals("java")
- || extension.toLowerCase().equals("class"))) {
- getProblemsForSourceEntry(sEntry, vResults);
- } else {
- if (fState.isZipElement(sEntryPath)) {
- getProblemsForZip(sEntryPath, vResults);
- }
+ /* convert set to array */
+ IPath[] results = new IPath[set.size()];
+ int i = 0;
+ for (Enumeration e = set.keys(); e.hasMoreElements();) {
+ results[i++] = (IPath) e.nextElement();
+ }
+ return results;
+}
+private void getProblemsForPath(IPath path, Vector vResults) {
+ for (Enumeration e = fState.getProblemReporter().getProblemKeys(); e.hasMoreElements();) {
+ SourceEntry sEntry = (SourceEntry)e.nextElement();
+ IPath sEntryPath = sEntry.getPath();
+ if (path.isPrefixOf(sEntryPath)) {
+ String extension = sEntryPath.getFileExtension();
+ // test most frequent cases first
+ if (extension != null && (extension.toLowerCase().equals("java") || extension.toLowerCase().equals("class"))) {
+ getProblemsForSourceEntry(sEntry, vResults);
+ } else {
+ if (fState.isZipElement(sEntryPath)) {
+ getProblemsForZip(sEntryPath, vResults);
}
}
}
}
-
- private void getProblemsForSourceEntry(SourceEntry sEntry, Vector results) {
- IProblemReporter pbReporter = fState.getProblemReporter();
- if (pbReporter.hasProblems(sEntry)) {
- // Only check image context if there are really problems with this element
- IPackage pkg =
- fState.getPathMap().packageHandleFromPath(
- sEntry.getPath().removeLastSegments(1));
- if (fImageContext == null || fImageContext.containsPackage(pkg)) {
- for (Enumeration e = pbReporter.getProblems(sEntry); e.hasMoreElements();) {
- results.addElement(e.nextElement());
- }
+}
+private void getProblemsForSourceEntry(SourceEntry sEntry, Vector results) {
+ IProblemReporter pbReporter = fState.getProblemReporter();
+ if (pbReporter.hasProblems(sEntry)) {
+ // Only check image context if there are really problems with this element
+ IPackage pkg = fState.getPathMap().packageHandleFromPath(sEntry.getPath().removeLastSegments(1));
+ if (fImageContext == null || fImageContext.containsPackage(pkg)) {
+ for (Enumeration e = pbReporter.getProblems(sEntry); e.hasMoreElements();) {
+ results.addElement(e.nextElement());
}
}
}
-
- protected void getProblemsForZip(IPath zipPath, Vector results) {
- // avoid iterating over all entries in the zip file
- IProblemReporter pbReporter = fState.getProblemReporter();
- for (Enumeration e = pbReporter.getAllProblems(); e.hasMoreElements();) {
- ProblemDetailImpl problem = (ProblemDetailImpl) e.nextElement();
- SourceEntry sEntry = problem.getSourceEntry();
- if (sEntry.fZipEntryFileName != null && sEntry.getPath().equals(zipPath)) {
- // Check image context.
- if (fImageContext == null
- || fImageContext.containsPackage(fState.packageFromSourceEntry(sEntry))) {
- results.addElement(problem);
- }
+}
+protected void getProblemsForZip(IPath zipPath, Vector results) {
+ // avoid iterating over all entries in the zip file
+ IProblemReporter pbReporter = fState.getProblemReporter();
+ for (Enumeration e = pbReporter.getAllProblems(); e.hasMoreElements();) {
+ ProblemDetailImpl problem = (ProblemDetailImpl) e.nextElement();
+ SourceEntry sEntry = problem.getSourceEntry();
+ if (sEntry.fZipEntryFileName != null && sEntry.getPath().equals(zipPath)) {
+ // Check image context.
+ if (fImageContext == null || fImageContext.containsPackage(fState.packageFromSourceEntry(sEntry))) {
+ results.addElement(problem);
}
}
}
-
- public IState getState() {
- return fState;
- }
-
- public boolean hasLeafProblems(IPath path) {
- return getLeafProblemsFor(path).length > 0;
- }
-
+}
+public IState getState() {
+ return fState;
+}
+public boolean hasLeafProblems(IPath path) {
+ return getLeafProblemsFor(path).length > 0;
+}
/**
* Returns a dictionary of problems keyed by their path.
* Each entry in the dictionary is a set of problems. The set is implemented as a
@@ -176,19 +155,18 @@ public class ReportCardImpl implements IReportCard {
private Hashtable problemTableFrom(IProblemDetail[] problems) {
Hashtable table = new Hashtable(25);
for (int i = 0; i < problems.length; i++) {
- IPath path = ((ProblemDetailImpl) problems[i]).getPath();
- if (path != null) {
+ IPath path = ((ProblemDetailImpl) problems[i]).getPath();
+ if (path != null) {
Hashtable entry = (Hashtable) table.get(path);
if (entry == null) {
entry = new Hashtable(10);
- table.put(path, entry);
+ table.put(path,entry);
}
entry.put(problems[i], problems[i]);
}
}
return table;
}
-
/**
* Returns true if the two sets of problems are the same, false otherwise.
* Don't use ProblemDetail.equals() because it doesn't consider source
@@ -202,7 +180,7 @@ public class ReportCardImpl implements IReportCard {
/* iterate through both tables */
for (Enumeration e = myProblems.keys(); e.hasMoreElements();) {
ProblemDetailImpl a = (ProblemDetailImpl) myProblems.get(e.nextElement());
- ProblemDetailImpl b = (ProblemDetailImpl) prevProblems.get(a);
+ ProblemDetailImpl b = (ProblemDetailImpl) prevProblems.get(a);
if (b == null) {
/* problem is not in prevProblems */
return false;
@@ -210,7 +188,7 @@ public class ReportCardImpl implements IReportCard {
}
for (Enumeration e = prevProblems.keys(); e.hasMoreElements();) {
ProblemDetailImpl a = (ProblemDetailImpl) prevProblems.get(e.nextElement());
- ProblemDetailImpl b = (ProblemDetailImpl) myProblems.get(a);
+ ProblemDetailImpl b = (ProblemDetailImpl) myProblems.get(a);
if (b == null) {
/* problem is not in myProblems */
return false;
@@ -218,5 +196,4 @@ public class ReportCardImpl implements IReportCard {
}
return true;
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/SourceElementTable.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/SourceElementTable.java
index 0f710da0c0..8d8446a91e 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/SourceElementTable.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/SourceElementTable.java
@@ -17,7 +17,7 @@ import java.util.Enumeration;
* table is keyed by name of source file name (e.g., "Object.class", or "Foo.java"),
* and has SourceEntry objects as values.
*/
-class SourceElementTable extends StateTables {
+class SourceElementTable extends StateTables{
LookupTable fPackageTable = new LookupTable(11);
/**
* Returns true if the package is in the table, false otherwise.
@@ -25,7 +25,6 @@ class SourceElementTable extends StateTables {
boolean containsPackage(IPackage pkg) {
return fPackageTable.containsKey(pkg);
}
-
/**
* Creates a copy of the table.
*/
@@ -39,95 +38,87 @@ class SourceElementTable extends StateTables {
copy.fPackageTable.put(pkg, pkgTable.clone());
}
return copy;
- } catch (CloneNotSupportedException e) {
+ }
+ catch (CloneNotSupportedException e) {
// Should not happen.
throw new Error();
}
}
-
/**
* Returns the table for a package. Returns null if no such table exists.
*/
LookupTable getPackageTable(IPackage pkg) {
return (LookupTable) fPackageTable.get(pkg);
}
-
- /**
- * Returns the source entries in the given package.
- * Returns null if no entries exist for that package.
- */
- SourceEntry[] getSourceEntries(IPackage pkg) {
- LookupTable pkgTable = getPackageTable(pkg);
- if (pkgTable == null) {
- return null;
- }
- int i = 0;
- SourceEntry[] results = new SourceEntry[pkgTable.size()];
- for (Enumeration e = pkgTable.elements(); e.hasMoreElements();) {
- results[i++] = (SourceEntry) e.nextElement();
- }
- return results;
- }
-
- /**
- * Returns the source entry for a package and file name. Returns null if
- * no entry exists.
- */
- SourceEntry getSourceEntry(IPackage pkg, String fileName) {
- /* make sure package is not state specific */
- Assert.isTrue(!pkg.isStateSpecific());
- LookupTable pkgTable = getPackageTable(pkg);
- if (pkgTable != null) {
- Assert.isTrue(fileName.indexOf('.') != -1, "name must have extension");
- return (SourceEntry) pkgTable.get(fileName);
- }
+/**
+ * Returns the source entries in the given package.
+ * Returns null if no entries exist for that package.
+ */
+SourceEntry[] getSourceEntries(IPackage pkg) {
+ LookupTable pkgTable = getPackageTable(pkg);
+ if (pkgTable == null) {
return null;
}
-
+ int i = 0;
+ SourceEntry[] results = new SourceEntry[pkgTable.size()];
+ for (Enumeration e = pkgTable.elements(); e.hasMoreElements();) {
+ results[i++] = (SourceEntry) e.nextElement();
+ }
+ return results;
+}
+/**
+ * Returns the source entry for a package and file name. Returns null if
+ * no entry exists.
+ */
+SourceEntry getSourceEntry(IPackage pkg, String fileName) {
+ /* make sure package is not state specific */
+ Assert.isTrue(!pkg.isStateSpecific());
+ LookupTable pkgTable = getPackageTable(pkg);
+ if (pkgTable != null) {
+ Assert.isTrue(fileName.indexOf('.') != -1, "name must have extension");
+ return (SourceEntry) pkgTable.get(fileName);
+ }
+ return null;
+}
/**
* Returns the number of packages in the table.
*/
int numPackages() {
return fPackageTable.size();
}
-
/**
* Adds the table for a package to the table.
*/
void putPackageTable(IPackage pkg, LookupTable pkgTable) {
fPackageTable.put(pkg, pkgTable);
}
-
/**
* Adds one source entry in the source element table
*/
public void putSourceEntry(IPackage pkg, SourceEntry sourceEntry) {
LookupTable pkgTable = getPackageTable(pkg);
- if (pkgTable == null) {
+ if (pkgTable == null){
putPackageTable(pkg, pkgTable = new LookupTable());
}
pkgTable.put(sourceEntry.getFileName(), sourceEntry);
}
-
/**
* Removes the source entries for a package.
*/
void removePackage(IPackage pkg) {
fPackageTable.remove(pkg);
}
-
- /**
- * Removes the source entry for a source element. Returns the
- * removed element or null if it didn't exist
- */
- SourceEntry removeSourceEntry(IPackage pkg, String fileName) {
- LookupTable pkgTable = getPackageTable(pkg);
- if (pkgTable != null) {
- return (SourceEntry) pkgTable.remove(fileName);
- }
- return null;
+/**
+ * Removes the source entry for a source element. Returns the
+ * removed element or null if it didn't exist
+ */
+SourceEntry removeSourceEntry(IPackage pkg, String fileName) {
+ LookupTable pkgTable = getPackageTable(pkg);
+ if (pkgTable != null) {
+ return (SourceEntry) pkgTable.remove(fileName);
}
-
+ return null;
+}
/**
* Returns a String that represents the value of this object.
* @return a string representation of the receiver
@@ -135,5 +126,4 @@ class SourceElementTable extends StateTables {
public String toString() {
return "SourceElementTable(" + fPackageTable + ")";
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/SourceEntry.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/SourceEntry.java
index 8ae8019df6..b90a098504 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/SourceEntry.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/SourceEntry.java
@@ -21,18 +21,16 @@ public class SourceEntry extends StateTables {
/**
* Creates a new SourceEntry.
*/
- public SourceEntry(IPath path, String zipEntryPath, String zipEntryFileName) {
+ public SourceEntry(IPath path , String zipEntryPath, String zipEntryFileName) {
fPath = path;
fZipEntryPath = zipEntryPath;
fZipEntryFileName = zipEntryFileName;
}
-
public boolean equals(Object o) {
- if (this == o)
- return true;
+ if (this == o) return true;
if (!(o instanceof SourceEntry))
return false;
- SourceEntry entry = (SourceEntry) o;
+ SourceEntry entry = (SourceEntry)o;
if (!this.fPath.equals(entry.fPath))
return false;
if (!Util.equalOrNull(fZipEntryPath, entry.fZipEntryPath))
@@ -41,31 +39,29 @@ public class SourceEntry extends StateTables {
return false;
return true;
}
-
- public static SourceEntry fromPathWithZipEntryName(String pathWithZipEntryName) {
- // Convert separators back. See getPathWithZipEntryName().
- pathWithZipEntryName = pathWithZipEntryName.replace(File.separatorChar, '/');
- int i = pathWithZipEntryName.lastIndexOf('#');
- if (i == -1) {
- return new SourceEntry(new Path(pathWithZipEntryName), null, null);
- } else {
- Path path = new Path(pathWithZipEntryName.substring(0, i));
- String zipEntryName = pathWithZipEntryName.substring(i + 1);
- String zipEntryPath = null, zipEntryFileName = null;
- if (zipEntryName != null) {
- int pos = zipEntryName.lastIndexOf('/');
- if (pos != -1) {
- zipEntryPath = zipEntryName.substring(0, pos);
- zipEntryFileName = zipEntryName.substring(pos + 1);
- } else {
- zipEntryPath = null;
- zipEntryFileName = zipEntryName;
- }
+public static SourceEntry fromPathWithZipEntryName(String pathWithZipEntryName) {
+ // Convert separators back. See getPathWithZipEntryName().
+ pathWithZipEntryName = pathWithZipEntryName.replace(File.separatorChar, '/');
+ int i = pathWithZipEntryName.lastIndexOf('#');
+ if (i == -1) {
+ return new SourceEntry(new Path(pathWithZipEntryName), null, null);
+ } else {
+ Path path = new Path(pathWithZipEntryName.substring(0, i));
+ String zipEntryName = pathWithZipEntryName.substring(i + 1);
+ String zipEntryPath = null, zipEntryFileName = null;
+ if (zipEntryName != null) {
+ int pos = zipEntryName.lastIndexOf('/');
+ if (pos != -1) {
+ zipEntryPath = zipEntryName.substring(0, pos);
+ zipEntryFileName = zipEntryName.substring(pos + 1);
+ } else {
+ zipEntryPath = null;
+ zipEntryFileName = zipEntryName;
}
- return new SourceEntry(path, zipEntryPath, zipEntryFileName);
}
+ return new SourceEntry(path, zipEntryPath, zipEntryFileName);
}
-
+}
/**
* Returns the 'file name'.
*/
@@ -75,39 +71,31 @@ public class SourceEntry extends StateTables {
}
return fPath.lastSegment();
}
-
- /**
- * Returns the 'file name' without the file extension.
- */
- public String getName() {
- String name = getFileName();
- int lastDot = name.lastIndexOf('.');
- if (lastDot != -1)
- name = name.substring(0, lastDot);
- return name;
- }
-
+/**
+ * Returns the 'file name' without the file extension.
+ */
+public String getName() {
+ String name = getFileName();
+ int lastDot = name.lastIndexOf('.');
+ if (lastDot != -1)
+ name = name.substring(0, lastDot);
+ return name;
+}
public IPath getPath() {
return fPath;
}
-
- public String getPathWithZipEntryName() {
- String s =
- fZipEntryFileName == null
- ? fPath.toString()
- : fPath.toString() + '#' + this.getZipEntryName();
- // Convert separators.
- // See 1FVQGE2: ITPJCORE:ALL - Class file has workbench relative source file attribute
- // and 1FW1LHM: LFCOM:ALL - Source file names and dependency info
- return s.replace('/', File.separatorChar);
- }
-
+public String getPathWithZipEntryName() {
+ String s = fZipEntryFileName == null ?
+ fPath.toString() :
+ fPath.toString() + '#' + this.getZipEntryName();
+ // Convert separators.
+ // See 1FVQGE2: ITPJCORE:ALL - Class file has workbench relative source file attribute
+ // and 1FW1LHM: LFCOM:ALL - Source file names and dependency info
+ return s.replace('/', File.separatorChar);
+}
public String getZipEntryName() {
- return fZipEntryPath == null
- ? fZipEntryFileName
- : fZipEntryPath + "/" + fZipEntryFileName;
+ return fZipEntryPath == null ? fZipEntryFileName : fZipEntryPath + "/" + fZipEntryFileName;
}
-
public int hashCode() {
int code = fPath.hashCode();
if (fZipEntryPath != null) {
@@ -118,7 +106,6 @@ public class SourceEntry extends StateTables {
}
return code;
}
-
/**
* Returns true if the source entry comes from a binary file, otherwise
* returns false.
@@ -130,7 +117,6 @@ public class SourceEntry extends StateTables {
String extension = fPath.getFileExtension();
return extension != null && extension.equalsIgnoreCase("class");
}
-
/**
* Returns true if the source entry comes from a compilation unit, otherwise
* returns false.
@@ -142,15 +128,11 @@ public class SourceEntry extends StateTables {
String extension = fPath.getFileExtension();
return extension != null && extension.equalsIgnoreCase("java");
}
-
- /**
- * Returns a String that represents the value of this object.
- * @return a string representation of the receiver
- */
- public String toString() {
- return fZipEntryFileName == null
- ? fPath.toString()
- : fPath.toString() + ", entry: " + this.getZipEntryName();
- }
-
+/**
+ * Returns a String that represents the value of this object.
+ * @return a string representation of the receiver
+ */
+public String toString() {
+ return fZipEntryFileName == null ? fPath.toString() : fPath.toString() + ", entry: " + this.getZipEntryName();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/SourceFragmentImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/SourceFragmentImpl.java
index 6fb1d29cf4..3ed0bf877c 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/SourceFragmentImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/SourceFragmentImpl.java
@@ -13,67 +13,56 @@ public class SourceFragmentImpl implements ISourceFragment {
private int fStartPos, fEndPos;
private IPath fPath;
private String fZipEntryName;
- public SourceFragmentImpl(int start, int end, IPath path) {
+ public SourceFragmentImpl (int start, int end, IPath path) {
fStartPos = start;
fEndPos = end;
fPath = path;
}
-
- public SourceFragmentImpl(int start, int end, SourceEntry sourceEntry) {
+ public SourceFragmentImpl (int start, int end, SourceEntry sourceEntry) {
fStartPos = start;
fEndPos = end;
fPath = sourceEntry.getPath();
fZipEntryName = sourceEntry.getZipEntryName();
}
-
- public SourceFragmentImpl(SourceEntry sourceEntry) {
+ public SourceFragmentImpl (SourceEntry sourceEntry) {
this(-1, -1, sourceEntry);
}
-
/**
* Compares this object against the specified object.
* Returns true if the objects are the same.
*/
public boolean equals(Object o) {
- if (this == o)
- return true;
- if (!(o instanceof SourceFragmentImpl))
- return false;
+ if (this == o) return true;
+ if (!(o instanceof SourceFragmentImpl)) return false;
SourceFragmentImpl frag = (SourceFragmentImpl) o;
- if (this.fStartPos != frag.fStartPos || this.fEndPos != frag.fEndPos)
+ if (this.fStartPos != frag.fStartPos || this.fEndPos != frag.fEndPos)
return false;
if (!Util.equalOrNull(this.fPath, frag.fPath))
return false;
return Util.equalOrNull(this.fZipEntryName, frag.fZipEntryName);
}
-
- public IPath getPath() {
- return fPath;
- }
-
- /**
- * getZipEntryName method comment.
- */
- public String getZipEntryName() {
- return fZipEntryName;
- }
-
+public IPath getPath() {
+ return fPath;
+}
+/**
+ * getZipEntryName method comment.
+ */
+public String getZipEntryName() {
+ return fZipEntryName;
+}
/**
* Returns a consistent hashcode for this source fragment
*/
public int hashCode() {
return fStartPos + fEndPos + fPath.hashCode() + fZipEntryName.hashCode();
}
-
/**
* Returns a string representation of the receiver.
*/
public String toString() {
- return "SourceFragmentImpl("
- + fPath
- + (fZipEntryName == null ? "" : " : " + fZipEntryName)
- + ")";
+ return
+ "SourceFragmentImpl(" + fPath
+ + (fZipEntryName == null ? "" : " : " + fZipEntryName) + ")";
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateImpl.java
index 214bfabf1f..2f8a4148de 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateImpl.java
@@ -115,7 +115,7 @@ public class StateImpl implements IState {
* The graph of source element dependencies, used for
* incremental compilation
*/
- private DependencyGraph fGraph = null;
+ private DependencyGraph fGraph= null;
/**
* The table of subtypes. Maps from IType to TypeStructureEntry[]. Absence in table implies no subtypes.
@@ -157,106 +157,92 @@ public class StateImpl implements IState {
/**
* Counter for unique state numbers (not the fingerprint).
*/
- private static int fgStateCounter = 0;
+ private static int fgStateCounter= 0;
/**
* Namespace flag indicating CU has parse error.
* Must not conflict with modifiers or other flags in IConstants.
*/
- private static final int F_HAS_PARSE_ERROR = 0x10000000;
+ private static final int F_HAS_PARSE_ERROR= 0x10000000;
/**
* Name for namespace node representing unknown dependencies.
*/
- private static final String UNKNOWN_DEPENDENCIES = "$UNKNOWN_DEPENDENCIES$";
+ private static final String UNKNOWN_DEPENDENCIES= "$UNKNOWN_DEPENDENCIES$";
/**
* Random number generator, used for generating fingerprints.
*/
- private static final Random fgRandom = new Random();
+ private static final Random fgRandom= new Random();
/**
* State constructor comment. The build context, fingerprint, and internal tables
* are not instantiated and must be filled in before use.
*/
protected StateImpl(JavaDevelopmentContextImpl dc, IProject project) {
- fDevelopmentContext = dc;
- fProject = project;
- fStateNumber = fgStateCounter++;
- fImage = new ImageImplSWH(this, (ImageImpl) dc.getImage());
- fVoidType = new PrimitiveTypeHandleImplSWH(this, dc.fVoidType);
- fIntType = new PrimitiveTypeHandleImplSWH(this, dc.fIntType);
- fByteType = new PrimitiveTypeHandleImplSWH(this, dc.fByteType);
- fCharType = new PrimitiveTypeHandleImplSWH(this, dc.fCharType);
- fDoubleType = new PrimitiveTypeHandleImplSWH(this, dc.fDoubleType);
- fFloatType = new PrimitiveTypeHandleImplSWH(this, dc.fFloatType);
- fLongType = new PrimitiveTypeHandleImplSWH(this, dc.fLongType);
- fShortType = new PrimitiveTypeHandleImplSWH(this, dc.fShortType);
- fBooleanType = new PrimitiveTypeHandleImplSWH(this, dc.fBooleanType);
- fFingerprint = generateFingerprint();
+ fDevelopmentContext= dc;
+ fProject= project;
+ fStateNumber= fgStateCounter++;
+ fImage= new ImageImplSWH(this, (ImageImpl) dc.getImage());
+ fVoidType= new PrimitiveTypeHandleImplSWH(this, dc.fVoidType);
+ fIntType= new PrimitiveTypeHandleImplSWH(this, dc.fIntType);
+ fByteType= new PrimitiveTypeHandleImplSWH(this, dc.fByteType);
+ fCharType= new PrimitiveTypeHandleImplSWH(this, dc.fCharType);
+ fDoubleType= new PrimitiveTypeHandleImplSWH(this, dc.fDoubleType);
+ fFloatType= new PrimitiveTypeHandleImplSWH(this, dc.fFloatType);
+ fLongType= new PrimitiveTypeHandleImplSWH(this, dc.fLongType);
+ fShortType= new PrimitiveTypeHandleImplSWH(this, dc.fShortType);
+ fBooleanType= new PrimitiveTypeHandleImplSWH(this, dc.fBooleanType);
+ fFingerprint= generateFingerprint();
}
-
/**
* State constructor comment.
*/
- protected StateImpl(
- JavaDevelopmentContextImpl dc,
- IProject project,
- IImageContext buildContext) {
+ protected StateImpl(JavaDevelopmentContextImpl dc, IProject project, IImageContext buildContext) {
this(dc, project);
- fBuildContext = buildContext;
+ fBuildContext= buildContext;
/* state tables */
- fPackageMap = new PackageMap();
- fSourceElementTable = new SourceElementTable();
- fPrincipalStructureTable = new Hashtable();
- fProblemReporter = new ProblemTable();
- fGraph = new DependencyGraph();
+ fPackageMap= new PackageMap();
+ fSourceElementTable= new SourceElementTable();
+ fPrincipalStructureTable= new Hashtable();
+ fProblemReporter= new ProblemTable();
+ fGraph= new DependencyGraph();
}
-
/**
* @see IState
*/
- public IImageBuilder applySourceDelta(
- IProject newProject,
- IResourceDelta projectDelta,
- IImageContext buildContext) {
+ public IImageBuilder applySourceDelta(IProject newProject, IResourceDelta projectDelta, IImageContext buildContext) {
/* create and return builder */
- IncrementalImageBuilder builder =
- new IncrementalImageBuilder(this, newProject, buildContext);
+ IncrementalImageBuilder builder= new IncrementalImageBuilder(this, newProject, buildContext);
builder.applySourceDelta(projectDelta);
return builder;
}
-
/**
* Creates state tables that are dependent only on the workspace, and not
* on build results. This includes the package map, source element table,
* and the namespace table.
*/
protected void buildInitialPackageMap() {
- fPackageMap = new PackageMap();
+ fPackageMap= new PackageMap();
/* do for each package fragment root in (classpath INTERSECT workspace) */
try {
- IPackageFragmentRoot[] roots = getPackageFragmentRootsInClassPath();
- IPath outputLocation = getJavaProject().getOutputLocation();
- for (int i = 0; i < roots.length; ++i) {
- IPackageFragmentRoot root = roots[i];
- if (root.exists()) {
- ((PackageFragmentRoot) root).refreshChildren();
- IJavaElement[] frags = root.getChildren();
- for (int j = 0; j < frags.length; ++j) {
- IPackageFragment frag = (IPackageFragment) frags[j];
- if (frag.exists()) {
- String pkgName = frag.getElementName();
- IPackage pkg =
- pkgName.length() == 0
- ? defaultPackageForProject()
- : fDevelopmentContext.getImage().getPackageHandle(pkgName, false);
- IPath path =
- root.isArchive() ? root.getPath() : frag.getUnderlyingResource().getFullPath();
+ IPackageFragmentRoot[] roots= getPackageFragmentRootsInClassPath();
+ IPath outputLocation= getJavaProject().getOutputLocation();
+ for (int i= 0; i < roots.length; ++i) {
+ PackageFragmentRoot root= (PackageFragmentRoot)roots[i];
+ if (root.exists0()) {
+ root.refreshChildren();
+ IJavaElement[] frags= root.getChildren();
+ for (int j= 0; j < frags.length; ++j) {
+ IPackageFragment frag= (IPackageFragment) frags[j];
+// if (frag.exists()) {
+ String pkgName= frag.getElementName();
+ IPackage pkg= pkgName.length() == 0 ? defaultPackageForProject() : fDevelopmentContext.getImage().getPackageHandle(pkgName, false);
+ IPath path= root.isArchive() ? root.getPath() : frag.getUnderlyingResource().getFullPath();
fPackageMap.putFragment(pkg, path);
- }
+// }
}
}
}
@@ -265,24 +251,18 @@ public class StateImpl implements IState {
}
/* build the reverse index -- the path map */
- fPathMap = new PathMap(fPackageMap);
+ fPathMap= new PathMap(fPackageMap);
}
-
protected void buildPrincipalStructureByPackageTable() {
- IPackage[] pkgs =
- fBuildContext != null
- ? fBuildContext.getPackages()
- : fPackageMap.getAllPackagesAsArray();
- Hashtable principalStructureByPackageTable = new Hashtable(pkgs.length * 2 + 1);
- for (int i = 0; i < pkgs.length; ++i) {
+ IPackage[] pkgs= fBuildContext != null ? fBuildContext.getPackages() : fPackageMap.getAllPackagesAsArray();
+ Hashtable principalStructureByPackageTable= new Hashtable(pkgs.length * 2 + 1);
+ for (int i= 0; i < pkgs.length; ++i) {
principalStructureByPackageTable.put(pkgs[i], new Vector(20));
}
- for (Enumeration e = fPrincipalStructureTable.elements();
- e.hasMoreElements();
- ) {
- TypeStructureEntry tsEntry = (TypeStructureEntry) e.nextElement();
- IPackage pkg = tsEntry.getType().getPackage();
- Vector v = (Vector) principalStructureByPackageTable.get(pkg);
+ for (Enumeration e= fPrincipalStructureTable.elements(); e.hasMoreElements();) {
+ TypeStructureEntry tsEntry= (TypeStructureEntry) e.nextElement();
+ IPackage pkg= tsEntry.getType().getPackage();
+ Vector v= (Vector) principalStructureByPackageTable.get(pkg);
/* Be careful to only gather types for packages in the given list.
Other packages may only be partially built. */
if (v != null) {
@@ -290,61 +270,52 @@ public class StateImpl implements IState {
}
}
/* Convert vectors to arrays */
- for (Enumeration e = principalStructureByPackageTable.keys();
- e.hasMoreElements();
- ) {
- IPackage pkg = (IPackage) e.nextElement();
- Vector v = (Vector) principalStructureByPackageTable.get(pkg);
- TypeStructureEntry[] tsEntries = new TypeStructureEntry[v.size()];
+ for (Enumeration e= principalStructureByPackageTable.keys(); e.hasMoreElements();) {
+ IPackage pkg= (IPackage) e.nextElement();
+ Vector v= (Vector) principalStructureByPackageTable.get(pkg);
+ TypeStructureEntry[] tsEntries= new TypeStructureEntry[v.size()];
v.copyInto(tsEntries);
principalStructureByPackageTable.put(pkg, tsEntries);
}
setPrincipalStructureByPackageTable(principalStructureByPackageTable);
}
-
/**
* Returns the type structure entry for the given type handle. Performs lazy
* analysis and compilation as necessary. Throws
* a NotPresentException if no element exists in the workspace that
* matches the given handle.
*/
- protected TypeStructureEntry buildTypeStructureEntry(IType handle)
- throws NotPresentException {
- TypeStructureEntry tsEntry = getTypeStructureEntry(handle, true);
+ protected TypeStructureEntry buildTypeStructureEntry(IType handle) throws NotPresentException {
+ TypeStructureEntry tsEntry= getTypeStructureEntry(handle, true);
if (tsEntry == null) {
throw new NotPresentException();
}
return tsEntry;
}
-
/**
* Canonicalize a package handle.
*/
protected IPackage canonicalize(IPackage pkg) {
- PackageMapEntry entry = fPackageMap.getEntry(pkg);
+ PackageMapEntry entry= fPackageMap.getEntry(pkg);
return entry != null ? entry.getPackage() : pkg;
}
-
/**
* Canonicalize a type handle.
*/
protected IType canonicalize(IType type) {
- TypeStructureEntry tsEntry =
- (TypeStructureEntry) fPrincipalStructureTable.get(type);
+ TypeStructureEntry tsEntry= (TypeStructureEntry) fPrincipalStructureTable.get(type);
if (tsEntry != null) {
return tsEntry.getType();
} else {
return type;
}
}
-
/**
* Canonicalizes the build context of this state through the package map.
*/
protected void canonicalizeBuildContext() {
- fBuildContext = canonicalizeBuildContext(fBuildContext);
+ fBuildContext= canonicalizeBuildContext(fBuildContext);
}
-
/**
* Returns a new build context that contains package handles
* that have been canonicalized in this state.
@@ -353,54 +324,47 @@ public class StateImpl implements IState {
if (oldContext == null) {
return null;
}
- IPackage[] oldPackages = oldContext.getPackages();
- int pkgCount = oldPackages.length;
- IPackage[] newPackages = new IPackage[pkgCount];
+ IPackage[] oldPackages= oldContext.getPackages();
+ int pkgCount= oldPackages.length;
+ IPackage[] newPackages= new IPackage[pkgCount];
/* canonicalize packages through package map */
- for (int i = 0; i < pkgCount; i++) {
- newPackages[i] = canonicalize(oldPackages[i]);
+ for (int i= 0; i < pkgCount; i++) {
+ newPackages[i]= canonicalize(oldPackages[i]);
}
return new ImageContextImpl(fDevelopmentContext, newPackages);
}
-
/**
* Clean up after a build.
*/
protected void cleanUp() {
//resetProject(); - no longer clear the project back pointer
}
-
/**
* Adds all binary broker keys still in use by this state
* to the given set.
*/
protected void collectBinaryBrokerKeys(Hashtable keysInUse) {
- for (Enumeration e = fPrincipalStructureTable.elements();
- e.hasMoreElements();
- ) {
- TypeStructureEntry tsEntry = (TypeStructureEntry) e.nextElement();
+ for (Enumeration e= fPrincipalStructureTable.elements(); e.hasMoreElements();) {
+ TypeStructureEntry tsEntry= (TypeStructureEntry) e.nextElement();
if (!tsEntry.isBinary()) {
- int crc = tsEntry.getCRC32();
+ int crc= tsEntry.getCRC32();
if (crc != 0) {
- IType type = tsEntry.getType();
- BinaryBrokerKey key = new BinaryBrokerKey(type, crc);
+ IType type= tsEntry.getType();
+ BinaryBrokerKey key= new BinaryBrokerKey(type, crc);
keysInUse.put(key, key);
}
}
}
}
-
/**
* Returns true if the given source entry contributes to the state, false otherwise.
*/
protected boolean contains(SourceEntry sEntry) {
- IPackage pkg = packageFromSourceEntry(sEntry);
- return getSourceElementTable().getSourceEntry(pkg, sEntry.getFileName())
- != null;
+ IPackage pkg= packageFromSourceEntry(sEntry);
+ return getSourceElementTable().getSourceEntry(pkg, sEntry.getFileName()) != null;
}
-
/**
* Converts a compilation result from the compiler's representation
* to the builder's representation. This version is to be called
@@ -408,114 +372,100 @@ public class StateImpl implements IState {
* this without having to parse the binary for principal structure
* information.
*/
- protected ConvertedCompilationResult convertCompilationResult(
- CompilationResult result,
- IPackage defaultPackage) {
- String fileName = new String(result.getFileName());
- SourceEntry sEntry = SourceEntry.fromPathWithZipEntryName(fileName);
- PackageElement resultUnit = packageElementFromSourceEntry(sEntry);
+ protected ConvertedCompilationResult convertCompilationResult(CompilationResult result, IPackage defaultPackage) {
+ String fileName= new String(result.getFileName());
+ SourceEntry sEntry= SourceEntry.fromPathWithZipEntryName(fileName);
+ PackageElement resultUnit= packageElementFromSourceEntry(sEntry);
/**
* Make sure the CU exists. May be null if unit is unavailable
* (e.g. package is not included in package map due to class path omission).
* If this is the case, we shouldn't have reached this point.
*/
- IPackage resultPkg = resultUnit.getPackage();
- IProblem[] compilerProblems = result.getProblems();
- Vector vProblems =
- new Vector(compilerProblems == null ? 0 : compilerProblems.length);
+ IPackage resultPkg= resultUnit.getPackage();
+ IProblem[] compilerProblems= result.getProblems();
+ Vector vProblems= new Vector(compilerProblems == null ? 0 : compilerProblems.length);
/* convert type names to type handles for the produced types */
- ClassFile[] classFiles = result.getClassFiles();
- Vector vTSEntries = new Vector(classFiles.length);
- boolean reportedPackageConflict = false;
- for (int i = 0; i < classFiles.length; ++i) {
- ClassFile classFile = classFiles[i];
- String className = Util.toString(classFile.getCompoundName());
+ ClassFile[] classFiles= result.getClassFiles();
+ Vector vTSEntries= new Vector(classFiles.length);
+ boolean reportedPackageConflict= false;
+ for (int i= 0; i < classFiles.length; ++i) {
+ ClassFile classFile= classFiles[i];
+ String className= Util.toString(classFile.getCompoundName());
if (classFile == null) {
// Could not discover principal structure
- String msg = "Error parsing binary for " + className;
- ProblemDetailImpl problem = new ProblemDetailImpl(msg, sEntry);
+ String msg= "Error parsing binary for " + className;
+ ProblemDetailImpl problem= new ProblemDetailImpl(msg, sEntry);
vProblems.addElement(problem);
// skip it
continue;
}
- IType typeHandle = typeNameToHandle(resultPkg, className);
- IPackage typePkg = typeHandle.getPackage();
+ IType typeHandle= typeNameToHandle(resultPkg, className);
+ IPackage typePkg= typeHandle.getPackage();
if (!resultPkg.equals(typePkg)) {
if (!reportedPackageConflict) {
// Fix for 1FW88LE: ITPJCORE:WIN2000 - What does the error mean (package declaration/package)
// and 1FW88DS: ITPJUI:WIN2000 - Go to file from task doesn't show line in editor
- IPath path = sEntry.getPath().removeLastSegments(1);
+ IPath path= sEntry.getPath().removeLastSegments(1);
if (!resultPkg.isUnnamed()) {
- path =
- path.removeLastSegments(
- new Path(resultPkg.getName().replace('.', IPath.SEPARATOR)).segmentCount());
+ path= path.removeLastSegments(new Path(resultPkg.getName().replace('.', IPath.SEPARATOR)).segmentCount());
}
if (!typePkg.isUnnamed()) {
- path = path.append(typePkg.getName().replace('.', IPath.SEPARATOR));
+ path= path.append(typePkg.getName().replace('.', IPath.SEPARATOR));
}
- String msg =
- "Package declaration does not match folder. Expected folder is " + path + ".";
- ProblemDetailImpl problem =
- new ProblemDetailImpl(msg, 0, IProblemDetail.S_ERROR, sEntry, 0, 0, 1);
+ String msg= "Package declaration does not match folder. Expected folder is " + path + ".";
+ ProblemDetailImpl problem= new ProblemDetailImpl(msg, 0, IProblemDetail.S_ERROR, sEntry, 0, 0, 1);
vProblems.addElement(problem);
// Only report the conflict once (there may be several types, but there's only one package declaration).
- reportedPackageConflict = true;
+ reportedPackageConflict= true;
}
// toss type result
continue;
}
- TypeStructureEntry tsEntry = new TypeStructureEntry(sEntry, typeHandle);
+ TypeStructureEntry tsEntry= new TypeStructureEntry(sEntry, typeHandle);
/* squirrel the binary away */
- byte[] binary = classFile.getBytes();
+ byte[] binary= classFile.getBytes();
// as a side effect, the following sets the crc32 for the type structure entry
getBinaryOutput().putBinary(tsEntry, binary);
vTSEntries.addElement(tsEntry);
}
- TypeStructureEntry[] tsEntries = new TypeStructureEntry[vTSEntries.size()];
+ TypeStructureEntry[] tsEntries= new TypeStructureEntry[vTSEntries.size()];
vTSEntries.copyInto(tsEntries);
/* convert dependencies */
- Vector dependencies = resolveDependencies(resultUnit, result);
+ Vector dependencies= resolveDependencies(resultUnit, result);
/* convert problems */
if (compilerProblems != null) {
- for (int i = 0; i < compilerProblems.length; i++) {
+ for (int i= 0; i < compilerProblems.length; i++) {
// The problem factory created the compiler problems as ProblemDetailImpl objects
// without the source entry set. Fill it in here.
- ProblemDetailImpl problem = (ProblemDetailImpl) compilerProblems[i];
+ ProblemDetailImpl problem= (ProblemDetailImpl) compilerProblems[i];
problem.setSourceEntry(sEntry);
vProblems.addElement(problem);
}
}
- IProblemDetail[] problems = new IProblemDetail[vProblems.size()];
+ IProblemDetail[] problems= new IProblemDetail[vProblems.size()];
vProblems.copyInto(problems);
- return new ConvertedCompilationResult(
- resultUnit,
- dependencies,
- problems,
- tsEntries);
+ return new ConvertedCompilationResult(resultUnit, dependencies, problems, tsEntries);
}
-
/**
* Returns a copy of the state with the given workspace and build context.
*/
protected StateImpl copy(IProject newProject, IImageContext context) {
- StateImpl newState = new StateImpl(this.fDevelopmentContext, newProject);
- newState.fPackageMap = this.fPackageMap.copy();
- newState.fPathMap = this.fPathMap;
- newState.fSourceElementTable = this.fSourceElementTable.copy();
- newState.fPrincipalStructureTable =
- (Hashtable) this.fPrincipalStructureTable.clone();
- newState.fProblemReporter = this.fProblemReporter.copy();
- newState.fGraph = this.fGraph.copy();
- newState.fBuildContext = context;
- newState.fCompilerOptions = this.fCompilerOptions;
+ StateImpl newState= new StateImpl(this.fDevelopmentContext, newProject);
+ newState.fPackageMap= this.fPackageMap.copy();
+ newState.fPathMap= this.fPathMap;
+ newState.fSourceElementTable= this.fSourceElementTable.copy();
+ newState.fPrincipalStructureTable= (Hashtable) this.fPrincipalStructureTable.clone();
+ newState.fProblemReporter= this.fProblemReporter.copy();
+ newState.fGraph= this.fGraph.copy();
+ newState.fBuildContext= context;
+ newState.fCompilerOptions= this.fCompilerOptions;
return newState;
}
-
/**
* Returns the default package which is visible by the given source entry,
* or null if there is no visible default package.
@@ -526,45 +476,37 @@ public class StateImpl implements IState {
protected IPackage defaultPackageFor(IPackage pkg) {
return pkg.isUnnamed() ? pkg : defaultPackageForProject();
}
-
/**
* Returns the default package for the project.
*/
protected IPackage defaultPackageForProject() {
- return fDevelopmentContext.getImage().getPackageHandle(
- PackageImpl.DEFAULT_PACKAGE_PREFIX + getProject().getName(),
- true);
+ return fDevelopmentContext.getImage().getPackageHandle(PackageImpl.DEFAULT_PACKAGE_PREFIX + getProject().getName(), true);
}
-
/**
* The IBinaryType for this TypeStructureEntry has been flushed from
* the cache. Rebuild the IBinaryType from binary. May or may not force
* a lazy build, depending on the parameter lazyBuildCU.
*/
- protected IBinaryType forceBinaryType(
- TypeStructureEntry tsEntry,
- boolean lazyBuildCU) {
- IType type = tsEntry.getType();
- SourceEntry sEntry = tsEntry.getSourceEntry();
- IBinaryType binaryType = null;
+ protected IBinaryType forceBinaryType(TypeStructureEntry tsEntry, boolean lazyBuildCU) {
+ IType type= tsEntry.getType();
+ SourceEntry sEntry= tsEntry.getSourceEntry();
+ IBinaryType binaryType= null;
/* if its a class file, get descriptor from binary index */
if (sEntry.isBinary()) {
try {
- byte[] bytes = getElementContentBytes(sEntry);
- binaryType =
- new ClassFileReader(bytes, sEntry.getPathWithZipEntryName().toCharArray());
+ byte[] bytes= getElementContentBytes(sEntry);
+ binaryType= new ClassFileReader(bytes, sEntry.getPathWithZipEntryName().toCharArray());
} catch (ClassFormatException e) {
/* problem will be generated below */
}
} else {
/* entry is source in workspace; get binary from broker */
- IType typeSS = (IType) type.inState(this);
- byte[] bytes = getBinary(typeSS, lazyBuildCU);
+ IType typeSS= (IType) type.inState(this);
+ byte[] bytes= getBinary(typeSS, lazyBuildCU);
if (bytes != null) {
try {
- binaryType =
- new ClassFileReader(bytes, sEntry.getPathWithZipEntryName().toCharArray());
+ binaryType= new ClassFileReader(bytes, sEntry.getPathWithZipEntryName().toCharArray());
} catch (ClassFormatException e) {
/* problem will be generated below */
}
@@ -572,40 +514,36 @@ public class StateImpl implements IState {
}
if (lazyBuildCU && binaryType == null) {
/* couldn't parse the class file */
- ProblemDetailImpl problem =
- new ProblemDetailImpl("unable to parse class file: " + type.getName(), sEntry);
+ ProblemDetailImpl problem= new ProblemDetailImpl("unable to parse class file: " + type.getName(), sEntry);
fProblemReporter.putProblem(sEntry, problem);
}
return binaryType;
}
-
/**
* Generate a unique fingerprint for a state.
*/
protected static byte[] generateFingerprint() {
// TBD: Better to use a UUID, but we don't have a convenient implementation.
// Chances are the fingerprint will be used only on one machine, so this should suffice.
- byte[] fingerprint = new byte[32];
+ byte[] fingerprint= new byte[32];
fgRandom.nextBytes(fingerprint);
return fingerprint;
}
-
/**
* Returns an array of all packages in the state (non-state-specific handles).
*/
protected IPackage[] getAllPackagesAsArray() {
return fPackageMap.getAllPackagesAsArray();
}
-
/**
* Returns an enumeration of TypeStructureEntry objects for all types
* in the given package, including nested types. Returns null if the package does not exist.
*/
protected TypeStructureEntry[] getAllTypesForPackage(IPackage pkg) {
if (fPrincipalStructureByPackageTable == null) {
- fPrincipalStructureByPackageTable = new Hashtable(11);
+ fPrincipalStructureByPackageTable= new Hashtable(11);
}
- Object o = fPrincipalStructureByPackageTable.get(pkg);
+ Object o= fPrincipalStructureByPackageTable.get(pkg);
if (o != null) {
return (TypeStructureEntry[]) o;
}
@@ -615,46 +553,37 @@ public class StateImpl implements IState {
// TBD: Doesn't support lazy builds.
- int max = 30;
- TypeStructureEntry[] list = new TypeStructureEntry[max];
- int count = 0;
- for (Enumeration e = fPrincipalStructureTable.elements();
- e.hasMoreElements();
- ) {
- TypeStructureEntry tsEntry = (TypeStructureEntry) e.nextElement();
+ int max= 30;
+ TypeStructureEntry[] list= new TypeStructureEntry[max];
+ int count= 0;
+ for (Enumeration e= fPrincipalStructureTable.elements(); e.hasMoreElements();) {
+ TypeStructureEntry tsEntry= (TypeStructureEntry) e.nextElement();
if (tsEntry.getType().getPackage().equals(pkg)) {
if (count == max)
- System.arraycopy(
- list,
- 0,
- list = new TypeStructureEntry[max = max * 2],
- 0,
- count);
- list[count++] = tsEntry;
+ System.arraycopy(list, 0, list= new TypeStructureEntry[max= max * 2], 0, count);
+ list[count++]= tsEntry;
}
}
if (count < max)
- System.arraycopy(list, 0, list = new TypeStructureEntry[count], 0, count);
+ System.arraycopy(list, 0, list= new TypeStructureEntry[count], 0, count);
fPrincipalStructureByPackageTable.put(pkg, list);
return list;
}
-
/**
* Returns the binary for a given type handle. The type handle must
* be state specific.
* @param type The type handle to get binaries for
* @param lazyBuildCU whether or not to perform a lazy build to get the binary.
*/
- protected byte[] getBinary(IType type, boolean lazyBuildCU)
- throws NotPresentException {
+ protected byte[] getBinary(IType type, boolean lazyBuildCU) throws NotPresentException {
if (!type.isStateSpecific()) {
throw new StateSpecificException();
}
- IType nssHandle = (IType) type.nonStateSpecific();
- TypeStructureEntry tsEntry = buildTypeStructureEntry(nssHandle);
+ IType nssHandle= (IType) type.nonStateSpecific();
+ TypeStructureEntry tsEntry= buildTypeStructureEntry(nssHandle);
/* Attempt to retrieve binary from binary output */
- byte[] binary = getBinaryOutput().getBinary(tsEntry, nssHandle);
+ byte[] binary= getBinaryOutput().getBinary(tsEntry, nssHandle);
if (binary != null)
return binary;
@@ -667,28 +596,26 @@ public class StateImpl implements IState {
}
/* make sure the entry is a compilation unit */
- PackageElement unit = packageElementFromSourceEntry(tsEntry.getSourceEntry());
+ PackageElement unit= packageElementFromSourceEntry(tsEntry.getSourceEntry());
new BatchImageBuilder(this).lazyBuild(unit);
- tsEntry = getTypeStructureEntry(nssHandle, false);
+ tsEntry= getTypeStructureEntry(nssHandle, false);
if (tsEntry == null) {
return null;
} else {
return getBinaryOutput().getBinary(tsEntry, nssHandle);
}
}
-
/**
* Returns the binary output for this state.
*/
protected BinaryOutput getBinaryOutput() {
- BinaryOutput output = fDevelopmentContext.getBinaryOutput();
+ BinaryOutput output= fDevelopmentContext.getBinaryOutput();
if (output != null) {
return output;
} else {
return fBinaryOutput;
}
}
-
/**
* Returns the IBinaryType for the given type structure entry.
* Performs lazy builds as necessary.
@@ -696,19 +623,15 @@ public class StateImpl implements IState {
* blobs are not available or the class file is corrupt), a NotPresentException
* is thrown.
*/
- protected IBinaryType getBinaryType(TypeStructureEntry tsEntry)
- throws NotPresentException {
+ protected IBinaryType getBinaryType(TypeStructureEntry tsEntry) throws NotPresentException {
/* rebuild descriptor from indexes or binary */
- IBinaryType binaryType = forceBinaryType(tsEntry, false);
- // Use false for 1FVQGL1: ITPJCORE:WINNT - SEVERE - Error saving java file
+ IBinaryType binaryType= forceBinaryType(tsEntry, false); // Use false for 1FVQGL1: ITPJCORE:WINNT - SEVERE - Error saving java file
if (binaryType == null) {
- throw new NotPresentException(
- "Unable to build type: " + tsEntry.getSourceEntry().getFileName());
+ throw new NotPresentException("Unable to build type: " + tsEntry.getSourceEntry().getFileName());
}
return binaryType;
}
-
/**
* Returns the IBinaryType for the given type structure entry if it
* is available. Parses the binary if necessary, but returns null if
@@ -719,7 +642,6 @@ public class StateImpl implements IState {
/* rebuild descriptor from binary */
return forceBinaryType(tsEntry, false);
}
-
/**
* Returns the ImageContext representing the subset of the
* image which is important to have built as early
@@ -733,7 +655,6 @@ public class StateImpl implements IState {
public IImageContext getBuildContext() {
return fBuildContext;
}
-
/**
* Returns the projects mentioned in the class path, including the one for this state.
*/
@@ -753,67 +674,54 @@ public class StateImpl implements IState {
projects.copyInto(result);
return result;
}
-
/**
* Given a compilation unit name from the compiler, and the default package which
* was active when it was produced, answer the corresponding CompilationUnit.
*/
- protected PackageElement getCompilationUnitFromName(
- String name,
- IPackage defaultPackage) {
- int i = name.lastIndexOf('.');
+ protected PackageElement getCompilationUnitFromName(String name, IPackage defaultPackage) {
+ int i= name.lastIndexOf('.');
IPackage pkg;
String simpleName;
if (i == -1) {
- pkg = defaultPackage;
- simpleName = name;
+ pkg= defaultPackage;
+ simpleName= name;
} else {
- pkg =
- fDevelopmentContext.getImage().getPackageHandle(name.substring(0, i), false);
- simpleName = name.substring(i + 1);
+ pkg= fDevelopmentContext.getImage().getPackageHandle(name.substring(0, i), false);
+ simpleName= name.substring(i + 1);
}
- pkg = canonicalize(pkg);
+ pkg= canonicalize(pkg);
if (!fSourceElementTable.containsPackage(pkg)) {
getSourceEntries(pkg);
}
- SourceEntry entry =
- fSourceElementTable.getSourceEntry(pkg, simpleName + ".java");
+ SourceEntry entry= fSourceElementTable.getSourceEntry(pkg, simpleName + ".java");
if (entry == null)
return null;
return new PackageElement(pkg, entry);
}
-
/**
* Returns the compiler options used to build this state.
*/
public ConfigurableOption[] getCompilerOptions() {
return fCompilerOptions;
}
-
/**
* Returns an enumeration of TypeStructureEntry objects for all top-level types
* in the given package. Returns null if the package does not exist.
*/
protected TypeStructureEntry[] getDeclaredTypesForPackage(IPackage pkg) {
- TypeStructureEntry[] all = getAllTypesForPackage(pkg);
- TypeStructureEntry[] declared = new TypeStructureEntry[all.length];
- int count = 0;
- for (int i = 0, len = all.length; i < len; ++i) {
+ TypeStructureEntry[] all= getAllTypesForPackage(pkg);
+ TypeStructureEntry[] declared= new TypeStructureEntry[all.length];
+ int count= 0;
+ for (int i= 0, len= all.length; i < len; ++i) {
if (BinaryStructure.isPackageMember(getBinaryType(all[i]))) {
- declared[count++] = all[i];
+ declared[count++]= all[i];
}
}
if (count < declared.length) {
- System.arraycopy(
- declared,
- 0,
- declared = new TypeStructureEntry[count],
- 0,
- count);
+ System.arraycopy(declared, 0, declared= new TypeStructureEntry[count], 0, count);
}
return declared;
}
-
/**
* Returns the dependency graph for this state, if supported,
* or null if the dependency graph is unknown.
@@ -821,40 +729,37 @@ public class StateImpl implements IState {
public IDependencyGraph getDependencyGraph() {
return new DependencyGraphImpl(this);
}
-
/**
* Returns this state's development context.
*/
public IDevelopmentContext getDevelopmentContext() {
return fDevelopmentContext;
}
-
/**
* Returns the byte contents for a source entry.
*/
protected byte[] getElementContentBytes(SourceEntry entry) {
if (entry.fZipEntryFileName != null) {
- ZipFile zipFile = null;
+ ZipFile zipFile= null;
try {
- IPath path = entry.getPath();
- JavaModelManager manager =
- (JavaModelManager) JavaModelManager.getJavaModelManager();
- zipFile = manager.getZipFile(path);
+ IPath path= entry.getPath();
+ JavaModelManager manager= (JavaModelManager) JavaModelManager.getJavaModelManager();
+ zipFile= manager.getZipFile(path);
if (zipFile == null) {
//throw internalException("Error reading file " + entry + "due to missing zip/jar file");
return new byte[0];
}
- ZipEntry zipEntry = zipFile.getEntry(entry.getZipEntryName());
+ ZipEntry zipEntry= zipFile.getEntry(entry.getZipEntryName());
if (zipEntry == null) {
//throw internalException("Error reading file " + entry + " due to missing zip/jar entry");
return new byte[0];
}
- InputStream input = zipFile.getInputStream(zipEntry);
- if (input == null) {
+ InputStream input= zipFile.getInputStream(zipEntry);
+ if (input == null){
//throw internalException("Error reading file " + entry + " due to missing zip/jar entry");
return new byte[0];
}
- byte[] contents = Util.readContentsAsBytes(input);
+ byte[] contents= Util.readContentsAsBytes(input);
if (contents == null) {
//throw internalException("Error reading file " + entry + " due to error reading contents");
return new byte[0];
@@ -864,21 +769,21 @@ public class StateImpl implements IState {
//throw internalException(e);
return new byte[0];
} catch (IOException e) {
- String message = e.getMessage();
- message = (message == null ? "." : " due to " + message + ".");
+ String message= e.getMessage();
+ message= (message == null ? "." : " due to " + message + ".");
//throw internalException("Error reading file " + entry + message);
return new byte[0];
} finally {
if (zipFile != null) {
try {
zipFile.close();
- } catch (IOException e) {
+ } catch(IOException e) {
// ignore
}
}
}
} else {
- IFile file = getFile(entry);
+ IFile file= getFile(entry);
try {
// Fix for 1FVTLHB: ITPCORE:WINNT - Importing a project does not import class files
JavaModelManager.getJavaModelManager().ensureLocal(file);
@@ -886,68 +791,63 @@ public class StateImpl implements IState {
} catch (CoreException e) {
return fDevelopmentContext.getBinaryFromFileSystem(file);
} catch (IOException e) {
- String message = e.getMessage();
- message = (message == null ? "." : " due to " + message + ".");
+ String message= e.getMessage();
+ message= (message == null ? "." : " due to " + message + ".");
//throw internalException("Error reading file " + entry + message);
return new byte[0];
}
}
}
-
/**
* Returns the contents for a source entry as a char array.
*/
protected char[] getElementContentCharArray(SourceEntry entry) {
// TBD: need proper byte->char conversion
- byte[] bytes = getElementContentBytes(entry);
+ byte[] bytes= getElementContentBytes(entry);
BufferedReader reader = null;
try {
- reader =
- new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes)));
- int length = bytes.length;
- char[] contents = new char[length];
- int len = 0;
- int readSize = 0;
+ reader= new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes)));
+ int length= bytes.length;
+ char[] contents= new char[length];
+ int len= 0;
+ int readSize= 0;
while ((readSize != -1) && (len != length)) {
// See PR 1FMS89U
// We record first the read size. In this case len is the actual read size.
len += readSize;
- readSize = reader.read(contents, len, length - len);
+ readSize= reader.read(contents, len, length - len);
}
reader.close();
// See PR 1FMS89U
// Now we need to resize in case the default encoding used more than one byte for each
// character
if (len != length)
- System.arraycopy(contents, 0, (contents = new char[len]), 0, len);
+ System.arraycopy(contents, 0, (contents= new char[len]), 0, len);
return contents;
} catch (IOException e) {
if (reader != null) {
try {
reader.close();
- } catch (IOException ioe) {
+ } catch(IOException ioe) {
}
}
- String message = e.getMessage();
- message = (message == null ? "." : " due to " + message + ".");
+ String message= e.getMessage();
+ message= (message == null ? "." : " due to " + message + ".");
throw internalException("Error reading file " + entry + message);
}
}
-
/**
* Returns the file for a workspace-relative path.
*/
protected IFile getFile(IPath path) {
return getProject().getWorkspace().getRoot().getFile(makeAbsolute(path));
}
-
/**
* Returns the file for a source entry.
*/
protected IFile getFile(SourceEntry sEntry) {
return getFile(sEntry.getPath());
}
-
/**
* Answer a unique fingerprint for this state.
* It is guaranteed that no other state can have the same
@@ -957,14 +857,12 @@ public class StateImpl implements IState {
public byte[] getFingerprint() {
return (byte[]) fFingerprint.clone(); // Trust no one.
}
-
/**
* Returns the folder for a project-relative path.
*/
protected IFolder getFolder(IPath path) {
return getProject().getFolder(makeAbsolute(path));
}
-
/**
* Returns the image described by this state. The result is state-specific.
*
@@ -974,52 +872,40 @@ public class StateImpl implements IState {
public IImage getImage() {
return fImage;
}
-
/**
* Returns the dependency graph for the state. Used by the incremental builder.
*/
protected DependencyGraph getInternalDependencyGraph() {
return fGraph;
}
-
/**
* Returns the Java Model element for a source entry.
*/
protected IJavaElement getJavaElement(SourceEntry sEntry) {
try {
- JavaProject javaProject = (JavaProject) getJavaProject();
- String zipEntryFileName = sEntry.fZipEntryFileName;
- IPackageFragment frag = null;
+ JavaProject javaProject= (JavaProject)getJavaProject();
+ String zipEntryFileName= sEntry.fZipEntryFileName;
+ IPackageFragment frag= null;
if (zipEntryFileName != null) {
IPackageFragmentRoot root;
IPath path = sEntry.getPath();
- if (!path.isAbsolute()
- || javaProject.getWorkspace().getRoot().findMember(path) != null) {
- root = javaProject.getPackageFragmentRoot(getFile(path));
+ if (!path.isAbsolute() || javaProject.getWorkspace().getRoot().findMember(path) != null) {
+ root= javaProject.getPackageFragmentRoot(getFile(path));
} else {
- root = javaProject.getPackageFragmentRoot(path.toOSString());
+ root= javaProject.getPackageFragmentRoot(path.toOSString());
}
String zipEntryPath = sEntry.fZipEntryPath;
- String pkgName =
- zipEntryPath == null
- ? IPackageFragment.DEFAULT_PACKAGE_NAME
- : zipEntryPath.replace('/', '.');
- frag = root.getPackageFragment(pkgName);
+ String pkgName= zipEntryPath == null ? IPackageFragment.DEFAULT_PACKAGE_NAME : zipEntryPath.replace('/', '.');
+ frag= root.getPackageFragment(pkgName);
} else {
- IPackageFragmentRoot[] roots = getPackageFragmentRootsInClassPath();
- for (int i = 0; i < roots.length; ++i) {
- IPackageFragmentRoot root = roots[i];
+ IPackageFragmentRoot[] roots= getPackageFragmentRootsInClassPath();
+ for (int i= 0; i < roots.length; ++i) {
+ IPackageFragmentRoot root= roots[i];
if (!root.isArchive() && root.exists()) {
- IPath rootPath = root.getUnderlyingResource().getFullPath();
+ IPath rootPath= root.getUnderlyingResource().getFullPath();
if (rootPath.isPrefixOf(sEntry.getPath())) {
- String pkgName =
- sEntry
- .getPath()
- .removeLastSegments(1)
- .removeFirstSegments(rootPath.segmentCount())
- .toString()
- .replace('/', '.');
- frag = root.getPackageFragment(pkgName);
+ String pkgName= sEntry.getPath().removeLastSegments(1).removeFirstSegments(rootPath.segmentCount()).toString().replace('/', '.');
+ frag= root.getPackageFragment(pkgName);
break;
}
}
@@ -1028,7 +914,7 @@ public class StateImpl implements IState {
if (frag == null) {
throw internalException("Missing file for " + sEntry);
}
- String fileName = sEntry.getPath().lastSegment();
+ String fileName= sEntry.getPath().lastSegment();
if (sEntry.isSource()) {
return frag.getCompilationUnit(fileName);
} else {
@@ -1042,143 +928,126 @@ public class StateImpl implements IState {
throw internalException(e);
}
}
-
/**
* Returns the Java Model element for the project.
*/
protected IJavaProject getJavaProject() {
return JavaCore.create(getProject());
}
-
/**
* For debugging only.
*/
protected INode getNode(String qualifiedNameWithSuffix) {
- PackageElement element = getPackageElement(qualifiedNameWithSuffix);
+ PackageElement element= getPackageElement(qualifiedNameWithSuffix);
if (element == null)
return null;
return fGraph.getNodeFor(element, false);
}
-
/**
* Returns the output location for this state.
* The binary output must be a ProjectBinaryOutput.
*/
protected IPath getOutputLocation() {
- BinaryOutput output = getBinaryOutput();
+ BinaryOutput output= getBinaryOutput();
if (output instanceof ProjectBinaryOutput) {
return ((ProjectBinaryOutput) output).getOutputPath();
} else {
return null;
}
}
-
- static Comparator getPackageComparator() {
- return new Comparator() {
- public int compare(Object o1, Object o2) {
- IPackage p1 = (IPackage) o1;
- IPackage p2 = (IPackage) o2;
- return p1.getName().compareTo(p2.getName());
- }
- };
- }
-
+static Comparator getPackageComparator() {
+ return new Comparator() {
+ public int compare(Object o1, Object o2) {
+ IPackage p1 = (IPackage) o1;
+ IPackage p2 = (IPackage) o2;
+ return p1.getName().compareTo(p2.getName());
+ }
+ };
+}
/**
* For debugging only.
*/
protected PackageElement getPackageElement(String qualifiedNameWithSuffix) {
- SourceEntry sEntry = getSourceEntry(qualifiedNameWithSuffix);
+ SourceEntry sEntry= getSourceEntry(qualifiedNameWithSuffix);
if (sEntry == null)
return null;
return packageElementFromSourceEntry(sEntry);
}
-
/**
* Returns the package fragment roots to build in classpath order.
*/
protected IPackageFragmentRoot[] getPackageFragmentRootsInClassPath() {
return fPackageFragmentRootsInClassPath;
}
-
/**
* Returns the package map
*/
protected PackageMap getPackageMap() {
return fPackageMap;
}
-
- static Comparator getPathComparator() {
- return new Comparator() {
- public int compare(Object o1, Object o2) {
- IPath p1 = (IPath) o1;
- IPath p2 = (IPath) o2;
- return p1.toString().compareTo(p2.toString());
- }
- };
- }
-
+static Comparator getPathComparator() {
+ return new Comparator() {
+ public int compare(Object o1, Object o2) {
+ IPath p1 = (IPath) o1;
+ IPath p2 = (IPath) o2;
+ return p1.toString().compareTo(p2.toString());
+ }
+ };
+}
/**
* Returns the path map.
*/
protected PathMap getPathMap() {
return fPathMap;
}
-
/**
* Returns the principal structure by package table.
*/
protected Hashtable getPrincipalStructureByPackageTable() {
if (fPrincipalStructureByPackageTable == null) {
- fPrincipalStructureByPackageTable = new Hashtable(11);
+ fPrincipalStructureByPackageTable= new Hashtable(11);
}
return fPrincipalStructureByPackageTable;
}
-
/**
* Returns the principal structure table
*/
protected Hashtable getPrincipalStructureTable() {
return fPrincipalStructureTable;
}
-
/**
* Returns the problem reporter
*/
protected IProblemReporter getProblemReporter() {
return fProblemReporter;
}
-
/**
* Returns the problems that were reported against the image itself
*/
protected Enumeration getProblems() {
return fProblemReporter.getImageProblems();
}
-
/**
* For debugging only.
*/
protected Vector getProblems(String qualifiedNameWithSuffix) {
- SourceEntry sEntry = getSourceEntry(qualifiedNameWithSuffix);
+ SourceEntry sEntry= getSourceEntry(qualifiedNameWithSuffix);
return fProblemReporter.getProblemVector(sEntry);
}
-
/**
* @see IState
*/
public IProject getProject() {
return fProject;
}
-
/**
* Returns the name of the project built by this state.
*/
protected String getProjectName() {
if (fProjectName == null)
- fProjectName = getProject().getName();
+ fProjectName= getProject().getName();
return fProjectName;
}
-
/**
* Returns an array of Package objects representing all other
* packages which this package directly references.
@@ -1206,17 +1075,16 @@ public class StateImpl implements IState {
protected IPackage[] getReferencedPackages(IPackage pkgHandle) {
/* set of referenced builder packages */
- Hashtable pkgTable = getTableOfReferencedPackages(pkgHandle);
+ Hashtable pkgTable= getTableOfReferencedPackages(pkgHandle);
/* convert to array and return */
- IPackage[] results = new IPackage[pkgTable.size()];
- int i = 0;
- for (Enumeration e = pkgTable.elements(); e.hasMoreElements(); i++) {
- results[i] = (IPackage) e.nextElement();
+ IPackage[] results= new IPackage[pkgTable.size()];
+ int i= 0;
+ for (Enumeration e= pkgTable.elements(); e.hasMoreElements(); i++) {
+ results[i]= (IPackage) e.nextElement();
}
return results;
}
-
/**
* Returns the references for the given package element. Returns null
* if the references could not be found.
@@ -1225,17 +1093,16 @@ public class StateImpl implements IState {
if (!builderUnit.isSource()) {
return null;
}
- SourceEntry sEntry = getSourceEntry(builderUnit);
- IJavaElement javaElement = getJavaElement(sEntry);
- ICompilationUnit unit = (ICompilationUnit) javaElement;
+ SourceEntry sEntry= getSourceEntry(builderUnit);
+ IJavaElement javaElement= getJavaElement(sEntry);
+ ICompilationUnit unit= (ICompilationUnit) javaElement;
try {
- return ((CompilationUnit) unit).getReferenceInfo();
+ return ((CompilationUnit)unit).getReferenceInfo();
} catch (JavaModelException e) {
System.out.println("Caught not present exception for unit: " + unit + e);
return null;
}
}
-
/**
* Returns an array of Package objects representing all packages
* in the given image context which directly reference this package.
@@ -1249,33 +1116,30 @@ public class StateImpl implements IState {
*
* This is an extremely slow implementation (n^3?). Avoid using it if possible.
*/
- protected IPackage[] getReferencingPackages(
- IPackage pkgHandle,
- IImageContext context) {
+ protected IPackage[] getReferencingPackages(IPackage pkgHandle, IImageContext context) {
/* the results */
- Vector vResults = new Vector();
- IImage image = fDevelopmentContext.getImage();
+ Vector vResults= new Vector();
+ IImage image= fDevelopmentContext.getImage();
/* do for each package in the image context */
- IPackage[] pkgs = context.getPackages();
- for (int i = 0; i < pkgs.length; i++) {
+ IPackage[] pkgs= context.getPackages();
+ for (int i= 0; i < pkgs.length; i++) {
/* skip the package we are looking for */
if (pkgs[i].equals(pkgHandle)) {
continue;
}
- Hashtable table = getTableOfReferencedPackages(pkgs[i]);
+ Hashtable table= getTableOfReferencedPackages(pkgs[i]);
/* if the package references this package */
if (table.contains(pkgHandle)) {
/* add it to results */
vResults.addElement(pkgs[i]);
}
}
- IPackage[] results = new IPackage[vResults.size()];
+ IPackage[] results= new IPackage[vResults.size()];
vResults.copyInto(results);
return results;
}
-
/**
* Returns a report card for this state., restricted to
* the given image context.
@@ -1289,95 +1153,105 @@ public class StateImpl implements IState {
public IReportCard getReportCard(IImageContext imageContext) {
return new ReportCardImpl(this, imageContext);
}
-
/**
* Iterates through the children of a package fragment and adds all visible source element entries to the table.
*/
- protected void getSourceElementEntries(
- IPackage pkg,
- IPath path,
- LookupTable entryTable) {
+ protected void getSourceElementEntries(IPackage pkg, IPath path, LookupTable entryTable) {
try {
- IPackageFragmentRoot root = null;
- IPackageFragment frag = null;
- boolean isDefault = pkg.isUnnamed();
- String pkgName =
- isDefault ? IPackageFragment.DEFAULT_PACKAGE_NAME : pkg.getName();
- String pkgPath = pkgName.replace('.', '/');
+ IPackageFragmentRoot root= null;
+ IPackageFragment frag= null;
+ boolean isDefault= pkg.isUnnamed();
+ String pkgName= isDefault ? IPackageFragment.DEFAULT_PACKAGE_NAME : pkg.getName();
+ String pkgPath= pkgName.replace('.', '/');
if (isZipElement(path)) {
- IResource member = null;
- if (!path.isAbsolute()
- || getProject().getWorkspace().getRoot().findMember(path) != null) {
- root = getJavaProject().getPackageFragmentRoot(getFile(path));
+ IResource member= null;
+ if (!path.isAbsolute() || getProject().getWorkspace().getRoot().findMember(path) != null) {
+ root= getJavaProject().getPackageFragmentRoot(getFile(path));
} else {
- root = getJavaProject().getPackageFragmentRoot(path.toOSString());
+ root= getJavaProject().getPackageFragmentRoot(path.toOSString());
}
- frag = root.getPackageFragment(pkgName);
+ frag= root.getPackageFragment(pkgName);
} else {
- IPackageFragmentRoot[] roots = getPackageFragmentRootsInClassPath();
- for (int i = 0; i < roots.length; ++i) {
- IPackageFragmentRoot testRoot = roots[i];
- if (!testRoot.isArchive()
- && testRoot.getUnderlyingResource().getFullPath().isPrefixOf(path)) {
- root = testRoot;
- frag = testRoot.getPackageFragment(pkgName);
+ IPackageFragmentRoot[] roots= getPackageFragmentRootsInClassPath();
+ for (int i= 0; i < roots.length; ++i) {
+ IPackageFragmentRoot testRoot= roots[i];
+ if (!testRoot.isArchive() && testRoot.getUnderlyingResource().getFullPath().isPrefixOf(path)) {
+ root= testRoot;
+ frag= testRoot.getPackageFragment(pkgName);
break;
}
}
}
- boolean isArchive = root.isArchive();
+ boolean isArchive= root.isArchive();
if (!isArchive && !root.exists()) {
return;
}
- if (isArchive
- && root.getUnderlyingResource() != null
- && !root.getUnderlyingResource().isLocal(IResource.DEPTH_ZERO)) {
+ if (isArchive && root.getUnderlyingResource() != null && !root.getUnderlyingResource().isLocal(IResource.DEPTH_ZERO)) {
return;
}
if (frag == null || !frag.exists()) {
return;
}
- IPath entryPath = null;
+ IPath entryPath= null;
String zipEntryPath = null;
- String zipEntryFileName = null;
+ String zipEntryFileName= null;
((PackageFragment) frag).refreshChildren();
- ICompilationUnit[] units = frag.getCompilationUnits();
- for (int i = 0; i < units.length; ++i) {
- ICompilationUnit unit = units[i];
- String fileName = unit.getElementName();
- /* see if a source entry exists for this file name */
- if (entryTable.get(fileName) == null) {
+ ICompilationUnit[] units= frag.getCompilationUnits();
+ for (int i= 0; i < units.length; ++i) {
+ ICompilationUnit unit= units[i];
+ String fileName= unit.getElementName();
+ // get the corresponding .class file name
+ String classFileName = "";
+ if (Util.isJavaFileName(fileName)) { // paranoia check
+ classFileName = fileName.substring(0, fileName.length()-5).concat(".class");
+ }
+ // see if a source entry exists for this file name
+ // or for the corresponding .class file
+ if (entryTable.get(fileName) == null && entryTable.get(classFileName) == null) {
if (isArchive) {
- entryPath = path;
+ entryPath= path;
zipEntryPath = isDefault || pkgPath.length() == 0 ? null : pkgPath;
- zipEntryFileName = fileName;
+ zipEntryFileName= fileName;
} else {
- entryPath = unit.getUnderlyingResource().getFullPath();
+ entryPath= unit.getUnderlyingResource().getFullPath();
zipEntryPath = null;
- zipEntryFileName = null;
+ zipEntryFileName= null;
}
- SourceEntry sEntry = new SourceEntry(entryPath, zipEntryPath, zipEntryFileName);
+ SourceEntry sEntry= new SourceEntry(entryPath, zipEntryPath, zipEntryFileName);
entryTable.put(fileName, sEntry);
}
}
- IClassFile[] classFiles = frag.getClassFiles();
- for (int i = 0; i < classFiles.length; ++i) {
- IClassFile classFile = classFiles[i];
- String fileName = classFile.getElementName();
- /* see if a source entry exists for this file name */
- if (entryTable.get(fileName) == null) {
+ IClassFile[] classFiles= frag.getClassFiles();
+ for (int i= 0; i < classFiles.length; ++i) {
+ IClassFile classFile= classFiles[i];
+ String fileName= classFile.getElementName();
+ // get the corresponding .java file name
+ // note: this handles nested types, but not secondary types (e.g. class B defined in A.java)
+ String javaFileName = "";
+ if (Util.isClassFileName(fileName)) { // paranoia check
+ // strip off any nested types
+ javaFileName = fileName.substring(0, fileName.length()-6);
+ int dol = javaFileName.indexOf('$');
+ if (dol != -1) {
+ javaFileName = javaFileName.substring(0, dol);
+ }
+ javaFileName = javaFileName.concat(".java");
+ }
+ // see if a source entry exists for this file name
+ // or for the corresponding .java file
+ if (entryTable.get(fileName) == null && entryTable.get(javaFileName) == null) {
if (isArchive) {
- entryPath = path;
+ entryPath= path;
zipEntryPath = isDefault || pkgPath.length() == 0 ? null : pkgPath;
- zipEntryFileName = fileName;
+ zipEntryFileName= fileName;
} else {
if (!classFile.getUnderlyingResource().isLocal(IResource.DEPTH_ZERO))
continue;
- entryPath = classFile.getUnderlyingResource().getFullPath();
+ entryPath= classFile.getUnderlyingResource().getFullPath();
zipEntryPath = null;
- zipEntryFileName = null;
+ zipEntryFileName= null;
}
- SourceEntry sEntry = new SourceEntry(entryPath, zipEntryPath, zipEntryFileName);
+ SourceEntry sEntry= new SourceEntry(entryPath, zipEntryPath, zipEntryFileName);
entryTable.put(fileName, sEntry);
}
}
@@ -1385,20 +1259,18 @@ public class StateImpl implements IState {
throw internalException(e);
}
}
-
/**
* Returns the source element table
*/
protected SourceElementTable getSourceElementTable() {
return fSourceElementTable;
}
-
/**
* Returns the source entries in the given package. Does lazy analysis
* of source entry table as necessary. Returns null if the package is not present.
*/
protected SourceEntry[] getSourceEntries(IPackage pkg) {
- SourceEntry[] entries = fSourceElementTable.getSourceEntries(pkg);
+ SourceEntry[] entries= fSourceElementTable.getSourceEntries(pkg);
if (entries != null) {
return entries;
}
@@ -1406,79 +1278,70 @@ public class StateImpl implements IState {
/* Need to build the table for the package */
/* go through package fragments and compute all source entries */
- IPath[] frags = fPackageMap.getFragments(pkg);
+ IPath[] frags= fPackageMap.getFragments(pkg);
if (frags == null) {
return null; // package not present
}
/* build a table of source entries, keyed by filename */
- LookupTable entryTable = new LookupTable(20);
- for (int i = 0; i < frags.length; i++) {
+ LookupTable entryTable= new LookupTable(20);
+ for (int i= 0; i < frags.length; i++) {
getSourceElementEntries(pkg, frags[i], entryTable);
}
fSourceElementTable.putPackageTable(pkg, entryTable);
return fSourceElementTable.getSourceEntries(pkg);
}
-
/**
* For debugging only.
*/
protected SourceEntry getSourceEntry(String qualifiedNameWithSuffix) {
- int dot = qualifiedNameWithSuffix.lastIndexOf('.');
- dot = qualifiedNameWithSuffix.lastIndexOf('.', dot - 1);
- String pkgName =
- (dot == -1 ? ".default" : qualifiedNameWithSuffix.substring(0, dot));
- String fileName =
- (dot == -1
- ? qualifiedNameWithSuffix
- : qualifiedNameWithSuffix.substring(dot + 1));
- IPackage pkg = fDevelopmentContext.getImage().getPackageHandle(pkgName, false);
+ int dot= qualifiedNameWithSuffix.lastIndexOf('.');
+ dot= qualifiedNameWithSuffix.lastIndexOf('.', dot - 1);
+ String pkgName= (dot == -1 ? ".default" : qualifiedNameWithSuffix.substring(0, dot));
+ String fileName= (dot == -1 ? qualifiedNameWithSuffix : qualifiedNameWithSuffix.substring(dot + 1));
+ IPackage pkg= fDevelopmentContext.getImage().getPackageHandle(pkgName, false);
getSourceEntries(pkg); // force
return fSourceElementTable.getSourceEntry(pkg, fileName);
}
-
/**
* Looks up and returns the source entry for a source element in the source element table.
* Returns null if the type does not exist.
*/
protected SourceEntry getSourceEntry(PackageElement element) {
- IPackage pkg = element.getPackage();
+ IPackage pkg= element.getPackage();
// lazy build if necessary
if (!fSourceElementTable.containsPackage(pkg)) {
getSourceEntries(pkg);
}
return fSourceElementTable.getSourceEntry(pkg, element.getFileName());
}
-
/**
* Returns the source entry for a type. Returns null if the type
* does not exist
*/
protected SourceEntry getSourceEntry(IType type) {
- IPackage pkg = type.getPackage();
+ IPackage pkg= type.getPackage();
// lazy build if necessary
if (!fSourceElementTable.containsPackage(pkg)) {
getSourceEntries(pkg);
}
- String simpleName = type.getSimpleName();
- SourceEntry entry =
- fSourceElementTable.getSourceEntry(pkg, simpleName + ".java");
+ String simpleName= type.getSimpleName();
+ SourceEntry entry= fSourceElementTable.getSourceEntry(pkg, simpleName + ".java");
if (entry == null) {
- entry = fSourceElementTable.getSourceEntry(pkg, simpleName + ".class");
+ entry= fSourceElementTable.getSourceEntry(pkg, simpleName + ".class");
if (entry == null) {
- int firstDollar = simpleName.indexOf('$');
+ int firstDollar= simpleName.indexOf('$');
if (firstDollar != -1) {
- simpleName = simpleName.substring(0, firstDollar);
- entry = fSourceElementTable.getSourceEntry(pkg, simpleName + ".java");
+ simpleName= simpleName.substring(0, firstDollar);
+ entry= fSourceElementTable.getSourceEntry(pkg, simpleName + ".java");
if (entry == null) {
- entry = fSourceElementTable.getSourceEntry(pkg, simpleName + ".class");
+ entry= fSourceElementTable.getSourceEntry(pkg, simpleName + ".class");
}
}
}
}
return entry;
}
-
/**
* Returns the table of subtypes which covers the given image context.
* All types in the table are state-specific
@@ -1490,41 +1353,36 @@ public class StateImpl implements IState {
return fSubtypesTable;
}
} else {
- if (fSubtypesTableImageContext == null
- || ((ImageContextImpl) imageContext).isSubsetOf(
- (ImageContextImpl) fSubtypesTableImageContext)) {
+ if (fSubtypesTableImageContext == null || ((ImageContextImpl) imageContext).isSubsetOf((ImageContextImpl) fSubtypesTableImageContext)) {
return fSubtypesTable;
}
}
}
- IPackage[] pkgs =
- (imageContext == null
- ? fPackageMap.getAllPackagesAsArray()
- : imageContext.getPackages());
- Hashtable table = new Hashtable(Math.max(pkgs.length * 5, 1));
- for (int i = 0; i < pkgs.length; ++i) {
- IPackage pkg = pkgs[i];
- TypeStructureEntry[] tsEntries = getAllTypesForPackage(pkg);
+ IPackage[] pkgs= (imageContext == null ? fPackageMap.getAllPackagesAsArray() : imageContext.getPackages());
+ Hashtable table= new Hashtable(Math.max(pkgs.length * 5, 1));
+ for (int i= 0; i < pkgs.length; ++i) {
+ IPackage pkg= pkgs[i];
+ TypeStructureEntry[] tsEntries= getAllTypesForPackage(pkg);
if (tsEntries != null) {
- for (int j = 0; j < tsEntries.length; ++j) {
- IType type = (IType) tsEntries[j].getType().inState(this);
+ for (int j= 0; j < tsEntries.length; ++j) {
+ IType type= (IType) tsEntries[j].getType().inState(this);
if (!type.isInterface()) {
- IType superclass = type.getSuperclass();
+ IType superclass= type.getSuperclass();
if (superclass != null) {
- Vector vSubtypes = (Vector) table.get(superclass);
+ Vector vSubtypes= (Vector) table.get(superclass);
if (vSubtypes == null) {
- vSubtypes = new Vector(5);
+ vSubtypes= new Vector(5);
table.put(superclass, vSubtypes);
}
vSubtypes.addElement(type);
}
}
- IType[] interfaces = type.getInterfaces();
- for (int k = 0; k < interfaces.length; ++k) {
- IType intf = interfaces[k];
- Vector vSubtypes = (Vector) table.get(intf);
+ IType[] interfaces= type.getInterfaces();
+ for (int k= 0; k < interfaces.length; ++k) {
+ IType intf= interfaces[k];
+ Vector vSubtypes= (Vector) table.get(intf);
if (vSubtypes == null) {
- vSubtypes = new Vector(5);
+ vSubtypes= new Vector(5);
table.put(intf, vSubtypes);
}
vSubtypes.addElement(type);
@@ -1532,37 +1390,34 @@ public class StateImpl implements IState {
}
}
}
- for (Enumeration e = table.keys(); e.hasMoreElements();) {
- IType type = (IType) e.nextElement();
- Vector vSubtypes = (Vector) table.get(type);
- IType[] subtypes = new IType[vSubtypes.size()];
+ for (Enumeration e= table.keys(); e.hasMoreElements();) {
+ IType type= (IType) e.nextElement();
+ Vector vSubtypes= (Vector) table.get(type);
+ IType[] subtypes= new IType[vSubtypes.size()];
vSubtypes.copyInto(subtypes);
table.put(type, subtypes);
}
- fSubtypesTable = table;
- fSubtypesTableImageContext = imageContext;
+ fSubtypesTable= table;
+ fSubtypesTableImageContext= imageContext;
return table;
}
-
/**
* Returns a hashtable of IPackage objects representing all other
* packages which this package directly references.
*/
protected Hashtable getTableOfReferencedPackages(IPackage pkgHandle) {
/* set of referenced builder packages */
- Hashtable pkgTable = new Hashtable();
+ Hashtable pkgTable= new Hashtable();
/* do for each type in this package */
- TypeStructureEntry[] types = getAllTypesForPackage(pkgHandle);
+ TypeStructureEntry[] types= getAllTypesForPackage(pkgHandle);
if (types != null) {
- for (int i = 0; i < types.length; i++) {
- PackageElement element =
- packageElementFromSourceEntry(types[i].getSourceEntry());
- IPackage[] deps =
- getInternalDependencyGraph().getNamespaceDependencies(element);
+ for (int i= 0; i < types.length; i++) {
+ PackageElement element= packageElementFromSourceEntry(types[i].getSourceEntry());
+ IPackage[] deps= getInternalDependencyGraph().getNamespaceDependencies(element);
/* make sure namespaces are actually packages */
- for (int j = 0; j < deps.length; j++) {
+ for (int j= 0; j < deps.length; j++) {
if (fPackageMap.getEntry(deps[j]) != null) {
pkgTable.put(deps[j], deps[j]);
}
@@ -1574,34 +1429,25 @@ public class StateImpl implements IState {
pkgTable.remove(pkgHandle);
return pkgTable;
}
-
/**
* For debugging only.
*/
protected TypeStructureEntry getTypeStructureEntry(String qualifiedNameWithoutSuffix) {
- int dot = qualifiedNameWithoutSuffix.lastIndexOf('.');
- String pkgName =
- (dot == -1 ? ".default" : qualifiedNameWithoutSuffix.substring(0, dot));
- String typeName =
- (dot == -1
- ? qualifiedNameWithoutSuffix
- : qualifiedNameWithoutSuffix.substring(dot + 1));
- IPackage pkg = fDevelopmentContext.getImage().getPackageHandle(pkgName, false);
- IType type = pkg.getClassHandle(typeName);
+ int dot= qualifiedNameWithoutSuffix.lastIndexOf('.');
+ String pkgName= (dot == -1 ? ".default" : qualifiedNameWithoutSuffix.substring(0, dot));
+ String typeName= (dot == -1 ? qualifiedNameWithoutSuffix : qualifiedNameWithoutSuffix.substring(dot + 1));
+ IPackage pkg= fDevelopmentContext.getImage().getPackageHandle(pkgName, false);
+ IType type= pkg.getClassHandle(typeName);
return (TypeStructureEntry) fPrincipalStructureTable.get(type);
}
-
/**
* Returns the type structure entry for the given type handle.
* If lazyBuildCU is true, performs lazy building of compilation units if necessary.
* Always performs lazy building of class files if necessary.
* Returns null if no type descriptor can be found.
*/
- protected TypeStructureEntry getTypeStructureEntry(
- IType handle,
- boolean lazyBuildCU) {
- TypeStructureEntry tsEntry =
- (TypeStructureEntry) fPrincipalStructureTable.get(handle);
+ protected TypeStructureEntry getTypeStructureEntry(IType handle, boolean lazyBuildCU) {
+ TypeStructureEntry tsEntry= (TypeStructureEntry) fPrincipalStructureTable.get(handle);
if (tsEntry != null) {
return tsEntry;
}
@@ -1609,8 +1455,8 @@ public class StateImpl implements IState {
// TBD: Doesn't handle lazy builds.
/* get the source element */
- IPackage pkg = handle.getPackage();
- SourceEntry sEntry = getSourceEntry(handle);
+ IPackage pkg= handle.getPackage();
+ SourceEntry sEntry= getSourceEntry(handle);
if (sEntry == null) {
return null;
}
@@ -1619,41 +1465,36 @@ public class StateImpl implements IState {
if (sEntry.isBinary()) {
//byte[] bytes = getElementContentBytes(sEntry);
// Canonicalize package part of type handle
- handle = canonicalize(pkg).getClassHandle(handle.getSimpleName());
- tsEntry = new TypeStructureEntry(sEntry, handle);
+ handle= canonicalize(pkg).getClassHandle(handle.getSimpleName());
+ tsEntry= new TypeStructureEntry(sEntry, handle);
//tsEntry.setCRC32(getBinaryOutput().crc32(bytes));
fPrincipalStructureTable.put(handle, tsEntry);
- } else
- if (lazyBuildCU) {
- if (fProblemReporter.hasProblems(sEntry)) {
- // If the entry has problems, that's a sure sign it has already been compiled.
- // Don't try again.
- return null;
- }
+ } else if (lazyBuildCU) {
+ if (fProblemReporter.hasProblems(sEntry)) {
+ // If the entry has problems, that's a sure sign it has already been compiled.
+ // Don't try again.
+ return null;
+ }
- // make sure the entry is a compilation unit
- PackageElement unit = packageElementFromSourceEntry(sEntry);
+ // make sure the entry is a compilation unit
+ PackageElement unit= packageElementFromSourceEntry(sEntry);
- // compile it
- new BatchImageBuilder(this).lazyBuild(unit);
+ // compile it
+ new BatchImageBuilder(this).lazyBuild(unit);
- // try to get the entry again; may still be null
- tsEntry = (TypeStructureEntry) fPrincipalStructureTable.get(handle);
- }
+ // try to get the entry again; may still be null
+ tsEntry= (TypeStructureEntry) fPrincipalStructureTable.get(handle);
+ }
return tsEntry;
}
-
/**
* Returns the (non-state-specific) package handle representing the namespace
* for unknown dependencies. All compilation units which have unknown dependencies
* depend on this namespace.
*/
protected IPackage getUnknownDependenciesNamespace() {
- return fDevelopmentContext.getImage().getPackageHandle(
- UNKNOWN_DEPENDENCIES,
- true);
+ return fDevelopmentContext.getImage().getPackageHandle(UNKNOWN_DEPENDENCIES, true);
}
-
/**
* Process an internal exception: if we're being called by the compiler, throw an AbortCompilation
* otherwise throw an internal image builder exception.
@@ -1661,7 +1502,6 @@ public class StateImpl implements IState {
protected RuntimeException internalException(String message) {
return fDevelopmentContext.internalException(message);
}
-
/**
* Process an internal exception: if we're being called by the compiler, throw an AbortCompilation
* otherwise throw an internal image builder exception.
@@ -1669,16 +1509,13 @@ public class StateImpl implements IState {
protected RuntimeException internalException(Throwable t) {
return fDevelopmentContext.internalException(t);
}
-
/**
* Returns whether the given path represents a zip file.
*/
protected static boolean isZipElement(IPath path) {
- String extension = path.getFileExtension();
- return extension != null
- && (extension.equalsIgnoreCase("zip") || extension.equalsIgnoreCase("jar"));
+ String extension= path.getFileExtension();
+ return extension != null && (extension.equalsIgnoreCase("zip") || extension.equalsIgnoreCase("jar"));
}
-
/**
* Given a project-relative path, returns an absolute path.
*/
@@ -1686,10 +1523,9 @@ public class StateImpl implements IState {
if (path.isAbsolute()) {
return path;
}
- IProject project = getProject();
+ IProject project= getProject();
return project.getFullPath().append(path);
}
-
/**
* Returns a new image delta representing the differences between this
* state (the new state) and another one (the old state). The delta is naive in that no delta information is initially provided.
@@ -1698,22 +1534,20 @@ public class StateImpl implements IState {
public IDelta newNaiveDeltaWith(IState oldState, IImageContext imgCtx) {
return new DeltaImpl(oldState, this, imgCtx);
}
-
/**
* Returns a package element corresponding to the given source entry.
* The source entry may or may not be present.
*/
protected PackageElement packageElementFromSourceEntry(SourceEntry entry) {
- IPackage pkgHandle = packageFromSourceEntry(entry);
+ IPackage pkgHandle= packageFromSourceEntry(entry);
return new PackageElement(pkgHandle, entry);
}
-
/**
* Returns a package handle corresponding to the given source entry's package.
* The source entry may or may not be present.
*/
protected IPackage packageFromSourceEntry(SourceEntry entry) {
- IPath path = entry.getPath();
+ IPath path= entry.getPath();
IPackage pkgHandle;
/* if it's a zip file */
@@ -1723,57 +1557,51 @@ public class StateImpl implements IState {
String zipEntryPath = entry.fZipEntryPath;
if (zipEntryPath == null) {
/* default unnamed package */
- pkgHandle = defaultPackageForProject();
+ pkgHandle= defaultPackageForProject();
} else {
- String pkgName = zipEntryPath.replace('/', '.');
- pkgHandle = fDevelopmentContext.getImage().getPackageHandle(pkgName, false);
+ String pkgName= zipEntryPath.replace('/', '.');
+ pkgHandle= fDevelopmentContext.getImage().getPackageHandle(pkgName, false);
}
} else {
/* compute filename and package from element id */
- IPath parent = path.removeLastSegments(1);
- pkgHandle = fPathMap.packageHandleFromPath(parent);
+ IPath parent= path.removeLastSegments(1);
+ pkgHandle= fPathMap.packageHandleFromPath(parent);
}
return canonicalize(pkgHandle);
}
-
/**
* Stores the result of a compilation in the state tables
*/
protected void putCompilationResult(ConvertedCompilationResult result) {
- PackageElement unit = result.getPackageElement();
+ PackageElement unit= result.getPackageElement();
/* get source entry for result */
- SourceEntry sEntry = getSourceEntry(unit);
+ SourceEntry sEntry= getSourceEntry(unit);
/* record problems */
fProblemReporter.removeNonSyntaxErrors(sEntry);
- IProblemDetail[] problems = result.getProblems();
- for (int i = 0; i < problems.length; ++i) {
+ IProblemDetail[] problems= result.getProblems();
+ for (int i= 0; i < problems.length; ++i) {
fProblemReporter.putProblem(sEntry, problems[i]);
}
/* This records the types actually contributed, */
/* to record in the dependency graph. */
- TypeStructureEntry[] tsEntries = result.getTypes();
- IType[] types = new IType[tsEntries.length];
- int count = 0;
+ TypeStructureEntry[] tsEntries= result.getTypes();
+ IType[] types= new IType[tsEntries.length];
+ int count= 0;
/* record type structure */
- for (int i = 0; i < tsEntries.length; i++) {
- TypeStructureEntry tsEntry = tsEntries[i];
- IType typeHandle = tsEntry.getType();
+ for (int i= 0; i < tsEntries.length; i++) {
+ TypeStructureEntry tsEntry= tsEntries[i];
+ IType typeHandle= tsEntry.getType();
// Sanity check before putting in table
- TypeStructureEntry tsExisting =
- (TypeStructureEntry) fPrincipalStructureTable.get(typeHandle);
+ TypeStructureEntry tsExisting= (TypeStructureEntry) fPrincipalStructureTable.get(typeHandle);
if (tsExisting != null) {
if (!tsExisting.getSourceEntry().getFileName().equals(sEntry.getFileName())) {
// Same type provided by different files
- String msg =
- "Type "
- + typeHandle.getName()
- + " already provided by "
- + tsExisting.getSourceEntry().getFileName();
- ProblemDetailImpl problem = new ProblemDetailImpl(msg, sEntry);
+ String msg= "Type " + typeHandle.getName() + " already provided by " + tsExisting.getSourceEntry().getFileName();
+ ProblemDetailImpl problem= new ProblemDetailImpl(msg, sEntry);
fProblemReporter.putProblem(sEntry, problem);
// skip it
continue;
@@ -1782,66 +1610,53 @@ public class StateImpl implements IState {
// Finally, put it in table.
fPrincipalStructureTable.put(typeHandle, tsEntry);
- types[count++] = typeHandle;
+ types[count++]= typeHandle;
}
/* Update the dependency graph. */
if (count < types.length) {
- System.arraycopy(types, 0, types = new IType[count], 0, count);
+ System.arraycopy(types, 0, types= new IType[count], 0, count);
}
fGraph.add(unit, types, result.getDependencies());
}
-
/**
* Stores the results of a compilation in the state tables
*/
protected void putCompilationResults(ConvertedCompilationResult[] results) {
- for (int i = 0; i < results.length; i++) {
+ for (int i= 0; i < results.length; i++) {
putCompilationResult(results[i]);
}
}
-
/**
* Adds one source entry in the source element table
*/
public void putSourceEntry(IPackage pkg, SourceEntry sourceEntry) {
this.fSourceElementTable.putSourceEntry(pkg, sourceEntry);
}
-
/**
* Reads the class path.
*/
protected void readClassPath() {
try {
- JavaProject jp = (JavaProject) getJavaProject();
- fPackageFragmentRootsInClassPath = jp.getBuilderRoots(null);
- fBinaryOutput =
- new ProjectBinaryOutput(
- getProject(),
- jp.getOutputLocation(),
- fDevelopmentContext);
+ JavaProject jp= (JavaProject) getJavaProject();
+ fPackageFragmentRootsInClassPath= jp.getBuilderRoots(null);
+ fBinaryOutput= new ProjectBinaryOutput(getProject(), jp.getOutputLocation(), fDevelopmentContext);
} catch (JavaModelException e) {
throw internalException(e);
}
}
-
/**
* Reads the class path.
*/
protected void readClassPath(IResourceDelta delta) {
try {
- JavaProject jp = (JavaProject) getJavaProject();
- fPackageFragmentRootsInClassPath = jp.getBuilderRoots(delta);
- fBinaryOutput =
- new ProjectBinaryOutput(
- getProject(),
- jp.getOutputLocation(),
- fDevelopmentContext);
+ JavaProject jp= (JavaProject) getJavaProject();
+ fPackageFragmentRootsInClassPath= jp.getBuilderRoots(delta);
+ fBinaryOutput= new ProjectBinaryOutput(getProject(), jp.getOutputLocation(), fDevelopmentContext);
} catch (JavaModelException e) {
throw internalException(e);
}
}
-
/**
* Remove one source entry from the source element table
*/
@@ -1849,40 +1664,35 @@ public class StateImpl implements IState {
this.fSourceElementTable.removeSourceEntry(pkg, fileName);
this.getPrincipalStructureTable().remove(handle);
}
-
protected void resetProject() {
// Remembers the name of the project before reseting it
if (fProjectName == null)
- fProjectName = fProject.getName();
- fProject = null;
+ fProjectName= fProject.getName();
+ fProject= null;
}
-
/**
* This method recalculates the dependency info to refer to the source element
* each type came from. Stand-alone sources and binaries are represented by
* PackageElement objects, zips are represented by the IPath of the zip file,
* and namespaces by IPackage objects.
*/
- protected Vector resolveDependencies(
- PackageElement resultUnit,
- CompilationResult result) {
- IPackage resultPackage = resultUnit.getPackage();
- SourceEntry resultSourceEntry = getSourceEntry(resultUnit);
- char[][] fileDependencies = result.getFileDependencies();
- char[][] namespaceDependencies = result.getNamespaceDependencies();
- Vector vSourceDeps = new Vector();
+ protected Vector resolveDependencies(PackageElement resultUnit, CompilationResult result) {
+ IPackage resultPackage= resultUnit.getPackage();
+ SourceEntry resultSourceEntry= getSourceEntry(resultUnit);
+ char[][] fileDependencies= result.getFileDependencies();
+ char[][] namespaceDependencies= result.getNamespaceDependencies();
+ Vector vSourceDeps= new Vector();
if (namespaceDependencies != null) {
- for (int i = 0; i < namespaceDependencies.length; i++) {
- String namespace = Util.toString(namespaceDependencies[i]);
+ for (int i= 0; i < namespaceDependencies.length; i++) {
+ String namespace= Util.toString(namespaceDependencies[i]);
if (namespace.length() == 0) {
- IPackage defaultPkg = defaultPackageFor(resultUnit.getPackage());
+ IPackage defaultPkg= defaultPackageFor(resultUnit.getPackage());
if (defaultPkg != null && !vSourceDeps.contains(defaultPkg)) {
vSourceDeps.addElement(defaultPkg);
}
} else {
- IPackage pkg =
- fDevelopmentContext.getImage().getPackageHandle(namespace, false);
- pkg = canonicalize(pkg);
+ IPackage pkg= fDevelopmentContext.getImage().getPackageHandle(namespace, false);
+ pkg= canonicalize(pkg);
if (!vSourceDeps.contains(pkg)) {
vSourceDeps.addElement(pkg);
}
@@ -1898,17 +1708,16 @@ public class StateImpl implements IState {
/* do for each file dependency */
if (fileDependencies != null) {
- for (int i = 0; i < fileDependencies.length; i++) {
+ for (int i= 0; i < fileDependencies.length; i++) {
if (fileDependencies[i] != null) {
- SourceEntry sEntry =
- SourceEntry.fromPathWithZipEntryName(Util.toString(fileDependencies[i]));
+ SourceEntry sEntry= SourceEntry.fromPathWithZipEntryName(Util.toString(fileDependencies[i]));
if (sEntry.fZipEntryFileName != null) {
- IPath path = sEntry.getPath();
+ IPath path= sEntry.getPath();
if (!vSourceDeps.contains(path)) {
vSourceDeps.addElement(path);
}
} else {
- PackageElement element = packageElementFromSourceEntry(sEntry);
+ PackageElement element= packageElementFromSourceEntry(sEntry);
/* Make sure it's a valid ref. */
if (getSourceEntry(element) != null) {
if (!vSourceDeps.contains(element.getPackage())) {
@@ -1922,87 +1731,75 @@ public class StateImpl implements IState {
}
return vSourceDeps;
}
-
/**
* setBuildContext method comment.
*/
protected void setBuildContext(IImageContext context) {
- fBuildContext = context;
+ fBuildContext= context;
}
-
/**
* Sets the compiler options that were in effect when
* this state was built.
*/
protected void setCompilerOptions(ConfigurableOption[] options) {
- fCompilerOptions = options;
+ fCompilerOptions= options;
}
-
/**
* Sets the fingerprint for this state.
*/
protected void setFingerprint(byte[] fp) {
- fFingerprint = fp;
+ fFingerprint= fp;
}
-
/**
* Sets the dependency graph for the state.
*/
protected void setInternalDependencyGraph(DependencyGraph graph) {
- fGraph = graph;
+ fGraph= graph;
}
-
/**
* Sets the package map
*/
protected void setPackageMap(PackageMap map) {
- fPackageMap = map;
+ fPackageMap= map;
/* build the reverse index -- the path map */
- fPathMap = new PathMap(fPackageMap);
+ fPathMap= new PathMap(fPackageMap);
}
-
/**
* Sets the path map
*/
protected void setPathMap(PathMap map) {
- fPathMap = map;
+ fPathMap= map;
}
-
/**
* Sets the principal structure by package table.
*/
protected void setPrincipalStructureByPackageTable(Hashtable table) {
- fPrincipalStructureByPackageTable = table;
+ fPrincipalStructureByPackageTable= table;
}
-
/**
* Sets the principal structure table.
*/
protected void setPrincipalStructureTable(Hashtable table) {
- fPrincipalStructureTable = table;
+ fPrincipalStructureTable= table;
}
-
/**
* Sets the problem reporter.
*/
protected void setProblemReporter(IProblemReporter problemReporter) {
- fProblemReporter = problemReporter;
+ fProblemReporter= problemReporter;
}
-
/**
* Sets the source element table.
*/
protected void setSourceElementTable(SourceElementTable table) {
- fSourceElementTable = table;
+ fSourceElementTable= table;
}
-
/**
* Returns a string representation of the receiver.
*/
public String toString() {
return "StateImpl(" + fStateNumber + ")";
}
-
/**
* Returns the type handle for the given type name,
* relative to the referring type given by tsEntry.
@@ -2013,7 +1810,6 @@ public class StateImpl implements IState {
protected IType typeNameToHandle(TypeStructureEntry tsEntry, String typeName) {
return typeNameToHandle(tsEntry.getType().getPackage(), typeName);
}
-
/**
* Returns the type handle for the given type name,
* relative to the referring package refPkg.
@@ -2022,50 +1818,48 @@ public class StateImpl implements IState {
* the same as refPkg).
*/
protected IType typeNameToHandle(IPackage refPkg, String typeName) {
- int lastDot = typeName.lastIndexOf('.');
+ int lastDot= typeName.lastIndexOf('.');
if (lastDot == -1) {
- IPackage pkg = defaultPackageFor(refPkg);
+ IPackage pkg= defaultPackageFor(refPkg);
if (pkg == null) {
// typeName is unqualified but there is no visible default package.
// Should not occur, but be resilient, and assume it's in the same package
// as tsEntry.
- pkg = refPkg;
+ pkg= refPkg;
}
return pkg.getClassHandle(typeName);
}
- String packageName = typeName.substring(0, lastDot);
- String simpleName = typeName.substring(lastDot + 1);
+ String packageName= typeName.substring(0, lastDot);
+ String simpleName= typeName.substring(lastDot + 1);
if (!refPkg.isUnnamed() && refPkg.getName().equals(packageName)) {
return refPkg.getClassHandle(simpleName);
}
- IPackage pkg =
- fDevelopmentContext.getImage().getPackageHandle(packageName, false);
- pkg = canonicalize(pkg);
+ IPackage pkg= fDevelopmentContext.getImage().getPackageHandle(packageName, false);
+ pkg= canonicalize(pkg);
return canonicalize(pkg.getClassHandle(simpleName));
}
-
/**
* Convert a type signature to a non-state-specific type handle.
*/
protected IType typeSignatureToHandle(TypeStructureEntry tsEntry, String sig) {
- int nestingDepth = 0;
- int i = 0;
- char c = sig.charAt(i);
+ int nestingDepth= 0;
+ int i= 0;
+ char c= sig.charAt(i);
while (c == '[') {
++nestingDepth;
++i;
- c = sig.charAt(i);
+ c= sig.charAt(i);
}
/* if its a class */
IType elementType;
if (c == 'L') {
/* class or interface */
- int semicolon = sig.indexOf(';', i + 1);
- elementType = typeNameToHandle(tsEntry, sig.substring(i + 1, semicolon));
+ int semicolon= sig.indexOf(';', i + 1);
+ elementType= typeNameToHandle(tsEntry, sig.substring(i + 1, semicolon));
} else {
/* base type or invalid type name */
- elementType = fDevelopmentContext.primitiveTypeFromTypeCode(c);
+ elementType= fDevelopmentContext.primitiveTypeFromTypeCode(c);
}
if (nestingDepth == 0) {
return elementType;
@@ -2073,5 +1867,4 @@ public class StateImpl implements IState {
return new ArrayTypeHandleImpl((TypeImpl) elementType, nestingDepth);
}
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSnap.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSnap.java
index 68b7da8d62..7ab1aa8840 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSnap.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSnap.java
@@ -57,50 +57,43 @@ public class StateSnap {
IPackage currentPackage;
static final int MAGIC = 0x53544154; // magic = "STAT"e
- static final int VERSION5 = 0x0005;
- static final int VERSION6 = 0x0006;
- /**
- * Creates a new StateSnap.
- */
- public StateSnap() {
- super();
- }
-
- /**
- * Reads and reconstructs a state from the given input stream.
- */
- public StateImpl read(
- JavaDevelopmentContextImpl dc,
- IProject project,
- DataInputStream in)
- throws IOException {
-
- int magic = in.readInt();
- int version = in.readShort();
- if (magic != MAGIC) { // magic = "STAT"e
- throw new IOException("Unrecognized format");
- }
+ static final int VERSION5 = 0x0005;
+ static final int VERSION6 = 0x0006;
+/**
+ * Creates a new StateSnap.
+ */
+public StateSnap() {
+ super();
+}
+/**
+ * Reads and reconstructs a state from the given input stream.
+ */
+public StateImpl read(JavaDevelopmentContextImpl dc, IProject project, DataInputStream in) throws IOException {
- /* dispatch to appropriate reader */
- switch (version) {
- case VERSION5 :
- return new StateSnapV5().read(dc, project, in);
- case VERSION6 :
- return new StateSnapV6().read(dc, project, in);
- default :
- throw new IOException("Unrecognized state format");
- }
+ int magic = in.readInt();
+ int version = in.readShort();
+ if (magic != MAGIC) { // magic = "STAT"e
+ throw new IOException("Unrecognized format");
}
- /**
- * Saves key information about the given state
- * to the given output stream. This snapshot can be used
- * subsequently in reconstructing the state.
- */
- public void save(StateImpl state, DataOutputStream out) throws IOException {
-
- /* current version for writing state is version 6 */
- new StateSnapV6().save(state, out);
+ /* dispatch to appropriate reader */
+ switch (version) {
+ case VERSION5:
+ return new StateSnapV5().read(dc, project, in);
+ case VERSION6:
+ return new StateSnapV6().read(dc, project, in);
+ default:
+ throw new IOException("Unrecognized state format");
}
+}
+/**
+ * Saves key information about the given state
+ * to the given output stream. This snapshot can be used
+ * subsequently in reconstructing the state.
+ */
+public void save(StateImpl state, DataOutputStream out) throws IOException {
+ /* current version for writing state is version 6 */
+ new StateSnapV6().save(state, out);
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSnapConstantPool.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSnapConstantPool.java
index 6b3c5baab1..c03075bb8f 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSnapConstantPool.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSnapConstantPool.java
@@ -18,656 +18,614 @@ class StateSnapConstantPool {
* The number of special pool entries at the beginning.
*/
static final int NUM_SPECIAL = 11;
- /**
- * StateSnapConstantPool constructor comment.
- */
- StateSnapConstantPool(IDevelopmentContext dc) {
- init(dc, 500);
- }
-
- /**
- * Read a StateSnapConstantPool from an input stream.
- */
- StateSnapConstantPool(
- IDevelopmentContext dc,
- DataInputStream in,
- StateSnapV5 snap)
- throws IOException {
- read(dc, in, snap);
- }
-
- /**
- * Add a Number to the pool.
- */
- public void add(Number num) {
- fSet.put(num);
- }
-
- /**
- * Add a String to the pool.
- */
- public void add(String str) {
- fSet.put(str);
- }
-
- /**
- * Add an IPath to the pool.
- */
- public void add(IPath path) {
- if (!fSet.includes(path)) {
- // Special handling needed to preserve device
- if (path.isRoot()) {
- fSet.put(path.toString());
- } else {
- IPath parent = path.removeLastSegments(1);
- add(parent);
- fSet.put(path.lastSegment());
- }
- fSet.put(path);
+/**
+ * StateSnapConstantPool constructor comment.
+ */
+StateSnapConstantPool(IDevelopmentContext dc) {
+ init(dc, 500);
+}
+/**
+ * Read a StateSnapConstantPool from an input stream.
+ */
+StateSnapConstantPool(IDevelopmentContext dc, DataInputStream in, StateSnapV5 snap) throws IOException {
+ read(dc, in, snap);
+}
+/**
+ * Add a Number to the pool.
+ */
+public void add(Number num) {
+ fSet.put(num);
+}
+/**
+ * Add a String to the pool.
+ */
+public void add(String str) {
+ fSet.put(str);
+}
+/**
+ * Add an IPath to the pool.
+ */
+public void add(IPath path) {
+ if (!fSet.includes(path)) {
+ // Special handling needed to preserve device
+ if (path.isRoot()) {
+ fSet.put(path.toString());
+ } else {
+ IPath parent = path.removeLastSegments(1);
+ add(parent);
+ fSet.put(path.lastSegment());
}
+ fSet.put(path);
}
-
- /**
- * Add an IPackage to the pool.
- */
- public void add(IHandle handle) {
- switch (handle.kind()) {
- case IHandle.K_JAVA_PACKAGE :
- add((IPackage) handle);
- break;
- case IHandle.K_JAVA_TYPE :
- add((IType) handle);
- break;
- case IHandle.K_JAVA_FIELD :
- if (!fSet.includes(handle)) {
- IField f = (IField) handle;
- add(f.getDeclaringClass());
- add(f.getName());
- fSet.put(handle);
- }
- break;
- case IHandle.K_JAVA_CONSTRUCTOR :
- if (!fSet.includes(handle)) {
- IConstructor c = (IConstructor) handle;
- add(c.getDeclaringClass());
- IType[] parms = c.getParameterTypes();
- for (int i = 0; i < parms.length; ++i) {
- add(parms[i]);
- }
- fSet.put(handle);
- }
- break;
- case IHandle.K_JAVA_METHOD :
- if (!fSet.includes(handle)) {
- IMethod m = (IMethod) handle;
- add(m.getDeclaringClass());
- add(m.getName());
- IType[] parms = m.getParameterTypes();
- for (int i = 0; i < parms.length; ++i) {
- add(parms[i]);
- }
- fSet.put(handle);
+}
+/**
+ * Add an IPackage to the pool.
+ */
+public void add(IHandle handle) {
+ switch (handle.kind()) {
+ case IHandle.K_JAVA_PACKAGE:
+ add((IPackage)handle);
+ break;
+ case IHandle.K_JAVA_TYPE:
+ add((IType)handle);
+ break;
+ case IHandle.K_JAVA_FIELD:
+ if (!fSet.includes(handle)) {
+ IField f = (IField)handle;
+ add(f.getDeclaringClass());
+ add(f.getName());
+ fSet.put(handle);
+ }
+ break;
+ case IHandle.K_JAVA_CONSTRUCTOR:
+ if (!fSet.includes(handle)) {
+ IConstructor c = (IConstructor)handle;
+ add(c.getDeclaringClass());
+ IType[] parms = c.getParameterTypes();
+ for (int i = 0; i < parms.length; ++i) {
+ add(parms[i]);
}
- break;
- case IHandle.K_JAVA_IMAGE :
- // NOP
- break;
- default :
- Assert.isTrue(false, "Unknown kind of handle");
- }
- }
-
- /**
- * Add a SourceEntry to the pool.
- */
- public void add(SourceEntry entry) {
- Assert.isNotNull(
- entry,
- "Null SourceEntry being added to StateSnapConstantPool");
- if (!fSet.includes(entry)) {
- add(entry.getPath());
- String zipEntryPath = entry.fZipEntryPath;
- if (zipEntryPath != null) {
- fSet.put(zipEntryPath);
+ fSet.put(handle);
}
- String zipEntryFileName = entry.fZipEntryFileName;
- if (zipEntryFileName != null) {
- fSet.put(zipEntryFileName);
+ break;
+ case IHandle.K_JAVA_METHOD:
+ if (!fSet.includes(handle)) {
+ IMethod m = (IMethod)handle;
+ add(m.getDeclaringClass());
+ add(m.getName());
+ IType[] parms = m.getParameterTypes();
+ for (int i = 0; i < parms.length; ++i) {
+ add(parms[i]);
+ }
+ fSet.put(handle);
}
- fSet.put(entry);
- }
+ break;
+ case IHandle.K_JAVA_IMAGE:
+ // NOP
+ break;
+ default:
+ Assert.isTrue(false, "Unknown kind of handle");
}
-
- /**
- * Add an IPackage to the pool.
- */
- public void add(IPackage pkg) {
- if (!fSet.includes(pkg)) {
- fSet.put(pkg.getName());
- fSet.put(pkg);
+}
+/**
+ * Add a SourceEntry to the pool.
+ */
+public void add(SourceEntry entry) {
+ Assert.isNotNull(entry, "Null SourceEntry being added to StateSnapConstantPool");
+ if (!fSet.includes(entry)) {
+ add(entry.getPath());
+ String zipEntryPath = entry.fZipEntryPath;
+ if (zipEntryPath != null) {
+ fSet.put(zipEntryPath);
}
+ String zipEntryFileName = entry.fZipEntryFileName;
+ if (zipEntryFileName != null) {
+ fSet.put(zipEntryFileName);
+ }
+ fSet.put(entry);
}
-
- /**
- * Add an IType to the pool.
- */
- public void add(IType type) {
- Assert.isTrue(!type.isStateSpecific());
- if (type.isPrimitive()) {
- return; // Already added
- }
- if (!fSet.includes(type)) {
- if (type.isArray()) {
- add(((ArrayTypeHandleImpl) type).getElementType());
- } else {
- ClassOrInterfaceHandleImpl cls = (ClassOrInterfaceHandleImpl) type;
- add(cls.getPackage());
- fSet.put(cls.getSimpleName());
- }
- fSet.put(type);
+}
+/**
+ * Add an IPackage to the pool.
+ */
+public void add(IPackage pkg) {
+ if (!fSet.includes(pkg)) {
+ fSet.put(pkg.getName());
+ fSet.put(pkg);
+ }
+}
+/**
+ * Add an IType to the pool.
+ */
+public void add(IType type) {
+ Assert.isTrue(!type.isStateSpecific());
+ if (type.isPrimitive()) {
+ return; // Already added
+ }
+ if (!fSet.includes(type)) {
+ if (type.isArray()) {
+ add(((ArrayTypeHandleImpl)type).getElementType());
+ }
+ else {
+ ClassOrInterfaceHandleImpl cls = (ClassOrInterfaceHandleImpl)type;
+ add(cls.getPackage());
+ fSet.put(cls.getSimpleName());
}
+ fSet.put(type);
}
-
- /**
- * Returns the IHandle at the given index. It must not be null.
- */
- public IHandle getHandle(int index) throws IOException {
- try {
- IHandle result = (IHandle) fSet.get(index);
- if (result == null) {
- throw new IOException("Error in format");
- }
- return result;
- } catch (ClassCastException e) {
+}
+/**
+ * Returns the IHandle at the given index. It must not be null.
+ */
+public IHandle getHandle(int index) throws IOException {
+ try {
+ IHandle result = (IHandle)fSet.get(index);
+ if (result == null) {
throw new IOException("Error in format");
}
+ return result;
}
-
- /**
- * Returns the Object at the given index. It may be null.
- */
- public Object getObject(int index) throws IOException {
- return fSet.get(index);
+ catch (ClassCastException e) {
+ throw new IOException("Error in format");
}
-
- /**
- * Returns the IPackage at the given index. It must not be null.
- */
- public IPackage getPackage(int index) throws IOException {
- try {
- IPackage result = (IPackage) fSet.get(index);
- if (result == null) {
- throw new IOException("Error in format");
- }
- return result;
- } catch (ClassCastException e) {
+}
+/**
+ * Returns the Object at the given index. It may be null.
+ */
+public Object getObject(int index) throws IOException {
+ return fSet.get(index);
+}
+/**
+ * Returns the IPackage at the given index. It must not be null.
+ */
+public IPackage getPackage(int index) throws IOException {
+ try {
+ IPackage result = (IPackage)fSet.get(index);
+ if (result == null) {
throw new IOException("Error in format");
}
+ return result;
}
-
- /**
- * Returns the IPath at the given index. It must not be null.
- */
- public IPath getPath(int index) throws IOException {
- try {
- IPath result = (IPath) fSet.get(index);
- if (result == null) {
- throw new IOException("Error in format");
- }
- return result;
- } catch (ClassCastException e) {
- throw new IOException("Error in format");
- }
+ catch (ClassCastException e) {
+ throw new IOException("Error in format");
}
-
- /**
- * Returns the SourceEntry at the given index. It must not be null.
- */
- public SourceEntry getSourceEntry(int index) throws IOException {
- try {
- SourceEntry result = (SourceEntry) fSet.get(index);
- if (result == null) {
- throw new IOException("Error in format");
- }
- return result;
- } catch (ClassCastException e) {
+}
+/**
+ * Returns the IPath at the given index. It must not be null.
+ */
+public IPath getPath(int index) throws IOException {
+ try {
+ IPath result = (IPath)fSet.get(index);
+ if (result == null) {
throw new IOException("Error in format");
}
+ return result;
}
-
- /**
- * Returns the String at the given index. It must not be null.
- */
- public String getString(int index) throws IOException {
- try {
- String result = (String) fSet.get(index);
- if (result == null) {
- throw new IOException("Error in format");
- }
- return result;
- } catch (ClassCastException e) {
+ catch (ClassCastException e) {
+ throw new IOException("Error in format");
+ }
+}
+/**
+ * Returns the SourceEntry at the given index. It must not be null.
+ */
+public SourceEntry getSourceEntry(int index) throws IOException {
+ try {
+ SourceEntry result = (SourceEntry)fSet.get(index);
+ if (result == null) {
throw new IOException("Error in format");
}
+ return result;
}
-
- /**
- * Returns the String at the given index. It may be null.
- */
- public String getStringOrNull(int index) throws IOException {
- return index == 0 ? null : getString(index);
+ catch (ClassCastException e) {
+ throw new IOException("Error in format");
}
-
- /**
- * Returns the String or Number at the given index. It may be null.
- */
- public Object getStringOrNumber(int index) throws IOException {
- if (index == 0) {
- return null;
- }
- Object result = (Object) fSet.get(index);
- if (result != null
- && ((result instanceof Number) || (result instanceof String))) {
- return result;
- } else {
+}
+/**
+ * Returns the String at the given index. It must not be null.
+ */
+public String getString(int index) throws IOException {
+ try {
+ String result = (String)fSet.get(index);
+ if (result == null) {
throw new IOException("Error in format");
}
+ return result;
}
-
- /**
- * Returns the IType at the given index. It must not be null.
- */
- public IType getType(int index) throws IOException {
- try {
- IType result = (IType) fSet.get(index);
- if (result == null) {
- throw new IOException("Error in format");
- }
- return result;
- } catch (ClassCastException e) {
+ catch (ClassCastException e) {
+ throw new IOException("Error in format");
+ }
+}
+/**
+ * Returns the String at the given index. It may be null.
+ */
+public String getStringOrNull(int index) throws IOException {
+ return index == 0 ? null : getString(index);
+}
+/**
+ * Returns the String or Number at the given index. It may be null.
+ */
+public Object getStringOrNumber(int index) throws IOException {
+ if (index == 0) {
+ return null;
+ }
+ Object result = (Object)fSet.get(index);
+ if (result != null && ((result instanceof Number) || (result instanceof String))) {
+ return result;
+ }
+ else {
+ throw new IOException("Error in format");
+ }
+}
+/**
+ * Returns the IType at the given index. It must not be null.
+ */
+public IType getType(int index) throws IOException {
+ try {
+ IType result = (IType)fSet.get(index);
+ if (result == null) {
throw new IOException("Error in format");
}
+ return result;
}
-
- /**
- * For debugging.
- */
- public String histogram() {
- int nStr = 0, nID = 0, nSE = 0, nH = 0, nN = 0;
-
- int n = fSet.size();
- for (int i = 10; i < n; ++i) {
- Object obj = fSet.get(i);
- if (obj instanceof String) {
- ++nStr;
- } else
- if (obj instanceof IPath) {
- ++nID;
- } else
- if (obj instanceof SourceEntry) {
- ++nSE;
- } else
- if (obj instanceof IHandle) {
- ++nH;
- } else
- if (obj instanceof Number) {
- ++nN;
- } else {
- Assert.isTrue(false, "Unexpected pool item");
- }
- }
- return "nStr="
- + nStr
- + ", nID="
- + nID
- + ", nSE="
- + nSE
- + ", nH="
- + nH
- + ",nN="
- + nN;
-
+ catch (ClassCastException e) {
+ throw new IOException("Error in format");
}
-
- /**
- * Returns the index of the given object.
- */
- public int index(Object obj) {
- if (obj == null) {
- return 0;
+}
+/**
+ * For debugging.
+ */
+public String histogram() {
+ int nStr = 0, nID = 0, nSE = 0, nH = 0, nN = 0;
+
+ int n = fSet.size();
+ for (int i = 10; i < n; ++i) {
+ Object obj = fSet.get(i);
+ if (obj instanceof String) {
+ ++nStr;
+ }
+ else if (obj instanceof IPath) {
+ ++nID;
+ }
+ else if (obj instanceof SourceEntry) {
+ ++nSE;
+ }
+ else if (obj instanceof IHandle) {
+ ++nH;
+ }
+ else if (obj instanceof Number) {
+ ++nN;
}
- try {
- return fSet.index(obj);
- } catch (IllegalArgumentException e) {
- throw new IllegalArgumentException(
- "Internal error in state serialization. Expected object missing from constant pool: "
- + obj);
+ else {
+ Assert.isTrue(false, "Unexpected pool item");
}
}
-
- /**
- * Initialize the constant pool for the given DC and initial size estimate.
- */
- private void init(IDevelopmentContext dc, int initSize) {
- // Set up constant pool with the special entries.
- // Number of entries must correspond with NUM_SPECIAL
- IImage image = dc.getImage();
- fSet = new OrderedSet(initSize * 2 + 1, 0.5f);
- fSet.put(new Object()); // 0: placeholder for null
- fSet.put(image.booleanType()); // 1: type boolean
- fSet.put(image.byteType()); // 2: type byte
- fSet.put(image.charType()); // 3: type char
- fSet.put(image.doubleType()); // 4: type double
- fSet.put(image.floatType()); // 5: type float
- fSet.put(image.intType()); // 6: type int
- fSet.put(image.longType()); // 7: type long
- fSet.put(image.shortType()); // 8: type short
- fSet.put(image.voidType()); // 9: type void
- fSet.put(image); // 10: image handle
-
+ return "nStr=" + nStr + ", nID=" + nID + ", nSE=" + nSE + ", nH=" + nH + ",nN=" + nN;
+
+}
+/**
+ * Returns the index of the given object.
+ */
+public int index(Object obj) {
+ if (obj == null) {
+ return 0;
}
-
- /**
- * Read a StateSnapConstantPool from an input stream.
- */
- private void read(IDevelopmentContext dc, DataInputStream in, StateSnapV5 snap)
- throws IOException {
- int n = in.readInt(); // Actual size of pool is (NUM_SPECIAL + n)
- init(dc, n);
-
- int i = NUM_SPECIAL;
- for (int j = 0; j < n; ++j, ++i) {
- int tag = in.readByte();
- switch (tag) {
- case 1 :
- // String
- String str = in.readUTF();
- fSet.put(i, str);
- break;
- case 2 :
- // IPath
- int temp = in.readInt();
- IPath parent = temp == 0 ? null : getPath(temp);
- String elementName = getString(in.readInt());
- if (parent == null) {
- fSet.put(i, new Path(elementName));
- } else {
- fSet.put(i, parent.append(elementName));
- }
- break;
- case 3 :
- // SourceEntry
- SourceEntry entry = snap.readSourceEntry(this, in);
- fSet.put(i, entry);
- break;
- case 4 :
- case 5 :
- case 6 :
- case 7 :
- case 8 :
- case 9 :
- case 10 :
- case 11 :
- fSet.put(i, readHandle(dc, in, tag));
- break;
- case 12 :
- case 13 :
- case 14 :
- case 15 :
- fSet.put(i, readNumber(in, tag));
- break;
- default :
- throw new IOException("Unexpected kind of pool item");
- }
- }
+ try {
+ return fSet.index(obj);
+ }
+ catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException("Internal error in state serialization. Expected object missing from constant pool: " + obj);
}
+}
+/**
+ * Initialize the constant pool for the given DC and initial size estimate.
+ */
+private void init (IDevelopmentContext dc, int initSize) {
+ // Set up constant pool with the special entries.
+ // Number of entries must correspond with NUM_SPECIAL
+ IImage image = dc.getImage();
+ fSet = new OrderedSet(initSize*2+1, 0.5f);
+ fSet.put(new Object()); // 0: placeholder for null
+ fSet.put(image.booleanType()); // 1: type boolean
+ fSet.put(image.byteType()); // 2: type byte
+ fSet.put(image.charType()); // 3: type char
+ fSet.put(image.doubleType()); // 4: type double
+ fSet.put(image.floatType()); // 5: type float
+ fSet.put(image.intType()); // 6: type int
+ fSet.put(image.longType()); // 7: type long
+ fSet.put(image.shortType()); // 8: type short
+ fSet.put(image.voidType()); // 9: type void
+ fSet.put(image); // 10: image handle
- /**
- * Internal -- Read an IHandle from an input stream into the pool.
- */
- private IHandle readHandle(IDevelopmentContext dc, DataInputStream in, int tag)
- throws IOException {
+}
+/**
+ * Read a StateSnapConstantPool from an input stream.
+ */
+private void read(IDevelopmentContext dc, DataInputStream in, StateSnapV5 snap) throws IOException {
+ int n = in.readInt(); // Actual size of pool is (NUM_SPECIAL + n)
+ init(dc, n);
+
+ int i = NUM_SPECIAL;
+ for (int j = 0; j < n; ++j, ++i) {
+ int tag = in.readByte();
switch (tag) {
- case 4 :
- {
- // package
- String name = getString(in.readInt());
- boolean isUnnamed = in.readBoolean();
- return dc.getImage().getPackageHandle(name, isUnnamed);
- }
- case 5 :
- {
- // primitive type
- // Should not occur since primitive types are well known and not written
- throw new IOException("Internal error");
- }
- case 6 :
- {
- // array type
- TypeImpl elementType = (TypeImpl) getType(in.readInt());
- int nesting = in.readByte() & 0xFF;
- return new ArrayTypeHandleImpl(elementType, nesting);
- }
- case 7 :
- {
- // class or interface type
- IPackage pkg = getPackage(in.readInt());
- String simpleName = getString(in.readInt());
- return pkg.getClassHandle(simpleName);
- }
- case 8 :
- {
- // method
- IType declaringClass = getType(in.readInt());
- if (declaringClass.isPrimitive() || declaringClass.isArray()) {
- throw new IOException("Bad format");
- }
- String name = getString(in.readInt());
- int numParams = in.readByte() & 0xFF;
- IType[] params = new IType[numParams];
- for (int i = 0; i < numParams; ++i) {
- params[i] = getType(in.readInt());
- }
- return declaringClass.getMethodHandle(name, params);
- }
- case 9 :
- {
- // constructor
- IType declaringClass = getType(in.readInt());
- if (declaringClass.isPrimitive() || declaringClass.isArray()) {
- throw new IOException("Bad format");
- }
- int numParams = in.readByte() & 0xFF;
- IType[] params = new IType[numParams];
- for (int i = 0; i < numParams; ++i) {
- params[i] = getType(in.readInt());
- }
- return declaringClass.getConstructorHandle(params);
+ case 1:
+ // String
+ String str = in.readUTF();
+ fSet.put(i, str);
+ break;
+ case 2:
+ // IPath
+ int temp = in.readInt();
+ IPath parent = temp == 0 ? null : getPath(temp);
+ String elementName = getString(in.readInt());
+ if (parent == null) {
+ fSet.put(i, new Path(elementName));
}
- case 10 :
- {
- // field
- IType declaringClass = getType(in.readInt());
- if (declaringClass.isPrimitive() || declaringClass.isArray()) {
- throw new IOException("Bad format");
- }
- String name = getString(in.readInt());
- return declaringClass.getFieldHandle(name);
+ else {
+ fSet.put(i, parent.append(elementName));
}
- case 11 :
- // image
- return dc.getImage();
- default :
+ break;
+ case 3:
+ // SourceEntry
+ SourceEntry entry = snap.readSourceEntry(this, in);
+ fSet.put(i, entry);
+ break;
+ case 4:
+ case 5:
+ case 6:
+ case 7:
+ case 8:
+ case 9:
+ case 10:
+ case 11:
+ fSet.put(i, readHandle(dc, in, tag));
+ break;
+ case 12:
+ case 13:
+ case 14:
+ case 15:
+ fSet.put(i, readNumber(in, tag));
+ break;
+ default:
throw new IOException("Unexpected kind of pool item");
}
}
-
- /**
- * Internal -- Read a Number from an input stream into the pool.
- */
- private Number readNumber(DataInputStream in, int tag) throws IOException {
- switch (tag) {
- case 12 :
- // Integer
- return new Integer(in.readInt());
- case 13 :
- // Long
- return new Long(in.readLong());
- case 14 :
- // Float
- return new Float(Float.intBitsToFloat(in.readInt()));
- case 15 :
- // Double
- return new Double(Double.longBitsToDouble(in.readLong()));
- default :
- throw new IOException("Unexpeced kind of Number");
+}
+/**
+ * Internal -- Read an IHandle from an input stream into the pool.
+ */
+private IHandle readHandle(IDevelopmentContext dc, DataInputStream in, int tag) throws IOException {
+ switch (tag) {
+ case 4: {
+ // package
+ String name = getString(in.readInt());
+ boolean isUnnamed = in.readBoolean();
+ return dc.getImage().getPackageHandle(name, isUnnamed);
+ }
+ case 5: {
+ // primitive type
+ // Should not occur since primitive types are well known and not written
+ throw new IOException("Internal error");
+ }
+ case 6: {
+ // array type
+ TypeImpl elementType = (TypeImpl) getType(in.readInt());
+ int nesting = in.readByte() & 0xFF;
+ return new ArrayTypeHandleImpl(elementType, nesting);
+ }
+ case 7: {
+ // class or interface type
+ IPackage pkg = getPackage(in.readInt());
+ String simpleName = getString(in.readInt());
+ return pkg.getClassHandle(simpleName);
+ }
+ case 8: {
+ // method
+ IType declaringClass = getType(in.readInt());
+ if (declaringClass.isPrimitive() || declaringClass.isArray()) {
+ throw new IOException("Bad format");
+ }
+ String name = getString(in.readInt());
+ int numParams = in.readByte() & 0xFF;
+ IType[] params = new IType[numParams];
+ for (int i = 0; i < numParams; ++i) {
+ params[i] = getType(in.readInt());
+ }
+ return declaringClass.getMethodHandle(name, params);
}
+ case 9: {
+ // constructor
+ IType declaringClass = getType(in.readInt());
+ if (declaringClass.isPrimitive() || declaringClass.isArray()) {
+ throw new IOException("Bad format");
+ }
+ int numParams = in.readByte() & 0xFF;
+ IType[] params = new IType[numParams];
+ for (int i = 0; i < numParams; ++i) {
+ params[i] = getType(in.readInt());
+ }
+ return declaringClass.getConstructorHandle(params);
+ }
+ case 10: {
+ // field
+ IType declaringClass = getType(in.readInt());
+ if (declaringClass.isPrimitive() || declaringClass.isArray()) {
+ throw new IOException("Bad format");
+ }
+ String name = getString(in.readInt());
+ return declaringClass.getFieldHandle(name);
+ }
+ case 11:
+ // image
+ return dc.getImage();
+ default:
+ throw new IOException("Unexpected kind of pool item");
}
-
- /**
- * Returns the number of entries in the pool.
- */
- public int size() {
- return fSet.size();
+}
+/**
+ * Internal -- Read a Number from an input stream into the pool.
+ */
+private Number readNumber(DataInputStream in, int tag) throws IOException {
+ switch (tag) {
+ case 12:
+ // Integer
+ return new Integer(in.readInt());
+ case 13:
+ // Long
+ return new Long(in.readLong());
+ case 14:
+ // Float
+ return new Float(Float.intBitsToFloat(in.readInt()));
+ case 15:
+ // Double
+ return new Double(Double.longBitsToDouble(in.readLong()));
+ default:
+ throw new IOException("Unexpeced kind of Number");
}
-
- /**
- * Write the constant pool to the given stream.
- */
- public void write(DataOutputStream out) throws IOException {
- int n = fSet.size();
- out.writeInt(n - NUM_SPECIAL);
- for (int i = NUM_SPECIAL; i < n; ++i) {
- Object obj = fSet.get(i);
- if (obj instanceof String) {
- out.writeByte(1);
- out.writeUTF((String) obj);
- } else
- if (obj instanceof IHandle) {
- writeHandle((IHandle) obj, out); // tags 4 through 11
- } else
- if (obj instanceof IPath) {
- IPath path = (IPath) obj;
- out.writeByte(2);
- // Special handling needed to preserve device
- if (path.isRoot()) {
- out.writeInt(0);
- out.writeInt(index(path.toString()));
- } else {
- IPath parent = path.removeLastSegments(1);
- out.writeInt(index(parent));
- out.writeInt(index(path.lastSegment()));
- }
- } else
- if (obj instanceof SourceEntry) {
- SourceEntry e = (SourceEntry) obj;
- out.writeByte(3);
- out.writeInt(index(e.getPath()));
- out.writeInt(index(e.fZipEntryPath));
- out.writeInt(index(e.fZipEntryFileName));
- } else
- if (obj instanceof Number) {
- writeNumber((Number) obj, out); // tags 12 through 15
- } else {
- Assert.isTrue(false, "Unexpected pool item");
- }
+}
+/**
+ * Returns the number of entries in the pool.
+ */
+public int size() {
+ return fSet.size();
+}
+/**
+ * Write the constant pool to the given stream.
+ */
+public void write(DataOutputStream out) throws IOException {
+ int n = fSet.size();
+ out.writeInt(n - NUM_SPECIAL);
+ for (int i = NUM_SPECIAL; i < n; ++i) {
+ Object obj = fSet.get(i);
+ if (obj instanceof String) {
+ out.writeByte(1);
+ out.writeUTF((String)obj);
+ }
+ else if (obj instanceof IHandle) {
+ writeHandle((IHandle)obj, out); // tags 4 through 11
+ }
+ else if (obj instanceof IPath) {
+ IPath path = (IPath)obj;
+ out.writeByte(2);
+ // Special handling needed to preserve device
+ if (path.isRoot()) {
+ out.writeInt(0);
+ out.writeInt(index(path.toString()));
+ }
+ else {
+ IPath parent = path.removeLastSegments(1);
+ out.writeInt(index(parent));
+ out.writeInt(index(path.lastSegment()));
+ }
+ }
+ else if (obj instanceof SourceEntry) {
+ SourceEntry e = (SourceEntry)obj;
+ out.writeByte(3);
+ out.writeInt(index(e.getPath()));
+ out.writeInt(index(e.fZipEntryPath));
+ out.writeInt(index(e.fZipEntryFileName));
+ }
+ else if (obj instanceof Number) {
+ writeNumber((Number)obj, out); // tags 12 through 15
+ }
+ else {
+ Assert.isTrue(false, "Unexpected pool item");
}
}
-
- /**
- * Write a handle to the given stream.
- */
- private void writeHandle(IHandle h, DataOutputStream out) throws IOException {
- switch (h.kind()) {
- case IHandle.K_JAVA_PACKAGE :
- IPackage pkg = (IPackage) h;
- out.writeByte(4);
- out.writeInt(index(pkg.getName()));
- out.writeBoolean(pkg.isUnnamed());
- break;
- case IHandle.K_JAVA_TYPE :
- IType t = (IType) h;
- if (t.isPrimitive()) {
- // tag=5
- // Primitive types should not show up since they are well known and are not written.
- throw new IOException("Internal error");
- } else
- if (t.isArray()) {
- ArrayTypeHandleImpl at = (ArrayTypeHandleImpl) t;
- out.writeByte(6);
- out.writeInt(index(at.getElementType()));
- int nesting = at.getNestingDepth();
- Assert.isTrue(nesting < 256);
- out.writeByte(nesting);
- } else {
- Assert.isTrue(t instanceof ClassOrInterfaceHandleImpl);
- out.writeByte(7);
- out.writeInt(index(t.getPackage()));
- out.writeInt(index(t.getSimpleName()));
- }
- break;
- case IHandle.K_JAVA_METHOD :
- {
- IMethod m = (IMethod) h;
- out.writeByte(8);
- out.writeInt(index(m.getDeclaringClass()));
- out.writeInt(index(m.getName()));
- IType[] params = m.getParameterTypes();
- Assert.isTrue(params.length < 256);
- out.writeByte(params.length);
- for (int j = 0; j < params.length; ++j) {
- out.writeInt(index(params[j]));
- }
- break;
- }
- case IHandle.K_JAVA_CONSTRUCTOR :
- {
- IConstructor c = (IConstructor) h;
- out.writeByte(9);
- out.writeInt(index(c.getDeclaringClass()));
- IType[] params = c.getParameterTypes();
- Assert.isTrue(params.length < 256);
- out.writeByte(params.length);
- for (int j = 0; j < params.length; ++j) {
- out.writeInt(index(params[j]));
- }
- break;
- }
- case IHandle.K_JAVA_FIELD :
- IField f = (IField) h;
- out.writeByte(10);
- out.writeInt(index(f.getDeclaringClass()));
- out.writeInt(index(f.getName()));
- break;
- case IHandle.K_JAVA_IMAGE :
- out.writeByte(11);
- break;
- default :
- Assert.isTrue(false, "Unknown handle type");
+}
+/**
+ * Write a handle to the given stream.
+ */
+private void writeHandle(IHandle h, DataOutputStream out) throws IOException {
+ switch (h.kind()) {
+ case IHandle.K_JAVA_PACKAGE:
+ IPackage pkg = (IPackage)h;
+ out.writeByte(4);
+ out.writeInt(index(pkg.getName()));
+ out.writeBoolean(pkg.isUnnamed());
+ break;
+ case IHandle.K_JAVA_TYPE:
+ IType t = (IType)h;
+ if (t.isPrimitive()) {
+ // tag=5
+ // Primitive types should not show up since they are well known and are not written.
+ throw new IOException("Internal error");
+ }
+ else if (t.isArray()) {
+ ArrayTypeHandleImpl at = (ArrayTypeHandleImpl)t;
+ out.writeByte(6);
+ out.writeInt(index(at.getElementType()));
+ int nesting = at.getNestingDepth();
+ Assert.isTrue(nesting < 256);
+ out.writeByte(nesting);
+ }
+ else {
+ Assert.isTrue(t instanceof ClassOrInterfaceHandleImpl);
+ out.writeByte(7);
+ out.writeInt(index(t.getPackage()));
+ out.writeInt(index(t.getSimpleName()));
+ }
+ break;
+ case IHandle.K_JAVA_METHOD: {
+ IMethod m = (IMethod)h;
+ out.writeByte(8);
+ out.writeInt(index(m.getDeclaringClass()));
+ out.writeInt(index(m.getName()));
+ IType[] params = m.getParameterTypes();
+ Assert.isTrue(params.length < 256);
+ out.writeByte(params.length);
+ for (int j = 0; j < params.length; ++j) {
+ out.writeInt(index(params[j]));
+ }
+ break;
}
+ case IHandle.K_JAVA_CONSTRUCTOR: {
+ IConstructor c = (IConstructor)h;
+ out.writeByte(9);
+ out.writeInt(index(c.getDeclaringClass()));
+ IType[] params = c.getParameterTypes();
+ Assert.isTrue(params.length < 256);
+ out.writeByte(params.length);
+ for (int j = 0; j < params.length; ++j) {
+ out.writeInt(index(params[j]));
+ }
+ break;
+ }
+ case IHandle.K_JAVA_FIELD:
+ IField f = (IField)h;
+ out.writeByte(10);
+ out.writeInt(index(f.getDeclaringClass()));
+ out.writeInt(index(f.getName()));
+ break;
+ case IHandle.K_JAVA_IMAGE:
+ out.writeByte(11);
+ break;
+ default:
+ Assert.isTrue(false, "Unknown handle type");
}
-
- /**
- * Write a Number to the given stream.
- */
- private void writeNumber(Number num, DataOutputStream out) throws IOException {
- if (num instanceof Integer) {
- out.writeByte(12);
- out.writeInt(num.intValue());
- } else
- if (num instanceof Long) {
- out.writeByte(13);
- out.writeLong(num.longValue());
- } else
- if (num instanceof Float) {
- out.writeByte(14);
- out.writeInt(Float.floatToIntBits(num.floatValue()));
- } else
- if (num instanceof Double) {
- out.writeByte(15);
- out.writeLong(Double.doubleToLongBits(num.doubleValue()));
- } else {
- Assert.isTrue(false, "Unexpeced kind of Number");
- }
+}
+/**
+ * Write a Number to the given stream.
+ */
+private void writeNumber(Number num, DataOutputStream out) throws IOException {
+ if (num instanceof Integer) {
+ out.writeByte(12);
+ out.writeInt(num.intValue());
+ }
+ else if (num instanceof Long) {
+ out.writeByte(13);
+ out.writeLong(num.longValue());
+ }
+ else if (num instanceof Float) {
+ out.writeByte(14);
+ out.writeInt(Float.floatToIntBits(num.floatValue()));
}
-
+ else if (num instanceof Double) {
+ out.writeByte(15);
+ out.writeLong(Double.doubleToLongBits(num.doubleValue()));
+ }
+ else {
+ Assert.isTrue(false, "Unexpeced kind of Number");
+ }
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSnapV5.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSnapV5.java
index a6d141f424..202d0368fd 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSnapV5.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSnapV5.java
@@ -28,790 +28,637 @@ public class StateSnapV5 {
IPackage currentPackage;
static final int MAGIC = 0x53544154; // magic = "STAT"e
static final int VERSION = 0x0005;
- /**
- * Add pool constants for the build context.
- */
- protected void addBuildContextToPool(
- IState state,
- StateSnapConstantPool pool) {
- IImageContext ctx = state.getBuildContext();
- if (ctx != null) {
- IPackage[] pkgs = ctx.getPackages();
- for (int i = 0; i < pkgs.length; ++i) {
- pool.add(pkgs[i]);
- }
- }
- }
-
- /**
- * Add pool constants for the dependency graph.
- */
- protected void addDependencyGraphToPool(
- StateImpl state,
- StateSnapConstantPool pool) {
- DependencyGraph graph = state.getInternalDependencyGraph();
- for (Enumeration e = graph.getNodes(); e.hasMoreElements();) {
- INode node = (INode) e.nextElement();
- switch (node.getKind()) {
- case INode.JCU_NODE :
- JCUNode jcuNode = (JCUNode) node;
- pool.add(state.getSourceEntry(jcuNode.getPackageElement()));
- IType[] types = jcuNode.getTypes();
- for (int i = 0; i < types.length; ++i) {
- pool.add(types[i]);
- }
- break;
- case INode.TYPE_NODE :
- TypeNode typeNode = (TypeNode) node;
- pool.add(state.getSourceEntry(typeNode.getPackageElement()));
- break;
- case INode.NAMESPACE_NODE :
- pool.add(((NamespaceNode) node).getPackage());
- break;
- case INode.ZIP_NODE :
- pool.add(((ZipNode) node).getZipFile());
- break;
- default :
- Assert.isTrue(false, "Unexpected kind of node");
- }
- // Don't need to process node dependents here, since they're nodes as well
- // and will have their info added to the pool above.
+/**
+ * Add pool constants for the build context.
+ */
+protected void addBuildContextToPool(IState state, StateSnapConstantPool pool) {
+ IImageContext ctx = state.getBuildContext();
+ if (ctx != null) {
+ IPackage[] pkgs = ctx.getPackages();
+ for (int i = 0; i < pkgs.length; ++i) {
+ pool.add(pkgs[i]);
}
}
-
- /**
- * Add pool constants for the package map.
- */
- protected void addPackageMapToPool(
- StateImpl state,
- StateSnapConstantPool pool) {
- PackageMap map = state.getPackageMap();
- for (Enumeration e = map.getAllPackages(); e.hasMoreElements();) {
- IPackage pkg = (IPackage) e.nextElement();
- pool.add(pkg);
- IPath[] fragments = map.getFragments(pkg);
- for (int i = 0; i < fragments.length; ++i) {
- pool.add(fragments[i]);
- }
+}
+/**
+ * Add pool constants for the dependency graph.
+ */
+protected void addDependencyGraphToPool(StateImpl state, StateSnapConstantPool pool) {
+ DependencyGraph graph = state.getInternalDependencyGraph();
+ for (Enumeration e = graph.getNodes(); e.hasMoreElements(); ) {
+ INode node = (INode)e.nextElement();
+ switch (node.getKind()) {
+ case INode.JCU_NODE:
+ JCUNode jcuNode = (JCUNode) node;
+ pool.add(state.getSourceEntry(jcuNode.getPackageElement()));
+ IType[] types = jcuNode.getTypes();
+ for (int i = 0; i < types.length; ++i) {
+ pool.add(types[i]);
+ }
+ break;
+ case INode.TYPE_NODE:
+ TypeNode typeNode = (TypeNode)node;
+ pool.add(state.getSourceEntry(typeNode.getPackageElement()));
+ break;
+ case INode.NAMESPACE_NODE:
+ pool.add(((NamespaceNode)node).getPackage());
+ break;
+ case INode.ZIP_NODE:
+ pool.add(((ZipNode)node).getZipFile());
+ break;
+ default:
+ Assert.isTrue(false, "Unexpected kind of node");
}
+ // Don't need to process node dependents here, since they're nodes as well
+ // and will have their info added to the pool above.
}
-
- /**
- * Add pool constants for the principal structure table.
- */
- protected void addPrincipalStructureTableToPool(
- StateImpl state,
- StateSnapConstantPool pool) {
- Hashtable table = state.getPrincipalStructureTable();
- for (Enumeration e = table.elements(); e.hasMoreElements();) {
- TypeStructureEntry tsEntry = (TypeStructureEntry) e.nextElement();
- addTypeStructureEntryToPool(tsEntry, pool);
+}
+/**
+ * Add pool constants for the package map.
+ */
+protected void addPackageMapToPool(StateImpl state, StateSnapConstantPool pool) {
+ PackageMap map = state.getPackageMap();
+ for (Enumeration e = map.getAllPackages(); e.hasMoreElements(); ) {
+ IPackage pkg = (IPackage)e.nextElement();
+ pool.add(pkg);
+ IPath[] fragments = map.getFragments(pkg);
+ for (int i = 0; i < fragments.length; ++i) {
+ pool.add(fragments[i]);
}
}
-
- /**
- * Add pool constants for the problem table.
- */
- protected void addProblemTableToPool(
- StateImpl state,
- StateSnapConstantPool pool) {
- IProblemReporter reporter = state.getProblemReporter();
- if (reporter instanceof ProblemTable) {
- for (Enumeration e = reporter.getAllProblems(); e.hasMoreElements();) {
- addProblemToPool((ProblemDetailImpl) e.nextElement(), pool);
- }
- for (Enumeration e = reporter.getImageProblems(); e.hasMoreElements();) {
- addProblemToPool((ProblemDetailImpl) e.nextElement(), pool);
- }
- }
+}
+/**
+ * Add pool constants for the principal structure table.
+ */
+protected void addPrincipalStructureTableToPool(StateImpl state, StateSnapConstantPool pool) {
+ Hashtable table = state.getPrincipalStructureTable();
+ for (Enumeration e = table.elements(); e.hasMoreElements(); ) {
+ TypeStructureEntry tsEntry = (TypeStructureEntry) e.nextElement();
+ addTypeStructureEntryToPool(tsEntry, pool);
}
-
- /**
- * Add pool constants for a problem.
- */
- protected void addProblemToPool(
- ProblemDetailImpl pb,
- StateSnapConstantPool pool) {
- SourceEntry sourceEntry = pb.getSourceEntry();
- if (sourceEntry != null) {
- pool.add(sourceEntry);
+}
+/**
+ * Add pool constants for the problem table.
+ */
+protected void addProblemTableToPool(StateImpl state, StateSnapConstantPool pool) {
+ IProblemReporter reporter = state.getProblemReporter();
+ if (reporter instanceof ProblemTable) {
+ for (Enumeration e = reporter.getAllProblems(); e.hasMoreElements();) {
+ addProblemToPool((ProblemDetailImpl) e.nextElement(), pool);
}
- pool.add(pb.getMessage());
- }
-
- /**
- * Add pool constants for the source element table.
- */
- protected void addSourceElementTableToPool(
- StateImpl state,
- StateSnapConstantPool pool) {
- SourceElementTable table = state.getSourceElementTable();
- for (Enumeration e = state.getPackageMap().getAllPackages();
- e.hasMoreElements();
- ) {
- IPackage pkg = (IPackage) e.nextElement();
- // Assume pkg has already been added to the pool
- LookupTable entryTable = table.getPackageTable(pkg);
- for (Enumeration keys = entryTable.keys(); keys.hasMoreElements();) {
- String fileName = (String) keys.nextElement();
- pool.add(fileName);
- SourceEntry sEntry = (SourceEntry) entryTable.get(fileName);
- pool.add(sEntry);
- }
+ for (Enumeration e = reporter.getImageProblems(); e.hasMoreElements();) {
+ addProblemToPool((ProblemDetailImpl) e.nextElement(), pool);
}
}
-
- /**
- * Add pool constants for a type structure entry.
- */
- protected void addTypeStructureEntryToPool(
- TypeStructureEntry tsEntry,
- StateSnapConstantPool pool) {
- pool.add(tsEntry.getType());
+}
+/**
+ * Add pool constants for a problem.
+ */
+protected void addProblemToPool(ProblemDetailImpl pb, StateSnapConstantPool pool) {
+ SourceEntry sourceEntry = pb.getSourceEntry();
+ if (sourceEntry != null) {
+ pool.add(sourceEntry);
}
-
- protected void badFormat() throws IOException {
- throw new IOException("Bad format");
+ pool.add(pb.getMessage());
+}
+/**
+ * Add pool constants for the source element table.
+ */
+protected void addSourceElementTableToPool(StateImpl state, StateSnapConstantPool pool) {
+ SourceElementTable table = state.getSourceElementTable();
+ for (Enumeration e = state.getPackageMap().getAllPackages(); e.hasMoreElements();) {
+ IPackage pkg = (IPackage) e.nextElement();
+ // Assume pkg has already been added to the pool
+ LookupTable entryTable = table.getPackageTable(pkg);
+ for (Enumeration keys = entryTable.keys(); keys.hasMoreElements();) {
+ String fileName = (String) keys.nextElement();
+ pool.add(fileName);
+ SourceEntry sEntry = (SourceEntry) entryTable.get(fileName);
+ pool.add(sEntry);
+ }
}
-
- /**
- * Check that the next section has the given name.
- */
- protected void checkSection(DataInputStream in, String name)
- throws IOException {
- String toCheck = in.readUTF();
- if (!toCheck.equals(name))
- badFormat();
+}
+/**
+ * Add pool constants for a type structure entry.
+ */
+protected void addTypeStructureEntryToPool(TypeStructureEntry tsEntry, StateSnapConstantPool pool) {
+ pool.add(tsEntry.getType());
+}
+protected void badFormat() throws IOException {
+ throw new IOException("Bad format");
+}
+/**
+ * Check that the next section has the given name.
+ */
+protected void checkSection(DataInputStream in, String name) throws IOException {
+ String toCheck = in.readUTF();
+ if (!toCheck.equals(name))
+ badFormat();
+}
+protected PackageElement getPackageElement(int entryNum, PackageElement[] packageElements, StateSnapConstantPool pool, StateImpl state) throws IOException {
+ if (packageElements[entryNum] == null) {
+ SourceEntry sourceEntry = pool.getSourceEntry(entryNum);
+ packageElements[entryNum] = state.packageElementFromSourceEntry(sourceEntry);
}
-
- protected PackageElement getPackageElement(
- int entryNum,
- PackageElement[] packageElements,
- StateSnapConstantPool pool,
- StateImpl state)
- throws IOException {
- if (packageElements[entryNum] == null) {
- SourceEntry sourceEntry = pool.getSourceEntry(entryNum);
- packageElements[entryNum] = state.packageElementFromSourceEntry(sourceEntry);
- }
- return packageElements[entryNum];
+ return packageElements[entryNum];
+}
+/**
+ * Reads and reconstructs a state from the given input stream.
+ */
+public StateImpl read(JavaDevelopmentContextImpl dc, IProject project, DataInputStream in) throws IOException {
+
+ /* magic number and version have already been read */
+ StateImpl state = new StateImpl(dc, project);
+ int fingerprintLen = in.readShort();
+ byte[] fingerprint = new byte[fingerprintLen];
+ in.readFully(fingerprint);
+ state.setFingerprint(fingerprint);
+
+ // Read pool.
+ StateSnapConstantPool pool = new StateSnapConstantPool(dc, in, this);
+ state.readClassPath(); // Read classpath from the project
+ state.setBuildContext(readBuildContext(dc, pool, in));
+ PackageMap packageMap = readPackageMap(pool, in);
+ state.setPackageMap(packageMap);
+ state.setSourceElementTable(readSourceElementTable(pool, in));
+ state.setPrincipalStructureTable(readPrincipalStructureTable(pool, in, state));
+ state.setProblemReporter(readProblemReporter(project, pool, in));
+ state.setInternalDependencyGraph(readDependencyGraph(pool, in, state));
+ state.buildPrincipalStructureByPackageTable();
+
+ // We don't need the project any more
+ //state.resetProject();
+ return state;
+}
+/**
+ * Read the build context.
+ */
+protected IImageContext readBuildContext(IDevelopmentContext dc, StateSnapConstantPool pool, DataInputStream in) throws IOException {
+ checkSection(in, "BuildContext");
+ int numPkgs = in.readInt();
+ if (numPkgs == -1) {
+ return null;
}
-
- /**
- * Reads and reconstructs a state from the given input stream.
- */
- public StateImpl read(
- JavaDevelopmentContextImpl dc,
- IProject project,
- DataInputStream in)
- throws IOException {
-
- /* magic number and version have already been read */
- StateImpl state = new StateImpl(dc, project);
- int fingerprintLen = in.readShort();
- byte[] fingerprint = new byte[fingerprintLen];
- in.readFully(fingerprint);
- state.setFingerprint(fingerprint);
-
- // Read pool.
- StateSnapConstantPool pool = new StateSnapConstantPool(dc, in, this);
- state.readClassPath(); // Read classpath from the project
- state.setBuildContext(readBuildContext(dc, pool, in));
- PackageMap packageMap = readPackageMap(pool, in);
- state.setPackageMap(packageMap);
- state.setSourceElementTable(readSourceElementTable(pool, in));
- state.setPrincipalStructureTable(readPrincipalStructureTable(pool, in, state));
- state.setProblemReporter(readProblemReporter(project, pool, in));
- state.setInternalDependencyGraph(readDependencyGraph(pool, in, state));
- state.buildPrincipalStructureByPackageTable();
-
- // We don't need the project any more
- //state.resetProject();
- return state;
+ IPackage[] pkgs = new IPackage[numPkgs];
+ for (int i = 0; i < pkgs.length; ++i) {
+ pkgs[i] = pool.getPackage(in.readInt());
}
-
- /**
- * Read the build context.
- */
- protected IImageContext readBuildContext(
- IDevelopmentContext dc,
- StateSnapConstantPool pool,
- DataInputStream in)
- throws IOException {
- checkSection(in, "BuildContext");
- int numPkgs = in.readInt();
- if (numPkgs == -1) {
- return null;
- }
- IPackage[] pkgs = new IPackage[numPkgs];
- for (int i = 0; i < pkgs.length; ++i) {
- pkgs[i] = pool.getPackage(in.readInt());
+ return dc.getImage().createImageContext(pkgs);
+}
+/**
+ * Read the dependency graph.
+ * The state is needed to create CompilationUnit objects from SourceEntry objects.
+ */
+protected DependencyGraph readDependencyGraph(StateSnapConstantPool pool, DataInputStream in, StateImpl state) throws IOException {
+ checkSection(in, "DependencyGraph");
+ DependencyGraph graph = new DependencyGraph();
+
+ // Avoid creating package elements for each node and dependency.
+ PackageElement[] packageElements = new PackageElement[pool.size()];
+ while (in.readBoolean()) {
+ JCUNode jcu = null;
+ try {
+ int entryNum = in.readInt();
+ PackageElement unit = getPackageElement(entryNum, packageElements, pool, state);
+ jcu = (JCUNode)graph.getNodeFor(unit);
+ int numTypes = in.readByte() & 0xFF;
+ IType[] types = new IType[numTypes];
+ for (int j = 0; j < numTypes; ++j) {
+ types[j] = pool.getType(in.readInt());
+ }
+ jcu.setTypes(types);
+ }
+ catch (ClassCastException e) { // the source entry should be a CU
+ badFormat();
}
- return dc.getImage().createImageContext(pkgs);
- }
- /**
- * Read the dependency graph.
- * The state is needed to create CompilationUnit objects from SourceEntry objects.
- */
- protected DependencyGraph readDependencyGraph(
- StateSnapConstantPool pool,
- DataInputStream in,
- StateImpl state)
- throws IOException {
- checkSection(in, "DependencyGraph");
- DependencyGraph graph = new DependencyGraph();
-
- // Avoid creating package elements for each node and dependency.
- PackageElement[] packageElements = new PackageElement[pool.size()];
- while (in.readBoolean()) {
- JCUNode jcu = null;
- try {
- int entryNum = in.readInt();
+ // Read dependencies
+ int numDep = in.readShort() & 0xFFFF;
+ INode[] dependencies = new INode[numDep];
+ for (int j = 0; j < numDep; ++j) {
+ int entryNum = in.readInt();
+ Object obj = pool.getObject(entryNum);
+ if (obj instanceof SourceEntry) {
PackageElement unit = getPackageElement(entryNum, packageElements, pool, state);
- jcu = (JCUNode) graph.getNodeFor(unit);
- int numTypes = in.readByte() & 0xFF;
- IType[] types = new IType[numTypes];
- for (int j = 0; j < numTypes; ++j) {
- types[j] = pool.getType(in.readInt());
- }
- jcu.setTypes(types);
- } catch (ClassCastException e) { // the source entry should be a CU
+ dependencies[j] = graph.getNodeFor(unit);
+ } else if (obj instanceof IPackage) {
+ dependencies[j] = graph.getNodeFor((IPackage) obj);
+ } else if (obj instanceof IPath) {
+ dependencies[j] = graph.getNodeFor((IPath) obj);
+ } else {
+ // Unexpected referrent
badFormat();
}
-
- // Read dependencies
- int numDep = in.readShort() & 0xFFFF;
- INode[] dependencies = new INode[numDep];
- for (int j = 0; j < numDep; ++j) {
- int entryNum = in.readInt();
- Object obj = pool.getObject(entryNum);
- if (obj instanceof SourceEntry) {
- PackageElement unit = getPackageElement(entryNum, packageElements, pool, state);
- dependencies[j] = graph.getNodeFor(unit);
- } else
- if (obj instanceof IPackage) {
- dependencies[j] = graph.getNodeFor((IPackage) obj);
- } else
- if (obj instanceof IPath) {
- dependencies[j] = graph.getNodeFor((IPath) obj);
- } else {
- // Unexpected referrent
- badFormat();
- }
- }
- jcu.setDependencies(dependencies);
}
- skipAttributes(in);
- graph.integrityCheck();
- return graph;
+ jcu.setDependencies(dependencies);
}
-
- /**
- * Read the package map.
- */
- protected PackageMap readPackageMap(
- StateSnapConstantPool pool,
- DataInputStream in)
- throws IOException {
- checkSection(in, "PackageMap");
- PackageMap map = new PackageMap();
- int size = in.readInt();
- for (int i = 0; i < size; ++i) {
- IPackage pkg = pool.getPackage(in.readInt());
- int numFragments = in.readShort() & 0xFFFF;
- IPath[] fragments = new IPath[numFragments];
- for (int j = 0; j < numFragments; ++j) {
- fragments[j] = pool.getPath(in.readInt());
- }
- map.putFragments(pkg, fragments);
+ skipAttributes(in);
+ graph.integrityCheck();
+ return graph;
+}
+/**
+ * Read the package map.
+ */
+protected PackageMap readPackageMap(StateSnapConstantPool pool, DataInputStream in) throws IOException {
+ checkSection(in, "PackageMap");
+ PackageMap map = new PackageMap();
+ int size = in.readInt();
+ for (int i = 0; i < size; ++i) {
+ IPackage pkg = pool.getPackage(in.readInt());
+ int numFragments = in.readShort() & 0xFFFF;
+ IPath[] fragments = new IPath[numFragments];
+ for (int j = 0; j < numFragments; ++j) {
+ fragments[j] = pool.getPath(in.readInt());
}
- return map;
+ map.putFragments(pkg, fragments);
}
-
- /**
- * Read the principal structure table.
- */
- protected Hashtable readPrincipalStructureTable(
- StateSnapConstantPool pool,
- DataInputStream in,
- StateImpl state)
- throws IOException {
- checkSection(in, "PrincipalStructureTable");
- int numEntries = in.readInt();
- Hashtable table = new Hashtable(numEntries * 2 + 1);
- for (int i = 0; i < numEntries; ++i) {
- TypeStructureEntry entry = readTypeStructureEntry(pool, in, state);
- table.put(entry.getType(), entry);
+ return map;
+}
+/**
+ * Read the principal structure table.
+ */
+protected Hashtable readPrincipalStructureTable(StateSnapConstantPool pool, DataInputStream in, StateImpl state) throws IOException {
+ checkSection(in, "PrincipalStructureTable");
+ int numEntries = in.readInt();
+ Hashtable table = new Hashtable(numEntries * 2 + 1);
+ for (int i = 0; i < numEntries; ++i) {
+ TypeStructureEntry entry = readTypeStructureEntry(pool, in, state);
+ table.put(entry.getType(), entry);
+ }
+ return table;
+}
+/**
+ * Read a problem.
+ */
+protected ProblemDetailImpl readProblem(StateSnapConstantPool pool, DataInputStream in) throws IOException {
+ String msg = pool.getString(in.readInt());
+ int id = in.readInt();
+ int severity = in.readInt();
+ int temp = in.readInt();
+ SourceEntry sourceEntry = (temp == 0) ? null : pool.getSourceEntry(temp);
+ int startPos = in.readInt();
+ int endPos = in.readInt();
+ int lineNumber = in.readInt();
+ skipAttributes(in);
+ return new ProblemDetailImpl(msg, id, severity, sourceEntry, startPos, endPos, lineNumber);
+}
+/**
+ * Read the problem reporter.
+ */
+protected IProblemReporter readProblemReporter(IProject project, StateSnapConstantPool pool, DataInputStream in) throws IOException {
+ checkSection(in, "Problems");
+ IProblemReporter reporter = null;
+ boolean isProblemTable = in.readBoolean();
+ if (isProblemTable) {
+ reporter = new ProblemTable();
+ int numProblems = in.readInt();
+ for (int i = 0; i < numProblems; ++i) {
+ ProblemDetailImpl pb = readProblem(pool, in);
+ reporter.putProblem(pb.getSourceEntry(), pb);
}
- return table;
- }
-
- /**
- * Read a problem.
- */
- protected ProblemDetailImpl readProblem(
- StateSnapConstantPool pool,
- DataInputStream in)
- throws IOException {
- String msg = pool.getString(in.readInt());
- int id = in.readInt();
- int severity = in.readInt();
- int temp = in.readInt();
- SourceEntry sourceEntry = (temp == 0) ? null : pool.getSourceEntry(temp);
- int startPos = in.readInt();
- int endPos = in.readInt();
- int lineNumber = in.readInt();
- skipAttributes(in);
- return new ProblemDetailImpl(
- msg,
- id,
- severity,
- sourceEntry,
- startPos,
- endPos,
- lineNumber);
- }
-
- /**
- * Read the problem reporter.
- */
- protected IProblemReporter readProblemReporter(
- IProject project,
- StateSnapConstantPool pool,
- DataInputStream in)
- throws IOException {
- checkSection(in, "Problems");
- IProblemReporter reporter = null;
- boolean isProblemTable = in.readBoolean();
- if (isProblemTable) {
- reporter = new ProblemTable();
- int numProblems = in.readInt();
- for (int i = 0; i < numProblems; ++i) {
- ProblemDetailImpl pb = readProblem(pool, in);
- reporter.putProblem(pb.getSourceEntry(), pb);
- }
- } else {
- String className = in.readUTF();
- Class clazz = null;
- try {
- clazz = Class.forName(className);
- } catch (ClassNotFoundException e) {
- throw new IOException("Class " + className + " was not found.");
- }
- try {
- reporter = (IProblemReporter) clazz.newInstance();
- } catch (InstantiationException e) {
- throw new IOException("Could not instanciate " + clazz.getName());
- } catch (IllegalAccessException e) {
- throw new IOException("Could not instanciate " + clazz.getName());
- }
- reporter.initialize(
- project,
- JavaModelManager.getJavaModelManager().getDevelopmentContext(project));
+ } else {
+ String className = in.readUTF();
+ Class clazz = null;
+ try {
+ clazz = Class.forName(className);
+ } catch (ClassNotFoundException e) {
+ throw new IOException("Class " + className + " was not found.");
}
- return reporter;
- }
-
- /**
- * Read the source element table.
- */
- protected SourceElementTable readSourceElementTable(
- StateSnapConstantPool pool,
- DataInputStream in)
- throws IOException {
- checkSection(in, "SourceElementTable");
- SourceElementTable table = new SourceElementTable();
- int numPackages = in.readInt();
- for (int i = 0; i < numPackages; ++i) {
- IPackage pkg = pool.getPackage(in.readInt());
- int numEntries = in.readInt();
- LookupTable entryTable = new LookupTable(numEntries);
- for (int j = 0; j < numEntries; ++j) {
- String fileName = pool.getString(in.readInt());
- SourceEntry sEntry = pool.getSourceEntry(in.readInt());
- entryTable.put(fileName, sEntry);
- }
- table.putPackageTable(pkg, entryTable);
+ try {
+ reporter = (IProblemReporter) clazz.newInstance();
+ } catch (InstantiationException e) {
+ throw new IOException("Could not instanciate " + clazz.getName());
+ } catch (IllegalAccessException e) {
+ throw new IOException("Could not instanciate " + clazz.getName());
}
- return table;
+ reporter.initialize(project, JavaModelManager.getJavaModelManager().getDevelopmentContext(project));
}
-
- /**
- * Read the next source entry.
- */
- protected SourceEntry readSourceEntry(
- StateSnapConstantPool pool,
- DataInputStream in)
- throws IOException {
- IPath path = pool.getPath(in.readInt());
- String zipEntryName = pool.getStringOrNull(in.readInt());
- String zipEntryPath = null, zipEntryFileName = null;
- if (zipEntryName != null) {
- int pos = zipEntryName.lastIndexOf('/');
- if (pos != -1) {
- zipEntryPath = zipEntryName.substring(0, pos);
- zipEntryFileName = zipEntryName.substring(pos + 1);
- } else {
- zipEntryPath = null;
- zipEntryFileName = zipEntryName;
- }
- }
- return new SourceEntry(path, zipEntryPath, zipEntryFileName);
- }
-
- /**
- * Read a type handle.
- * Allow null if allowNull is true.
- */
- IType readTypeHandle(
- StateSnapConstantPool pool,
- DataInputStream in,
- boolean allowNull)
- throws IOException {
- int index = in.readInt();
- if (index == 0) {
- if (!allowNull)
- badFormat();
- return null;
+ return reporter;
+}
+/**
+ * Read the source element table.
+ */
+protected SourceElementTable readSourceElementTable(StateSnapConstantPool pool, DataInputStream in) throws IOException {
+ checkSection(in, "SourceElementTable");
+ SourceElementTable table = new SourceElementTable();
+ int numPackages = in.readInt();
+ for (int i = 0; i < numPackages; ++i) {
+ IPackage pkg = pool.getPackage(in.readInt());
+ int numEntries = in.readInt();
+ LookupTable entryTable = new LookupTable(numEntries);
+ for (int j = 0; j < numEntries; ++j) {
+ String fileName = pool.getString(in.readInt());
+ SourceEntry sEntry = pool.getSourceEntry(in.readInt());
+ entryTable.put(fileName, sEntry);
}
- return pool.getType(index);
+ table.putPackageTable(pkg, entryTable);
}
-
- /**
- * Read a class or interface type handle and return its name.
- * Allow null if allowNull is true.
- */
- String readTypeHandleAsName(
- StateSnapConstantPool pool,
- DataInputStream in,
- boolean allowNull)
- throws IOException {
- IType typeHandle = readTypeHandle(pool, in, allowNull);
- if (typeHandle == null) {
- if (!allowNull)
- badFormat();
- return null;
+ return table;
+}
+/**
+ * Read the next source entry.
+ */
+protected SourceEntry readSourceEntry(StateSnapConstantPool pool, DataInputStream in) throws IOException {
+ IPath path = pool.getPath(in.readInt());
+ String zipEntryName = pool.getStringOrNull(in.readInt());
+ String zipEntryPath = null, zipEntryFileName = null;
+ if (zipEntryName != null) {
+ int pos = zipEntryName.lastIndexOf('/');
+ if (pos != -1) {
+ zipEntryPath = zipEntryName.substring(0, pos);
+ zipEntryFileName = zipEntryName.substring(pos + 1);
+ } else {
+ zipEntryPath = null;
+ zipEntryFileName = zipEntryName;
}
- Assert.isTrue(!typeHandle.isPrimitive() && !typeHandle.isArray());
- // must not be a class or interface handle
- return typeHandle.getName(); //.intern(); // intern it
}
-
- /**
- * Read a class or interface type handle and return its name.
- * Allow null if allowNull is true.
- */
- String readTypeHandleAsSignature(
- StateSnapConstantPool pool,
- DataInputStream in)
- throws IOException {
- IType typeHandle = readTypeHandle(pool, in, false);
- return ((TypeImpl) typeHandle).getVMSignature(); //.intern(); // intern it
+ return new SourceEntry(path, zipEntryPath, zipEntryFileName);
+}
+/**
+ * Read a type handle.
+ * Allow null if allowNull is true.
+ */
+IType readTypeHandle(StateSnapConstantPool pool, DataInputStream in, boolean allowNull) throws IOException {
+ int index = in.readInt();
+ if (index == 0) {
+ if (!allowNull)
+ badFormat();
+ return null;
}
-
- /**
- * Read a type structure entry.
- */
- protected TypeStructureEntry readTypeStructureEntry(
- StateSnapConstantPool pool,
- DataInputStream in,
- StateImpl state)
- throws IOException {
- SourceEntry sEntry = pool.getSourceEntry(in.readInt());
- IType type = readTypeHandle(pool, in, false);
- return new TypeStructureEntry(sEntry, type);
+ return pool.getType(index);
+}
+/**
+ * Read a class or interface type handle and return its name.
+ * Allow null if allowNull is true.
+ */
+String readTypeHandleAsName(StateSnapConstantPool pool, DataInputStream in, boolean allowNull) throws IOException {
+ IType typeHandle = readTypeHandle(pool, in, allowNull);
+ if (typeHandle == null) {
+ if (!allowNull)
+ badFormat();
+ return null;
}
+ Assert.isTrue(!typeHandle.isPrimitive() && !typeHandle.isArray()); // must not be a class or interface handle
+ return typeHandle.getName(); //.intern(); // intern it
+}
+/**
+ * Read a class or interface type handle and return its name.
+ * Allow null if allowNull is true.
+ */
+String readTypeHandleAsSignature(StateSnapConstantPool pool, DataInputStream in) throws IOException {
+ IType typeHandle = readTypeHandle(pool, in, false);
+ return ((TypeImpl) typeHandle).getVMSignature(); //.intern(); // intern it
+}
+/**
+ * Read a type structure entry.
+ */
+protected TypeStructureEntry readTypeStructureEntry(StateSnapConstantPool pool, DataInputStream in, StateImpl state) throws IOException {
+ SourceEntry sEntry = pool.getSourceEntry(in.readInt());
+ IType type = readTypeHandle(pool, in, false);
+ return new TypeStructureEntry(sEntry, type);
+}
+/**
+ * Saves key information about the given state
+ * to the given output stream. This snapshot can be used
+ * subsequently in reconstructing the state.
+ */
+public void save(StateImpl state, DataOutputStream out) throws IOException {
+
+ // Build up pool.
+ IDevelopmentContext dc = state.getDevelopmentContext();
+ StateSnapConstantPool pool = new StateSnapConstantPool(dc);
+ addBuildContextToPool(state, pool);
+ addPackageMapToPool(state, pool);
+ addSourceElementTableToPool(state, pool);
+ addPrincipalStructureTableToPool(state, pool);
+ addProblemTableToPool(state, pool);
+ addDependencyGraphToPool(state, pool);
+
+ // Write all.
+ out.writeInt(MAGIC);
+ out.writeShort(VERSION);
+
+ byte[] fingerprint = state.getFingerprint();
+ // regression test for 1F9M2KH: RQIB:ALL - Problem saving incrementally built state
+ Assert.isNotNull(fingerprint);
+ out.writeShort(fingerprint.length);
+ out.write(fingerprint);
+
+ pool.write(out);
+ writeBuildContext(state, pool, out);
+ writePackageMap(state, pool, out);
+ writeSourceElementTable(state, pool, out);
+ writePrincipalStructureTable(state, pool, out);
+ writeProblemReporter(state, pool, out);
+ writeDependencyGraph(state, pool, out);
- /**
- * Saves key information about the given state
- * to the given output stream. This snapshot can be used
- * subsequently in reconstructing the state.
- */
- public void save(StateImpl state, DataOutputStream out) throws IOException {
-
- // Build up pool.
- IDevelopmentContext dc = state.getDevelopmentContext();
- StateSnapConstantPool pool = new StateSnapConstantPool(dc);
- addBuildContextToPool(state, pool);
- addPackageMapToPool(state, pool);
- addSourceElementTableToPool(state, pool);
- addPrincipalStructureTableToPool(state, pool);
- addProblemTableToPool(state, pool);
- addDependencyGraphToPool(state, pool);
-
- // Write all.
- out.writeInt(MAGIC);
- out.writeShort(VERSION);
-
- byte[] fingerprint = state.getFingerprint();
- // regression test for 1F9M2KH: RQIB:ALL - Problem saving incrementally built state
- Assert.isNotNull(fingerprint);
- out.writeShort(fingerprint.length);
- out.write(fingerprint);
-
- pool.write(out);
- writeBuildContext(state, pool, out);
- writePackageMap(state, pool, out);
- writeSourceElementTable(state, pool, out);
- writePrincipalStructureTable(state, pool, out);
- writeProblemReporter(state, pool, out);
- writeDependencyGraph(state, pool, out);
-
+}
+/**
+ * Skip over the attributes on read.
+ */
+protected void skipAttributes(DataInputStream in) throws IOException {
+ int numAttributes = in.readShort() & 0xFFFF;
+ for (int i = 0; i < numAttributes; ++i) {
+ int nameIndex = in.readInt();
+ int len = in.readShort() & 0xFFFF;
+ in.skipBytes(len);
}
-
- /**
- * Skip over the attributes on read.
- */
- protected void skipAttributes(DataInputStream in) throws IOException {
- int numAttributes = in.readShort() & 0xFFFF;
- for (int i = 0; i < numAttributes; ++i) {
- int nameIndex = in.readInt();
- int len = in.readShort() & 0xFFFF;
- in.skipBytes(len);
+}
+/**
+ * Write the build context.
+ */
+protected void writeBuildContext(StateImpl state, StateSnapConstantPool pool, DataOutputStream out) throws IOException {
+ out.writeUTF("BuildContext");
+ IImageContext ctx = state.getBuildContext();
+ if (ctx == null) {
+ out.writeInt(-1);
+ }
+ else {
+ IPackage[] pkgs = ctx.getPackages();
+ out.writeInt(pkgs.length);
+ for (int i = 0; i < pkgs.length; ++i) {
+ out.writeInt(pool.index(pkgs[i]));
}
}
-
- /**
- * Write the build context.
- */
- protected void writeBuildContext(
- StateImpl state,
- StateSnapConstantPool pool,
- DataOutputStream out)
- throws IOException {
- out.writeUTF("BuildContext");
- IImageContext ctx = state.getBuildContext();
- if (ctx == null) {
- out.writeInt(-1);
+}
+/**
+ * Write the dependency graph.
+ */
+protected void writeDependencyGraph(StateImpl state, StateSnapConstantPool pool, DataOutputStream out) throws IOException {
+ out.writeUTF("DependencyGraph");
+ DependencyGraph graph = state.getInternalDependencyGraph();
+ graph.integrityCheck();
+ /**
+ * We only care about serializing JCU nodes, since they
+ * are the only nodes with dependency information. All
+ * other nodes will be serialized indirectly as dependencies
+ * of JCU nodes.
+ * Do we care about Type/Zip/Namespace nodes that have no dependents???
+ */
+ for (Enumeration e = graph.getJCUNodes(); e.hasMoreElements();) {
+ JCUNode jcu = (JCUNode) e.nextElement();
+ out.writeBoolean(true);
+ SourceEntry sEntry = state.getSourceEntry(jcu.getPackageElement());
+ if (sEntry == null) {
+ System.out.println("Warning: StatSnap: Attempt to serialize dependency graph node for missing JCU: " + jcu.getPackageElement() + ". Skipping...");
} else {
- IPackage[] pkgs = ctx.getPackages();
- out.writeInt(pkgs.length);
- for (int i = 0; i < pkgs.length; ++i) {
- out.writeInt(pool.index(pkgs[i]));
+ Assert.isNotNull(sEntry);
+ out.writeInt(pool.index(sEntry));
+ IType[] types = jcu.getTypes();
+ Assert.isTrue(types.length < 256);
+ out.writeByte(types.length);
+ for (int i = 0; i < types.length; ++i) {
+ out.writeInt(pool.index(types[i]));
}
- }
- }
-
- /**
- * Write the dependency graph.
- */
- protected void writeDependencyGraph(
- StateImpl state,
- StateSnapConstantPool pool,
- DataOutputStream out)
- throws IOException {
- out.writeUTF("DependencyGraph");
- DependencyGraph graph = state.getInternalDependencyGraph();
- graph.integrityCheck();
- /**
- * We only care about serializing JCU nodes, since they
- * are the only nodes with dependency information. All
- * other nodes will be serialized indirectly as dependencies
- * of JCU nodes.
- * Do we care about Type/Zip/Namespace nodes that have no dependents???
- */
- for (Enumeration e = graph.getJCUNodes(); e.hasMoreElements();) {
- JCUNode jcu = (JCUNode) e.nextElement();
- out.writeBoolean(true);
- SourceEntry sEntry = state.getSourceEntry(jcu.getPackageElement());
- if (sEntry == null) {
- System.out.println(
- "Warning: StatSnap: Attempt to serialize dependency graph node for missing JCU: "
- + jcu.getPackageElement()
- + ". Skipping...");
- } else {
- Assert.isNotNull(sEntry);
- out.writeInt(pool.index(sEntry));
- IType[] types = jcu.getTypes();
- Assert.isTrue(types.length < 256);
- out.writeByte(types.length);
- for (int i = 0; i < types.length; ++i) {
- out.writeInt(pool.index(types[i]));
- }
- // Write dependencies
- INode[] dependencies = jcu.getDependencies();
- int numDep = dependencies.length;
- Assert.isTrue(numDep < 65536);
- out.writeShort(numDep);
- for (int i = 0; i < numDep; ++i) {
- INode dep = dependencies[i];
- switch (dep.getKind()) {
- case INode.JCU_NODE :
- {
- PackageElement element = ((JCUNode) dep).getPackageElement();
- SourceEntry depEntry = state.getSourceEntry(element);
- out.writeInt(pool.index(depEntry));
- break;
- }
- case INode.TYPE_NODE :
- {
- PackageElement element = ((TypeNode) dep).getPackageElement();
- SourceEntry depEntry = state.getSourceEntry(element);
- out.writeInt(pool.index(depEntry));
- break;
- }
- case INode.NAMESPACE_NODE :
- {
- IPackage pkg = ((NamespaceNode) dep).getPackage();
- out.writeInt(pool.index(pkg));
- break;
- }
- case INode.ZIP_NODE :
- {
- IPath path = ((ZipNode) dep).getZipFile();
- out.writeInt(pool.index(path));
- break;
- }
- default :
- badFormat();
- }
+ // Write dependencies
+ INode[] dependencies = jcu.getDependencies();
+ int numDep = dependencies.length;
+ Assert.isTrue(numDep < 65536);
+ out.writeShort(numDep);
+ for (int i = 0; i < numDep; ++i) {
+ INode dep = dependencies[i];
+ switch (dep.getKind()) {
+ case INode.JCU_NODE :
+ {
+ PackageElement element = ((JCUNode) dep).getPackageElement();
+ SourceEntry depEntry = state.getSourceEntry(element);
+ out.writeInt(pool.index(depEntry));
+ break;
+ }
+ case INode.TYPE_NODE :
+ {
+ PackageElement element = ((TypeNode) dep).getPackageElement();
+ SourceEntry depEntry = state.getSourceEntry(element);
+ out.writeInt(pool.index(depEntry));
+ break;
+ }
+ case INode.NAMESPACE_NODE :
+ {
+ IPackage pkg = ((NamespaceNode) dep).getPackage();
+ out.writeInt(pool.index(pkg));
+ break;
+ }
+ case INode.ZIP_NODE :
+ {
+ IPath path = ((ZipNode) dep).getZipFile();
+ out.writeInt(pool.index(path));
+ break;
+ }
+ default :
+ badFormat();
}
}
}
- out.writeBoolean(false);
- writeEmptyAttributes(out);
}
-
- /**
- * Write an empty set of attributes.
- */
- protected void writeEmptyAttributes(DataOutputStream out) throws IOException {
- out.writeShort(0);
- }
-
- /**
- * Write the package map.
- */
- protected void writePackageMap(
- StateImpl state,
- StateSnapConstantPool pool,
- DataOutputStream out)
- throws IOException {
- out.writeUTF("PackageMap");
- PackageMap map = state.getPackageMap();
- out.writeInt(map.size());
- int count = 0;
- for (Enumeration e = map.getAllPackages(); e.hasMoreElements();) {
- ++count;
- IPackage pkg = (IPackage) e.nextElement();
- IPath[] fragments = map.getFragments(pkg);
- out.writeInt(pool.index(pkg));
- out.writeShort(fragments.length);
- for (int i = 0; i < fragments.length; ++i) {
- out.writeInt(pool.index(fragments[i]));
- }
+ out.writeBoolean(false);
+ writeEmptyAttributes(out);
+}
+/**
+ * Write an empty set of attributes.
+ */
+protected void writeEmptyAttributes(DataOutputStream out) throws IOException {
+ out.writeShort(0);
+}
+/**
+ * Write the package map.
+ */
+protected void writePackageMap(StateImpl state, StateSnapConstantPool pool, DataOutputStream out) throws IOException {
+ out.writeUTF("PackageMap");
+ PackageMap map = state.getPackageMap();
+ out.writeInt(map.size());
+ int count = 0;
+ for (Enumeration e = map.getAllPackages(); e.hasMoreElements(); ) {
+ ++count;
+ IPackage pkg = (IPackage)e.nextElement();
+ IPath[] fragments = map.getFragments(pkg);
+ out.writeInt(pool.index(pkg));
+ out.writeShort(fragments.length);
+ for (int i = 0; i < fragments.length; ++i) {
+ out.writeInt(pool.index(fragments[i]));
}
- Assert.isTrue(count == map.size()); // Sanity check
}
-
- /**
- * Write the principal structure table.
- */
- protected void writePrincipalStructureTable(
- StateImpl state,
- StateSnapConstantPool pool,
- DataOutputStream out)
- throws IOException {
- out.writeUTF("PrincipalStructureTable");
- Hashtable table = state.getPrincipalStructureTable();
- int num = table.size();
- out.writeInt(num);
- int count = 0;
- for (Enumeration e = table.elements(); e.hasMoreElements();) {
- ++count;
- TypeStructureEntry tsEntry = (TypeStructureEntry) e.nextElement();
- writeTypeStructureEntry(tsEntry, pool, out);
+ Assert.isTrue(count == map.size()); // Sanity check
+}
+/**
+ * Write the principal structure table.
+ */
+protected void writePrincipalStructureTable(StateImpl state, StateSnapConstantPool pool, DataOutputStream out) throws IOException {
+ out.writeUTF("PrincipalStructureTable");
+ Hashtable table = state.getPrincipalStructureTable();
+ int num = table.size();
+ out.writeInt(num);
+ int count = 0;
+ for (Enumeration e = table.elements(); e.hasMoreElements();) {
+ ++count;
+ TypeStructureEntry tsEntry = (TypeStructureEntry) e.nextElement();
+ writeTypeStructureEntry(tsEntry, pool, out);
+ }
+ Assert.isTrue(count == num); // Sanity check
+}
+/**
+ * Write a problem.
+ */
+protected void writeProblem(ProblemDetailImpl pb, StateSnapConstantPool pool, DataOutputStream out) throws IOException {
+ out.writeInt(pool.index(pb.getMessage()));
+ out.writeInt(pb.getID());
+ out.writeInt(pb.getSeverity());
+ out.writeInt(pool.index(pb.getSourceEntry()));
+ out.writeInt(pb.getStartPos());
+ out.writeInt(pb.getEndPos());
+ out.writeInt(pb.getLineNumber());
+ writeEmptyAttributes(out);
+}
+/**
+ * Write the problem reporter.
+ */
+protected void writeProblemReporter(StateImpl state, StateSnapConstantPool pool, DataOutputStream out) throws IOException {
+ out.writeUTF("Problems");
+ IProblemReporter reporter = state.getProblemReporter();
+ if (reporter instanceof ProblemTable) {
+ out.writeBoolean(true);
+ Vector problems = new Vector();
+ for (Enumeration e = reporter.getAllProblems(); e.hasMoreElements();) {
+ problems.addElement(e.nextElement());
}
- Assert.isTrue(count == num); // Sanity check
- }
-
- /**
- * Write a problem.
- */
- protected void writeProblem(
- ProblemDetailImpl pb,
- StateSnapConstantPool pool,
- DataOutputStream out)
- throws IOException {
- out.writeInt(pool.index(pb.getMessage()));
- out.writeInt(pb.getID());
- out.writeInt(pb.getSeverity());
- out.writeInt(pool.index(pb.getSourceEntry()));
- out.writeInt(pb.getStartPos());
- out.writeInt(pb.getEndPos());
- out.writeInt(pb.getLineNumber());
- writeEmptyAttributes(out);
- }
-
- /**
- * Write the problem reporter.
- */
- protected void writeProblemReporter(
- StateImpl state,
- StateSnapConstantPool pool,
- DataOutputStream out)
- throws IOException {
- out.writeUTF("Problems");
- IProblemReporter reporter = state.getProblemReporter();
- if (reporter instanceof ProblemTable) {
- out.writeBoolean(true);
- Vector problems = new Vector();
- for (Enumeration e = reporter.getAllProblems(); e.hasMoreElements();) {
- problems.addElement(e.nextElement());
- }
- for (Enumeration e = reporter.getImageProblems(); e.hasMoreElements();) {
- problems.addElement(e.nextElement());
- }
- out.writeInt(problems.size());
- for (Enumeration e = problems.elements(); e.hasMoreElements();) {
- writeProblem((ProblemDetailImpl) e.nextElement(), pool, out);
- }
- } else {
- out.writeBoolean(false);
- out.writeUTF(reporter.getClass().getName());
+ for (Enumeration e = reporter.getImageProblems(); e.hasMoreElements();) {
+ problems.addElement(e.nextElement());
}
- }
-
- /**
- * Write the source element table.
- */
- protected void writeSourceElementTable(
- StateImpl state,
- StateSnapConstantPool pool,
- DataOutputStream out)
- throws IOException {
- out.writeUTF("SourceElementTable");
- SourceElementTable table = state.getSourceElementTable();
- int num = table.numPackages();
- out.writeInt(num);
- for (Enumeration e = state.getPackageMap().getAllPackages();
- e.hasMoreElements();
- ) {
- IPackage pkg = (IPackage) e.nextElement();
- out.writeInt(pool.index(pkg));
- LookupTable entryTable = table.getPackageTable(pkg);
- out.writeInt(entryTable.size());
- for (Enumeration keys = entryTable.keys(); keys.hasMoreElements();) {
- String fileName = (String) keys.nextElement();
- out.writeInt(pool.index(fileName));
- SourceEntry sEntry = (SourceEntry) entryTable.get(fileName);
- out.writeInt(pool.index(sEntry));
- }
+ out.writeInt(problems.size());
+ for (Enumeration e = problems.elements(); e.hasMoreElements();) {
+ writeProblem((ProblemDetailImpl) e.nextElement(), pool, out);
}
+ } else {
+ out.writeBoolean(false);
+ out.writeUTF(reporter.getClass().getName());
}
-
- /**
- * Write a type structure entry.
- */
- protected void writeTypeStructureEntry(
- TypeStructureEntry tsEntry,
- StateSnapConstantPool pool,
- DataOutputStream out)
- throws IOException {
- out.writeInt(pool.index(tsEntry.getSourceEntry()));
- out.writeInt(pool.index(tsEntry.getType()));
+}
+/**
+ * Write the source element table.
+ */
+protected void writeSourceElementTable(StateImpl state, StateSnapConstantPool pool, DataOutputStream out) throws IOException {
+ out.writeUTF("SourceElementTable");
+ SourceElementTable table = state.getSourceElementTable();
+ int num = table.numPackages();
+ out.writeInt(num);
+ for (Enumeration e = state.getPackageMap().getAllPackages(); e.hasMoreElements();) {
+ IPackage pkg = (IPackage) e.nextElement();
+ out.writeInt(pool.index(pkg));
+ LookupTable entryTable = table.getPackageTable(pkg);
+ out.writeInt(entryTable.size());
+ for (Enumeration keys = entryTable.keys(); keys.hasMoreElements();) {
+ String fileName = (String) keys.nextElement();
+ out.writeInt(pool.index(fileName));
+ SourceEntry sEntry = (SourceEntry) entryTable.get(fileName);
+ out.writeInt(pool.index(sEntry));
+ }
}
-
+}
+/**
+ * Write a type structure entry.
+ */
+protected void writeTypeStructureEntry(TypeStructureEntry tsEntry, StateSnapConstantPool pool, DataOutputStream out) throws IOException {
+ out.writeInt(pool.index(tsEntry.getSourceEntry()));
+ out.writeInt(pool.index(tsEntry.getType()));
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSnapV6.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSnapV6.java
index 055a3e7e02..6ca4ab9bd5 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSnapV6.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSnapV6.java
@@ -13,54 +13,49 @@ import java.io.*;
* @see StateSnap
*/
public class StateSnapV6 extends StateSnapV5 {
- /**
- * Read the next source entry.
- */
- protected SourceEntry readSourceEntry(
- StateSnapConstantPool pool,
- DataInputStream in)
- throws IOException {
- IPath path = pool.getPath(in.readInt());
- String zipEntryPath = pool.getStringOrNull(in.readInt());
- String zipEntryFileName = pool.getStringOrNull(in.readInt());
- return new SourceEntry(path, zipEntryPath, zipEntryFileName);
- }
-
- /**
- * Saves key information about the given state
- * to the given output stream. This snapshot can be used
- * subsequently in reconstructing the state.
- */
- public void save(StateImpl state, DataOutputStream out) throws IOException {
-
- // Build up pool.
- IDevelopmentContext dc = state.getDevelopmentContext();
- StateSnapConstantPool pool = new StateSnapConstantPool(dc);
- addBuildContextToPool(state, pool);
- addPackageMapToPool(state, pool);
- addSourceElementTableToPool(state, pool);
- addPrincipalStructureTableToPool(state, pool);
- addProblemTableToPool(state, pool);
- addDependencyGraphToPool(state, pool);
-
- // Write all.
- out.writeInt(MAGIC);
- out.writeShort(StateSnap.VERSION6);
-
- byte[] fingerprint = state.getFingerprint();
- // regression test for 1F9M2KH: RQIB:ALL - Problem saving incrementally built state
- Assert.isNotNull(fingerprint);
- out.writeShort(fingerprint.length);
- out.write(fingerprint);
-
- pool.write(out);
- writeBuildContext(state, pool, out);
- writePackageMap(state, pool, out);
- writeSourceElementTable(state, pool, out);
- writePrincipalStructureTable(state, pool, out);
- writeProblemReporter(state, pool, out);
- writeDependencyGraph(state, pool, out);
-
- }
+/**
+ * Read the next source entry.
+ */
+protected SourceEntry readSourceEntry(StateSnapConstantPool pool, DataInputStream in) throws IOException {
+ IPath path = pool.getPath(in.readInt());
+ String zipEntryPath = pool.getStringOrNull(in.readInt());
+ String zipEntryFileName = pool.getStringOrNull(in.readInt());
+ return new SourceEntry(path, zipEntryPath, zipEntryFileName);
+}
+/**
+ * Saves key information about the given state
+ * to the given output stream. This snapshot can be used
+ * subsequently in reconstructing the state.
+ */
+public void save(StateImpl state, DataOutputStream out) throws IOException {
+
+ // Build up pool.
+ IDevelopmentContext dc = state.getDevelopmentContext();
+ StateSnapConstantPool pool = new StateSnapConstantPool(dc);
+ addBuildContextToPool(state, pool);
+ addPackageMapToPool(state, pool);
+ addSourceElementTableToPool(state, pool);
+ addPrincipalStructureTableToPool(state, pool);
+ addProblemTableToPool(state, pool);
+ addDependencyGraphToPool(state, pool);
+
+ // Write all.
+ out.writeInt(MAGIC);
+ out.writeShort(StateSnap.VERSION6);
+
+ byte[] fingerprint = state.getFingerprint();
+ // regression test for 1F9M2KH: RQIB:ALL - Problem saving incrementally built state
+ Assert.isNotNull(fingerprint);
+ out.writeShort(fingerprint.length);
+ out.write(fingerprint);
+
+ pool.write(out);
+ writeBuildContext(state, pool, out);
+ writePackageMap(state, pool, out);
+ writeSourceElementTable(state, pool, out);
+ writePrincipalStructureTable(state, pool, out);
+ writeProblemReporter(state, pool, out);
+ writeDependencyGraph(state, pool, out);
}
+}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSpecificHandleImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSpecificHandleImpl.java
index ec386596e5..ae3561e7f3 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSpecificHandleImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/StateSpecificHandleImpl.java
@@ -8,62 +8,52 @@ import org.eclipse.jdt.internal.core.builder.IHandle;
import org.eclipse.jdt.internal.core.builder.IState;
import org.eclipse.jdt.internal.core.builder.IDevelopmentContext;
+
/**
* The root of the State Specific Handle implementation hierarchy.
*/
public abstract class StateSpecificHandleImpl implements IHandle {
- StateImpl fState; // The state
+ StateImpl fState; // The state
//NonStateSpecificHandleImpl fHandle; //Put this in the subclasses
/**
* Returns whether the receiver and anObject have the same handle and
* same wrapped object; i.e., same states and objects.
*/
public boolean equals(Object o) {
- if (this == o)
- return true;
- if (!(o instanceof StateSpecificHandleImpl))
- return false;
+ if (this == o) return true;
+ if (!(o instanceof StateSpecificHandleImpl)) return false;
StateSpecificHandleImpl ssh = (StateSpecificHandleImpl) o;
- return nonStateSpecific().equals(ssh.nonStateSpecific())
- && fState.equals(ssh.fState);
+ return nonStateSpecific().equals(ssh.nonStateSpecific()) &&
+ fState.equals(ssh.fState);
}
-
public IDevelopmentContext getDevelopmentContext() {
return fState.getDevelopmentContext();
}
-
public IState getState() {
return fState;
}
-
public int hashCode() {
return nonStateSpecific().hashCode();
}
-
public IHandle inState(IState state) {
throw new org.eclipse.jdt.internal.core.builder.StateSpecificException();
}
-
public boolean isFictional() {
return false;
}
-
public abstract boolean isPresent();
public boolean isStateSpecific() {
return true;
}
-
public int kind() {
return nonStateSpecific().kind();
}
-
/**
* Return the non state specific handle associated with this handle
*/
public abstract IHandle nonStateSpecific();
- public String toString() {
- return nonStateSpecific().toString();
- }
-
+public String toString() {
+ return nonStateSpecific().toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeCollaboratorIndictment.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeCollaboratorIndictment.java
index 4772d8d5e6..f9c2dc2015 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeCollaboratorIndictment.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeCollaboratorIndictment.java
@@ -1,27 +1,24 @@
package org.eclipse.jdt.internal.core.builder.impl;
class TypeCollaboratorIndictment extends Indictment {
- /**
- * Creates a new TypeCollaboratorIndictment.
- */
- protected TypeCollaboratorIndictment(char[] name) {
- super(name);
- }
-
+/**
+ * Creates a new TypeCollaboratorIndictment.
+ */
+protected TypeCollaboratorIndictment(char[] name) {
+ super(name);
+}
/**
* Returns what kind of indictment this is
*/
public int getKind() {
return K_TYPE;
}
-
- /**
- * Returns a string representation of this class. For debugging purposes
- * only (NON-NLS).
- */
- public String toString() {
- // don't use + with char[]
- return new StringBuffer("TypeIndictment(").append(fName).append(")").toString();
- }
-
+/**
+ * Returns a string representation of this class. For debugging purposes
+ * only (NON-NLS).
+ */
+public String toString() {
+ // don't use + with char[]
+ return new StringBuffer("TypeIndictment(").append(fName).append(")").toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeHierarchyIndictment.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeHierarchyIndictment.java
index 02d0849260..af0233329b 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeHierarchyIndictment.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeHierarchyIndictment.java
@@ -1,30 +1,24 @@
package org.eclipse.jdt.internal.core.builder.impl;
public class TypeHierarchyIndictment extends Indictment {
- /**
- * Creates a new TypeHierarchyIndictment.
- */
- protected TypeHierarchyIndictment(char[] name) {
- super(name);
- }
-
+/**
+ * Creates a new TypeHierarchyIndictment.
+ */
+protected TypeHierarchyIndictment(char[] name) {
+ super(name);
+}
/**
* Returns what kind of indictment this is
*/
public int getKind() {
return K_HIERARCHY;
}
-
- /**
- * Returns a string representation of this class. For debugging purposes
- * only (NON-NLS).
- */
- public String toString() {
- // don't use + with char[]
- return new StringBuffer("TypeHierarchyIndictment(")
- .append(fName)
- .append(")")
- .toString();
- }
-
+/**
+ * Returns a string representation of this class. For debugging purposes
+ * only (NON-NLS).
+ */
+public String toString() {
+ // don't use + with char[]
+ return new StringBuffer("TypeHierarchyIndictment(").append(fName).append(")").toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeImpl.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeImpl.java
index 929e61f827..ffd1b9b064 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeImpl.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeImpl.java
@@ -8,22 +8,19 @@ import org.eclipse.jdt.internal.core.Assert;
import org.eclipse.jdt.internal.core.builder.*;
import org.eclipse.jdt.internal.core.Util;
-public abstract class TypeImpl
- extends NonStateSpecificHandleImpl
- implements IType {
+public abstract class TypeImpl extends NonStateSpecificHandleImpl implements IType {
public static Util.Comparer COMPARER = new Util.Comparer() {
public int compare(Object a, Object b) {
IType typeA = null, typeB = null;
try {
- typeA = (IType) a;
- typeB = (IType) b;
+ typeA = (IType)a;
+ typeB = (IType)b;
} catch (ClassCastException e) {
Assert.isTrue(false, "Should only be comparing ITypes");
}
return typeA.getName().compareTo(typeB.getName());
}
};
-
/**
* Appends the signature for this type to the StringBuffer
* If includeUnnamed is true, then the identifiers for unnamed packages
@@ -34,331 +31,306 @@ public abstract class TypeImpl
* Appends the VM signature of the type to the StringBuffer.
*/
abstract void appendVMSignature(StringBuffer sb);
- /**
- * Returns a Type object representing an array type with
- * the type represented by this object as its component type.
- * This is a handle-only method.
- */
- public org.eclipse.jdt.internal.core.builder.IType getArrayHandle() {
- return new ArrayTypeHandleImpl(this, 1);
- }
-
- /**
- * If this class represents an array type, returns the Type
- * object representing the component type of the array; otherwise
- * returns null. The component type of an array may itself be
- * an array type.
- * This is a handle-only method.
- */
- public org.eclipse.jdt.internal.core.builder.IType getComponentType() {
- return null;
- }
-
- /**
- * Returns a Constructor object that represents the specified
- * constructor of the class represented by this object.
- * The parameterTypes parameter is an array of Type objects that
- * identify the constructor's formal parameter types, in declared
- * order.
- * Returns null if this type does not represent a class or interface.
- * This is a handle-only method; the specified constructor may
- * or may not actually be present in the class or interface.
- */
- public IConstructor getConstructorHandle(IType[] parameterTypes) {
- return null;
- }
-
- /**
- * @see IType#getCRC
- */
- public int getCRC() throws NotPresentException {
- return 0;
- }
-
- /**
- * Returns an array of Type objects representing all the classes
- * and interfaces declared as members of the class represented by
- * this object. This includes public, protected, default
- * (package) access, and private classes and interfaces declared
- * by the class, but excludes inherited classes and interfaces.
- * Returns an array of length 0 if the class declares no classes
- * or interfaces as members, or if this object represents an
- * array type or primitive type.
- * The resulting Types are in no particular order.
- */
- public IType[] getDeclaredClasses() throws NotPresentException {
- return new IType[0];
- }
-
- /**
- * Returns an array of Constructor objects representing all the
- * constructors declared by the class represented by this
- * object. These are public, protected, default (package) access,
- * and private constructors. Returns an array of length 0 if this
- * object represents an interface, an array type or a primitive type.
- * The resulting Constructors are in no particular order.
- */
- public IConstructor[] getDeclaredConstructors() throws NotPresentException {
- return new IConstructor[0];
- }
-
- /**
- * Returns an array of Field objects representing all the fields
- * declared by the class or interface represented by this
- * object. This includes public, protected, default (package)
- * access, and private fields, but excludes inherited
- * fields. Returns an array of length 0 if the class or interface
- * declares no fields, or if this object represents a
- * primitive type or an array type (the implicit <code>length</code>
- * field of array types is not considered to be a declared field).
- * The resulting Fields are in no particular order.
- */
- public IField[] getDeclaredFields() throws NotPresentException {
- return new IField[0];
- }
-
- /**
- * Returns an array of Method objects representing all the methods
- * declared by the class or interface represented by this
- * object. This includes public, protected, default (package)
- * access, and private methods, but excludes inherited
- * methods. Returns an array of length 0 if the class or interface
- * declares no methods, or if this object represents an
- * array type or primitive type.
- * The resulting Methods are in no particular order.
- */
- public IMethod[] getDeclaredMethods() throws NotPresentException {
- return new IMethod[0];
- }
-
- /**
- * Returns the declared Java language modifiers, as specified in the declaration
- * of this class or interface, encoded in an integer.
- * The modifiers consist of the Java Virtual Machine's constants
- * for public, protected, private, and final; they should be decoded
- * using the methods of class Modifier.
- * The result may not correspond to the modifiers in the compiled
- * binary, since the compiler may change them (in particular,
- * for inner classes). The <code>getModifiers()</code>
- * method should be used if the compiled modifiers are needed.
- * Returns 0 if this type does not represent a class or interface.
- *
- * <p>The modifier encodings are defined in <em>The Java Virtual
- * Machine Specification</em>, table 4.1.
- */
- public int getDeclaredModifiers() throws NotPresentException {
- return 0;
- }
-
- /**
- * Returns the declared name of the class or interface represented
- * by this object, as a String.
- * The name is the simple, unqualified name used in the source code.
- * If this represents an inner class, it does not include the names
- * of any containing classes.
- * If this represents an anonymous class, it returns a String of length 0.
- * If this does not represent a class or interface, it returns
- * a String of length 0.
- */
- public String getDeclaredName() throws NotPresentException {
- return "";
- }
-
- /**
- * If the class or interface represented by this Type object is
- * a member of another class or interface (i.e. it is a nested class),
- * this returns the Type object representing the class or interface
- * of which it is a member (its <em>declaring class</em>).
- * If this class or interface is a local class, returns the Type
- * object representing the class containing the member in which
- * this class is declared.
- * Returns null if this class or interface is not a nested class,
- * or if this type does not represent a class or interface.
- */
- public IType getDeclaringClass() {
- return null;
- }
-
- /**
- * Returns a Field object that represents the specified
- * member field of the class or interface represented
- * by this object. The name parameter is a String specifying
- * the simple name of the desired field.
- * Returns null if this type does not represent a class or interface.
- * This is a handle-only method; the specified field may
- * or may not actually be present in the class or interface.
- */
- public IField getFieldHandle(String name) {
- return null;
- }
-
- /**
- * Returns an array of Type objects representing the
- * classes in the given ImageContext which directly implement this interface.
- * A class is said to directly implement this interface if the interface
- * appears in the <code>implements</code> clause of the class's declaration.
- * Although all array types are considered to implement the <code>Cloneable</code>
- * interface, this method never returns array types, only class types.
- * Returns an array of length 0 if this object does not represent
- * an interface.
- * The resulting Types are in no particular order.
- * See <em>The Java Language Specification</em> section 8.1.4
- * for more details.
- */
- public IType[] getImplementingClasses(IImageContext imageContext)
- throws NotPresentException {
- return new IType[0];
- }
-
- /**
- * Returns an array of Type objects representing the direct
- * superinterfaces of the class or interface represented by this object.
- * <p>
- * If this object represents a class, the return value is an array
- * containing objects representing all interfaces directly implemented by the
- * class. The order of the interface objects in the array corresponds
- * to the order of the interface names in the <code>implements</code>
- * clause of the declaration of the class represented by this object.
- * <p>
- * If this object represents an interface, the array contains
- * objects representing all interfaces directly extended by the interface.
- * The order of the interface objects in the array corresponds to the
- * order of the interface names in the <code>extends</code> clause of
- * the declaration of the interface represented by this object.
- * <p>
- * If the class or interface implements no interfaces, or if this
- * object represents neither a class nor an interface, this method
- * returns an array of length 0.
- *
- * See <em>The Java Language Specification</em> sections 8.1.4 and 9.1.3
- * for more details.
- */
- public IType[] getInterfaces() throws NotPresentException {
- return new IType[0];
- }
-
- /**
- * Returns a Method object that represents the specified
- * member method of the class or interface represented
- * by this object. The name parameter is a String specifying the
- * simple name the desired method, and the parameterTypes
- * parameter is an array of Type objects that identify the
- * method's formal parameter types, in declared order.
- * Returns null if this type does not represent a class or interface.
- * This is a handle-only method; the specified method may
- * or may not actually be present in the class or interface.
- */
- public IMethod getMethodHandle(String name, IType[] parameterTypes) {
- return null;
- }
-
- /**
- * Returns the compiled Java language modifiers for this class or
- * interface, encoded in an integer. The modifiers consist of the
- * Java Virtual Machine's constants for public, protected,
- * private, and final; they should be decoded using the
- * methods of class Modifier.
- * The result may not correspond to the modifiers as declared in
- * the source, since the compiler may change them (in particular,
- * for inner classes). The <code>getDeclaredModifiers()</code>
- * method should be used if the original modifiers are needed.
- * Returns 0 if this type does not represent a class or interface.
- */
- public int getModifiers() throws NotPresentException {
- return 0;
- }
-
- /**
- * Returns the fully-qualified name of the type (class, interface,
- * array, or primitive) represented by this object, as a String.
- * For classes and interfaces, the name is the VM class name,
- * including the package name.
- * For inner classes, the name is as described in the
- * <em>Inner Classes Specification</em>.
- * For array types, the name is the name of the component type, followed by '[]'.
- * For primitive types, the name is the keyword for the primitive type.
- * This is a handle-only method.
- */
- public abstract String getName();
- /**
- * Returns the Package in which this class or interface is declared.
- * Returns null if this object represents a primitive type or array type.
- * This is a handle-only method.
- */
- public IPackage getPackage() {
- return null;
- }
-
- /**
- * Returns the simple name of the type (class, interface, array,
- * or primitive) represented by this object, as a String.
- * For classes and interfaces, this is the VM class name,
- * excluding the package name.
- * For array types, this is the simple name of the component type, followed by '[]'.
- * For primitive types, this is the keyword for the primitive type.
- * This is a handle-only method.
- */
- public abstract String getSimpleName();
- /**
- * Returns a SourceFragment describing the fragment of source
- * from which this member is derived.
- * Returns null if this type represent a primitive type or an
- * array type, or if this type is not derived directly from source
- * (e.g. a fictional type, which is created by the image builder).
- */
- public ISourceFragment getSourceFragment() throws NotPresentException {
- return null;
- }
-
- /**
- * Returns an array of Type objects representing the
- * classes in the given ImageContext which are direct subclasses of
- * this class.
- * Returns an array of length 0 if this object does not represent
- * a class.
- * The resulting Types are in no particular order.
- * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
- * for more details.
- */
- public IType[] getSubclasses(IImageContext imageContext)
- throws NotPresentException {
- return new IType[0];
- }
-
- /**
- * Returns an array of Type objects representing the
- * interfaces in the given ImageContext which are direct subinterfaces of
- * this interface.
- * Returns an array of length 0 if this object does not represent
- * an interface.
- * The resulting Types are in no particular order.
- * See <em>The Java Language Specification</em> section 9.1.3
- * for more details.
- */
- public IType[] getSubinterfaces(IImageContext imageContext)
- throws NotPresentException {
- return new IType[0];
- }
-
- /**
- * If this object represents any class other than the class
- * <code>java.lang.Object</code>, then the object that represents
- * the direct superclass of that class is returned.
- * <p>
- * If this object represents the class <code>java.lang.Object</code>
- * or this object represents an interface or a primitive type,
- * <code>null</code> is returned.
- * If this object represents an array type, then the Type that represents
- * class <code>java.lang.Object</code> is returned.
- * <p>
- * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
- * for more details.
- */
- public org.eclipse.jdt.internal.core.builder.IType getSuperclass()
- throws org.eclipse.jdt.internal.core.builder.NotPresentException {
- return null;
- }
-
+/**
+ * Returns a Type object representing an array type with
+ * the type represented by this object as its component type.
+ * This is a handle-only method.
+ */
+public org.eclipse.jdt.internal.core.builder.IType getArrayHandle() {
+ return new ArrayTypeHandleImpl(this, 1);
+}
+/**
+ * If this class represents an array type, returns the Type
+ * object representing the component type of the array; otherwise
+ * returns null. The component type of an array may itself be
+ * an array type.
+ * This is a handle-only method.
+ */
+public org.eclipse.jdt.internal.core.builder.IType getComponentType() {
+ return null;
+}
+/**
+ * Returns a Constructor object that represents the specified
+ * constructor of the class represented by this object.
+ * The parameterTypes parameter is an array of Type objects that
+ * identify the constructor's formal parameter types, in declared
+ * order.
+ * Returns null if this type does not represent a class or interface.
+ * This is a handle-only method; the specified constructor may
+ * or may not actually be present in the class or interface.
+ */
+public IConstructor getConstructorHandle(IType[] parameterTypes) {
+ return null;
+}
+/**
+ * @see IType#getCRC
+ */
+public int getCRC() throws NotPresentException {
+ return 0;
+}
+/**
+ * Returns an array of Type objects representing all the classes
+ * and interfaces declared as members of the class represented by
+ * this object. This includes public, protected, default
+ * (package) access, and private classes and interfaces declared
+ * by the class, but excludes inherited classes and interfaces.
+ * Returns an array of length 0 if the class declares no classes
+ * or interfaces as members, or if this object represents an
+ * array type or primitive type.
+ * The resulting Types are in no particular order.
+ */
+public IType[] getDeclaredClasses() throws NotPresentException {
+ return new IType[0];
+}
+/**
+ * Returns an array of Constructor objects representing all the
+ * constructors declared by the class represented by this
+ * object. These are public, protected, default (package) access,
+ * and private constructors. Returns an array of length 0 if this
+ * object represents an interface, an array type or a primitive type.
+ * The resulting Constructors are in no particular order.
+ */
+public IConstructor[] getDeclaredConstructors() throws NotPresentException {
+ return new IConstructor[0];
+}
+/**
+ * Returns an array of Field objects representing all the fields
+ * declared by the class or interface represented by this
+ * object. This includes public, protected, default (package)
+ * access, and private fields, but excludes inherited
+ * fields. Returns an array of length 0 if the class or interface
+ * declares no fields, or if this object represents a
+ * primitive type or an array type (the implicit <code>length</code>
+ * field of array types is not considered to be a declared field).
+ * The resulting Fields are in no particular order.
+ */
+public IField[] getDeclaredFields() throws NotPresentException {
+ return new IField[0];
+}
+/**
+ * Returns an array of Method objects representing all the methods
+ * declared by the class or interface represented by this
+ * object. This includes public, protected, default (package)
+ * access, and private methods, but excludes inherited
+ * methods. Returns an array of length 0 if the class or interface
+ * declares no methods, or if this object represents an
+ * array type or primitive type.
+ * The resulting Methods are in no particular order.
+ */
+public IMethod[] getDeclaredMethods() throws NotPresentException {
+ return new IMethod[0];
+}
+/**
+ * Returns the declared Java language modifiers, as specified in the declaration
+ * of this class or interface, encoded in an integer.
+ * The modifiers consist of the Java Virtual Machine's constants
+ * for public, protected, private, and final; they should be decoded
+ * using the methods of class Modifier.
+ * The result may not correspond to the modifiers in the compiled
+ * binary, since the compiler may change them (in particular,
+ * for inner classes). The <code>getModifiers()</code>
+ * method should be used if the compiled modifiers are needed.
+ * Returns 0 if this type does not represent a class or interface.
+ *
+ * <p>The modifier encodings are defined in <em>The Java Virtual
+ * Machine Specification</em>, table 4.1.
+ */
+public int getDeclaredModifiers() throws NotPresentException {
+ return 0;
+}
+/**
+ * Returns the declared name of the class or interface represented
+ * by this object, as a String.
+ * The name is the simple, unqualified name used in the source code.
+ * If this represents an inner class, it does not include the names
+ * of any containing classes.
+ * If this represents an anonymous class, it returns a String of length 0.
+ * If this does not represent a class or interface, it returns
+ * a String of length 0.
+ */
+public String getDeclaredName() throws NotPresentException {
+ return "";
+}
+/**
+ * If the class or interface represented by this Type object is
+ * a member of another class or interface (i.e. it is a nested class),
+ * this returns the Type object representing the class or interface
+ * of which it is a member (its <em>declaring class</em>).
+ * If this class or interface is a local class, returns the Type
+ * object representing the class containing the member in which
+ * this class is declared.
+ * Returns null if this class or interface is not a nested class,
+ * or if this type does not represent a class or interface.
+ */
+public IType getDeclaringClass() {
+ return null;
+}
+/**
+ * Returns a Field object that represents the specified
+ * member field of the class or interface represented
+ * by this object. The name parameter is a String specifying
+ * the simple name of the desired field.
+ * Returns null if this type does not represent a class or interface.
+ * This is a handle-only method; the specified field may
+ * or may not actually be present in the class or interface.
+ */
+public IField getFieldHandle(String name) {
+ return null;
+}
+/**
+ * Returns an array of Type objects representing the
+ * classes in the given ImageContext which directly implement this interface.
+ * A class is said to directly implement this interface if the interface
+ * appears in the <code>implements</code> clause of the class's declaration.
+ * Although all array types are considered to implement the <code>Cloneable</code>
+ * interface, this method never returns array types, only class types.
+ * Returns an array of length 0 if this object does not represent
+ * an interface.
+ * The resulting Types are in no particular order.
+ * See <em>The Java Language Specification</em> section 8.1.4
+ * for more details.
+ */
+public IType[] getImplementingClasses(IImageContext imageContext) throws NotPresentException {
+ return new IType[0];
+}
+/**
+ * Returns an array of Type objects representing the direct
+ * superinterfaces of the class or interface represented by this object.
+ * <p>
+ * If this object represents a class, the return value is an array
+ * containing objects representing all interfaces directly implemented by the
+ * class. The order of the interface objects in the array corresponds
+ * to the order of the interface names in the <code>implements</code>
+ * clause of the declaration of the class represented by this object.
+ * <p>
+ * If this object represents an interface, the array contains
+ * objects representing all interfaces directly extended by the interface.
+ * The order of the interface objects in the array corresponds to the
+ * order of the interface names in the <code>extends</code> clause of
+ * the declaration of the interface represented by this object.
+ * <p>
+ * If the class or interface implements no interfaces, or if this
+ * object represents neither a class nor an interface, this method
+ * returns an array of length 0.
+ *
+ * See <em>The Java Language Specification</em> sections 8.1.4 and 9.1.3
+ * for more details.
+ */
+public IType[] getInterfaces() throws NotPresentException {
+ return new IType[0];
+}
+/**
+ * Returns a Method object that represents the specified
+ * member method of the class or interface represented
+ * by this object. The name parameter is a String specifying the
+ * simple name the desired method, and the parameterTypes
+ * parameter is an array of Type objects that identify the
+ * method's formal parameter types, in declared order.
+ * Returns null if this type does not represent a class or interface.
+ * This is a handle-only method; the specified method may
+ * or may not actually be present in the class or interface.
+ */
+public IMethod getMethodHandle(String name, IType[] parameterTypes) {
+ return null;
+}
+/**
+ * Returns the compiled Java language modifiers for this class or
+ * interface, encoded in an integer. The modifiers consist of the
+ * Java Virtual Machine's constants for public, protected,
+ * private, and final; they should be decoded using the
+ * methods of class Modifier.
+ * The result may not correspond to the modifiers as declared in
+ * the source, since the compiler may change them (in particular,
+ * for inner classes). The <code>getDeclaredModifiers()</code>
+ * method should be used if the original modifiers are needed.
+ * Returns 0 if this type does not represent a class or interface.
+ */
+public int getModifiers() throws NotPresentException {
+ return 0;
+}
+/**
+ * Returns the fully-qualified name of the type (class, interface,
+ * array, or primitive) represented by this object, as a String.
+ * For classes and interfaces, the name is the VM class name,
+ * including the package name.
+ * For inner classes, the name is as described in the
+ * <em>Inner Classes Specification</em>.
+ * For array types, the name is the name of the component type, followed by '[]'.
+ * For primitive types, the name is the keyword for the primitive type.
+ * This is a handle-only method.
+ */
+public abstract String getName();
+/**
+ * Returns the Package in which this class or interface is declared.
+ * Returns null if this object represents a primitive type or array type.
+ * This is a handle-only method.
+ */
+public IPackage getPackage() {
+ return null;
+}
+/**
+ * Returns the simple name of the type (class, interface, array,
+ * or primitive) represented by this object, as a String.
+ * For classes and interfaces, this is the VM class name,
+ * excluding the package name.
+ * For array types, this is the simple name of the component type, followed by '[]'.
+ * For primitive types, this is the keyword for the primitive type.
+ * This is a handle-only method.
+ */
+public abstract String getSimpleName();
+/**
+ * Returns a SourceFragment describing the fragment of source
+ * from which this member is derived.
+ * Returns null if this type represent a primitive type or an
+ * array type, or if this type is not derived directly from source
+ * (e.g. a fictional type, which is created by the image builder).
+ */
+public ISourceFragment getSourceFragment() throws NotPresentException {
+ return null;
+}
+/**
+ * Returns an array of Type objects representing the
+ * classes in the given ImageContext which are direct subclasses of
+ * this class.
+ * Returns an array of length 0 if this object does not represent
+ * a class.
+ * The resulting Types are in no particular order.
+ * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
+ * for more details.
+ */
+public IType[] getSubclasses(IImageContext imageContext) throws NotPresentException {
+ return new IType[0];
+}
+/**
+ * Returns an array of Type objects representing the
+ * interfaces in the given ImageContext which are direct subinterfaces of
+ * this interface.
+ * Returns an array of length 0 if this object does not represent
+ * an interface.
+ * The resulting Types are in no particular order.
+ * See <em>The Java Language Specification</em> section 9.1.3
+ * for more details.
+ */
+public IType[] getSubinterfaces(IImageContext imageContext) throws NotPresentException {
+ return new IType[0];
+}
+/**
+ * If this object represents any class other than the class
+ * <code>java.lang.Object</code>, then the object that represents
+ * the direct superclass of that class is returned.
+ * <p>
+ * If this object represents the class <code>java.lang.Object</code>
+ * or this object represents an interface or a primitive type,
+ * <code>null</code> is returned.
+ * If this object represents an array type, then the Type that represents
+ * class <code>java.lang.Object</code> is returned.
+ * <p>
+ * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
+ * for more details.
+ */
+public org.eclipse.jdt.internal.core.builder.IType getSuperclass() throws org.eclipse.jdt.internal.core.builder.NotPresentException {
+ return null;
+}
/**
* Returns the VM signature of the type.
*/
@@ -367,154 +339,138 @@ public abstract class TypeImpl
appendVMSignature(sb);
return sb.toString();
}
-
- /**
- * Returns true if this object represents an anonymous class,
- * false otherwise.
- * An anonymous class is a local inner class with no declared name.
- * <p>
- * See the <em>Java Inner Classes Specification</em> for more details.
- */
- public boolean isAnonymous()
- throws org.eclipse.jdt.internal.core.builder.NotPresentException {
- return false;
- }
-
- /**
- * If this Type object represents an array type, returns true,
- * otherwise returns false.
- * This is a handle-only method.
- */
- public boolean isArray() {
- return false;
- }
-
- /**
- * Return true if this represents a binary class or interface, false otherwise.
- * A binary type is one which is in .class file format in the source tree.
- * Returns false if this represents a primitive type or an array type.
- */
- public boolean isBinary() throws NotPresentException {
- return false;
- }
-
- /**
- * Determines if this object represents a class type.
- * This returns false if this object represents an interface,
- * an array type, or a primitive type.
- */
- public boolean isClass() throws NotPresentException {
- // overridden for classes and interfaces
- return false;
- }
-
- /**
- * @see IType
- */
- public boolean isDeprecated() throws NotPresentException {
- return false;
- }
-
- /**
- * Returns true if this object represents an inner class or interface,
- * false otherwise.
- * An inner class is one which can only be created in the context of
- * an instance of its outer class. This does not include package member
- * classes or other top-level classes. Such a class cannot be static.
- * <p>
- * See the <em>Java Inner Classes Specification</em> for more details.
- */
- public boolean isInnerClass() throws NotPresentException {
- return false;
- }
-
- /**
- * Determines if this object represents an interface type.
- * This returns false if this object represents a class,
- * an array type, or a primitive type.
- */
- public boolean isInterface() throws NotPresentException {
- return false;
- }
-
- /**
- * Returns true if this object represents a local inner class,
- * false otherwise.
- * A local inner class is an inner class which is defined in the body of
- * a method or other block, not as a class field.
- * <p>
- * See the <em>Java Inner Classes Specification</em> for more details.
- */
- public boolean isLocal() throws NotPresentException {
- return false;
- }
-
- /**
- * Returns true if this object represents a class or interface
- * which is declared as a package member (i.e. a 'normal' class
- * as in JDK 1.02). Returns false otherwise.
- * In particular, this method returns false if this object represents a
- * top-level class which is declared as a member of a class.
- * For the sake of consistent terminology, a class which is
- * not a package member is considered 'nested', whether or not
- * it is top-level.
- * <p>
- * See the <em>Java Inner Classes Specification</em> for more details.
- */
- public boolean isPackageMember() throws NotPresentException {
- return false;
- }
-
- /**
- * Determines if the specified Type object represents a primitive Java
- * type.
- * This is a handle-only method.
- *
- * <p>There are nine predefined Type objects to represent the eight
- * primitive Java types and void. These are created by the Java
- * Virtual Machine, and have the same names as the primitive types
- * that they represent, namely boolean, byte, char, short, int,
- * long, float, and double, and void.
- */
- public boolean isPrimitive() {
- return false;
- }
-
- /**
- * Returns true if the type represented by this object is
- * synthetic, false otherwise. A synthetic object is one that
- * was invented by the compiler, but was not declared in the source.
- * See <em>The Inner Classes Specification</em>.
- * A synthetic object is not the same as a fictitious object.
- */
- public boolean isSynthetic() throws NotPresentException {
- return false;
- }
-
- /**
- * Returns true if this object represents a top-level class or interface,
- * false otherwise.
- * A top-level class is declared either as a package member or as a
- * static member of another top-level class. Unlike inner classes,
- * instances of top-level classes are not created in the context of
- * another object.
- * Given the appropriate access modifiers, a top-level class can be
- * referred to directly by a qualified name.
- * <p>
- * See the <em>Java Inner Classes Specification</em> for more details.
- */
- public boolean isTopLevel()
- throws org.eclipse.jdt.internal.core.builder.NotPresentException {
- return false;
- }
-
+/**
+ * Returns true if this object represents an anonymous class,
+ * false otherwise.
+ * An anonymous class is a local inner class with no declared name.
+ * <p>
+ * See the <em>Java Inner Classes Specification</em> for more details.
+ */
+public boolean isAnonymous() throws org.eclipse.jdt.internal.core.builder.NotPresentException {
+ return false;
+}
+/**
+ * If this Type object represents an array type, returns true,
+ * otherwise returns false.
+ * This is a handle-only method.
+ */
+public boolean isArray() {
+ return false;
+}
+/**
+ * Return true if this represents a binary class or interface, false otherwise.
+ * A binary type is one which is in .class file format in the source tree.
+ * Returns false if this represents a primitive type or an array type.
+ */
+public boolean isBinary() throws NotPresentException {
+ return false;
+}
+/**
+ * Determines if this object represents a class type.
+ * This returns false if this object represents an interface,
+ * an array type, or a primitive type.
+ */
+public boolean isClass() throws NotPresentException {
+ // overridden for classes and interfaces
+ return false;
+}
+/**
+ * @see IType
+ */
+public boolean isDeprecated() throws NotPresentException {
+ return false;
+}
+/**
+ * Returns true if this object represents an inner class or interface,
+ * false otherwise.
+ * An inner class is one which can only be created in the context of
+ * an instance of its outer class. This does not include package member
+ * classes or other top-level classes. Such a class cannot be static.
+ * <p>
+ * See the <em>Java Inner Classes Specification</em> for more details.
+ */
+public boolean isInnerClass() throws NotPresentException {
+ return false;
+}
+/**
+ * Determines if this object represents an interface type.
+ * This returns false if this object represents a class,
+ * an array type, or a primitive type.
+ */
+public boolean isInterface() throws NotPresentException {
+ return false;
+}
+/**
+ * Returns true if this object represents a local inner class,
+ * false otherwise.
+ * A local inner class is an inner class which is defined in the body of
+ * a method or other block, not as a class field.
+ * <p>
+ * See the <em>Java Inner Classes Specification</em> for more details.
+ */
+public boolean isLocal() throws NotPresentException {
+ return false;
+}
+/**
+ * Returns true if this object represents a class or interface
+ * which is declared as a package member (i.e. a 'normal' class
+ * as in JDK 1.02). Returns false otherwise.
+ * In particular, this method returns false if this object represents a
+ * top-level class which is declared as a member of a class.
+ * For the sake of consistent terminology, a class which is
+ * not a package member is considered 'nested', whether or not
+ * it is top-level.
+ * <p>
+ * See the <em>Java Inner Classes Specification</em> for more details.
+ */
+public boolean isPackageMember() throws NotPresentException {
+ return false;
+}
+/**
+ * Determines if the specified Type object represents a primitive Java
+ * type.
+ * This is a handle-only method.
+ *
+ * <p>There are nine predefined Type objects to represent the eight
+ * primitive Java types and void. These are created by the Java
+ * Virtual Machine, and have the same names as the primitive types
+ * that they represent, namely boolean, byte, char, short, int,
+ * long, float, and double, and void.
+ */
+public boolean isPrimitive() {
+ return false;
+}
+/**
+ * Returns true if the type represented by this object is
+ * synthetic, false otherwise. A synthetic object is one that
+ * was invented by the compiler, but was not declared in the source.
+ * See <em>The Inner Classes Specification</em>.
+ * A synthetic object is not the same as a fictitious object.
+ */
+public boolean isSynthetic() throws NotPresentException {
+ return false;
+}
+/**
+ * Returns true if this object represents a top-level class or interface,
+ * false otherwise.
+ * A top-level class is declared either as a package member or as a
+ * static member of another top-level class. Unlike inner classes,
+ * instances of top-level classes are not created in the context of
+ * another object.
+ * Given the appropriate access modifiers, a top-level class can be
+ * referred to directly by a qualified name.
+ * <p>
+ * See the <em>Java Inner Classes Specification</em> for more details.
+ */
+public boolean isTopLevel() throws org.eclipse.jdt.internal.core.builder.NotPresentException {
+ return false;
+}
/**
* Returns a constant indicating what kind of handle this is.
*/
public int kind() {
return K_JAVA_TYPE;
}
-
/**
* Returns a string representation of the package. For debugging purposes
* only (NON-NLS).
@@ -522,5 +478,4 @@ public abstract class TypeImpl
public String toString() {
return "type " + getName();
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeImplSWH.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeImplSWH.java
index 6c985d5127..7c14badc37 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeImplSWH.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeImplSWH.java
@@ -8,486 +8,444 @@ import org.eclipse.jdt.internal.compiler.env.IConstants;
import org.eclipse.jdt.internal.core.builder.*;
abstract class TypeImplSWH extends StateSpecificHandleImpl implements IType {
- /**
- * Returns a Type object representing an array type with
- * the type represented by this object as its component type.
- * This is a handle-only method.
- */
- public IType getArrayHandle() {
- return (IType) getHandle().getArrayHandle().inState(fState);
- }
-
- /**
- * If this class represents an array type, returns the Type
- * object representing the component type of the array; otherwise
- * returns null. The component type of an array may itself be
- * an array type.
- * This is a handle-only method.
- */
- public org.eclipse.jdt.internal.core.builder.IType getComponentType() {
- return null;
- }
-
- /**
- * Returns a Constructor object that represents the specified
- * constructor of the class represented by this object.
- * The parameterTypes parameter is an array of Type objects that
- * identify the constructor's formal parameter types, in declared
- * order.
- * Returns null if this type does not represent a class or interface.
- * This is a handle-only method; the specified constructor may
- * or may not actually be present in the class or interface.
- */
- public IConstructor getConstructorHandle(IType[] parameterTypes) {
- return null;
- }
-
- /**
- * @see IType#getCRC
- */
- public int getCRC() throws NotPresentException {
- return 0;
- }
-
- /**
- * Returns an array of Type objects representing all the classes
- * and interfaces declared as members of the class represented by
- * this object. This includes public, protected, default
- * (package) access, and private classes and interfaces declared
- * by the class, but excludes inherited classes and interfaces.
- * Returns an array of length 0 if the class declares no classes
- * or interfaces as members, or if this object represents an
- * array type or primitive type.
- * The resulting Types are in no particular order.
- */
- public IType[] getDeclaredClasses() throws NotPresentException {
- return new IType[0];
- }
-
- /**
- * Returns an array of Constructor objects representing all the
- * constructors declared by the class represented by this
- * object. These are public, protected, default (package) access,
- * and private constructors. Returns an array of length 0 if this
- * object represents an interface, an array type or a primitive type.
- * The resulting Constructors are in no particular order.
- */
- public IConstructor[] getDeclaredConstructors() throws NotPresentException {
- return new IConstructor[0];
- }
-
- /**
- * Returns an array of Field objects representing all the fields
- * declared by the class or interface represented by this
- * object. This includes public, protected, default (package)
- * access, and private fields, but excludes inherited
- * fields. Returns an array of length 0 if the class or interface
- * declares no fields, or if this object represents a
- * primitive type or an array type (the implicit <code>length</code>
- * field of array types is not considered to be a declared field).
- * The resulting Fields are in no particular order.
- */
- public IField[] getDeclaredFields() throws NotPresentException {
- return new IField[0];
- }
-
- /**
- * Returns an array of Method objects representing all the methods
- * declared by the class or interface represented by this
- * object. This includes public, protected, default (package)
- * access, and private methods, but excludes inherited
- * methods. Returns an array of length 0 if the class or interface
- * declares no methods, or if this object represents an
- * array type or primitive type.
- * The resulting Methods are in no particular order.
- */
- public IMethod[] getDeclaredMethods() throws NotPresentException {
- return new IMethod[0];
- }
-
- /**
- * Returns the declared Java language modifiers, as specified in the declaration
- * of this class or interface, encoded in an integer.
- * The modifiers consist of the Java Virtual Machine's constants
- * for public, protected, private, and final; they should be decoded
- * using the methods of class Modifier.
- * The result may not correspond to the modifiers in the compiled
- * binary, since the compiler may change them (in particular,
- * for inner classes). The <code>getModifiers()</code>
- * method should be used if the compiled modifiers are needed.
- * Returns 0 if this type does not represent a class or interface.
- *
- * <p>The modifier encodings are defined in <em>The Java Virtual
- * Machine Specification</em>, table 4.1.
- */
- public int getDeclaredModifiers() throws NotPresentException {
- return 0;
- }
-
- /**
- * Returns the declared name of the class or interface represented
- * by this object, as a String.
- * The name is the simple, unqualified name used in the source code.
- * If this represents an inner class, it does not include the names
- * of any containing classes.
- * If this represents an anonymous class, it returns a String of length 0.
- * If this does not represent a class or interface, it returns
- * a String of length 0.
- */
- public String getDeclaredName() throws NotPresentException {
- return "";
- }
-
- /**
- * If the class or interface represented by this Type object is
- * a member of another class or interface (i.e. it is a nested class),
- * this returns the Type object representing the class or interface
- * of which it is a member (its <em>declaring class</em>).
- * If this class or interface is a local class, returns the Type
- * object representing the class containing the member in which
- * this class is declared.
- * Returns null if this class or interface is not a nested class,
- * or if this type does not represent a class or interface.
- */
- public IType getDeclaringClass() {
- return null;
- }
-
- /**
- * Returns a Field object that represents the specified
- * member field of the class or interface represented
- * by this object. The name parameter is a String specifying
- * the simple name of the desired field.
- * Returns null if this type does not represent a class or interface.
- * This is a handle-only method; the specified field may
- * or may not actually be present in the class or interface.
- */
- public IField getFieldHandle(String name) {
- return null;
- }
-
+/**
+ * Returns a Type object representing an array type with
+ * the type represented by this object as its component type.
+ * This is a handle-only method.
+ */
+public IType getArrayHandle() {
+ return (IType) getHandle().getArrayHandle().inState(fState);
+}
+/**
+ * If this class represents an array type, returns the Type
+ * object representing the component type of the array; otherwise
+ * returns null. The component type of an array may itself be
+ * an array type.
+ * This is a handle-only method.
+ */
+public org.eclipse.jdt.internal.core.builder.IType getComponentType() {
+ return null;
+}
+/**
+ * Returns a Constructor object that represents the specified
+ * constructor of the class represented by this object.
+ * The parameterTypes parameter is an array of Type objects that
+ * identify the constructor's formal parameter types, in declared
+ * order.
+ * Returns null if this type does not represent a class or interface.
+ * This is a handle-only method; the specified constructor may
+ * or may not actually be present in the class or interface.
+ */
+public IConstructor getConstructorHandle(IType[] parameterTypes) {
+ return null;
+}
+/**
+ * @see IType#getCRC
+ */
+public int getCRC() throws NotPresentException {
+ return 0;
+}
+/**
+ * Returns an array of Type objects representing all the classes
+ * and interfaces declared as members of the class represented by
+ * this object. This includes public, protected, default
+ * (package) access, and private classes and interfaces declared
+ * by the class, but excludes inherited classes and interfaces.
+ * Returns an array of length 0 if the class declares no classes
+ * or interfaces as members, or if this object represents an
+ * array type or primitive type.
+ * The resulting Types are in no particular order.
+ */
+public IType[] getDeclaredClasses() throws NotPresentException {
+ return new IType[0];
+}
+/**
+ * Returns an array of Constructor objects representing all the
+ * constructors declared by the class represented by this
+ * object. These are public, protected, default (package) access,
+ * and private constructors. Returns an array of length 0 if this
+ * object represents an interface, an array type or a primitive type.
+ * The resulting Constructors are in no particular order.
+ */
+public IConstructor[] getDeclaredConstructors() throws NotPresentException {
+ return new IConstructor[0];
+}
+/**
+ * Returns an array of Field objects representing all the fields
+ * declared by the class or interface represented by this
+ * object. This includes public, protected, default (package)
+ * access, and private fields, but excludes inherited
+ * fields. Returns an array of length 0 if the class or interface
+ * declares no fields, or if this object represents a
+ * primitive type or an array type (the implicit <code>length</code>
+ * field of array types is not considered to be a declared field).
+ * The resulting Fields are in no particular order.
+ */
+public IField[] getDeclaredFields() throws NotPresentException {
+ return new IField[0];
+}
+/**
+ * Returns an array of Method objects representing all the methods
+ * declared by the class or interface represented by this
+ * object. This includes public, protected, default (package)
+ * access, and private methods, but excludes inherited
+ * methods. Returns an array of length 0 if the class or interface
+ * declares no methods, or if this object represents an
+ * array type or primitive type.
+ * The resulting Methods are in no particular order.
+ */
+public IMethod[] getDeclaredMethods() throws NotPresentException {
+ return new IMethod[0];
+}
+/**
+ * Returns the declared Java language modifiers, as specified in the declaration
+ * of this class or interface, encoded in an integer.
+ * The modifiers consist of the Java Virtual Machine's constants
+ * for public, protected, private, and final; they should be decoded
+ * using the methods of class Modifier.
+ * The result may not correspond to the modifiers in the compiled
+ * binary, since the compiler may change them (in particular,
+ * for inner classes). The <code>getModifiers()</code>
+ * method should be used if the compiled modifiers are needed.
+ * Returns 0 if this type does not represent a class or interface.
+ *
+ * <p>The modifier encodings are defined in <em>The Java Virtual
+ * Machine Specification</em>, table 4.1.
+ */
+public int getDeclaredModifiers() throws NotPresentException {
+ return 0;
+}
+/**
+ * Returns the declared name of the class or interface represented
+ * by this object, as a String.
+ * The name is the simple, unqualified name used in the source code.
+ * If this represents an inner class, it does not include the names
+ * of any containing classes.
+ * If this represents an anonymous class, it returns a String of length 0.
+ * If this does not represent a class or interface, it returns
+ * a String of length 0.
+ */
+public String getDeclaredName() throws NotPresentException {
+ return "";
+}
+/**
+ * If the class or interface represented by this Type object is
+ * a member of another class or interface (i.e. it is a nested class),
+ * this returns the Type object representing the class or interface
+ * of which it is a member (its <em>declaring class</em>).
+ * If this class or interface is a local class, returns the Type
+ * object representing the class containing the member in which
+ * this class is declared.
+ * Returns null if this class or interface is not a nested class,
+ * or if this type does not represent a class or interface.
+ */
+public IType getDeclaringClass() {
+ return null;
+}
+/**
+ * Returns a Field object that represents the specified
+ * member field of the class or interface represented
+ * by this object. The name parameter is a String specifying
+ * the simple name of the desired field.
+ * Returns null if this type does not represent a class or interface.
+ * This is a handle-only method; the specified field may
+ * or may not actually be present in the class or interface.
+ */
+public IField getFieldHandle(String name) {
+ return null;
+}
/**
* Returns the handle for this type
*/
protected abstract TypeImpl getHandle();
- /**
- * Returns an array of Type objects representing the
- * classes in the given ImageContext which directly implement this interface.
- * A class is said to directly implement this interface if the interface
- * appears in the <code>implements</code> clause of the class's declaration.
- * Although all array types are considered to implement the <code>Cloneable</code>
- * interface, this method never returns array types, only class types.
- * Returns an array of length 0 if this object does not represent
- * an interface.
- * The resulting Types are in no particular order.
- * See <em>The Java Language Specification</em> section 8.1.4
- * for more details.
- */
- public IType[] getImplementingClasses(IImageContext imageContext)
- throws NotPresentException {
- return new IType[0];
- }
-
- /**
- * Returns an array of Type objects representing the direct
- * superinterfaces of the class or interface represented by this object.
- * <p>
- * If this object represents a class, the return value is an array
- * containing objects representing all interfaces directly implemented by the
- * class. The order of the interface objects in the array corresponds
- * to the order of the interface names in the <code>implements</code>
- * clause of the declaration of the class represented by this object.
- * <p>
- * If this object represents an interface, the array contains
- * objects representing all interfaces directly extended by the interface.
- * The order of the interface objects in the array corresponds to the
- * order of the interface names in the <code>extends</code> clause of
- * the declaration of the interface represented by this object.
- * <p>
- * If the class or interface implements no interfaces, or if this
- * object represents neither a class nor an interface, this method
- * returns an array of length 0.
- *
- * See <em>The Java Language Specification</em> sections 8.1.4 and 9.1.3
- * for more details.
- */
- public IType[] getInterfaces() throws NotPresentException {
- return new IType[0];
- }
-
- /**
- * Returns a Method object that represents the specified
- * member method of the class or interface represented
- * by this object. The name parameter is a String specifying the
- * simple name the desired method, and the parameterTypes
- * parameter is an array of Type objects that identify the
- * method's formal parameter types, in declared order.
- * Returns null if this type does not represent a class or interface.
- * This is a handle-only method; the specified method may
- * or may not actually be present in the class or interface.
- */
- public IMethod getMethodHandle(String name, IType[] parameterTypes) {
- return null;
- }
-
- /**
- * Returns the compiled Java language modifiers for this class or
- * interface, encoded in an integer. The modifiers consist of the
- * Java Virtual Machine's constants for public, protected,
- * private, and final; they should be decoded using the
- * methods of class Modifier.
- * The result may not correspond to the modifiers as declared in
- * the source, since the compiler may change them (in particular,
- * for inner classes). The <code>getDeclaredModifiers()</code>
- * method should be used if the original modifiers are needed.
- * Returns 0 if this type does not represent a class or interface.
- */
- public int getModifiers() throws NotPresentException {
- return 0;
- }
-
- /**
- * Returns the fully-qualified name of the type (class, interface,
- * array, or primitive) represented by this object, as a String.
- * For classes and interfaces, the name is the VM class name,
- * including the package name.
- * For inner classes, the name is as described in the
- * <em>Inner Classes Specification</em>.
- * For array types, the name is the name of the component type, followed by '[]'.
- * For primitive types, the name is the keyword for the primitive type.
- * This is a handle-only method.
- */
- public String getName() {
- return getHandle().getName();
- }
-
- /**
- * Returns the Package in which this class or interface is declared.
- * Returns null if this object represents a primitive type or array type.
- * This is a handle-only method.
- */
- public IPackage getPackage() {
- return null;
- }
-
- /**
- * Returns the simple name of the type (class, interface, array,
- * or primitive) represented by this object, as a String.
- * For classes and interfaces, this is the VM class name,
- * excluding the package name.
- * For array types, this is the simple name of the component type, followed by '[]'.
- * For primitive types, this is the keyword for the primitive type.
- * This is a handle-only method.
- */
- public String getSimpleName() {
- return getHandle().getSimpleName();
- }
-
- /**
- * Returns a SourceFragment describing the fragment of source
- * from which this member is derived.
- * Returns null if this type represent a primitive type or an
- * array type, or if this type is not derived directly from source
- * (e.g. a fictional type, which is created by the image builder).
- */
- public ISourceFragment getSourceFragment() throws NotPresentException {
- return null;
- }
-
- /**
- * Returns an array of Type objects representing the
- * classes in the given ImageContext which are direct subclasses of
- * this class.
- * Returns an array of length 0 if this object does not represent
- * a class.
- * The resulting Types are in no particular order.
- * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
- * for more details.
- */
- public IType[] getSubclasses(IImageContext imageContext)
- throws NotPresentException {
- return new IType[0];
- }
-
- /**
- * Returns an array of Type objects representing the
- * interfaces in the given ImageContext which are direct subinterfaces of
- * this interface.
- * Returns an array of length 0 if this object does not represent
- * an interface.
- * The resulting Types are in no particular order.
- * See <em>The Java Language Specification</em> section 9.1.3
- * for more details.
- */
- public IType[] getSubinterfaces(IImageContext imageContext)
- throws NotPresentException {
- return new IType[0];
- }
-
- /**
- * If this object represents any class other than the class
- * <code>java.lang.Object</code>, then the object that represents
- * the direct superclass of that class is returned.
- * <p>
- * If this object represents the class <code>java.lang.Object</code>
- * or this object represents an interface or a primitive type,
- * <code>null</code> is returned.
- * If this object represents an array type, then the Type that represents
- * class <code>java.lang.Object</code> is returned.
- * <p>
- * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
- * for more details.
- */
- public org.eclipse.jdt.internal.core.builder.IType getSuperclass()
- throws org.eclipse.jdt.internal.core.builder.NotPresentException {
- return null;
- }
-
- /**
- * Returns true if this object represents an anonymous class,
- * false otherwise.
- * An anonymous class is a local inner class with no declared name.
- * <p>
- * See the <em>Java Inner Classes Specification</em> for more details.
- */
- public boolean isAnonymous()
- throws org.eclipse.jdt.internal.core.builder.NotPresentException {
- return false;
- }
-
- /**
- * If this Type object represents an array type, returns true,
- * otherwise returns false.
- * This is a handle-only method.
- */
- public boolean isArray() {
- return false;
- }
-
- /**
- * Return true if this represents a binary class or interface, false otherwise.
- * A binary type is one which is in .class file format in the source tree.
- * Returns false if this represents a primitive type or an array type.
- */
- public boolean isBinary() throws NotPresentException {
- return false;
- }
-
- /**
- * Determines if this object represents a class type.
- * This returns false if this object represents an interface,
- * an array type, or a primitive type.
- */
- public boolean isClass() throws NotPresentException {
- // overridden for classes and interfaces
- return false;
- }
-
- /**
- * @see IType
- */
- public boolean isDeprecated() throws NotPresentException {
- return false;
- }
-
- /**
- * Returns true if this object represents an inner class or interface,
- * false otherwise.
- * An inner class is one which can only be created in the context of
- * an instance of its outer class. This does not include package member
- * classes or other top-level classes. Such a class cannot be static.
- * <p>
- * See the <em>Java Inner Classes Specification</em> for more details.
- */
- public boolean isInnerClass() throws NotPresentException {
- return false;
- }
-
- /**
- * Determines if this object represents an interface type.
- * This returns false if this object represents a class,
- * an array type, or a primitive type.
- */
- public boolean isInterface() throws NotPresentException {
- return false;
- }
-
- /**
- * Returns true if this object represents a local inner class,
- * false otherwise.
- * A local inner class is an inner class which is defined in the body of
- * a method or other block, not as a class field.
- * <p>
- * See the <em>Java Inner Classes Specification</em> for more details.
- */
- public boolean isLocal() throws NotPresentException {
- return false;
- }
-
- /**
- * Returns true if this object represents a class or interface
- * which is declared as a package member (i.e. a 'normal' class
- * as in JDK 1.02). Returns false otherwise.
- * In particular, this method returns false if this object represents a
- * top-level class which is declared as a member of a class.
- * For the sake of consistent terminology, a class which is
- * not a package member is considered 'nested', whether or not
- * it is top-level.
- * <p>
- * See the <em>Java Inner Classes Specification</em> for more details.
- */
- public boolean isPackageMember() throws NotPresentException {
- return false;
- }
-
- /**
- * Determines if the specified Type object represents a primitive Java
- * type.
- * This is a handle-only method.
- *
- * <p>There are nine predefined Type objects to represent the eight
- * primitive Java types and void. These are created by the Java
- * Virtual Machine, and have the same names as the primitive types
- * that they represent, namely boolean, byte, char, short, int,
- * long, float, and double, and void.
- */
- public boolean isPrimitive() {
- return false;
- }
-
- /**
- * Returns true if the type represented by this object is
- * synthetic, false otherwise. A synthetic object is one that
- * was invented by the compiler, but was not declared in the source.
- * See <em>The Inner Classes Specification</em>.
- * A synthetic object is not the same as a fictitious object.
- */
- public boolean isSynthetic() throws NotPresentException {
- return false;
- }
-
- /**
- * Returns true if this object represents a top-level class or interface,
- * false otherwise.
- * A top-level class is declared either as a package member or as a
- * static member of another top-level class. Unlike inner classes,
- * instances of top-level classes are not created in the context of
- * another object.
- * Given the appropriate access modifiers, a top-level class can be
- * referred to directly by a qualified name.
- * <p>
- * See the <em>Java Inner Classes Specification</em> for more details.
- */
- public boolean isTopLevel()
- throws org.eclipse.jdt.internal.core.builder.NotPresentException {
- return false;
- }
-
+/**
+ * Returns an array of Type objects representing the
+ * classes in the given ImageContext which directly implement this interface.
+ * A class is said to directly implement this interface if the interface
+ * appears in the <code>implements</code> clause of the class's declaration.
+ * Although all array types are considered to implement the <code>Cloneable</code>
+ * interface, this method never returns array types, only class types.
+ * Returns an array of length 0 if this object does not represent
+ * an interface.
+ * The resulting Types are in no particular order.
+ * See <em>The Java Language Specification</em> section 8.1.4
+ * for more details.
+ */
+public IType[] getImplementingClasses(IImageContext imageContext) throws NotPresentException {
+ return new IType[0];
+}
+/**
+ * Returns an array of Type objects representing the direct
+ * superinterfaces of the class or interface represented by this object.
+ * <p>
+ * If this object represents a class, the return value is an array
+ * containing objects representing all interfaces directly implemented by the
+ * class. The order of the interface objects in the array corresponds
+ * to the order of the interface names in the <code>implements</code>
+ * clause of the declaration of the class represented by this object.
+ * <p>
+ * If this object represents an interface, the array contains
+ * objects representing all interfaces directly extended by the interface.
+ * The order of the interface objects in the array corresponds to the
+ * order of the interface names in the <code>extends</code> clause of
+ * the declaration of the interface represented by this object.
+ * <p>
+ * If the class or interface implements no interfaces, or if this
+ * object represents neither a class nor an interface, this method
+ * returns an array of length 0.
+ *
+ * See <em>The Java Language Specification</em> sections 8.1.4 and 9.1.3
+ * for more details.
+ */
+public IType[] getInterfaces() throws NotPresentException {
+ return new IType[0];
+}
+/**
+ * Returns a Method object that represents the specified
+ * member method of the class or interface represented
+ * by this object. The name parameter is a String specifying the
+ * simple name the desired method, and the parameterTypes
+ * parameter is an array of Type objects that identify the
+ * method's formal parameter types, in declared order.
+ * Returns null if this type does not represent a class or interface.
+ * This is a handle-only method; the specified method may
+ * or may not actually be present in the class or interface.
+ */
+public IMethod getMethodHandle(String name, IType[] parameterTypes) {
+ return null;
+}
+/**
+ * Returns the compiled Java language modifiers for this class or
+ * interface, encoded in an integer. The modifiers consist of the
+ * Java Virtual Machine's constants for public, protected,
+ * private, and final; they should be decoded using the
+ * methods of class Modifier.
+ * The result may not correspond to the modifiers as declared in
+ * the source, since the compiler may change them (in particular,
+ * for inner classes). The <code>getDeclaredModifiers()</code>
+ * method should be used if the original modifiers are needed.
+ * Returns 0 if this type does not represent a class or interface.
+ */
+public int getModifiers() throws NotPresentException {
+ return 0;
+}
+/**
+ * Returns the fully-qualified name of the type (class, interface,
+ * array, or primitive) represented by this object, as a String.
+ * For classes and interfaces, the name is the VM class name,
+ * including the package name.
+ * For inner classes, the name is as described in the
+ * <em>Inner Classes Specification</em>.
+ * For array types, the name is the name of the component type, followed by '[]'.
+ * For primitive types, the name is the keyword for the primitive type.
+ * This is a handle-only method.
+ */
+public String getName() {
+ return getHandle().getName();
+}
+/**
+ * Returns the Package in which this class or interface is declared.
+ * Returns null if this object represents a primitive type or array type.
+ * This is a handle-only method.
+ */
+public IPackage getPackage() {
+ return null;
+}
+/**
+ * Returns the simple name of the type (class, interface, array,
+ * or primitive) represented by this object, as a String.
+ * For classes and interfaces, this is the VM class name,
+ * excluding the package name.
+ * For array types, this is the simple name of the component type, followed by '[]'.
+ * For primitive types, this is the keyword for the primitive type.
+ * This is a handle-only method.
+ */
+public String getSimpleName() {
+ return getHandle().getSimpleName();
+}
+/**
+ * Returns a SourceFragment describing the fragment of source
+ * from which this member is derived.
+ * Returns null if this type represent a primitive type or an
+ * array type, or if this type is not derived directly from source
+ * (e.g. a fictional type, which is created by the image builder).
+ */
+public ISourceFragment getSourceFragment() throws NotPresentException {
+ return null;
+}
+/**
+ * Returns an array of Type objects representing the
+ * classes in the given ImageContext which are direct subclasses of
+ * this class.
+ * Returns an array of length 0 if this object does not represent
+ * a class.
+ * The resulting Types are in no particular order.
+ * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
+ * for more details.
+ */
+public IType[] getSubclasses(IImageContext imageContext) throws NotPresentException {
+ return new IType[0];
+}
+/**
+ * Returns an array of Type objects representing the
+ * interfaces in the given ImageContext which are direct subinterfaces of
+ * this interface.
+ * Returns an array of length 0 if this object does not represent
+ * an interface.
+ * The resulting Types are in no particular order.
+ * See <em>The Java Language Specification</em> section 9.1.3
+ * for more details.
+ */
+public IType[] getSubinterfaces(IImageContext imageContext) throws NotPresentException {
+ return new IType[0];
+}
+/**
+ * If this object represents any class other than the class
+ * <code>java.lang.Object</code>, then the object that represents
+ * the direct superclass of that class is returned.
+ * <p>
+ * If this object represents the class <code>java.lang.Object</code>
+ * or this object represents an interface or a primitive type,
+ * <code>null</code> is returned.
+ * If this object represents an array type, then the Type that represents
+ * class <code>java.lang.Object</code> is returned.
+ * <p>
+ * See <em>The Java Language Specification</em> sections 8.1.3 and 20.3.4
+ * for more details.
+ */
+public org.eclipse.jdt.internal.core.builder.IType getSuperclass() throws org.eclipse.jdt.internal.core.builder.NotPresentException {
+ return null;
+}
+/**
+ * Returns true if this object represents an anonymous class,
+ * false otherwise.
+ * An anonymous class is a local inner class with no declared name.
+ * <p>
+ * See the <em>Java Inner Classes Specification</em> for more details.
+ */
+public boolean isAnonymous() throws org.eclipse.jdt.internal.core.builder.NotPresentException {
+ return false;
+}
+/**
+ * If this Type object represents an array type, returns true,
+ * otherwise returns false.
+ * This is a handle-only method.
+ */
+public boolean isArray() {
+ return false;
+}
+/**
+ * Return true if this represents a binary class or interface, false otherwise.
+ * A binary type is one which is in .class file format in the source tree.
+ * Returns false if this represents a primitive type or an array type.
+ */
+public boolean isBinary() throws NotPresentException {
+ return false;
+}
+/**
+ * Determines if this object represents a class type.
+ * This returns false if this object represents an interface,
+ * an array type, or a primitive type.
+ */
+public boolean isClass() throws NotPresentException {
+ // overridden for classes and interfaces
+ return false;
+}
+/**
+ * @see IType
+ */
+public boolean isDeprecated() throws NotPresentException {
+ return false;
+}
+/**
+ * Returns true if this object represents an inner class or interface,
+ * false otherwise.
+ * An inner class is one which can only be created in the context of
+ * an instance of its outer class. This does not include package member
+ * classes or other top-level classes. Such a class cannot be static.
+ * <p>
+ * See the <em>Java Inner Classes Specification</em> for more details.
+ */
+public boolean isInnerClass() throws NotPresentException {
+ return false;
+}
+/**
+ * Determines if this object represents an interface type.
+ * This returns false if this object represents a class,
+ * an array type, or a primitive type.
+ */
+public boolean isInterface() throws NotPresentException {
+ return false;
+}
+/**
+ * Returns true if this object represents a local inner class,
+ * false otherwise.
+ * A local inner class is an inner class which is defined in the body of
+ * a method or other block, not as a class field.
+ * <p>
+ * See the <em>Java Inner Classes Specification</em> for more details.
+ */
+public boolean isLocal() throws NotPresentException {
+ return false;
+}
+/**
+ * Returns true if this object represents a class or interface
+ * which is declared as a package member (i.e. a 'normal' class
+ * as in JDK 1.02). Returns false otherwise.
+ * In particular, this method returns false if this object represents a
+ * top-level class which is declared as a member of a class.
+ * For the sake of consistent terminology, a class which is
+ * not a package member is considered 'nested', whether or not
+ * it is top-level.
+ * <p>
+ * See the <em>Java Inner Classes Specification</em> for more details.
+ */
+public boolean isPackageMember() throws NotPresentException {
+ return false;
+}
+/**
+ * Determines if the specified Type object represents a primitive Java
+ * type.
+ * This is a handle-only method.
+ *
+ * <p>There are nine predefined Type objects to represent the eight
+ * primitive Java types and void. These are created by the Java
+ * Virtual Machine, and have the same names as the primitive types
+ * that they represent, namely boolean, byte, char, short, int,
+ * long, float, and double, and void.
+ */
+public boolean isPrimitive() {
+ return false;
+}
+/**
+ * Returns true if the type represented by this object is
+ * synthetic, false otherwise. A synthetic object is one that
+ * was invented by the compiler, but was not declared in the source.
+ * See <em>The Inner Classes Specification</em>.
+ * A synthetic object is not the same as a fictitious object.
+ */
+public boolean isSynthetic() throws NotPresentException {
+ return false;
+}
+/**
+ * Returns true if this object represents a top-level class or interface,
+ * false otherwise.
+ * A top-level class is declared either as a package member or as a
+ * static member of another top-level class. Unlike inner classes,
+ * instances of top-level classes are not created in the context of
+ * another object.
+ * Given the appropriate access modifiers, a top-level class can be
+ * referred to directly by a qualified name.
+ * <p>
+ * See the <em>Java Inner Classes Specification</em> for more details.
+ */
+public boolean isTopLevel() throws org.eclipse.jdt.internal.core.builder.NotPresentException {
+ return false;
+}
/**
* Return the non state specific handle associated with this handle
*/
public IHandle nonStateSpecific() {
return getHandle();
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeNode.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeNode.java
index 1497a81422..3ae8509102 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeNode.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeNode.java
@@ -8,6 +8,7 @@ import org.eclipse.jdt.internal.core.builder.IType;
import java.util.*;
+
/**
* Type nodes represent compiled types in the graph. They are types
* that were importing into the workspace with no source code available.
@@ -21,7 +22,6 @@ public class TypeNode extends AbstractNode {
public TypeNode(PackageElement type) {
fType = type;
}
-
/**
* Returns a copy of this node, without copying dependencies. Used
* by DependencyGraph.copy().
@@ -29,14 +29,12 @@ public class TypeNode extends AbstractNode {
public AbstractNode copy() {
return new TypeNode(fType);
}
-
/**
* Returns the element which this node represents.
*/
public Object getElement() {
return fType;
}
-
/**
* Returns the number of bytes that this node uses.
* For debugging and profiling purposes only.
@@ -45,25 +43,21 @@ public class TypeNode extends AbstractNode {
/* one slot for type */
return super.getFootprint() + 4;
}
-
/**
* Returns what kind of node this is.
*/
public int getKind() {
return TYPE_NODE;
}
-
public PackageElement getPackageElement() {
return fType;
}
-
- public IType[] getTypes() {
- String fileName = fType.getFileName();
- int lastDot = fileName.lastIndexOf('.');
- IType type = fType.getPackage().getClassHandle(fileName.substring(0, lastDot));
- return new IType[] { type };
- }
-
+public IType[] getTypes() {
+ String fileName = fType.getFileName();
+ int lastDot = fileName.lastIndexOf('.');
+ IType type = fType.getPackage().getClassHandle(fileName.substring(0, lastDot));
+ return new IType[] {type};
+}
/**
* Prints a string representation of the node. This method is for debugging
* purposes only.
@@ -71,5 +65,4 @@ public class TypeNode extends AbstractNode {
public String toString() {
return "TypeNode(" + fType.getFileName() + ")";
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeStructureEntry.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeStructureEntry.java
index cb3d3aee06..dd67c9da07 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeStructureEntry.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/TypeStructureEntry.java
@@ -23,7 +23,6 @@ public class TypeStructureEntry extends StateTables {
TypeStructureEntry(SourceEntry sEntry, IType type) {
this(sEntry, type, 0);
}
-
/**
* Creates a new TypeStructureEntry.
*/
@@ -32,50 +31,44 @@ public class TypeStructureEntry extends StateTables {
fType = type;
fCRC32 = crc;
}
-
/**
* Returns true if the given object is equal to this one, and false otherwise
* A TypeStructureEntry equals method is needed because they are keys to the
* TypeDescriptorCache in the State.
*/
public boolean equals(Object o) {
- if (this == o)
- return true;
- if (!(o instanceof TypeStructureEntry))
- return false;
+ if (this == o) return true;
+ if (!(o instanceof TypeStructureEntry)) return false;
- TypeStructureEntry e = (TypeStructureEntry) o;
+ TypeStructureEntry e = (TypeStructureEntry)o;
return fType.equals(e.fType);
}
-
- int getCRC32() {
- Assert.isTrue(fCRC32 != 0);
- return fCRC32;
- }
-
+int getCRC32() {
+ Assert.isTrue(fCRC32 != 0);
+ return fCRC32;
+}
/**
* Returns the key for this type in the dependency graph.
*/
Object getDependencyGraphKey() {
if (fSourceEntry.isSource()) {
return new PackageElement(fType.getPackage(), fSourceEntry);
- } else {
+ }
+ else {
return fType;
}
}
-
public SourceEntry getSourceEntry() {
return fSourceEntry;
}
-
ISourceFragment getSourceFragment() {
- return new SourceFragmentImpl(-1, -1, fSourceEntry);
+ return new SourceFragmentImpl(
+ -1, -1,
+ fSourceEntry);
}
-
public IType getType() {
return fType;
}
-
/**
* Returns a consistent hashcode for this entry.
* A hashcode method is needed because TypeStructureEntrys are keys to the
@@ -84,7 +77,6 @@ public class TypeStructureEntry extends StateTables {
public int hashcode() {
return fType.hashCode();
}
-
/**
* Returns true if this entry comes from a binary file, otherwise
* returns false.
@@ -92,22 +84,19 @@ public class TypeStructureEntry extends StateTables {
boolean isBinary() {
return fSourceEntry.isBinary();
}
-
void setCRC32(int val) {
fCRC32 = val;
}
-
- /**
- * Returns a String that represents the value of this object.
- * @return a string representation of the receiver
- */
- public String toString() {
- StringBuffer buf = new StringBuffer("TypeStructureEntry(");
- if (fType != null) {
- buf.append(fType.getName());
- }
- buf.append(")");
- return buf.toString();
+/**
+ * Returns a String that represents the value of this object.
+ * @return a string representation of the receiver
+ */
+public String toString() {
+ StringBuffer buf = new StringBuffer("TypeStructureEntry(");
+ if (fType != null) {
+ buf.append(fType.getName());
}
-
+ buf.append(")");
+ return buf.toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/UnmodifiedBuilderType.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/UnmodifiedBuilderType.java
index 90cd974024..fe514db5a6 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/UnmodifiedBuilderType.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/UnmodifiedBuilderType.java
@@ -12,54 +12,46 @@ import org.eclipse.jdt.internal.core.Assert;
* be the same in both the old and new states.
*/
public class UnmodifiedBuilderType extends NewBuilderType {
- /**
- * UnmodifiedBuilderType constructor comment.
- */
- public UnmodifiedBuilderType(
- IncrementalImageBuilder builder,
- TypeStructureEntry entry) {
- super(builder, entry);
-
- /* we don't yet know if there is a hierarchy change */
- fComputedHierarchy = false;
- }
-
- /**
- * Should not be trying to compute indictments for an unmodified type.
- */
- public void computeIndictments(IndictmentSet indictments) {
- Assert.isTrue(false);
- }
-
- /**
- * Returns true if there is a change to the supertype hierarchy of this type.
- * Needs to check the whole hierarchy because changes from higher up are -not-
- * automatically propagated through the dependency graph.
- */
- protected boolean detectHierarchyChange() {
- return false;
- }
-
- /**
- * Returns the tsEntry in the old state (same in both states)
- */
- public TypeStructureEntry getOldTypeStructureEntry() {
- return fNewTSEntry;
- }
-
- /**
- * Returns true if the given type was affected by the build
- * (either added, removed, or changed)
- */
- public boolean isAffected() {
- return false;
- }
-
- /**
- * For debugging only
- */
- public String toString() {
- return "UnmodifiedBuilderType(" + fNewTSEntry.getType().getName() + ")";
- }
+/**
+ * UnmodifiedBuilderType constructor comment.
+ */
+public UnmodifiedBuilderType(IncrementalImageBuilder builder, TypeStructureEntry entry) {
+ super(builder, entry);
+ /* we don't yet know if there is a hierarchy change */
+ fComputedHierarchy = false;
+}
+/**
+ * Should not be trying to compute indictments for an unmodified type.
+ */
+public void computeIndictments(IndictmentSet indictments) {
+ Assert.isTrue(false);
+}
+/**
+ * Returns true if there is a change to the supertype hierarchy of this type.
+ * Needs to check the whole hierarchy because changes from higher up are -not-
+ * automatically propagated through the dependency graph.
+ */
+protected boolean detectHierarchyChange() {
+ return false;
+}
+/**
+ * Returns the tsEntry in the old state (same in both states)
+ */
+public TypeStructureEntry getOldTypeStructureEntry() {
+ return fNewTSEntry;
+}
+/**
+ * Returns true if the given type was affected by the build
+ * (either added, removed, or changed)
+ */
+public boolean isAffected() {
+ return false;
+}
+/**
+ * For debugging only
+ */
+public String toString() {
+ return "UnmodifiedBuilderType(" + fNewTSEntry.getType().getName() + ")";
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/WorkQueue.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/WorkQueue.java
index f55bc0ec9c..0d05f5966c 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/WorkQueue.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/WorkQueue.java
@@ -17,7 +17,7 @@ public class WorkQueue {
* in the order in which they were added to the queue.
*/
protected Vector needsCompileList = new Vector();
-
+
protected static class Entry {
protected PackageElement element;
protected int status;
@@ -32,102 +32,91 @@ public class WorkQueue {
* Status flag. The element is unaffected by the latest changes.
*/
private static final int UNAFFECTED = 0;
-
+
/**
* Status flag. The element has been convicted and must be compiled before any other
* type can use it.
*/
private static final int NEEDS_COMPILE = 2;
-
+
/**
* Status flag. The element was affected by the changes, and was compiled as a result.
*/
private static final int COMPILED = 3;
-
- /**
- * Creates a new WorkQueue.
- */
- public WorkQueue() {
- }
-
- /**
- * Adds an element to the queue. The element is marked as NEEDS_COMPILE.
- */
- public void add(PackageElement element) {
- Entry entry = (Entry) entries.get(element);
- if (entry == null) {
- entry = new Entry(element);
- entries.put(element, entry);
- needsCompileList.addElement(element);
- } else {
- if (entry.status != NEEDS_COMPILE) {
- if (entry.status == COMPILED) {
- System.out.println(
- "Warning: image builder wants to recompile already compiled element: "
- + element);
- }
- entry.status = NEEDS_COMPILE;
- needsCompileList.addElement(element);
+
+/**
+ * Creates a new WorkQueue.
+ */
+public WorkQueue() {
+}
+/**
+ * Adds an element to the queue. The element is marked as NEEDS_COMPILE.
+ */
+public void add(PackageElement element) {
+ Entry entry = (Entry) entries.get(element);
+ if (entry == null) {
+ entry = new Entry(element);
+ entries.put(element, entry);
+ needsCompileList.addElement(element);
+ } else {
+ if (entry.status != NEEDS_COMPILE) {
+ if (entry.status == COMPILED) {
+ System.out.println("Warning: image builder wants to recompile already compiled element: " + element);
}
+ entry.status = NEEDS_COMPILE;
+ needsCompileList.addElement(element);
}
}
-
- /**
- * Marks the given element as COMPILED.
- */
- public void compiled(PackageElement element) {
- Entry entry = (Entry) entries.get(element);
- if (entry == null) {
- //System.out.println("Warning: Java builder compiled unexpected element: " + element);
- entry = new Entry(element);
- entries.put(element, entry);
- } else {
- if (entry.status != NEEDS_COMPILE) {
- System.out.println(
- "Warning: Java builder compiled the same element twice: " + element);
- }
- needsCompileList.removeElement(element);
+}
+/**
+ * Marks the given element as COMPILED.
+ */
+public void compiled(PackageElement element) {
+ Entry entry = (Entry) entries.get(element);
+ if (entry == null){
+ //System.out.println("Warning: Java builder compiled unexpected element: " + element);
+ entry = new Entry(element);
+ entries.put(element, entry);
+ } else {
+ if (entry.status != NEEDS_COMPILE) {
+ System.out.println("Warning: Java builder compiled the same element twice: " + element);
}
- entry.status = COMPILED;
-
- }
-
- /**
- * Returns true if the given element is in the queue, false otherwise.
- */
- public boolean contains(PackageElement element) {
- return entries.containsKey(element);
- }
-
- /**
- * Returns the elements which are marked NEEDS_COMPILE,
- * in the order in which they should be compiled.
- */
- public Vector getElementsToCompile() {
- // Important to clone because needsCompileList may
- // be modified while the result is being examined.
- // Also, the caller may modify the result.
- return (Vector) needsCompileList.clone();
- }
-
- /**
- * Returns true if the given element is marked as COMPILED.
- */
- public boolean hasBeenCompiled(PackageElement element) {
- Entry entry = (Entry) entries.get(element);
- return entry != null && entry.status == COMPILED;
- }
-
- /**
- * Returns true if the given element is marked as NEEDS_COMPILE.
- */
- public boolean needsCompile(PackageElement element) {
- Entry entry = (Entry) entries.get(element);
- return entry != null && entry.status == NEEDS_COMPILE;
- }
-
- public String toString() {
- return "WorkQueue: " + needsCompileList;
+ needsCompileList.removeElement(element);
}
+ entry.status = COMPILED;
}
+/**
+ * Returns true if the given element is in the queue, false otherwise.
+ */
+public boolean contains(PackageElement element) {
+ return entries.containsKey(element);
+}
+/**
+ * Returns the elements which are marked NEEDS_COMPILE,
+ * in the order in which they should be compiled.
+ */
+public Vector getElementsToCompile() {
+ // Important to clone because needsCompileList may
+ // be modified while the result is being examined.
+ // Also, the caller may modify the result.
+ return (Vector) needsCompileList.clone();
+}
+/**
+ * Returns true if the given element is marked as COMPILED.
+ */
+public boolean hasBeenCompiled(PackageElement element) {
+ Entry entry = (Entry) entries.get(element);
+ return entry != null && entry.status == COMPILED;
+}
+/**
+ * Returns true if the given element is marked as NEEDS_COMPILE.
+ */
+public boolean needsCompile(PackageElement element) {
+ Entry entry = (Entry) entries.get(element);
+ return entry != null && entry.status == NEEDS_COMPILE;
+}
+public String toString() {
+ return "WorkQueue: " + needsCompileList;
+}
+}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ZipNode.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ZipNode.java
index 5259a751d0..3149537914 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ZipNode.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/builder/impl/ZipNode.java
@@ -17,47 +17,41 @@ public class ZipNode extends AbstractNode {
* this be an IPath or an IFile?
*/
IPath fZipFile;
- /**
- * Creates a new JarNode instance.
- */
- protected ZipNode(IPath zipPath) {
- fZipFile = zipPath;
- }
-
- /**
- * Creates and returns a copy of this node.
- */
- public AbstractNode copy() {
- return new ZipNode(fZipFile);
- }
-
- /**
- * @see INode
- */
- public Object getElement() {
- return fZipFile;
- }
-
- /**
- * @see INode
- */
- public int getKind() {
- return INode.ZIP_NODE;
- }
-
- /**
- * Returns the name of the jar associated with this jar node
- */
- public IPath getZipFile() {
- return fZipFile;
- }
-
- /**
- * Prints a string representation of the node. This method is for debugging
- * purposes only.
- */
- public String toString() {
- return "ZipNode(" + fZipFile + ")";
- }
-
+/**
+ * Creates a new JarNode instance.
+ */
+protected ZipNode(IPath zipPath) {
+ fZipFile = zipPath;
+}
+/**
+ * Creates and returns a copy of this node.
+ */
+public AbstractNode copy() {
+ return new ZipNode(fZipFile);
+}
+/**
+ * @see INode
+ */
+public Object getElement() {
+ return fZipFile;
+}
+/**
+ * @see INode
+ */
+public int getKind() {
+ return INode.ZIP_NODE;
+}
+/**
+ * Returns the name of the jar associated with this jar node
+ */
+public IPath getZipFile() {
+ return fZipFile;
+}
+/**
+ * Prints a string representation of the node. This method is for debugging
+ * purposes only.
+ */
+public String toString() {
+ return "ZipNode(" + fZipFile + ")";
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
index 5078019101..2f0718b415 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/eval/EvaluationContextWrapper.java
@@ -27,315 +27,257 @@ import java.util.Locale;
public class EvaluationContextWrapper implements IEvaluationContext {
protected EvaluationContext context;
protected JavaProject project;
- /**
- * Creates a new wrapper around the given infrastructure evaluation context
- * and project.
- */
- public EvaluationContextWrapper(
- EvaluationContext context,
- JavaProject project) {
- this.context = context;
- this.project = project;
- }
-
- /**
- * @see org.eclipse.jdt.core.eval.IEvaluationContext#allVariables
- */
- public IGlobalVariable[] allVariables() {
- GlobalVariable[] vars = this.context.allVariables();
- int length = vars.length;
- GlobalVariableWrapper[] result = new GlobalVariableWrapper[length];
- for (int i = 0; i < length; i++) {
- result[i] = new GlobalVariableWrapper(vars[i]);
- }
- return result;
+/**
+ * Creates a new wrapper around the given infrastructure evaluation context
+ * and project.
+ */
+public EvaluationContextWrapper(EvaluationContext context, JavaProject project) {
+ this.context = context;
+ this.project = project;
+}
+/**
+ * @see org.eclipse.jdt.core.eval.IEvaluationContext#allVariables
+ */
+public IGlobalVariable[] allVariables() {
+ GlobalVariable[] vars = this.context.allVariables();
+ int length = vars.length;
+ GlobalVariableWrapper[] result = new GlobalVariableWrapper[length];
+ for (int i = 0; i < length; i++) {
+ result[i] = new GlobalVariableWrapper(vars[i]);
}
-
- /**
- * Checks to ensure that there is a previously built state.
- */
- protected void checkBuilderState() throws JavaModelException {
- if (!getProject().hasBuildState()) {
- throw new JavaModelException(
- new JavaModelStatus(
- IJavaModelStatusConstants.EVALUATION_ERROR,
- "Cannot evaluate if the project has not been built once"));
- }
+ return result;
+}
+/**
+ * Checks to ensure that there is a previously built state.
+ */
+protected void checkBuilderState() throws JavaModelException {
+ if (!getProject().hasBuildState()) {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.EVALUATION_ERROR, "Cannot evaluate if the project has not been built once"));
}
-
- /**
- * @see org.eclipse.jdt.core.eval.IEvaluationContext#codeComplete.
- */
- public void codeComplete(
- String codeSnippet,
- int position,
- ICodeCompletionRequestor requestor)
- throws JavaModelException {
- this.context.complete(
- codeSnippet.toCharArray(),
- position,
- this.project.getSearchableNameEnvironment(),
- new CompletionRequestorWrapper(requestor),
- JavaModelManager.convertConfigurableOptions(JavaCore.getOptions()));
+}
+/**
+ * @see org.eclipse.jdt.core.eval.IEvaluationContext#codeComplete.
+ */
+public void codeComplete(String codeSnippet, int position, ICodeCompletionRequestor requestor) throws JavaModelException {
+ this.context.complete(
+ codeSnippet.toCharArray(),
+ position,
+ this.project.getSearchableNameEnvironment(),
+ new CompletionRequestorWrapper(requestor),
+ JavaModelManager.convertConfigurableOptions(JavaCore.getOptions())
+ );
+}
+/**
+ * @see org.eclipse.jdt.core.eval.IEvaluationContext#codeSelect.
+ */
+public IJavaElement[] codeSelect(String codeSnippet, int offset, int length) throws JavaModelException {
+ SelectionRequestor requestor= new SelectionRequestor(this.project.getNameLookup(), null); // null because there is no need to look inside the code snippet itself
+ this.context.select(
+ codeSnippet.toCharArray(),
+ offset,
+ offset + length - 1,
+ this.project.getSearchableNameEnvironment(),
+ requestor,
+ JavaModelManager.convertConfigurableOptions(JavaCore.getOptions())
+ );
+ return requestor.getElements();
+}
+/**
+ * @see org.eclipse.jdt.core.eval.IEvaluationContext#deleteVariable.
+ */
+public void deleteVariable(IGlobalVariable variable) {
+ if (variable instanceof GlobalVariableWrapper) {
+ GlobalVariableWrapper wrapper = (GlobalVariableWrapper)variable;
+ this.context.deleteVariable(wrapper.variable);
+ } else {
+ throw new Error("Unknown implementation of IGlobalVariable");
}
-
- /**
- * @see org.eclipse.jdt.core.eval.IEvaluationContext#codeSelect.
- */
- public IJavaElement[] codeSelect(String codeSnippet, int offset, int length)
- throws JavaModelException {
- SelectionRequestor requestor =
- new SelectionRequestor(this.project.getNameLookup(), null);
- // null because there is no need to look inside the code snippet itself
- this.context.select(
- codeSnippet.toCharArray(),
- offset,
- offset + length,
- this.project.getSearchableNameEnvironment(),
- requestor,
- JavaModelManager.convertConfigurableOptions(JavaCore.getOptions()));
- return requestor.getElements();
+}
+/**
+ * @see IEvaluationContext#evaluateCodeSnippet
+ */
+public void evaluateCodeSnippet(
+ String codeSnippet,
+ String[] localVariableTypeNames,
+ String[] localVariableNames,
+ int[] localVariableModifiers,
+ IType declaringType,
+ boolean isStatic,
+ boolean isConstructorCall,
+ ICodeSnippetRequestor requestor,
+ IProgressMonitor progressMonitor) throws org.eclipse.jdt.core.JavaModelException {
+
+ checkBuilderState();
+
+ int length = localVariableTypeNames.length;
+ char[][] varTypeNames = new char[length][];
+ for (int i = 0; i < length; i++){
+ varTypeNames[i] = localVariableTypeNames[i].toCharArray();
}
- /**
- * @see org.eclipse.jdt.core.eval.IEvaluationContext#deleteVariable.
- */
- public void deleteVariable(IGlobalVariable variable) {
- if (variable instanceof GlobalVariableWrapper) {
- GlobalVariableWrapper wrapper = (GlobalVariableWrapper) variable;
- this.context.deleteVariable(wrapper.variable);
- } else {
- throw new Error("Unknown implementation of IGlobalVariable");
- }
+ length = localVariableNames.length;
+ char[][] varNames = new char[length][];
+ for (int i = 0; i < length; i++){
+ varNames[i] = localVariableNames[i].toCharArray();
}
- /**
- * @see IEvaluationContext#evaluateCodeSnippet
- */
- public void evaluateCodeSnippet(
- String codeSnippet,
- String[] localVariableTypeNames,
- String[] localVariableNames,
- int[] localVariableModifiers,
- IType declaringType,
- boolean isStatic,
- boolean isConstructorCall,
- ICodeSnippetRequestor requestor,
- IProgressMonitor progressMonitor)
- throws org.eclipse.jdt.core.JavaModelException {
-
- checkBuilderState();
-
- int length = localVariableTypeNames.length;
- char[][] varTypeNames = new char[length][];
- for (int i = 0; i < length; i++) {
- varTypeNames[i] = localVariableTypeNames[i].toCharArray();
- }
-
- length = localVariableNames.length;
- char[][] varNames = new char[length][];
- for (int i = 0; i < length; i++) {
- varNames[i] = localVariableNames[i].toCharArray();
- }
-
- // transfer the imports of the IType to the evaluation context
- if (declaringType != null) {
- // retrieves the package statement
- this.context.setPackageName(
- declaringType.getPackageFragment().getElementName().toCharArray());
- ICompilationUnit compilationUnit = declaringType.getCompilationUnit();
- if (compilationUnit != null) {
- // retrieves the import statement
- IImportDeclaration[] imports = compilationUnit.getImports();
- int importsLength = imports.length;
- if (importsLength != 0) {
- char[][] importsNames = new char[importsLength][];
- for (int i = 0; i < importsLength; i++) {
- importsNames[i] = imports[i].getElementName().toCharArray();
- }
- this.context.setImports(importsNames);
+ // transfer the imports of the IType to the evaluation context
+ if (declaringType != null) {
+ // retrieves the package statement
+ this.context.setPackageName(declaringType.getPackageFragment().getElementName().toCharArray());
+ ICompilationUnit compilationUnit = declaringType.getCompilationUnit();
+ if (compilationUnit != null) {
+ // retrieves the import statement
+ IImportDeclaration[] imports = compilationUnit.getImports();
+ int importsLength = imports.length;
+ if (importsLength != 0) {
+ char[][] importsNames = new char[importsLength][];
+ for (int i = 0; i < importsLength; i++) {
+ importsNames[i] = imports[i].getElementName().toCharArray();
}
+ this.context.setImports(importsNames);
}
}
- try {
- this.context.evaluate(
- codeSnippet.toCharArray(),
- varTypeNames,
- varNames,
- localVariableModifiers,
- declaringType == null
- ? null
- : declaringType.getFullyQualifiedName().toCharArray(),
- isStatic,
- isConstructorCall,
- getBuildNameEnvironment(),
- getCompilerOptions(),
- getInfrastructureEvaluationRequestor(requestor),
- getProblemFactory());
- } catch (InstallException e) {
- handleInstallException(e);
- }
- }
-
- /**
- * @see IEvaluationContext#evaluateCodeSnippet
- */
- public void evaluateCodeSnippet(
- String codeSnippet,
- ICodeSnippetRequestor requestor,
- IProgressMonitor progressMonitor)
- throws JavaModelException {
- checkBuilderState();
- try {
- this.context.evaluate(
- codeSnippet.toCharArray(),
- getBuildNameEnvironment(),
- getCompilerOptions(),
- getInfrastructureEvaluationRequestor(requestor),
- getProblemFactory());
- } catch (InstallException e) {
- handleInstallException(e);
- }
- }
-
- /**
- * @see IEvaluationContext#evaluateVariable
- */
- public void evaluateVariable(
- IGlobalVariable variable,
- ICodeSnippetRequestor requestor,
- IProgressMonitor progressMonitor)
- throws JavaModelException {
- checkBuilderState();
- try {
- this.context.evaluateVariable(
- ((GlobalVariableWrapper) variable).variable,
- getBuildNameEnvironment(),
- getCompilerOptions(),
- getInfrastructureEvaluationRequestor(requestor),
- getProblemFactory());
- } catch (InstallException e) {
- handleInstallException(e);
- }
- }
-
- /**
- * Returns a name environment for the last built state.
- */
- protected INameEnvironment getBuildNameEnvironment()
- throws JavaModelException {
- return JavaModelManager.getJavaModelManager().getNameEnvironment(
- getProject().getProject());
}
-
- /**
- * Returns the compiler's configurable options.
- */
- protected ConfigurableOption[] getCompilerOptions() throws JavaModelException {
- return JavaModelManager.convertConfigurableOptions(JavaCore.getOptions());
- }
-
- /**
- * @see org.eclipse.jdt.core.eval.IEvaluationContext#getImports
- */
- public String[] getImports() {
- char[][] imports = this.context.getImports();
- int length = imports.length;
- String[] result = new String[length];
- for (int i = 0; i < length; i++) {
- result[i] = new String(imports[i]);
- }
- return result;
- }
-
- /**
- * Returns the infrastructure evaluation context.
- */
- public EvaluationContext getInfrastructureEvaluationContext() {
- return this.context;
- }
-
- /**
- * Returns a new infrastructure evaluation requestor instance.
- */
- protected IRequestor getInfrastructureEvaluationRequestor(ICodeSnippetRequestor requestor) {
- return new RequestorWrapper(requestor);
- }
-
- /**
- * @see org.eclipse.jdt.core.eval.IEvaluationContext#getPackageName
- */
- public String getPackageName() {
- return new String(this.context.getPackageName());
- }
-
- /**
- * Returns the problem factory to be used during evaluation.
- */
- protected IProblemFactory getProblemFactory() throws JavaModelException {
- return ProblemFactory.getProblemFactory(Locale.getDefault());
- }
-
- /**
- * @see org.eclipse.jdt.core.eval.IEvaluationContext#getProject
- */
- public IJavaProject getProject() {
- return this.project;
- }
-
- /**
- * Handles an install exception by throwing a Java Model exception.
- */
- protected void handleInstallException(InstallException e)
- throws JavaModelException {
- throw new JavaModelException(
- new JavaModelStatus(IJavaModelStatusConstants.EVALUATION_ERROR, e.toString()));
+ try {
+ this.context.evaluate(
+ codeSnippet.toCharArray(),
+ varTypeNames,
+ varNames,
+ localVariableModifiers,
+ declaringType == null? null : declaringType.getFullyQualifiedName().toCharArray(),
+ isStatic,
+ isConstructorCall,
+ getBuildNameEnvironment(),
+ getCompilerOptions(),
+ getInfrastructureEvaluationRequestor(requestor),
+ getProblemFactory());
+ } catch (InstallException e) {
+ handleInstallException(e);
}
-
- /**
- * @see org.eclipse.jdt.core.eval.IEvaluationContext#newVariable
- */
- public IGlobalVariable newVariable(
- String typeName,
- String name,
- String initializer) {
- GlobalVariable newVar =
- this.context.newVariable(
- typeName.toCharArray(),
- name.toCharArray(),
- (initializer == null) ? null : initializer.toCharArray());
- return new GlobalVariableWrapper(newVar);
+}
+/**
+ * @see IEvaluationContext#evaluateCodeSnippet
+ */
+public void evaluateCodeSnippet(String codeSnippet, ICodeSnippetRequestor requestor, IProgressMonitor progressMonitor) throws JavaModelException {
+ checkBuilderState();
+ try {
+ this.context.evaluate(codeSnippet.toCharArray(), getBuildNameEnvironment(), getCompilerOptions(), getInfrastructureEvaluationRequestor(requestor), getProblemFactory());
+ } catch (InstallException e) {
+ handleInstallException(e);
}
-
- /**
- * @see org.eclipse.jdt.core.eval.IEvaluationContext#setImports
- */
- public void setImports(String[] imports) {
- int length = imports.length;
- char[][] result = new char[length][];
- for (int i = 0; i < length; i++) {
- result[i] = imports[i].toCharArray();
- }
- this.context.setImports(result);
+}
+/**
+ * @see IEvaluationContext#evaluateVariable
+ */
+public void evaluateVariable(IGlobalVariable variable, ICodeSnippetRequestor requestor, IProgressMonitor progressMonitor) throws JavaModelException {
+ checkBuilderState();
+ try {
+ this.context.evaluateVariable(
+ ((GlobalVariableWrapper)variable).variable,
+ getBuildNameEnvironment(),
+ getCompilerOptions(),
+ getInfrastructureEvaluationRequestor(requestor),
+ getProblemFactory());
+ } catch (InstallException e) {
+ handleInstallException(e);
}
-
- /**
- * @see org.eclipse.jdt.core.eval.IEvaluationContext#setPackageName
- */
- public void setPackageName(String packageName) {
- this.context.setPackageName(packageName.toCharArray());
+}
+/**
+ * Returns a name environment for the last built state.
+ */
+protected INameEnvironment getBuildNameEnvironment() throws JavaModelException {
+ return JavaModelManager.getJavaModelManager().getNameEnvironment(getProject().getProject());
+}
+/**
+ * Returns the compiler's configurable options.
+ */
+protected ConfigurableOption[] getCompilerOptions() throws JavaModelException {
+ return JavaModelManager.convertConfigurableOptions(JavaCore.getOptions());
+}
+/**
+ * @see org.eclipse.jdt.core.eval.IEvaluationContext#getImports
+ */
+public String[] getImports() {
+ char[][] imports = this.context.getImports();
+ int length = imports.length;
+ String[] result = new String[length];
+ for (int i = 0; i < length; i++) {
+ result[i] = new String(imports[i]);
}
-
- /**
- * @see IEvaluationContext#validateImports
- */
- public void validateImports(ICodeSnippetRequestor requestor)
- throws JavaModelException {
- checkBuilderState();
- this.context.evaluateImports(
- getBuildNameEnvironment(),
- getInfrastructureEvaluationRequestor(requestor),
- getProblemFactory());
+ return result;
+}
+/**
+ * Returns the infrastructure evaluation context.
+ */
+public EvaluationContext getInfrastructureEvaluationContext() {
+ return this.context;
+}
+/**
+ * Returns a new infrastructure evaluation requestor instance.
+ */
+protected IRequestor getInfrastructureEvaluationRequestor(ICodeSnippetRequestor requestor) {
+ return new RequestorWrapper(requestor);
+}
+/**
+ * @see org.eclipse.jdt.core.eval.IEvaluationContext#getPackageName
+ */
+public String getPackageName() {
+ return new String(this.context.getPackageName());
+}
+/**
+ * Returns the problem factory to be used during evaluation.
+ */
+protected IProblemFactory getProblemFactory() throws JavaModelException {
+ return ProblemFactory.getProblemFactory(Locale.getDefault());
+}
+/**
+ * @see org.eclipse.jdt.core.eval.IEvaluationContext#getProject
+ */
+public IJavaProject getProject() {
+ return this.project;
+}
+/**
+ * Handles an install exception by throwing a Java Model exception.
+ */
+protected void handleInstallException(InstallException e) throws JavaModelException {
+ throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.EVALUATION_ERROR, e.toString()));
+}
+/**
+ * @see org.eclipse.jdt.core.eval.IEvaluationContext#newVariable
+ */
+public IGlobalVariable newVariable(String typeName, String name, String initializer) {
+ GlobalVariable newVar =
+ this.context.newVariable(
+ typeName.toCharArray(),
+ name.toCharArray(),
+ (initializer == null) ?
+ null :
+ initializer.toCharArray());
+ return new GlobalVariableWrapper(newVar);
+}
+/**
+ * @see org.eclipse.jdt.core.eval.IEvaluationContext#setImports
+ */
+public void setImports(String[] imports) {
+ int length = imports.length;
+ char[][] result = new char[length][];
+ for (int i = 0; i < length; i++) {
+ result[i] = imports[i].toCharArray();
}
-
+ this.context.setImports(result);
+}
+/**
+ * @see org.eclipse.jdt.core.eval.IEvaluationContext#setPackageName
+ */
+public void setPackageName(String packageName) {
+ this.context.setPackageName(packageName.toCharArray());
+}
+/**
+ * @see IEvaluationContext#validateImports
+ */
+public void validateImports(ICodeSnippetRequestor requestor) throws JavaModelException {
+ checkBuilderState();
+ this.context.evaluateImports(getBuildNameEnvironment(), getInfrastructureEvaluationRequestor(requestor), getProblemFactory());
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/eval/GlobalVariableWrapper.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/eval/GlobalVariableWrapper.java
index 7384c8dd4b..87e78eea44 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/eval/GlobalVariableWrapper.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/eval/GlobalVariableWrapper.java
@@ -13,37 +13,33 @@ import org.eclipse.jdt.internal.eval.GlobalVariable;
*/
class GlobalVariableWrapper implements IGlobalVariable {
GlobalVariable variable;
- /**
- * Creates a new wrapper around the given infrastructure global variable.
- */
- GlobalVariableWrapper(GlobalVariable variable) {
- this.variable = variable;
- }
-
- /**
- * @see org.eclipse.jdt.core.eval.IGlobalVariable#getInitializer
- */
- public String getInitializer() {
- char[] initializer = this.variable.getInitializer();
- if (initializer != null) {
- return new String(initializer);
- } else {
- return null;
- }
- }
-
- /**
- * @see org.eclipse.jdt.core.eval.IGlobalVariable#getName
- */
- public String getName() {
- return new String(this.variable.getName());
- }
-
- /**
- * @see org.eclipse.jdt.core.eval.IGlobalVariable#getTypeName
- */
- public String getTypeName() {
- return new String(this.variable.getTypeName());
+/**
+ * Creates a new wrapper around the given infrastructure global variable.
+ */
+GlobalVariableWrapper(GlobalVariable variable) {
+ this.variable = variable;
+}
+/**
+ * @see org.eclipse.jdt.core.eval.IGlobalVariable#getInitializer
+ */
+public String getInitializer() {
+ char[] initializer = this.variable.getInitializer();
+ if (initializer != null) {
+ return new String(initializer);
+ } else {
+ return null;
}
-
+}
+/**
+ * @see org.eclipse.jdt.core.eval.IGlobalVariable#getName
+ */
+public String getName() {
+ return new String(this.variable.getName());
+}
+/**
+ * @see org.eclipse.jdt.core.eval.IGlobalVariable#getTypeName
+ */
+public String getTypeName() {
+ return new String(this.variable.getTypeName());
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/eval/RequestorWrapper.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/eval/RequestorWrapper.java
index 5f80400b6e..355d50b588 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/eval/RequestorWrapper.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/eval/RequestorWrapper.java
@@ -14,63 +14,48 @@ import org.eclipse.jdt.core.eval.ICodeSnippetRequestor;
import org.eclipse.jdt.internal.eval.IRequestor;
import org.eclipse.jdt.core.IJavaModelMarker;
-
+
public class RequestorWrapper implements IRequestor {
ICodeSnippetRequestor requestor;
- public RequestorWrapper(ICodeSnippetRequestor requestor) {
- this.requestor = requestor;
- }
-
- /**
- * @see ICodeSnippetRequestor
- */
- public boolean acceptClassFiles(
- ClassFile[] classFiles,
- char[] codeSnippetClassName) {
- int length = classFiles.length;
- byte[][] classFileBytes = new byte[length][];
- String[][] compoundNames = new String[length][];
- for (int i = 0; i < length; i++) {
- ClassFile classFile = classFiles[i];
- classFileBytes[i] = classFile.getBytes();
- char[][] classFileCompundName = classFile.getCompoundName();
- int length2 = classFileCompundName.length;
- String[] compoundName = new String[length2];
- for (int j = 0; j < length2; j++) {
- compoundName[j] = new String(classFileCompundName[j]);
- }
- compoundNames[i] = compoundName;
+public RequestorWrapper(ICodeSnippetRequestor requestor) {
+ this.requestor = requestor;
+}
+/**
+ * @see ICodeSnippetRequestor
+ */
+public boolean acceptClassFiles(ClassFile[] classFiles, char[] codeSnippetClassName) {
+ int length = classFiles.length;
+ byte[][] classFileBytes = new byte[length][];
+ String[][] compoundNames = new String[length][];
+ for (int i = 0; i < length; i++) {
+ ClassFile classFile = classFiles[i];
+ classFileBytes[i] = classFile.getBytes();
+ char[][] classFileCompundName = classFile.getCompoundName();
+ int length2 = classFileCompundName.length;
+ String[] compoundName = new String[length2];
+ for (int j = 0; j < length2; j++){
+ compoundName[j] = new String(classFileCompundName[j]);
}
- return this.requestor.acceptClassFiles(
- classFileBytes,
- compoundNames,
- codeSnippetClassName == null ? null : new String(codeSnippetClassName));
+ compoundNames[i] = compoundName;
}
-
- /**
- * @see ICodeSnippetRequestor
- */
- public void acceptProblem(
- IProblem problem,
- char[] fragmentSource,
- int fragmentKind) {
- try {
- IMarker marker =
- ResourcesPlugin.getWorkspace().getRoot().createMarker(
- IJavaModelMarker.TRANSIENT_PROBLEM);
- marker.setAttribute(IJavaModelMarker.ID, problem.getID());
- marker.setAttribute(IMarker.CHAR_START, problem.getSourceStart());
- marker.setAttribute(IMarker.CHAR_END, problem.getSourceEnd() + 1);
- marker.setAttribute(IMarker.LINE_NUMBER, problem.getSourceLineNumber());
- //marker.setAttribute(IMarker.LOCATION, "#" + problem.getSourceLineNumber());
- marker.setAttribute(IMarker.MESSAGE, problem.getMessage());
- marker.setAttribute(
- IMarker.SEVERITY,
- (problem.isWarning() ? IMarker.SEVERITY_WARNING : IMarker.SEVERITY_ERROR));
- this.requestor.acceptProblem(marker, new String(fragmentSource), fragmentKind);
- } catch (CoreException e) {
- e.printStackTrace();
- }
+ return this.requestor.acceptClassFiles(classFileBytes, compoundNames, codeSnippetClassName == null ? null : new String(codeSnippetClassName));
+}
+/**
+ * @see ICodeSnippetRequestor
+ */
+public void acceptProblem(IProblem problem, char[] fragmentSource, int fragmentKind) {
+ try {
+ IMarker marker = ResourcesPlugin.getWorkspace().getRoot().createMarker(IJavaModelMarker.TRANSIENT_PROBLEM);
+ marker.setAttribute(IJavaModelMarker.ID, problem.getID());
+ marker.setAttribute(IMarker.CHAR_START, problem.getSourceStart());
+ marker.setAttribute(IMarker.CHAR_END, problem.getSourceEnd() + 1);
+ marker.setAttribute(IMarker.LINE_NUMBER, problem.getSourceLineNumber());
+ //marker.setAttribute(IMarker.LOCATION, "#" + problem.getSourceLineNumber());
+ marker.setAttribute(IMarker.MESSAGE, problem.getMessage());
+ marker.setAttribute(IMarker.SEVERITY, (problem.isWarning() ? IMarker.SEVERITY_WARNING : IMarker.SEVERITY_ERROR));
+ this.requestor.acceptProblem(marker, new String(fragmentSource), fragmentKind);
+ } catch (CoreException e) {
+ e.printStackTrace();
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBinaryType.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBinaryType.java
index 3dd3bee3af..1ab5992ff1 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBinaryType.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBinaryType.java
@@ -15,216 +15,184 @@ public class HierarchyBinaryType implements IBinaryType {
private char[] enclosingTypeName;
private char[] superclass;
private char[][] superInterfaces = NoInterface;
- public HierarchyBinaryType(
- int modifiers,
- char[] qualification,
- char[] typeName,
- char[] enclosingTypeName,
- char classOrInterface) {
+public HierarchyBinaryType(int modifiers, char[] qualification, char[] typeName, char[] enclosingTypeName, char classOrInterface){
- this.modifiers = modifiers;
- this.isClass = classOrInterface == IIndexConstants.CLASS_SUFFIX;
+ this.modifiers = modifiers;
+ this.isClass = classOrInterface == IIndexConstants.CLASS_SUFFIX;
+ this.name = CharOperation.concat(qualification, typeName, '/');
+ if (enclosingTypeName == null){
this.name = CharOperation.concat(qualification, typeName, '/');
- if (enclosingTypeName == null) {
- this.name = CharOperation.concat(qualification, typeName, '/');
- } else {
- this.name =
- CharOperation.concat(qualification, '/', enclosingTypeName, '$', typeName);
- //rebuild A$B name
- this.enclosingTypeName =
- CharOperation.concat(qualification, enclosingTypeName, '/');
- CharOperation.replace(this.enclosingTypeName, '.', '/');
- }
- CharOperation.replace(this.name, '.', '/');
+ } else {
+ this.name = CharOperation.concat(qualification, '/', enclosingTypeName, '$', typeName); //rebuild A$B name
+ this.enclosingTypeName = CharOperation.concat(qualification, enclosingTypeName,'/');
+ CharOperation.replace(this.enclosingTypeName, '.', '/');
}
-
- /**
- * Answer the resolved name of the enclosing type in the
- * class file format as specified in section 4.2 of the Java 2 VM spec
- * or null if the receiver is a top level type.
- *
- * For example, java.lang.String is java/lang/String.
- */
- public char[] getEnclosingTypeName() {
- return this.enclosingTypeName;
- }
-
- /**
- * Answer the receiver's fields or null if the array is empty.
- */
- public IBinaryField[] getFields() {
- return null;
- }
-
- /**
- * Answer the file name which defines the type.
- *
- * The path part (optional) must be separated from the actual
- * file proper name by a java.io.File.separator.
- *
- * The proper file name includes the suffix extension (e.g. ".java")
- *
- * e.g. "c:/com/ibm/compiler/java/api/Compiler.java"
- */
- public char[] getFileName() {
- return null;
- }
-
- /**
- * Answer the resolved names of the receiver's interfaces in the
- * class file format as specified in section 4.2 of the Java 2 VM spec
- * or null if the array is empty.
- *
- * For example, java.lang.String is java/lang/String.
- */
- public char[][] getInterfaceNames() {
- return superInterfaces;
- }
-
- /**
- * Answer the receiver's nested types or null if the array is empty.
- *
- * This nested type info is extracted from the inner class attributes.
- * Ask the name environment to find a member type using its compound name.
- */
- public IBinaryNestedType[] getMemberTypes() {
- return null;
- }
-
- /**
- * Answer the receiver's methods or null if the array is empty.
- */
- public IBinaryMethod[] getMethods() {
- return null;
- }
-
- /**
- * Answer an int whose bits are set according the access constants
- * defined by the VM spec.
- */
- public int getModifiers() {
- return modifiers;
- }
-
- /**
- * Answer the resolved name of the type in the
- * class file format as specified in section 4.2 of the Java 2 VM spec.
- *
- * For example, java.lang.String is java/lang/String.
- */
- public char[] getName() {
- return name;
+ CharOperation.replace(this.name, '.', '/');
+}
+/**
+ * Answer the resolved name of the enclosing type in the
+ * class file format as specified in section 4.2 of the Java 2 VM spec
+ * or null if the receiver is a top level type.
+ *
+ * For example, java.lang.String is java/lang/String.
+ */
+public char[] getEnclosingTypeName() {
+ return this.enclosingTypeName;
+}
+/**
+ * Answer the receiver's fields or null if the array is empty.
+ */
+public IBinaryField[] getFields() {
+ return null;
+}
+/**
+ * Answer the file name which defines the type.
+ *
+ * The path part (optional) must be separated from the actual
+ * file proper name by a java.io.File.separator.
+ *
+ * The proper file name includes the suffix extension (e.g. ".java")
+ *
+ * e.g. "c:/com/ibm/compiler/java/api/Compiler.java"
+ */
+public char[] getFileName() {
+ return null;
+}
+/**
+ * Answer the resolved names of the receiver's interfaces in the
+ * class file format as specified in section 4.2 of the Java 2 VM spec
+ * or null if the array is empty.
+ *
+ * For example, java.lang.String is java/lang/String.
+ */
+public char[][] getInterfaceNames() {
+ return superInterfaces;
+}
+/**
+ * Answer the receiver's nested types or null if the array is empty.
+ *
+ * This nested type info is extracted from the inner class attributes.
+ * Ask the name environment to find a member type using its compound name.
+ */
+public IBinaryNestedType[] getMemberTypes() {
+ return null;
+}
+/**
+ * Answer the receiver's methods or null if the array is empty.
+ */
+public IBinaryMethod[] getMethods() {
+ return null;
+}
+/**
+ * Answer an int whose bits are set according the access constants
+ * defined by the VM spec.
+ */
+public int getModifiers() {
+ return modifiers;
+}
+/**
+ * Answer the resolved name of the type in the
+ * class file format as specified in section 4.2 of the Java 2 VM spec.
+ *
+ * For example, java.lang.String is java/lang/String.
+ */
+public char[] getName() {
+ return name;
+}
+/**
+ * Answer the resolved name of the receiver's superclass in the
+ * class file format as specified in section 4.2 of the Java 2 VM spec
+ * or null if it does not have one.
+ *
+ * For example, java.lang.String is java/lang/String.
+ */
+public char[] getSuperclassName() {
+ return superclass;
+}
+/**
+ * Answer whether the receiver contains the resolved binary form
+ * or the unresolved source form of the type.
+ */
+public boolean isBinaryType() {
+ return true;
+}
+/**
+ * isClass method comment.
+ */
+public boolean isClass() {
+ return isClass;
+}
+/**
+ * isInterface method comment.
+ */
+public boolean isInterface() {
+ return !isClass;
+}
+public void recordSuperType(char[] superTypeName, char[] superQualification, char superClassOrInterface){
+
+ // index encoding of p.A$B was B/p.A$, rebuild the proper name
+ if (superQualification != null){
+ int length = superQualification.length;
+ if (superQualification[length-1] == '$'){
+ char[] enclosingSuperName = CharOperation.lastSegment(superQualification, '.');
+ superTypeName = CharOperation.concat(enclosingSuperName, superTypeName);
+ superQualification = CharOperation.subarray(superQualification, 0, length - enclosingSuperName.length - 1);
+ }
}
-
- /**
- * Answer the resolved name of the receiver's superclass in the
- * class file format as specified in section 4.2 of the Java 2 VM spec
- * or null if it does not have one.
- *
- * For example, java.lang.String is java/lang/String.
- */
- public char[] getSuperclassName() {
- return superclass;
+
+ if (superClassOrInterface == IIndexConstants.CLASS_SUFFIX){
+ // interfaces are indexed as having superclass references to Object by default,
+ // this is an artifact used for being able to query them only.
+ if (!this.isClass) return;
+ char[] encodedName = CharOperation.concat(superQualification, superTypeName, '/');
+ CharOperation.replace(encodedName, '.', '/');
+ this.superclass = encodedName;
+ } else {
+ char[] encodedName = CharOperation.concat(superQualification, superTypeName, '/');
+ CharOperation.replace(encodedName, '.', '/');
+ if (this.superInterfaces == NoInterface){
+ this.superInterfaces = new char[][] { encodedName };
+ } else {
+ int length = this.superInterfaces.length;
+ System.arraycopy(this.superInterfaces, 0, this.superInterfaces = new char[length+1][], 0, length);
+ this.superInterfaces[length] = encodedName;
+ }
}
-
- /**
- * Answer whether the receiver contains the resolved binary form
- * or the unresolved source form of the type.
- */
- public boolean isBinaryType() {
- return true;
+}
+public String toString() {
+ StringBuffer buffer = new StringBuffer();
+ if (this.modifiers == IConstants.AccPublic) {
+ buffer.append("public ");
}
-
- /**
- * isClass method comment.
- */
- public boolean isClass() {
- return isClass;
+ if (this.isClass()) {
+ buffer.append("class ");
+ } else {
+ buffer.append("interface ");
}
-
- /**
- * isInterface method comment.
- */
- public boolean isInterface() {
- return !isClass;
+ if (this.name != null) {
+ buffer.append(this.name);
}
-
- public void recordSuperType(
- char[] superTypeName,
- char[] superQualification,
- char superClassOrInterface) {
-
- // index encoding of p.A$B was B/p.A$, rebuild the proper name
- if (superQualification != null) {
- int length = superQualification.length;
- if (superQualification[length - 1] == '$') {
- char[] enclosingSuperName = CharOperation.lastSegment(superQualification, '.');
- superTypeName = CharOperation.concat(enclosingSuperName, superTypeName);
- superQualification =
- CharOperation.subarray(
- superQualification,
- 0,
- length - enclosingSuperName.length - 1);
- }
- }
-
- if (superClassOrInterface == IIndexConstants.CLASS_SUFFIX) {
- // interfaces are indexed as having superclass references to Object by default,
- // this is an artifact used for being able to query them only.
- if (!this.isClass)
- return;
- char[] encodedName =
- CharOperation.concat(superQualification, superTypeName, '/');
- CharOperation.replace(encodedName, '.', '/');
- this.superclass = encodedName;
- } else {
- char[] encodedName =
- CharOperation.concat(superQualification, superTypeName, '/');
- CharOperation.replace(encodedName, '.', '/');
- if (this.superInterfaces == NoInterface) {
- this.superInterfaces = new char[][] { encodedName };
- } else {
- int length = this.superInterfaces.length;
- System.arraycopy(
- this.superInterfaces,
- 0,
- this.superInterfaces = new char[length + 1][],
- 0,
- length);
- this.superInterfaces[length] = encodedName;
- }
- }
+ if (this.superclass != null) {
+ buffer.append("\n extends ");
+ buffer.append(this.superclass);
}
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- if (this.modifiers == IConstants.AccPublic) {
- buffer.append("public ");
- }
- if (this.isClass()) {
- buffer.append("class ");
- } else {
- buffer.append("interface ");
- }
- if (this.name != null) {
- buffer.append(this.name);
- }
- if (this.superclass != null) {
- buffer.append("\n extends ");
- buffer.append(this.superclass);
- }
- int length;
- if (this.superInterfaces != null
- && (length = this.superInterfaces.length) != 0) {
- buffer.append("\n implements ");
- for (int i = 0; i < length; i++) {
- buffer.append(this.superInterfaces[i]);
- if (i != length - 1) {
- buffer.append(", ");
- }
+ int length;
+ if (this.superInterfaces != null && (length = this.superInterfaces.length) != 0) {
+ buffer.append("\n implements ");
+ for (int i = 0; i < length; i++) {
+ buffer.append(this.superInterfaces[i]);
+ if (i != length - 1) {
+ buffer.append(", ");
}
}
- return buffer.toString();
}
+ return buffer.toString();
+}
+/**
+ * @see org.eclipse.jdt.internal.compiler.env.IBinaryType.
+ */
+public char[] sourceFileName() {
+ return null;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
index 398c269975..6e953a860f 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/HierarchyBuilder.java
@@ -20,12 +20,14 @@ import org.eclipse.jdt.internal.core.*;
import java.util.Hashtable;
import java.util.Vector;
+import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
+
public abstract class HierarchyBuilder implements IHierarchyRequestor {
/**
* The hierarchy being built.
*/
protected TypeHierarchy hierarchy;
-
+
/**
* The name environment used by the HierarchyResolver
*/
@@ -49,156 +51,138 @@ public abstract class HierarchyBuilder implements IHierarchyRequestor {
* the region).
*/
protected Hashtable infoToHandle;
- public HierarchyBuilder(TypeHierarchy hierarchy) throws JavaModelException {
- this.hierarchy = hierarchy;
- JavaProject project = (JavaProject) hierarchy.javaProject();
- this.searchableEnvironment =
- (SearchableEnvironment) project.getSearchableNameEnvironment();
- this.nameLookup = project.getNameLookup();
- this.hierarchyResolver =
- new HierarchyResolver(this.searchableEnvironment, this, new ProblemFactory());
- this.infoToHandle = new Hashtable(5);
+public HierarchyBuilder(TypeHierarchy hierarchy) throws JavaModelException {
+ this.hierarchy = hierarchy;
+ JavaProject project = (JavaProject)hierarchy.javaProject();
+ this.searchableEnvironment = (SearchableEnvironment)project.getSearchableNameEnvironment();
+ this.nameLookup = project.getNameLookup();
+ this.hierarchyResolver =
+ new HierarchyResolver(this.searchableEnvironment, this, new DefaultProblemFactory());
+ this.infoToHandle = new Hashtable(5);
+}
+public abstract void build(boolean computeSubtypes) throws JavaModelException, CoreException;
+/**
+ * Configure this type hierarchy by computing the supertypes only.
+ */
+protected void buildSupertypes() {
+ IType focusType = this.getType();
+ if (focusType == null) return;
+
+ // get generic type from focus type
+ IGenericType type;
+ try {
+ type = (IGenericType)((JavaElement) focusType).getRawInfo();
+ } catch (JavaModelException e) {
+ // if the focus type is not present, or if cannot get workbench path
+ // we cannot create the hierarchy
+ return;
}
- public abstract void build(boolean computeSubtypes)
- throws JavaModelException, CoreException;
- /**
- * Configure this type hierarchy by computing the supertypes only.
- */
- protected void buildSupertypes() {
- IType focusType = this.getType();
- if (focusType == null)
- return;
-
- // get generic type from focus type
- IGenericType type;
- try {
- type = (IGenericType) ((JavaElement) focusType).getRawInfo();
- } catch (JavaModelException e) {
- // if the focus type is not present, or if cannot get workbench path
- // we cannot create the hierarchy
- return;
- }
-
- // resolve
- this.searchableEnvironment.unitToLookInside =
- (CompilationUnit) focusType.getCompilationUnit();
- this.hierarchyResolver.resolve(type);
- this.searchableEnvironment.unitToLookInside = null;
+ // resolve
+ this.searchableEnvironment.unitToLookInside = (CompilationUnit)focusType.getCompilationUnit();
+ this.hierarchyResolver.resolve(type);
+ this.searchableEnvironment.unitToLookInside = null;
- // Add focus if not already in (case of a type with no explicit super type)
- if (!this.hierarchy.contains(focusType)) {
- this.hierarchy.addRootClass(focusType);
- }
+ // Add focus if not already in (case of a type with no explicit super type)
+ if (!this.hierarchy.contains(focusType)) {
+ this.hierarchy.addRootClass(focusType);
}
+}
+/**
+ * @see IHierarchyRequestor
+ */
+public void connect(IGenericType suppliedType, IGenericType superclass, IGenericType[] superinterfaces) {
- /**
- * @see IHierarchyRequestor
- */
- public void connect(
- IGenericType suppliedType,
- IGenericType superclass,
- IGenericType[] superinterfaces) {
-
- this.worked(1);
-
- // convert all infos to handles
- IType typeHandle = getHandle(suppliedType);
-
- /*
- * Temporary workaround for 1G2O5WK: ITPJCORE:WINNT - NullPointerException when selecting "Show in Type Hierarchy" for a inner class
- */
- if (typeHandle == null)
- return;
+ this.worked(1);
+
+ // convert all infos to handles
+ IType typeHandle= getHandle(suppliedType);
- IType superHandle = null;
- if (superclass != null) {
- superHandle = getHandle(superclass);
- }
- IType[] interfaceHandles = null;
- if (superinterfaces != null && superinterfaces.length > 0) {
- interfaceHandles = new IType[superinterfaces.length];
- for (int i = 0; i < interfaceHandles.length; i++) {
- interfaceHandles[i] = getHandle(superinterfaces[i]);
- }
+ /*
+ * Temporary workaround for 1G2O5WK: ITPJCORE:WINNT - NullPointerException when selecting "Show in Type Hierarchy" for a inner class
+ */
+ if (typeHandle == null) return;
+
+ IType superHandle= null;
+ if (superclass != null) {
+ superHandle= getHandle(superclass);
+ }
+ IType[] interfaceHandles= null;
+ if (superinterfaces != null && superinterfaces.length > 0) {
+ interfaceHandles= new IType[superinterfaces.length];
+ for (int i= 0; i < interfaceHandles.length; i++) {
+ interfaceHandles[i]= getHandle(superinterfaces[i]);
}
+ }
- // now do the caching
- if (suppliedType.isClass()) {
- if (superHandle == null) {
- this.hierarchy.addRootClass(typeHandle);
- } else {
- this.hierarchy.cacheSuperclass(typeHandle, superHandle);
- }
+ // now do the caching
+ if (suppliedType.isClass()) {
+ if (superHandle == null) {
+ this.hierarchy.addRootClass(typeHandle);
} else {
- this.hierarchy.addInterface(typeHandle);
- }
-
- if (interfaceHandles == null) {
- interfaceHandles = this.hierarchy.fgEmpty;
+ this.hierarchy.cacheSuperclass(typeHandle, superHandle);
}
- this.hierarchy.cacheSuperInterfaces(typeHandle, interfaceHandles);
- }
-
- /**
- * Returns a handle for the given generic type or null if not found.
- */
- protected IType getHandle(IGenericType genericType) {
- if (genericType.isBinaryType()) {
- IClassFile classFile = (IClassFile) this.infoToHandle.get(genericType);
- // if it's null, it's from outside the region, so do lookup
- if (classFile == null) {
- IType handle = lookupBinaryHandle((IBinaryType) genericType);
- if (handle == null)
- return null;
- // case of an anonymous type (see 1G2O5WK: ITPJCORE:WINNT - NullPointerException when selecting "Show in Type Hierarchy" for a inner class)
-
- // optimization: remember the handle for next call (case of java.io.Serializable that a lot of classes implement)
- this.infoToHandle.put(genericType, handle.getParent());
- return handle;
- } else {
- try {
- return classFile.getType();
- } catch (JavaModelException e) {
- return null;
- }
- }
- } else
- if (genericType instanceof SourceTypeElementInfo) {
- return ((SourceTypeElementInfo) genericType).getHandle();
- } else
- return null;
+ } else {
+ this.hierarchy.addInterface(typeHandle);
}
- protected IType getType() {
- return this.hierarchy.getType();
+ if (interfaceHandles == null) {
+ interfaceHandles= this.hierarchy.fgEmpty;
}
-
- /**
- * Looks up and returns a handle for the given binary info.
- */
- protected IType lookupBinaryHandle(IBinaryType typeInfo) {
- int flag;
- String qualifiedName;
- if (typeInfo.isClass()) {
- flag = this.nameLookup.ACCEPT_CLASSES;
+ this.hierarchy.cacheSuperInterfaces(typeHandle, interfaceHandles);
+}
+/**
+ * Returns a handle for the given generic type or null if not found.
+ */
+protected IType getHandle(IGenericType genericType) {
+ if (genericType.isBinaryType()) {
+ IClassFile classFile = (IClassFile)this.infoToHandle.get(genericType);
+ // if it's null, it's from outside the region, so do lookup
+ if (classFile == null) {
+ IType handle = lookupBinaryHandle((IBinaryType)genericType);
+ if (handle == null) return null; // case of an anonymous type (see 1G2O5WK: ITPJCORE:WINNT - NullPointerException when selecting "Show in Type Hierarchy" for a inner class)
+
+ // optimization: remember the handle for next call (case of java.io.Serializable that a lot of classes implement)
+ this.infoToHandle.put(genericType, handle.getParent());
+ return handle;
} else {
- flag = this.nameLookup.ACCEPT_INTERFACES;
+ try {
+ return classFile.getType();
+ } catch (JavaModelException e) {
+ return null;
+ }
}
- char[] bName = typeInfo.getName();
- qualifiedName = new String(ClassFile.translatedName(bName));
- return this.nameLookup.findType(qualifiedName, false, flag);
+ } else if (genericType instanceof SourceTypeElementInfo) {
+ return ((SourceTypeElementInfo)genericType).getHandle();
+ } else
+ return null;
+}
+protected IType getType() {
+ return this.hierarchy.getType();
+}
+/**
+ * Looks up and returns a handle for the given binary info.
+ */
+protected IType lookupBinaryHandle(IBinaryType typeInfo) {
+ int flag;
+ String qualifiedName;
+ if (typeInfo.isClass()) {
+ flag = this.nameLookup.ACCEPT_CLASSES;
+ } else {
+ flag = this.nameLookup.ACCEPT_INTERFACES;
}
-
- protected void worked(int work) {
- IProgressMonitor progressMonitor = this.hierarchy.fProgressMonitor;
- if (progressMonitor != null) {
- if (progressMonitor.isCanceled()) {
- throw new OperationCanceledException();
- } else {
- progressMonitor.worked(work);
- }
+ char[] bName = typeInfo.getName();
+ qualifiedName = new String(ClassFile.translatedName(bName));
+ return this.nameLookup.findType(qualifiedName, false, flag);
+}
+protected void worked(int work) {
+ IProgressMonitor progressMonitor = this.hierarchy.fProgressMonitor;
+ if (progressMonitor != null) {
+ if (progressMonitor.isCanceled()) {
+ throw new OperationCanceledException();
+ } else {
+ progressMonitor.worked(work);
}
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java
index c306256693..0877d9960c 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/IndexBasedHierarchyBuilder.java
@@ -27,6 +27,8 @@ import org.eclipse.jdt.internal.core.*;
import org.eclipse.jdt.internal.compiler.util.HashtableOfObject;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
+import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
+
public class IndexBasedHierarchyBuilder extends HierarchyBuilder {
/**
* A temporary cache of compilation units to handles to speed info
@@ -45,7 +47,7 @@ public class IndexBasedHierarchyBuilder extends HierarchyBuilder {
* Cache used to record binaries recreated from index matches
*/
protected Hashtable binariesFromIndexMatches;
-
+
/**
* Collection used to queue subtype index queries
*/
@@ -53,505 +55,436 @@ public class IndexBasedHierarchyBuilder extends HierarchyBuilder {
public char[][] names = new char[10][];
public int start = 0;
public int end = -1;
- public void add(char[] name) {
- if (++this.end == this.names.length) {
+ public void add(char[] name){
+ if (++this.end == this.names.length){
this.end -= this.start;
- System.arraycopy(
- this.names,
- this.start,
- this.names = new char[this.end * 2][],
- 0,
- this.end);
+ System.arraycopy(this.names, this.start, this.names = new char[this.end*2][], 0, this.end);
this.start = 0;
}
this.names[this.end] = name;
}
- public char[] retrieve() {
- if (this.start > this.end)
- return null; // none
-
+ public char[] retrieve(){
+ if (this.start > this.end) return null; // none
+
char[] name = this.names[this.start++];
- if (this.start > this.end) {
+ if (this.start > this.end){
this.start = 0;
this.end = -1;
}
return name;
}
- public String toString() {
+ public String toString(){
StringBuffer buffer = new StringBuffer("Queue:\n");
- for (int i = this.start; i <= this.end; i++) {
- buffer.append(names[i]).append('\n');
+ for (int i = this.start; i <= this.end; i++){
+ buffer.append(names[i]).append('\n');
}
return buffer.toString();
}
}
-
- public IndexBasedHierarchyBuilder(
- TypeHierarchy hierarchy,
- IJavaSearchScope scope)
- throws JavaModelException {
- super(hierarchy);
- this.cuToHandle = new Hashtable(5);
- this.binariesFromIndexMatches = new Hashtable(10);
- this.scope = scope;
- }
-
- /**
- * Add the type info from the given hierarchy binary type to the given list of infos.
- */
- private void addInfoFromBinaryIndexMatch(
- Openable handle,
- HierarchyBinaryType binaryType,
- Vector infos)
- throws JavaModelException {
- infos.addElement(binaryType);
- this.infoToHandle.put(binaryType, handle);
+public IndexBasedHierarchyBuilder(TypeHierarchy hierarchy, IJavaSearchScope scope) throws JavaModelException {
+ super(hierarchy);
+ this.cuToHandle = new Hashtable(5);
+ this.binariesFromIndexMatches = new Hashtable(10);
+ this.scope = scope;
+}
+/**
+ * Add the type info from the given hierarchy binary type to the given list of infos.
+ */
+private void addInfoFromBinaryIndexMatch(Openable handle, HierarchyBinaryType binaryType, Vector infos) throws JavaModelException {
+ infos.addElement(binaryType);
+ this.infoToHandle.put(binaryType, handle);
+}
+/**
+ * Add the type info from the given class file to the given list of infos.
+ */
+private void addInfoFromOpenClassFile(ClassFile classFile, Vector infos) throws JavaModelException {
+ IType type = classFile.getType();
+ IGenericType info = (IGenericType) ((BinaryType) type).getRawInfo();
+ infos.addElement(info);
+ this.infoToHandle.put(info, classFile);
+}
+/**
+ * Add the type info from the given CU to the given list of infos.
+ */
+private void addInfoFromOpenCU(CompilationUnit cu, Vector infos) throws JavaModelException {
+ IType[] types = cu.getTypes();
+ for (int j = 0; j < types.length; j++) {
+ SourceType type = (SourceType)types[j];
+ this.addInfoFromOpenSourceType(type, infos);
}
-
- /**
- * Add the type info from the given class file to the given list of infos.
- */
- private void addInfoFromOpenClassFile(ClassFile classFile, Vector infos)
- throws JavaModelException {
- IType type = classFile.getType();
- IGenericType info = (IGenericType) ((BinaryType) type).getRawInfo();
- infos.addElement(info);
- this.infoToHandle.put(info, classFile);
+}
+/**
+ * Add the type info from the given CU to the given list of infos.
+ */
+private void addInfoFromOpenSourceType(SourceType type, Vector infos) throws JavaModelException {
+ IGenericType info = (IGenericType)type.getRawInfo();
+ infos.addElement(info);
+ this.infoToHandle.put(info, type);
+ IType[] members = type.getTypes();
+ for (int i = 0; i < members.length; i++) {
+ this.addInfoFromOpenSourceType((SourceType)members[i], infos);
}
-
- /**
- * Add the type info from the given CU to the given list of infos.
- */
- private void addInfoFromOpenCU(CompilationUnit cu, Vector infos)
- throws JavaModelException {
- IType[] types = cu.getTypes();
- for (int j = 0; j < types.length; j++) {
- SourceType type = (SourceType) types[j];
- this.addInfoFromOpenSourceType(type, infos);
+}
+public void build(boolean computeSubtypes) throws JavaModelException, CoreException {
+ if (computeSubtypes) {
+ String[] allPossibleSubtypes = this.determinePossibleSubTypes();
+ if (allPossibleSubtypes != null) {
+ this.hierarchy.initialize(allPossibleSubtypes.length);
+ buildFromPotentialSubtypes(allPossibleSubtypes);
}
+ } else {
+ this.hierarchy.initialize(1);
+ this.buildSupertypes();
}
-
- /**
- * Add the type info from the given CU to the given list of infos.
- */
- private void addInfoFromOpenSourceType(SourceType type, Vector infos)
- throws JavaModelException {
- IGenericType info = (IGenericType) type.getRawInfo();
- infos.addElement(info);
- this.infoToHandle.put(info, type);
- IType[] members = type.getTypes();
- for (int i = 0; i < members.length; i++) {
- this.addInfoFromOpenSourceType((SourceType) members[i], infos);
+}
+private void buildForProject(JavaProject project, Vector infos, Vector units) throws JavaModelException {
+ IType focusType = this.getType();
+ if (focusType != null && focusType.getJavaProject().equals(project)) {
+ // add focus type
+ try {
+ infos.addElement(((JavaElement) focusType).getRawInfo());
+ } catch (JavaModelException e) {
+ // if the focus type is not present, or if cannot get workbench path
+ // we cannot create the hierarchy
+ return;
}
}
-
- public void build(boolean computeSubtypes)
- throws JavaModelException, CoreException {
- if (computeSubtypes) {
- String[] allPossibleSubtypes = this.determinePossibleSubTypes();
- if (allPossibleSubtypes != null) {
- this.hierarchy.initialize(allPossibleSubtypes.length);
- buildFromPotentialSubtypes(allPossibleSubtypes);
- }
- } else {
- this.hierarchy.initialize(1);
- this.buildSupertypes();
- }
+
+ // copy vectors into arrays
+ IGenericType[] genericTypes;
+ int infosSize = infos.size();
+ if (infosSize > 0) {
+ genericTypes = new IGenericType[infosSize];
+ infos.copyInto(genericTypes);
+ } else {
+ genericTypes = new IGenericType[0];
+ }
+ ICompilationUnit[] compilationUnits;
+ int unitsSize = units.size();
+ if (unitsSize > 0) {
+ compilationUnits = new ICompilationUnit[unitsSize];
+ units.copyInto(compilationUnits);
+ } else {
+ compilationUnits = new ICompilationUnit[0];
}
- private void buildForProject(JavaProject project, Vector infos, Vector units)
- throws JavaModelException {
- IType focusType = this.getType();
+ // resolve
+ if (infosSize > 0 || unitsSize > 0) {
+ this.searchableEnvironment = (SearchableEnvironment)project.getSearchableNameEnvironment();
if (focusType != null && focusType.getJavaProject().equals(project)) {
- // add focus type
- try {
- infos.addElement(((JavaElement) focusType).getRawInfo());
- } catch (JavaModelException e) {
- // if the focus type is not present, or if cannot get workbench path
- // we cannot create the hierarchy
- return;
- }
+ this.searchableEnvironment.unitToLookInside = (CompilationUnit)focusType.getCompilationUnit();
}
-
- // copy vectors into arrays
- IGenericType[] genericTypes;
- int infosSize = infos.size();
- if (infosSize > 0) {
- genericTypes = new IGenericType[infosSize];
- infos.copyInto(genericTypes);
- } else {
- genericTypes = new IGenericType[0];
- }
- ICompilationUnit[] compilationUnits;
- int unitsSize = units.size();
- if (unitsSize > 0) {
- compilationUnits = new ICompilationUnit[unitsSize];
- units.copyInto(compilationUnits);
- } else {
- compilationUnits = new ICompilationUnit[0];
- }
-
- // resolve
- if (infosSize > 0 || unitsSize > 0) {
- this.searchableEnvironment =
- (SearchableEnvironment) project.getSearchableNameEnvironment();
- if (focusType != null && focusType.getJavaProject().equals(project)) {
- this.searchableEnvironment.unitToLookInside =
- (CompilationUnit) focusType.getCompilationUnit();
- }
- this.nameLookup = project.getNameLookup();
- this.hierarchyResolver =
- new HierarchyResolver(this.searchableEnvironment, this, new ProblemFactory());
- this.hierarchyResolver.resolve(genericTypes, compilationUnits);
- if (focusType != null && focusType.getJavaProject().equals(project)) {
- this.searchableEnvironment.unitToLookInside = null;
- }
+ this.nameLookup = project.getNameLookup();
+ this.hierarchyResolver =
+ new HierarchyResolver(this.searchableEnvironment, this, new DefaultProblemFactory());
+ this.hierarchyResolver.resolve(genericTypes, compilationUnits);
+ if (focusType != null && focusType.getJavaProject().equals(project)) {
+ this.searchableEnvironment.unitToLookInside = null;
}
}
-
- /**
- * Configure this type hierarchy based on the given potential subtypes.
+}
+/**
+ * Configure this type hierarchy based on the given potential subtypes.
+ */
+private void buildFromPotentialSubtypes(String[] allPotentialSubTypes) {
+ // sort by projects
+ /*
+ * NOTE: To workaround pb with hierarchy resolver that requests top
+ * level types in the process of caching an enclosing type, this needs to
+ * be sorted in reverse alphabetical order so that top level types are cached
+ * before their inner types.
*/
- private void buildFromPotentialSubtypes(String[] allPotentialSubTypes) {
- // sort by projects
- /*
- * NOTE: To workaround pb with hierarchy resolver that requests top
- * level types in the process of caching an enclosing type, this needs to
- * be sorted in reverse alphabetical order so that top level types are cached
- * before their inner types.
- */
- Util.sortReverseOrder(allPotentialSubTypes);
-
- Vector infos = new Vector();
- Vector units = new Vector();
-
- IType focusType = this.getType();
-
- // create element infos for subtypes
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- IWorkspace workspace = focusType.getJavaProject().getProject().getWorkspace();
- HandleFactory factory = new HandleFactory(workspace.getRoot(), manager);
- IJavaProject currentProject = null;
- for (int i = 0, length = allPotentialSubTypes.length; i < length; i++) {
- try {
- String resourcePath = allPotentialSubTypes[i];
- Openable handle = factory.createOpenable(resourcePath);
- if (handle == null)
- continue; // match is outside classpath
- IJavaProject project = handle.getJavaProject();
- if (currentProject == null) {
- currentProject = project;
- infos = new Vector(5);
- units = new Vector(5);
- } else
- if (!currentProject.equals(project)) {
- this.buildForProject((JavaProject) currentProject, infos, units);
- currentProject = project;
- infos = new Vector(5);
- units = new Vector(5);
- }
- if (handle.isOpen()) {
- // reuse the info from the java model cache
- if (handle instanceof CompilationUnit) {
- this.addInfoFromOpenCU((CompilationUnit) handle, infos);
- } else
- if (handle instanceof ClassFile) {
- this.addInfoFromOpenClassFile((ClassFile) handle, infos);
- }
+ Util.sortReverseOrder(allPotentialSubTypes);
+
+ Vector infos = new Vector();
+ Vector units = new Vector();
+
+ IType focusType = this.getType();
+
+ // create element infos for subtypes
+ JavaModelManager manager = JavaModelManager.getJavaModelManager();
+ IWorkspace workspace = focusType.getJavaProject().getProject().getWorkspace();
+ HandleFactory factory = new HandleFactory(workspace.getRoot(), manager);
+ IJavaProject currentProject = null;
+ for (int i = 0, length = allPotentialSubTypes.length; i < length; i++) {
+ try {
+ String resourcePath = allPotentialSubTypes[i];
+ Openable handle = factory.createOpenable(resourcePath);
+ if (handle == null) continue; // match is outside classpath
+ IJavaProject project = handle.getJavaProject();
+ if (currentProject == null) {
+ currentProject = project;
+ infos = new Vector(5);
+ units = new Vector(5);
+ } else if (!currentProject.equals(project)) {
+ this.buildForProject((JavaProject)currentProject, infos, units);
+ currentProject = project;
+ infos = new Vector(5);
+ units = new Vector(5);
+ }
+ if (handle.isOpen()) {
+ // reuse the info from the java model cache
+ if (handle instanceof CompilationUnit) {
+ this.addInfoFromOpenCU((CompilationUnit)handle, infos);
+ } else if (handle instanceof ClassFile) {
+ this.addInfoFromOpenClassFile((ClassFile)handle, infos);
+ }
+ } else {
+ HierarchyBinaryType binaryType = (HierarchyBinaryType) binariesFromIndexMatches.get(resourcePath);
+ if (binaryType != null){
+ this.addInfoFromBinaryIndexMatch(handle, binaryType, infos);
} else {
- HierarchyBinaryType binaryType =
- (HierarchyBinaryType) binariesFromIndexMatches.get(resourcePath);
- if (binaryType != null) {
- this.addInfoFromBinaryIndexMatch(handle, binaryType, infos);
+ // create a temporary info
+ IJavaElement pkg = handle.getParent();
+ PackageFragmentRoot root = (PackageFragmentRoot)pkg.getParent();
+ if (root.isArchive()) {
+ // class file in a jar
+ this.createInfoFromClassFileInJar(handle, infos);
} else {
- // create a temporary info
- IJavaElement pkg = handle.getParent();
- PackageFragmentRoot root = (PackageFragmentRoot) pkg.getParent();
- if (root.isArchive()) {
- // class file in a jar
- this.createInfoFromClassFileInJar(handle, infos);
- } else {
- // file in a directory
- IPath path = new Path(resourcePath);
- IFile file = workspace.getRoot().getFile(path);
- String osPath = file.getLocation().toOSString();
+ // file in a directory
+ IPath path = new Path(resourcePath);
+ IFile file = workspace.getRoot().getFile(path);
+ IPath location = file.getLocation();
+ if (location != null){
+ String osPath = location.toOSString();
if (handle instanceof CompilationUnit) {
// compilation unit in a directory
this.createCompilationUnitFromPath(handle, osPath, units);
- } else
- if (handle instanceof ClassFile) {
- // class file in a directory
- this.createInfoFromClassFile(handle, osPath, infos);
- }
+ } else if (handle instanceof ClassFile) {
+ // class file in a directory
+ this.createInfoFromClassFile(handle, osPath, infos);
+ }
}
}
}
- worked(1);
- } catch (JavaModelException e) {
- continue;
}
- }
- try {
- if (currentProject == null)
- currentProject = focusType.getJavaProject(); // case of no potential subtypes
- this.buildForProject((JavaProject) currentProject, infos, units);
+ worked(1);
} catch (JavaModelException e) {
- }
-
- // Add focus if not already in (case of a type with no explicit super type)
- if (!this.hierarchy.contains(focusType)) {
- this.hierarchy.addRootClass(focusType);
+ continue;
}
}
-
- /**
- * Create an ICompilationUnit info from the given compilation unit on disk and
- * adds it to the given list of units.
- */
- private void createCompilationUnitFromPath(
- Openable handle,
- String osPath,
- Vector units)
- throws JavaModelException {
- BasicCompilationUnit unit = new BasicCompilationUnit(null, osPath);
- units.addElement(unit);
- this.cuToHandle.put(unit, handle);
+ try {
+ if (currentProject == null) currentProject = focusType.getJavaProject(); // case of no potential subtypes
+ this.buildForProject((JavaProject)currentProject, infos, units);
+ } catch (JavaModelException e) {
}
-
- /**
- * Creates the type info from the given class file on disk and
- * adds it to the given list of infos.
- */
- private void createInfoFromClassFile(
- Openable handle,
- String osPath,
- Vector infos)
- throws JavaModelException {
- IGenericType info = null;
+
+ // Compute hierarchy of focus type if not already done (case of a type with potential subtypes that are not real subtypes)
+ if (!this.hierarchy.contains(focusType)) {
try {
- info = org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(osPath);
- } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException e) {
- e.printStackTrace();
- return;
- } catch (java.io.IOException e) {
- e.printStackTrace();
- return;
+ currentProject = focusType.getJavaProject();
+ this.buildForProject((JavaProject)currentProject, new Vector(), new Vector());
+ } catch (JavaModelException e) {
}
- infos.addElement(info);
- this.infoToHandle.put(info, handle);
}
-
- /**
- * Create a type info from the given class file in a jar and adds it to the given list of infos.
- */
- private void createInfoFromClassFileInJar(Openable classFile, Vector infos)
- throws JavaModelException {
- IJavaElement pkg = classFile.getParent();
- String classFilePath =
- pkg.getElementName().replace('.', '/') + "/" + classFile.getElementName();
- IGenericType info = null;
- java.util.zip.ZipFile zipFile = null;
- try {
- zipFile = ((JarPackageFragmentRoot) pkg.getParent()).getJar();
- info =
- org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(
- zipFile,
- classFilePath);
- } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException e) {
- e.printStackTrace();
- return;
- } catch (java.io.IOException e) {
- e.printStackTrace();
- return;
- } catch (CoreException e) {
- e.printStackTrace();
- return;
- } finally {
- if (zipFile != null) {
- try {
- zipFile.close();
- } catch (java.io.IOException e) {
- // ignore
- }
- }
- }
- infos.addElement(info);
- this.infoToHandle.put(info, classFile);
+
+ // Add focus if not already in (case of a type with no explicit super type)
+ if (!this.hierarchy.contains(focusType)) {
+ this.hierarchy.addRootClass(focusType);
}
-
- /**
- * Returns all of the possible subtypes of this type hierarchy.
- * Returns null if they could not be determine.
- */
- private String[] determinePossibleSubTypes()
- throws JavaModelException, CoreException {
-
- class PathCollector implements IPathRequestor {
- Hashtable paths = new Hashtable(10);
- public void acceptPath(String path) {
- paths.put(path, path);
+}
+/**
+ * Create an ICompilationUnit info from the given compilation unit on disk and
+ * adds it to the given list of units.
+ */
+private void createCompilationUnitFromPath(Openable handle, String osPath, Vector units) throws JavaModelException {
+ BasicCompilationUnit unit =
+ new BasicCompilationUnit(
+ null,
+ osPath);
+ units.addElement(unit);
+ this.cuToHandle.put(unit, handle);
+}
+/**
+ * Creates the type info from the given class file on disk and
+ * adds it to the given list of infos.
+ */
+private void createInfoFromClassFile(Openable handle, String osPath, Vector infos) throws JavaModelException {
+ IGenericType info = null;
+ try {
+ info = org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(osPath);
+ } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException e) {
+ e.printStackTrace();
+ return;
+ } catch (java.io.IOException e) {
+ e.printStackTrace();
+ return;
+ }
+ infos.addElement(info);
+ this.infoToHandle.put(info, handle);
+}
+/**
+ * Create a type info from the given class file in a jar and adds it to the given list of infos.
+ */
+private void createInfoFromClassFileInJar(Openable classFile, Vector infos) throws JavaModelException {
+ IJavaElement pkg = classFile.getParent();
+ String classFilePath = pkg.getElementName().replace('.', '/') + "/" + classFile.getElementName();
+ IGenericType info = null;
+ java.util.zip.ZipFile zipFile = null;
+ try {
+ zipFile = ((JarPackageFragmentRoot)pkg.getParent()).getJar();
+ info = org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(
+ zipFile,
+ classFilePath);
+ } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException e) {
+ e.printStackTrace();
+ return;
+ } catch (java.io.IOException e) {
+ e.printStackTrace();
+ return;
+ } catch (CoreException e) {
+ e.printStackTrace();
+ return;
+ } finally {
+ if (zipFile != null) {
+ try {
+ zipFile.close();
+ } catch (java.io.IOException e) {
+ // ignore
}
- }
- PathCollector collector = new PathCollector();
- IProject project = this.hierarchy.javaProject().getProject();
-
- searchAllPossibleSubTypes(
- project.getWorkspace(),
- this.getType(),
- this.scope,
- this.binariesFromIndexMatches,
- collector,
- IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
- this.hierarchy.fProgressMonitor);
+ }
+ }
+ infos.addElement(info);
+ this.infoToHandle.put(info, classFile);
+}
+/**
+ * Returns all of the possible subtypes of this type hierarchy.
+ * Returns null if they could not be determine.
+ */
+private String[] determinePossibleSubTypes() throws JavaModelException, CoreException {
- Hashtable paths = collector.paths;
- int length = paths.size();
- String[] result = new String[length];
- int count = 0;
- for (Enumeration elements = paths.elements(); elements.hasMoreElements();) {
- result[count++] = (String) elements.nextElement();
+ class PathCollector implements IPathRequestor {
+ Hashtable paths = new Hashtable(10);
+ public void acceptPath(String path) {
+ paths.put(path, path);
}
- return result;
}
-
- /**
- * Returns a handle for the given generic type or null if not found.
- */
- protected IType getHandle(IGenericType genericType) {
- if (genericType instanceof HierarchyType) {
- IType type = (IType) this.infoToHandle.get(genericType);
- if (type == null) {
- HierarchyType hierarchyType = (HierarchyType) genericType;
- CompilationUnit unit =
- (CompilationUnit) this.cuToHandle.get(hierarchyType.originatingUnit);
-
- // collect enclosing type names
- Vector enclosingTypeNames = new Vector();
- HierarchyType enclosingType = hierarchyType;
- do {
- enclosingTypeNames.addElement(enclosingType.name);
- enclosingType = enclosingType.enclosingType;
- } while (enclosingType != null);
- int length = enclosingTypeNames.size();
- char[][] simpleTypeNames = new char[length][];
- enclosingTypeNames.copyInto(simpleTypeNames);
-
- // build handle
- type = unit.getType(new String(simpleTypeNames[length - 1]));
- for (int i = length - 2; i >= 0; i--) {
- type = type.getType(new String(simpleTypeNames[i]));
- }
- this.infoToHandle.put(genericType, type);
+ PathCollector collector = new PathCollector();
+ IProject project = this.hierarchy.javaProject().getProject();
+
+ searchAllPossibleSubTypes(
+ project.getWorkspace(),
+ this.getType(),
+ this.scope,
+ this.binariesFromIndexMatches,
+ collector,
+ IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
+ this.hierarchy.fProgressMonitor);
+
+ Hashtable paths = collector.paths;
+ int length = paths.size();
+ String[] result = new String[length];
+ int count = 0;
+ for (Enumeration elements = paths.elements(); elements.hasMoreElements(); ) {
+ result[count++] = (String) elements.nextElement();
+ }
+ return result;
+}
+/**
+ * Returns a handle for the given generic type or null if not found.
+ */
+protected IType getHandle(IGenericType genericType) {
+ if (genericType instanceof HierarchyType) {
+ IType type = (IType)this.infoToHandle.get(genericType);
+ if (type == null) {
+ HierarchyType hierarchyType = (HierarchyType)genericType;
+ CompilationUnit unit = (CompilationUnit)this.cuToHandle.get(hierarchyType.originatingUnit);
+
+ // collect enclosing type names
+ Vector enclosingTypeNames = new Vector();
+ HierarchyType enclosingType = hierarchyType;
+ do {
+ enclosingTypeNames.addElement(enclosingType.name);
+ enclosingType = enclosingType.enclosingType;
+ } while (enclosingType != null);
+ int length = enclosingTypeNames.size();
+ char[][] simpleTypeNames = new char[length][];
+ enclosingTypeNames.copyInto(simpleTypeNames);
+
+ // build handle
+ type = unit.getType(new String(simpleTypeNames[length-1]));
+ for (int i = length-2; i >= 0; i--) {
+ type = type.getType(new String(simpleTypeNames[i]));
}
- return type;
- } else
- return super.getHandle(genericType);
- }
-
- /**
- * Find the set of candidate subtypes of a given type.
- *
- * The requestor is notified of super type references (with actual path of
- * its occurrence) for all types which are potentially involved inside a particular
- * hierarchy.
- * The match locator is not used here to narrow down the results, the type hierarchy
- * resolver is rather used to compute the whole hierarchy at once.
- */
-
- public static void searchAllPossibleSubTypes(
- IWorkspace workbench,
- IType type,
- IJavaSearchScope scope,
- final Hashtable binariesFromIndexMatches,
- final IPathRequestor pathRequestor,
- int waitingPolicy,
- // WaitUntilReadyToSearch | ForceImmediateSearch | CancelIfNotReadyToSearch
- IProgressMonitor progressMonitor) throws JavaModelException, CoreException {
-
- /* embed constructs inside arrays so as to pass them to (inner) collector */
- final Queue awaitings = new Queue();
- final HashtableOfObject foundSuperNames = new HashtableOfObject(5);
-
- IndexManager indexManager =
- ((JavaModelManager) JavaModelManager.getJavaModelManager()).getIndexManager();
- if (indexManager == null)
- return;
+ this.infoToHandle.put(genericType, type);
+ }
+ return type;
+ } else
+ return super.getHandle(genericType);
+}
+/**
+ * Find the set of candidate subtypes of a given type.
+ *
+ * The requestor is notified of super type references (with actual path of
+ * its occurrence) for all types which are potentially involved inside a particular
+ * hierarchy.
+ * The match locator is not used here to narrow down the results, the type hierarchy
+ * resolver is rather used to compute the whole hierarchy at once.
+ */
- /* use a special collector to collect paths and queue new subtype names */
- IIndexSearchRequestor searchRequestor = new IndexSearchAdapter() {
- public void acceptSuperTypeReference(
- String resourcePath,
- char[] qualification,
- char[] typeName,
- char[] enclosingTypeName,
- char classOrInterface,
- char[] superQualification,
- char[] superTypeName,
- char superClassOrInterface,
- int modifiers) {
- pathRequestor.acceptPath(resourcePath);
- if (resourcePath.endsWith("class")) {
- HierarchyBinaryType binaryType =
- (HierarchyBinaryType) binariesFromIndexMatches.get(resourcePath);
- if (binaryType == null) {
- binaryType =
- new HierarchyBinaryType(
- modifiers,
- qualification,
- typeName,
- enclosingTypeName,
- classOrInterface);
- binariesFromIndexMatches.put(resourcePath, binaryType);
- }
- binaryType.recordSuperType(
- superTypeName,
- superQualification,
- superClassOrInterface);
- }
- if (!foundSuperNames.containsKey(typeName)) {
- foundSuperNames.put(typeName, typeName);
- awaitings.add(typeName);
+public static void searchAllPossibleSubTypes(
+ IWorkspace workbench,
+ IType type,
+ IJavaSearchScope scope,
+ final Hashtable binariesFromIndexMatches,
+ final IPathRequestor pathRequestor,
+ int waitingPolicy, // WaitUntilReadyToSearch | ForceImmediateSearch | CancelIfNotReadyToSearch
+ IProgressMonitor progressMonitor) throws JavaModelException, CoreException {
+
+ /* embed constructs inside arrays so as to pass them to (inner) collector */
+ final Queue awaitings = new Queue();
+ final HashtableOfObject foundSuperNames = new HashtableOfObject(5);
+
+ IndexManager indexManager = ((JavaModelManager)JavaModelManager.getJavaModelManager()).getIndexManager();
+ if (indexManager == null) return;
+
+ /* use a special collector to collect paths and queue new subtype names */
+ IIndexSearchRequestor searchRequestor = new IndexSearchAdapter(){
+ public void acceptSuperTypeReference(String resourcePath, char[] qualification, char[] typeName, char[] enclosingTypeName, char classOrInterface, char[] superQualification, char[] superTypeName, char superClassOrInterface, int modifiers) {
+ pathRequestor.acceptPath(resourcePath);
+ if (resourcePath.endsWith("class")){
+ HierarchyBinaryType binaryType = (HierarchyBinaryType)binariesFromIndexMatches.get(resourcePath);
+ if (binaryType == null){
+ binaryType = new HierarchyBinaryType(modifiers, qualification, typeName, enclosingTypeName, classOrInterface);
+ binariesFromIndexMatches.put(resourcePath, binaryType);
}
+ binaryType.recordSuperType(superTypeName, superQualification, superClassOrInterface);
}
- };
-
- SuperTypeReferencePattern pattern =
- new SuperTypeReferencePattern(
- null,
- null,
- IJavaSearchConstants.EXACT_MATCH,
- IJavaSearchConstants.CASE_SENSITIVE);
- SubTypeSearchJob job =
- new SubTypeSearchJob(
- pattern,
+ if (!foundSuperNames.containsKey(typeName)){
+ foundSuperNames.put(typeName, typeName);
+ awaitings.add(typeName);
+ }
+ }
+ };
+
+ SuperTypeReferencePattern pattern = new SuperTypeReferencePattern(null, null, IJavaSearchConstants.EXACT_MATCH, IJavaSearchConstants.CASE_SENSITIVE);
+ SubTypeSearchJob job = new SubTypeSearchJob(
+ pattern,
scope,
- type,
- IInfoConstants.PathInfo,
- searchRequestor,
- indexManager,
+ type,
+ IInfoConstants.PathInfo,
+ searchRequestor,
+ indexManager,
progressMonitor);
-
- /* iterate all queued names */
- awaitings.add(type.getElementName().toCharArray());
- while (awaitings.start <= awaitings.end) {
- if (progressMonitor != null && progressMonitor.isCanceled())
- return;
-
- char[] currentTypeName = awaitings.retrieve();
-
- /* all subclasses of OBJECT are actually all types */
- if (CharOperation.equals(currentTypeName, AbstractIndexer.OBJECT)) {
- currentTypeName = null;
- }
- /* search all index references to a given supertype */
- pattern.superSimpleName = currentTypeName;
- indexManager.performConcurrentJob(job, waitingPolicy, progressMonitor);
- /* in case, we search all subtypes, no need to search further */
- if (currentTypeName == null)
- break;
- }
- /* close all cached index inputs */
- job.closeAll();
+
+ /* iterate all queued names */
+ awaitings.add(type.getElementName().toCharArray());
+ while (awaitings.start <= awaitings.end){
+ if (progressMonitor != null && progressMonitor.isCanceled()) return;
+
+ char[] currentTypeName = awaitings.retrieve();
+
+ /* all subclasses of OBJECT are actually all types */
+ if (CharOperation.equals(currentTypeName, AbstractIndexer.OBJECT)){
+ currentTypeName = null;
+ }
+ /* search all index references to a given supertype */
+ pattern.superSimpleName = currentTypeName;
+ indexManager.performConcurrentJob(job, waitingPolicy, progressMonitor);
+ /* in case, we search all subtypes, no need to search further */
+ if (currentTypeName == null) break;
}
-
+ /* close all cached index inputs */
+ job.closeAll();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedHierarchyBuilder.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedHierarchyBuilder.java
index ca1bc34c92..ad34b7ea3c 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedHierarchyBuilder.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedHierarchyBuilder.java
@@ -15,199 +15,178 @@ import java.util.Hashtable;
import java.util.Vector;
public class RegionBasedHierarchyBuilder extends HierarchyBuilder {
- public RegionBasedHierarchyBuilder(TypeHierarchy hierarchy)
- throws JavaModelException {
- super(hierarchy);
+public RegionBasedHierarchyBuilder(TypeHierarchy hierarchy) throws JavaModelException {
+ super(hierarchy);
+}
+public void build(boolean computeSubtypes) {
+ if (this.hierarchy.fType == null || computeSubtypes) {
+ Vector allTypesInRegion = determineTypesInRegion();
+ this.hierarchy.initialize(allTypesInRegion.size());
+ createTypeHierarchyBasedOnRegion(allTypesInRegion);
+ } else {
+ this.hierarchy.initialize(1);
+ this.buildSupertypes();
}
-
- public void build(boolean computeSubtypes) {
- if (this.hierarchy.fType == null || computeSubtypes) {
- Vector allTypesInRegion = determineTypesInRegion();
- this.hierarchy.initialize(allTypesInRegion.size());
- createTypeHierarchyBasedOnRegion(allTypesInRegion);
- } else {
- this.hierarchy.initialize(1);
- this.buildSupertypes();
- }
+}
+/**
+ * Configure this type hierarchy that is based on a region.
+ */
+private void createTypeHierarchyBasedOnRegion(Vector allTypesInRegion) {
+ int size = allTypesInRegion.size();
+ if (size != 0) {
+ this.infoToHandle= new Hashtable(size);
}
-
- /**
- * Configure this type hierarchy that is based on a region.
- */
- private void createTypeHierarchyBasedOnRegion(Vector allTypesInRegion) {
- int size = allTypesInRegion.size();
- if (size != 0) {
- this.infoToHandle = new Hashtable(size);
- }
- Vector temp = new Vector(size);
- types : for (int i = 0; i < size; i++) {
- try {
- IType type = (IType) allTypesInRegion.elementAt(i);
- IGenericType info = (IGenericType) ((JavaElement) type).getRawInfo();
- temp.addElement(info);
- if (info.isBinaryType()) {
- this.infoToHandle.put(info, type.getParent());
- }
- worked(1);
- } catch (JavaModelException npe) {
- continue types;
- }
- }
-
- size = temp.size();
- if (size > 0) {
- IGenericType[] genericTypes = new IGenericType[size];
- temp.copyInto(genericTypes);
- IType focusType = this.getType();
- if (focusType != null) {
- this.searchableEnvironment.unitToLookInside =
- (CompilationUnit) focusType.getCompilationUnit();
- }
- this.hierarchyResolver.resolve(genericTypes);
- if (focusType != null) {
- this.searchableEnvironment.unitToLookInside = null;
+ Vector temp = new Vector(size);
+ types : for (int i = 0; i < size; i++) {
+ try {
+ IType type = (IType) allTypesInRegion.elementAt(i);
+ IGenericType info= (IGenericType) ((JavaElement) type).getRawInfo();
+ temp.addElement(info);
+ if (info.isBinaryType()) {
+ this.infoToHandle.put(info, type.getParent());
}
-
+ worked(1);
+ } catch (JavaModelException npe) {
+ continue types;
}
}
- /**
- * Returns all of the types defined in the region of this type hierarchy.
- */
- private Vector determineTypesInRegion() {
-
- Vector types = new Vector();
- IJavaElement[] roots =
- ((RegionBasedTypeHierarchy) this.hierarchy).fRegion.getElements();
- for (int i = 0; i < roots.length; i++) {
- try {
- IJavaElement root = roots[i];
- switch (root.getElementType()) {
- case IJavaElement.JAVA_PROJECT :
- injectAllTypesForJavaProject((IJavaProject) root, types);
- break;
- case IJavaElement.PACKAGE_FRAGMENT_ROOT :
- injectAllTypesForPackageFragmentRoot((IPackageFragmentRoot) root, types);
- break;
- case IJavaElement.PACKAGE_FRAGMENT :
- injectAllTypesForPackageFragment((IPackageFragment) root, types);
- break;
- case IJavaElement.CLASS_FILE :
- types.addElement(((IClassFile) root).getType());
- break;
- case IJavaElement.COMPILATION_UNIT :
- IType[] cuTypes = ((ICompilationUnit) root).getAllTypes();
- for (int j = 0; j < cuTypes.length; j++) {
- types.addElement(cuTypes[j]);
- }
- break;
- case IJavaElement.TYPE :
- types.addElement(root);
- break;
- default :
- break;
- }
- } catch (JavaModelException npe) {
- // just continue
- }
+ size = temp.size();
+ if (size > 0) {
+ IGenericType[] genericTypes = new IGenericType[size];
+ temp.copyInto(genericTypes);
+ IType focusType = this.getType();
+ if (focusType != null) {
+ this.searchableEnvironment.unitToLookInside = (CompilationUnit)focusType.getCompilationUnit();
}
- return types;
- }
-
- /**
- * Adds all of the types defined within this java project to the
- * vector.
- */
- private void injectAllTypesForJavaProject(IJavaProject project, Vector types) {
- try {
- IPackageFragmentRoot[] devPathRoots =
- ((JavaProject) project).getPackageFragmentRoots();
- if (devPathRoots == null) {
- return;
- }
- for (int j = 0; j < devPathRoots.length; j++) {
- IPackageFragmentRoot root = devPathRoots[j];
- injectAllTypesForPackageFragmentRoot(root, types);
- }
- } catch (JavaModelException e) {
+ this.hierarchyResolver.resolve(genericTypes);
+ if (focusType != null) {
+ this.searchableEnvironment.unitToLookInside = null;
}
- }
- /**
- * Adds all of the types defined within this package fragment to the
- * vector.
- */
- private void injectAllTypesForPackageFragment(
- IPackageFragment packFrag,
- Vector types) {
+ }
+}
+/**
+ * Returns all of the types defined in the region of this type hierarchy.
+ */
+private Vector determineTypesInRegion() {
+
+ Vector types = new Vector();
+ IJavaElement[] roots = ((RegionBasedTypeHierarchy)this.hierarchy).fRegion.getElements();
+ for (int i = 0; i < roots.length; i++) {
try {
- IPackageFragmentRoot root = (IPackageFragmentRoot) packFrag.getParent();
- int kind = root.getKind();
- if (kind != 0) {
- boolean isSourcePackageFragment = (kind == IPackageFragmentRoot.K_SOURCE);
- if (isSourcePackageFragment) {
- ICompilationUnit[] typeContainers = packFrag.getCompilationUnits();
- injectAllTypesForTypeContainers(typeContainers, types);
- } else {
- IClassFile[] typeContainers = packFrag.getClassFiles();
- injectAllTypesForTypeContainers(typeContainers, types);
- }
+ IJavaElement root = roots[i];
+ switch (root.getElementType()) {
+ case IJavaElement.JAVA_PROJECT :
+ injectAllTypesForJavaProject((IJavaProject) root, types);
+ break;
+ case IJavaElement.PACKAGE_FRAGMENT_ROOT :
+ injectAllTypesForPackageFragmentRoot((IPackageFragmentRoot) root, types);
+ break;
+ case IJavaElement.PACKAGE_FRAGMENT :
+ injectAllTypesForPackageFragment((IPackageFragment) root, types);
+ break;
+ case IJavaElement.CLASS_FILE :
+ types.addElement(((IClassFile) root).getType());
+ break;
+ case IJavaElement.COMPILATION_UNIT :
+ IType[] cuTypes = ((ICompilationUnit) root).getAllTypes();
+ for (int j = 0; j < cuTypes.length; j++) {
+ types.addElement(cuTypes[j]);
+ }
+ break;
+ case IJavaElement.TYPE :
+ types.addElement(root);
+ break;
+ default :
+ break;
}
} catch (JavaModelException npe) {
+ // just continue
}
}
-
- /**
- * Adds all of the types defined within this package fragment root to the
- * vector.
- */
- private void injectAllTypesForPackageFragmentRoot(
- IPackageFragmentRoot root,
- Vector types) {
- try {
- IJavaElement[] packFrags = root.getChildren();
- for (int k = 0; k < packFrags.length; k++) {
- IPackageFragment packFrag = (IPackageFragment) packFrags[k];
- injectAllTypesForPackageFragment(packFrag, types);
- }
- } catch (JavaModelException npe) {
+ return types;
+}
+/**
+ * Adds all of the types defined within this java project to the
+ * vector.
+ */
+private void injectAllTypesForJavaProject(IJavaProject project, Vector types) {
+ try {
+ IPackageFragmentRoot[] devPathRoots = ((JavaProject) project).getPackageFragmentRoots();
+ if (devPathRoots == null) {
return;
}
+ for (int j = 0; j < devPathRoots.length; j++) {
+ IPackageFragmentRoot root = devPathRoots[j];
+ injectAllTypesForPackageFragmentRoot(root, types);
+ }
+ } catch (JavaModelException e) {
}
-
- /**
- * Adds all of the types defined within the type containers (IClassFile).
- */
- private void injectAllTypesForTypeContainers(
- IClassFile[] containers,
- Vector types) {
- try {
- for (int i = 0; i < containers.length; i++) {
- IClassFile cf = containers[i];
- types.addElement(cf.getType());
- this.worked(1);
+}
+/**
+ * Adds all of the types defined within this package fragment to the
+ * vector.
+ */
+private void injectAllTypesForPackageFragment(IPackageFragment packFrag, Vector types) {
+ try {
+ IPackageFragmentRoot root = (IPackageFragmentRoot) packFrag.getParent();
+ int kind = root.getKind();
+ if (kind != 0) {
+ boolean isSourcePackageFragment = (kind == IPackageFragmentRoot.K_SOURCE);
+ if (isSourcePackageFragment) {
+ ICompilationUnit[] typeContainers = packFrag.getCompilationUnits();
+ injectAllTypesForTypeContainers(typeContainers, types);
+ } else {
+ IClassFile[] typeContainers = packFrag.getClassFiles();
+ injectAllTypesForTypeContainers(typeContainers, types);
}
- } catch (JavaModelException npe) {
}
+ } catch (JavaModelException npe) {
}
-
- /**
- * Adds all of the types defined within the type containers (ICompilationUnit).
- */
- private void injectAllTypesForTypeContainers(
- ICompilationUnit[] containers,
- Vector types) {
- try {
- for (int i = 0; i < containers.length; i++) {
- ICompilationUnit cu = containers[i];
- IType[] cuTypes = cu.getAllTypes();
- for (int j = 0; j < cuTypes.length; j++) {
- types.addElement(cuTypes[j]);
- }
- this.worked(1);
+}
+/**
+ * Adds all of the types defined within this package fragment root to the
+ * vector.
+ */
+private void injectAllTypesForPackageFragmentRoot(IPackageFragmentRoot root, Vector types) {
+ try {
+ IJavaElement[] packFrags = root.getChildren();
+ for (int k = 0; k < packFrags.length; k++) {
+ IPackageFragment packFrag = (IPackageFragment) packFrags[k];
+ injectAllTypesForPackageFragment(packFrag, types);
+ }
+ } catch (JavaModelException npe) {
+ return;
+ }
+}
+/**
+ * Adds all of the types defined within the type containers (IClassFile).
+ */
+private void injectAllTypesForTypeContainers(IClassFile[] containers, Vector types) {
+ try {
+ for (int i = 0; i < containers.length; i++) {
+ IClassFile cf = containers[i];
+ types.addElement(cf.getType());
+ this.worked(1);
+ }
+ } catch (JavaModelException npe) {
+ }
+}
+/**
+ * Adds all of the types defined within the type containers (ICompilationUnit).
+ */
+private void injectAllTypesForTypeContainers(ICompilationUnit[] containers, Vector types) {
+ try {
+ for (int i = 0; i < containers.length; i++) {
+ ICompilationUnit cu = containers[i];
+ IType[] cuTypes = cu.getAllTypes();
+ for (int j = 0; j < cuTypes.length; j++) {
+ types.addElement(cuTypes[j]);
}
- } catch (JavaModelException npe) {
+ this.worked(1);
}
+ } catch (JavaModelException npe) {
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedTypeHierarchy.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedTypeHierarchy.java
index a79c4ade3b..198eecf54f 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedTypeHierarchy.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/RegionBasedTypeHierarchy.java
@@ -30,89 +30,73 @@ public class RegionBasedTypeHierarchy extends TypeHierarchy {
* provides the context (i.e. classpath and namelookup rules)
*/
protected IJavaProject fProject;
- /**
- * Creates a TypeHierarchy on the types in the specified region,
- * using the given project for a name lookup contenxt. If a specific
- * type is also specified, the type hierarchy is pruned to only
- * contain the branch including the specified type.
- */
- public RegionBasedTypeHierarchy(
- IRegion region,
- IJavaProject project,
- IType type,
- boolean computeSubtypes)
- throws JavaModelException {
- super(type, null, computeSubtypes);
- fRegion = region;
- fProject = project;
- }
-
- /**
- * Activates this hierarchy for change listeners
- */
- protected void activate() {
- super.activate();
- IJavaElement[] roots = fRegion.getElements();
- for (int i = 0; i < roots.length; i++) {
- IJavaElement root = roots[i];
- if (root instanceof IOpenable) {
- this.files.put(root, root);
- } else {
- Openable o = (Openable) ((JavaElement) root).getOpenableParent();
- if (o != null) {
- this.files.put(o, o);
- }
+/**
+ * Creates a TypeHierarchy on the types in the specified region,
+ * using the given project for a name lookup contenxt. If a specific
+ * type is also specified, the type hierarchy is pruned to only
+ * contain the branch including the specified type.
+ */
+public RegionBasedTypeHierarchy(IRegion region, IJavaProject project, IType type, boolean computeSubtypes) throws JavaModelException {
+ super(type, null, computeSubtypes);
+ fRegion = region;
+ fProject = project;
+}
+/**
+ * Activates this hierarchy for change listeners
+ */
+protected void activate() {
+ super.activate();
+ IJavaElement[] roots = fRegion.getElements();
+ for (int i = 0; i < roots.length; i++) {
+ IJavaElement root = roots[i];
+ if (root instanceof IOpenable) {
+ this.files.put(root, root);
+ } else {
+ Openable o = (Openable) ((JavaElement) root).getOpenableParent();
+ if (o != null) {
+ this.files.put(o, o);
}
- checkCanceled();
}
+ checkCanceled();
}
-
- /**
- * Compute this type hierarchy.
- */
- protected void compute() throws JavaModelException, CoreException {
- HierarchyBuilder builder = new RegionBasedHierarchyBuilder(this);
- builder.build(this.computeSubtypes);
- }
-
- protected void destroy() {
- fRegion = new Region();
- super.destroy();
- }
-
- protected boolean isAffectedByType(
- IJavaElementDelta delta,
- IJavaElement element) {
- // ignore changes to working copies
- if (element instanceof CompilationUnit
- && ((CompilationUnit) element).isWorkingCopy()) {
- return false;
- }
-
- // if no focus, hierarchy is affected if the element is part of the region
- if (fType == null) {
- return fRegion.contains(element);
- } else {
- return super.isAffectedByType(delta, element);
- }
+}
+/**
+ * Compute this type hierarchy.
+ */
+protected void compute() throws JavaModelException, CoreException {
+ HierarchyBuilder builder = new RegionBasedHierarchyBuilder(this);
+ builder.build(this.computeSubtypes);
+}
+protected void destroy() {
+ fRegion = new Region();
+ super.destroy();
+}
+protected boolean isAffectedByType(IJavaElementDelta delta, IJavaElement element) {
+ // ignore changes to working copies
+ if (element instanceof CompilationUnit && ((CompilationUnit)element).isWorkingCopy()) {
+ return false;
}
- /**
- * Returns the java project this hierarchy was created in.
- */
- public IJavaProject javaProject() {
- return fProject;
+ // if no focus, hierarchy is affected if the element is part of the region
+ if (fType == null) {
+ return fRegion.contains(element);
+ } else {
+ return super.isAffectedByType(delta, element);
}
-
- protected void pruneTypeHierarchy(IType type, IProgressMonitor monitor)
- throws JavaModelException {
- // there is no pruning to do if the hierarchy was created for the single type
- IJavaElement[] roots = fRegion.getElements();
- if (roots.length == 1 && roots[0].equals(type)) {
- return;
- }
-
- super.pruneTypeHierarchy(type, monitor);
+}
+/**
+ * Returns the java project this hierarchy was created in.
+ */
+public IJavaProject javaProject() {
+ return fProject;
+}
+protected void pruneTypeHierarchy(IType type, IProgressMonitor monitor) throws JavaModelException {
+ // there is no pruning to do if the hierarchy was created for the single type
+ IJavaElement[] roots= fRegion.getElements();
+ if (roots.length == 1 && roots[0].equals(type)) {
+ return;
}
+ super.pruneTypeHierarchy(type, monitor);
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
index 3d51b1ab2c..8fa6da89f4 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/hierarchy/TypeHierarchy.java
@@ -40,11 +40,11 @@ public class TypeHierarchy implements ITypeHierarchy, IElementChangedListener {
protected Hashtable fClassToSuperclass;
protected Hashtable fTypeToSuperInterfaces;
protected Hashtable fTypeToSubtypes;
- protected TypeVector fRootClasses = new TypeVector();
- protected Vector fInterfaces = new Vector(10);
-
- protected static final IType[] fgEmpty = new IType[0];
-
+ protected TypeVector fRootClasses= new TypeVector();
+ protected Vector fInterfaces= new Vector(10);
+
+ protected static final IType[] fgEmpty= new IType[0];
+
/**
* The progress monitor to report work completed too.
*/
@@ -53,46 +53,46 @@ public class TypeHierarchy implements ITypeHierarchy, IElementChangedListener {
/**
* Change listeners - null if no one is listening.
*/
- protected Vector fChangeListeners = null;
+ protected Vector fChangeListeners= null;
/**
* A set of the compilation units and class
* files that are considered in this hierarchy. Null if
* not activated.
*/
- protected Hashtable files = null;
+ protected Hashtable files= null;
/**
* A region describing the packages considered by this
* hierarchy. Null if not activated.
*/
- protected Region fPackageRegion = null;
+ protected Region fPackageRegion= null;
/**
* A region describing the package fragment roots considered by this
* hierarchy. Null if not activated.
*/
- protected Region fRootRegion = null;
-
+ protected Region fRootRegion= null;
+
/**
* A region describing the projects considered by this
* hierarchy. Null if not activated.
*/
- protected Region fProjectRegion = null;
+ protected Region fProjectRegion= null;
/**
* A boolean indicating if this hierarchy is actively tracking changes
* in the Java Model.
*/
- protected boolean fIsActivated = false;
+ protected boolean fIsActivated= false;
/**
* A boolean indicating if the hierarchy exists
*
* fix for 1FW67PA
*/
- protected boolean fExists = true;
-
+ protected boolean fExists= true;
+
/**
* Whether this hierarchy should contains subtypes.
*/
@@ -103,1195 +103,1096 @@ public class TypeHierarchy implements ITypeHierarchy, IElementChangedListener {
*/
IJavaSearchScope scope;
- /**
- * Creates a TypeHierarchy on the given type.
- */
- public TypeHierarchy(
- IType type,
- IJavaSearchScope scope,
- boolean computeSubtypes)
- throws JavaModelException {
- fType = type;
- this.computeSubtypes = computeSubtypes;
- this.scope = scope;
- }
-
- /**
- * Activates this hierarchy for change listeners
- */
- protected void activate() {
-
- // determine my file, package, root, & project regions.
- this.files = new Hashtable(5);
- fProjectRegion = new Region();
- fPackageRegion = new Region();
- fRootRegion = new Region();
- IType[] types = getAllTypes();
- for (int i = 0; i < types.length; i++) {
- IType type = types[i];
- Openable o = (Openable) ((JavaElement) type).getOpenableParent();
- if (o != null) {
- this.files.put(o, o);
- }
- IPackageFragment pkg = type.getPackageFragment();
- fPackageRegion.add(pkg);
- fRootRegion.add(pkg.getParent());
- IJavaProject project = type.getJavaProject();
- if (project != null) {
- fProjectRegion.add(project);
- }
- checkCanceled();
- }
- JavaModelManager.getJavaModelManager().addElementChangedListener(this);
- fIsActivated = true;
- }
-
- /**
- * Adds all of the elements in the collection to the vector if the
- * element is not already in the vector.
- */
- private void addAllCheckingDuplicates(Vector vector, IType[] collection) {
- for (int i = 0; i < collection.length; i++) {
- IType element = collection[i];
- if (!vector.contains(element)) {
- vector.addElement(element);
- }
+/**
+ * Creates a TypeHierarchy on the given type.
+ */
+public TypeHierarchy(IType type, IJavaSearchScope scope, boolean computeSubtypes) throws JavaModelException {
+ fType = type;
+ this.computeSubtypes = computeSubtypes;
+ this.scope = scope;
+}
+/**
+ * Activates this hierarchy for change listeners
+ */
+protected void activate() {
+
+ // determine my file, package, root, & project regions.
+ this.files = new Hashtable(5);
+ fProjectRegion = new Region();
+ fPackageRegion = new Region();
+ fRootRegion = new Region();
+ IType[] types = getAllTypes();
+ for (int i = 0; i < types.length; i++) {
+ IType type = types[i];
+ Openable o = (Openable) ((JavaElement) type).getOpenableParent();
+ if (o != null) {
+ this.files.put(o, o);
+ }
+ IPackageFragment pkg = type.getPackageFragment();
+ fPackageRegion.add(pkg);
+ fRootRegion.add(pkg.getParent());
+ IJavaProject project = type.getJavaProject();
+ if (project != null) {
+ fProjectRegion.add(project);
+ }
+ checkCanceled();
+ }
+ JavaModelManager.getJavaModelManager().addElementChangedListener(this);
+ fIsActivated = true;
+}
+/**
+ * Adds all of the elements in the collection to the vector if the
+ * element is not already in the vector.
+ */
+private void addAllCheckingDuplicates(Vector vector, IType[] collection) {
+ for (int i = 0; i < collection.length; i++) {
+ IType element = collection[i];
+ if (!vector.contains(element)) {
+ vector.addElement(element);
}
}
-
- /**
- * Adds the type to the collection of interfaces.
- */
- protected void addInterface(IType type) {
- fInterfaces.addElement(type);
- }
-
- /**
- * Adds the type to the collection of root classes
- * if the classes is not already present in the collection.
- */
- protected void addRootClass(IType type) {
- if (fRootClasses.contains(type))
- return;
- fRootClasses.add(type);
+}
+/**
+ * Adds the type to the collection of interfaces.
+ */
+protected void addInterface(IType type) {
+ fInterfaces.addElement(type);
+}
+/**
+ * Adds the type to the collection of root classes
+ * if the classes is not already present in the collection.
+ */
+protected void addRootClass(IType type) {
+ if (fRootClasses.contains(type)) return;
+ fRootClasses.add(type);
+}
+/**
+ * Adds the given subtype to the type.
+ */
+protected void addSubtype(IType type, IType subtype) {
+ TypeVector subtypes = (TypeVector)fTypeToSubtypes.get(type);
+ if (subtypes == null) {
+ subtypes = new TypeVector();
+ fTypeToSubtypes.put(type, subtypes);
}
-
- /**
- * Adds the given subtype to the type.
- */
- protected void addSubtype(IType type, IType subtype) {
- TypeVector subtypes = (TypeVector) fTypeToSubtypes.get(type);
- if (subtypes == null) {
- subtypes = new TypeVector();
- fTypeToSubtypes.put(type, subtypes);
- }
- if (!subtypes.contains(subtype)) {
- subtypes.add(subtype);
- }
+ if (!subtypes.contains(subtype)) {
+ subtypes.add(subtype);
}
-
- /**
- * @see ITypeHierarchy
- */
- public void addTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener) {
- if (fChangeListeners == null) {
- fChangeListeners = new Vector();
- // fix for 1FW67PA
- if (fExists) {
- activate();
- }
- }
- // add listener only if it is not already present
- if (fChangeListeners.indexOf(listener) == -1) {
- fChangeListeners.addElement(listener);
+}
+/**
+ * @see ITypeHierarchy
+ */
+public void addTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener) {
+ if (fChangeListeners == null) {
+ fChangeListeners= new Vector();
+ // fix for 1FW67PA
+ if (fExists) {
+ activate();
}
}
-
- /**
- * Caches the handle of the superclass for the specified type.
- * As a side effect cache this type as a subtype of the superclass.
- */
- protected void cacheSuperclass(IType type, IType superclass) {
- if (superclass != null) {
- fClassToSuperclass.put(type, superclass);
- addSubtype(superclass, type);
- }
+ // add listener only if it is not already present
+ if (fChangeListeners.indexOf(listener) == -1) {
+ fChangeListeners.addElement(listener);
}
-
- /**
- * Caches all of the superinterfaces that are specified for the
- * type.
- */
- protected void cacheSuperInterfaces(IType type, IType[] superinterfaces) {
- fTypeToSuperInterfaces.put(type, superinterfaces);
- for (int i = 0; i < superinterfaces.length; i++) {
- IType superinterface = superinterfaces[i];
- if (superinterface != null) {
- addSubtype(superinterface, type);
- }
+}
+/**
+ * Caches the handle of the superclass for the specified type.
+ * As a side effect cache this type as a subtype of the superclass.
+ */
+protected void cacheSuperclass(IType type, IType superclass) {
+ if (superclass != null) {
+ fClassToSuperclass.put(type, superclass);
+ addSubtype(superclass, type);
+ }
+}
+/**
+ * Caches all of the superinterfaces that are specified for the
+ * type.
+ */
+protected void cacheSuperInterfaces(IType type, IType[] superinterfaces) {
+ fTypeToSuperInterfaces.put(type, superinterfaces);
+ for (int i = 0; i < superinterfaces.length; i++) {
+ IType superinterface = superinterfaces[i];
+ if (superinterface != null) {
+ addSubtype(superinterface, type);
}
}
-
- /**
- * Checks with the progress monitor to see whether the creation of the type hierarchy
- * should be canceled. Should be regularly called
- * so that the user can cancel.
- *
- * @exception OperationCanceledException if cancelling the operation has been requested
- * @see IProgressMonitor#isCanceled
- */
- protected void checkCanceled() {
- if (fProgressMonitor != null && fProgressMonitor.isCanceled()) {
- throw new OperationCanceledException();
- }
+}
+/**
+ * Checks with the progress monitor to see whether the creation of the type hierarchy
+ * should be canceled. Should be regularly called
+ * so that the user can cancel.
+ *
+ * @exception OperationCanceledException if cancelling the operation has been requested
+ * @see IProgressMonitor#isCanceled
+ */
+protected void checkCanceled() {
+ if (fProgressMonitor != null && fProgressMonitor.isCanceled()) {
+ throw new OperationCanceledException();
}
-
- /**
- * Compute this type hierarchy.
- */
- protected void compute() throws JavaModelException, CoreException {
- if (JavaModelManager.ENABLE_INDEXING && fType != null) {
- HierarchyBuilder builder = new IndexBasedHierarchyBuilder(this, this.scope);
- builder.build(this.computeSubtypes);
- } // else a RegionBasedTypeHierarchy should be used
+}
+/**
+ * Compute this type hierarchy.
+ */
+protected void compute() throws JavaModelException, CoreException {
+ if (JavaModelManager.ENABLE_INDEXING && fType != null) {
+ HierarchyBuilder builder =
+ new IndexBasedHierarchyBuilder(
+ this,
+ this.scope);
+ builder.build(this.computeSubtypes);
+ } // else a RegionBasedTypeHierarchy should be used
+}
+/**
+ * @see ITypeHierarchy
+ */
+public boolean contains(IType type) {
+ // classes
+ if (fClassToSuperclass.get(type) != null) {
+ return true;
}
- /**
- * @see ITypeHierarchy
- */
- public boolean contains(IType type) {
- // classes
- if (fClassToSuperclass.get(type) != null) {
- return true;
- }
+ // root classes
+ if (fRootClasses.contains(type)) return true;
- // root classes
- if (fRootClasses.contains(type))
+ // interfaces
+ for (Enumeration enum = fInterfaces.elements(); enum.hasMoreElements();) {
+ if (enum.nextElement().equals(type)) {
return true;
-
- // interfaces
- for (Enumeration enum = fInterfaces.elements(); enum.hasMoreElements();) {
- if (enum.nextElement().equals(type)) {
- return true;
- }
}
-
- return false;
- }
-
- /**
- * Deactivates this hierarchy for change listeners
- */
- protected void deactivate() {
- JavaModelManager.getJavaModelManager().removeElementChangedListener(this);
- this.files = null;
- fPackageRegion = null;
- fRootRegion = null;
- fProjectRegion = null;
- fChangeListeners = null;
- fIsActivated = false;
}
-
- /**
- * Empties this hierarchy.
- *
- * fix for 1FW67PA
- */
- protected void destroy() {
- fExists = false;
- fClassToSuperclass = new Hashtable(1);
- this.files = new Hashtable(5);
- fInterfaces = new Vector(0);
- fPackageRegion = new Region();
- fProjectRegion = new Region();
- fRootClasses = new TypeVector();
- fRootRegion = new Region();
- fTypeToSubtypes = new Hashtable(1);
- fTypeToSuperInterfaces = new Hashtable(1);
- JavaModelManager.getJavaModelManager().removeElementChangedListener(this);
- }
-
- /**
- * Determines if the change effects this hierarchy, and fires
- * change notification if required.
- */
- public void elementChanged(ElementChangedEvent event) {
- // fix for 1FW67PA
- if (fExists) {
- if (exists()) {
- if (isAffected(event.getDelta())) {
- fireChange();
- }
- } else {
- destroy();
+
+ return false;
+}
+/**
+ * Deactivates this hierarchy for change listeners
+ */
+protected void deactivate() {
+ JavaModelManager.getJavaModelManager().removeElementChangedListener(this);
+ this.files= null;
+ fPackageRegion= null;
+ fRootRegion= null;
+ fProjectRegion= null;
+ fChangeListeners= null;
+ fIsActivated= false;
+}
+/**
+ * Empties this hierarchy.
+ *
+ * fix for 1FW67PA
+ */
+protected void destroy() {
+ fExists = false;
+ fClassToSuperclass = new Hashtable(1);
+ this.files = new Hashtable(5);
+ fInterfaces = new Vector(0);
+ fPackageRegion = new Region();
+ fProjectRegion = new Region();
+ fRootClasses = new TypeVector();
+ fRootRegion = new Region();
+ fTypeToSubtypes = new Hashtable(1);
+ fTypeToSuperInterfaces = new Hashtable(1);
+ JavaModelManager.getJavaModelManager().removeElementChangedListener(this);
+}
+/**
+ * Determines if the change effects this hierarchy, and fires
+ * change notification if required.
+ */
+public void elementChanged(ElementChangedEvent event) {
+ // fix for 1FW67PA
+ if (fExists) {
+ if (exists()) {
+ if (isAffected(event.getDelta())) {
fireChange();
}
+ } else {
+ destroy();
+ fireChange();
}
-
}
- /**
- * @see ITypeHierarchy
- *
- * fix for 1FW67PA
- */
- public boolean exists() {
- if (fExists) {
- fExists =
- (fType == null || (fType != null && fType.exists()))
- && this.javaProject().exists();
- if (!fExists) {
- destroy();
- }
+}
+/**
+ * @see ITypeHierarchy
+ *
+ * fix for 1FW67PA
+ */
+public boolean exists() {
+ if (fExists) {
+ fExists = (fType == null || (fType != null && fType.exists())) && this.javaProject().exists();
+ if (!fExists) {
+ destroy();
}
- return fExists;
}
-
- /**
- * Notifies listeners that this hierarchy has changed and needs
- * refreshing. Note that listeners can be removed as we iterate
- * through the list.
- */
- protected void fireChange() {
- if (fChangeListeners == null) {
- return;
- }
- Vector listeners = (Vector) fChangeListeners.clone();
- for (int i = 0; i < listeners.size(); i++) {
- ITypeHierarchyChangedListener listener =
- (ITypeHierarchyChangedListener) listeners.elementAt(i);
- // ensure the listener is still a listener
- if (fChangeListeners != null && fChangeListeners.indexOf(listener) >= 0) {
- listener.typeHierarchyChanged(this);
- }
- }
+ return fExists;
+}
+/**
+ * Notifies listeners that this hierarchy has changed and needs
+ * refreshing. Note that listeners can be removed as we iterate
+ * through the list.
+ */
+protected void fireChange() {
+ if (fChangeListeners == null) {
+ return;
}
-
- /**
- * @see ITypeHierarchy
- */
- public IType[] getAllClasses() {
- Enumeration keys = fClassToSuperclass.keys();
- TypeVector classes = fRootClasses.copy();
- while (keys.hasMoreElements()) {
- classes.add((IType) keys.nextElement());
+ Vector listeners= (Vector)fChangeListeners.clone();
+ for (int i= 0; i < listeners.size(); i++) {
+ ITypeHierarchyChangedListener listener= (ITypeHierarchyChangedListener)listeners.elementAt(i);
+ // ensure the listener is still a listener
+ if (fChangeListeners != null && fChangeListeners.indexOf(listener) >= 0) {
+ listener.typeHierarchyChanged(this);
}
- return classes.elements();
}
-
- /**
- * @see ITypeHierarchy
- */
- public IType[] getAllInterfaces() {
- IType[] collection = new IType[fInterfaces.size()];
- fInterfaces.copyInto(collection);
- return collection;
- }
-
- /**
- * @see ITypeHierarchy
- */
- public IType[] getAllSubtypes(IType type) {
- return getAllSubtypesForType(type);
- }
-
- /**
- * @see getAllSubtypes(IType)
- */
- private IType[] getAllSubtypesForType(IType type) {
- Vector subTypes = new Vector();
- getAllSubtypesForType0(type, subTypes);
- IType[] subClasses = new IType[subTypes.size()];
- subTypes.copyInto(subClasses);
- return subClasses;
+}
+/**
+ * @see ITypeHierarchy
+ */
+public IType[] getAllClasses() {
+ Enumeration keys = fClassToSuperclass.keys();
+ TypeVector classes = fRootClasses.copy();
+ while (keys.hasMoreElements()) {
+ classes.add((IType)keys.nextElement());
}
-
- /**
- */
- private void getAllSubtypesForType0(IType type, Vector subs) {
- IType[] subTypes = getSubtypesForType(type);
- if (subTypes.length != 0) {
- for (int i = 0; i < subTypes.length; i++) {
- IType subType = subTypes[i];
- subs.addElement(subType);
- getAllSubtypesForType0(subType, subs);
- }
+ return classes.elements();
+}
+/**
+ * @see ITypeHierarchy
+ */
+public IType[] getAllInterfaces() {
+ IType[] collection= new IType[fInterfaces.size()];
+ fInterfaces.copyInto(collection);
+ return collection;
+}
+/**
+ * @see ITypeHierarchy
+ */
+public IType[] getAllSubtypes(IType type) {
+ return getAllSubtypesForType(type);
+}
+/**
+ * @see getAllSubtypes(IType)
+ */
+private IType[] getAllSubtypesForType(IType type) {
+ Vector subTypes = new Vector();
+ getAllSubtypesForType0(type, subTypes);
+ IType[] subClasses = new IType[subTypes.size()];
+ subTypes.copyInto(subClasses);
+ return subClasses;
+}
+/**
+ */
+private void getAllSubtypesForType0(IType type, Vector subs) {
+ IType[] subTypes = getSubtypesForType(type);
+ if (subTypes.length != 0) {
+ for (int i = 0; i < subTypes.length; i++) {
+ IType subType = subTypes[i];
+ subs.addElement(subType);
+ getAllSubtypesForType0(subType, subs);
}
}
-
- /**
- * @see ITypeHierarchy
- */
- public IType[] getAllSuperclasses(IType type) {
- IType superclass = getSuperclass(type);
- TypeVector supers = new TypeVector();
- while (superclass != null) {
- supers.add(superclass);
- superclass = getSuperclass(superclass);
+}
+/**
+ * @see ITypeHierarchy
+ */
+public IType[] getAllSuperclasses(IType type) {
+ IType superclass = getSuperclass(type);
+ TypeVector supers = new TypeVector();
+ while (superclass != null) {
+ supers.add(superclass);
+ superclass = getSuperclass(superclass);
+ }
+ return supers.elements();
+}
+/**
+ * @see ITypeHierarchy
+ */
+public IType[] getAllSuperInterfaces(IType type) {
+ Vector supers = new Vector();
+ if (fTypeToSuperInterfaces.get(type) == null) {
+ return fgEmpty;
+ }
+ getAllSuperInterfaces0(type, supers);
+ IType[] superinterfaces = new IType[supers.size()];
+ supers.copyInto(superinterfaces);
+ return superinterfaces;
+}
+private void getAllSuperInterfaces0(IType type, Vector supers) {
+ IType[] superinterfaces = (IType[]) fTypeToSuperInterfaces.get(type);
+ if (superinterfaces != null && superinterfaces.length != 0) {
+ addAllCheckingDuplicates(supers, superinterfaces);
+ for (int i = 0; i < superinterfaces.length; i++) {
+ getAllSuperInterfaces0(superinterfaces[i], supers);
}
- return supers.elements();
}
-
- /**
- * @see ITypeHierarchy
- */
- public IType[] getAllSuperInterfaces(IType type) {
- Vector supers = new Vector();
- if (fTypeToSuperInterfaces.get(type) == null) {
- return fgEmpty;
- }
- getAllSuperInterfaces0(type, supers);
- IType[] superinterfaces = new IType[supers.size()];
- supers.copyInto(superinterfaces);
- return superinterfaces;
+ IType superclass = (IType) fClassToSuperclass.get(type);
+ if (superclass != null) {
+ getAllSuperInterfaces0(superclass, supers);
}
-
- private void getAllSuperInterfaces0(IType type, Vector supers) {
- IType[] superinterfaces = (IType[]) fTypeToSuperInterfaces.get(type);
- if (superinterfaces != null && superinterfaces.length != 0) {
- addAllCheckingDuplicates(supers, superinterfaces);
- for (int i = 0; i < superinterfaces.length; i++) {
- getAllSuperInterfaces0(superinterfaces[i], supers);
- }
- }
- IType superclass = (IType) fClassToSuperclass.get(type);
- if (superclass != null) {
- getAllSuperInterfaces0(superclass, supers);
+}
+/**
+ * @see ITypeHierarchy
+ */
+public IType[] getAllSupertypes(IType type) {
+ Vector supers = new Vector();
+ if (fTypeToSuperInterfaces.get(type) == null) {
+ return fgEmpty;
+ }
+ getAllSupertypes0(type, supers);
+ IType[] supertypes = new IType[supers.size()];
+ supers.copyInto(supertypes);
+ return supertypes;
+}
+private void getAllSupertypes0(IType type, Vector supers) {
+ IType[] superinterfaces = (IType[]) fTypeToSuperInterfaces.get(type);
+ if (superinterfaces != null && superinterfaces.length != 0) {
+ addAllCheckingDuplicates(supers, superinterfaces);
+ for (int i = 0; i < superinterfaces.length; i++) {
+ getAllSuperInterfaces0(superinterfaces[i], supers);
}
}
-
- /**
- * @see ITypeHierarchy
- */
- public IType[] getAllSupertypes(IType type) {
- Vector supers = new Vector();
- if (fTypeToSuperInterfaces.get(type) == null) {
- return fgEmpty;
- }
- getAllSupertypes0(type, supers);
- IType[] supertypes = new IType[supers.size()];
- supers.copyInto(supertypes);
- return supertypes;
+ IType superclass = (IType) fClassToSuperclass.get(type);
+ if (superclass != null) {
+ supers.addElement(superclass);
+ getAllSupertypes0(superclass, supers);
}
-
- private void getAllSupertypes0(IType type, Vector supers) {
- IType[] superinterfaces = (IType[]) fTypeToSuperInterfaces.get(type);
- if (superinterfaces != null && superinterfaces.length != 0) {
- addAllCheckingDuplicates(supers, superinterfaces);
- for (int i = 0; i < superinterfaces.length; i++) {
- getAllSuperInterfaces0(superinterfaces[i], supers);
- }
- }
- IType superclass = (IType) fClassToSuperclass.get(type);
- if (superclass != null) {
- supers.addElement(superclass);
- getAllSupertypes0(superclass, supers);
+}
+/**
+ * @see ITypeHierarchy
+ */
+public IType[] getAllTypes() {
+ IType[] classes = getAllClasses();
+ int classesLength = classes.length;
+ IType[] interfaces = getAllInterfaces();
+ int interfacesLength = interfaces.length;
+ IType[] all = new IType[classesLength + interfacesLength];
+ System.arraycopy(classes, 0, all, 0, classesLength);
+ System.arraycopy(interfaces, 0, all, classesLength, interfacesLength);
+ return all;
+}
+/**
+ * @see ITypeHierarchy
+ */
+public IType[] getExtendingInterfaces(IType type) {
+ try {
+ if (type.isClass()) {
+ return new IType[] {};
}
+ } catch (JavaModelException npe) {
+ return new IType[] {};
}
-
- /**
- * @see ITypeHierarchy
- */
- public IType[] getAllTypes() {
- IType[] classes = getAllClasses();
- int classesLength = classes.length;
- IType[] interfaces = getAllInterfaces();
- int interfacesLength = interfaces.length;
- IType[] all = new IType[classesLength + interfacesLength];
- System.arraycopy(classes, 0, all, 0, classesLength);
- System.arraycopy(interfaces, 0, all, classesLength, interfacesLength);
- return all;
- }
-
- /**
- * @see ITypeHierarchy
- */
- public IType[] getExtendingInterfaces(IType type) {
+ return getExtendingInterfaces0(type);
+}
+/**
+ * Assumes that the type is an interface
+ * @see getExtendingInterfaces
+ */
+private IType[] getExtendingInterfaces0(IType interfce) {
+ Enumeration keys = fTypeToSuperInterfaces.keys();
+ Vector xers = new Vector();
+ while (keys.hasMoreElements()) {
+ IType type = (IType) keys.nextElement();
try {
if (type.isClass()) {
- return new IType[] {
- };
- }
- } catch (JavaModelException npe) {
- return new IType[] {
- };
- }
- return getExtendingInterfaces0(type);
- }
-
- /**
- * Assumes that the type is an interface
- * @see getExtendingInterfaces
- */
- private IType[] getExtendingInterfaces0(IType interfce) {
- Enumeration keys = fTypeToSuperInterfaces.keys();
- Vector xers = new Vector();
- while (keys.hasMoreElements()) {
- IType type = (IType) keys.nextElement();
- try {
- if (type.isClass()) {
- continue;
- }
- } catch (JavaModelException npe) {
continue;
}
- IType[] interfaces = (IType[]) fTypeToSuperInterfaces.get(type);
- if (interfaces != null) {
- for (int i = 0; i < interfaces.length; i++) {
- IType iFace = interfaces[i];
- if (iFace.equals(interfce)) {
- xers.addElement(type);
- }
- }
- }
- }
- IType[] extenders = new IType[xers.size()];
- xers.copyInto(extenders);
- return extenders;
- }
-
- /**
- * @see ITypeHierarchy
- */
- public IType[] getImplementingClasses(IType type) {
- try {
- if (type.isClass()) {
- return fgEmpty;
- }
} catch (JavaModelException npe) {
- return fgEmpty;
+ continue;
}
- return getImplementingClasses0(type);
- }
-
- /**
- * Assumes that the type is an interface
- * @see getImplementingClasses
- */
- private IType[] getImplementingClasses0(IType interfce) {
- Enumeration keys = fTypeToSuperInterfaces.keys();
- Vector iMenters = new Vector();
- while (keys.hasMoreElements()) {
- IType type = (IType) keys.nextElement();
- try {
- if (type.isInterface()) {
- continue;
- }
- } catch (JavaModelException npe) {
- continue;
- }
- IType[] interfaces = (IType[]) fTypeToSuperInterfaces.get(type);
+ IType[] interfaces = (IType[]) fTypeToSuperInterfaces.get(type);
+ if (interfaces != null) {
for (int i = 0; i < interfaces.length; i++) {
IType iFace = interfaces[i];
if (iFace.equals(interfce)) {
- iMenters.addElement(type);
+ xers.addElement(type);
}
}
}
- IType[] implementers = new IType[iMenters.size()];
- iMenters.copyInto(implementers);
- return implementers;
- }
-
- /**
- * @see ITypeHierarchy
- */
- public IType[] getRootClasses() {
- return fRootClasses.elements();
}
-
- /**
- * @see ITypeHierarchy
- */
- public IType[] getRootInterfaces() {
- IType[] allInterfaces = getAllInterfaces();
- IType[] roots = new IType[allInterfaces.length];
- int rootNumber = 0;
- for (int i = 0; i < allInterfaces.length; i++) {
- IType[] superInterfaces = getSuperInterfaces(allInterfaces[i]);
- if (superInterfaces == null || superInterfaces.length == 0) {
- roots[rootNumber++] = allInterfaces[i];
- }
- }
- IType[] result = new IType[rootNumber];
- if (result.length > 0) {
- System.arraycopy(roots, 0, result, 0, rootNumber);
+ IType[] extenders = new IType[xers.size()];
+ xers.copyInto(extenders);
+ return extenders;
+}
+/**
+ * @see ITypeHierarchy
+ */
+public IType[] getImplementingClasses(IType type) {
+ try {
+ if (type.isClass()) {
+ return fgEmpty;
}
- return result;
+ } catch (JavaModelException npe) {
+ return fgEmpty;
}
-
- /**
- * @see ITypeHierarchy
- */
- public IType[] getSubclasses(IType type) {
+ return getImplementingClasses0(type);
+}
+/**
+ * Assumes that the type is an interface
+ * @see getImplementingClasses
+ */
+private IType[] getImplementingClasses0(IType interfce) {
+ Enumeration keys = fTypeToSuperInterfaces.keys();
+ Vector iMenters = new Vector();
+ while (keys.hasMoreElements()) {
+ IType type = (IType) keys.nextElement();
try {
if (type.isInterface()) {
- return fgEmpty;
+ continue;
}
} catch (JavaModelException npe) {
- return new IType[] {
- };
+ continue;
+ }
+ IType[] interfaces = (IType[]) fTypeToSuperInterfaces.get(type);
+ for (int i = 0; i < interfaces.length; i++) {
+ IType iFace = interfaces[i];
+ if (iFace.equals(interfce)) {
+ iMenters.addElement(type);
+ }
}
- TypeVector vector = (TypeVector) fTypeToSubtypes.get(type);
- if (vector == null)
- return fgEmpty;
- else
- return vector.elements();
}
-
- /**
- * @see ITypeHierarchy
- */
- public IType[] getSubtypes(IType type) {
- return getSubtypesForType(type);
+ IType[] implementers = new IType[iMenters.size()];
+ iMenters.copyInto(implementers);
+ return implementers;
+}
+/**
+ * @see ITypeHierarchy
+ */
+public IType[] getRootClasses() {
+ return fRootClasses.elements();
+}
+/**
+ * @see ITypeHierarchy
+ */
+public IType[] getRootInterfaces() {
+ IType[] allInterfaces = getAllInterfaces();
+ IType[] roots = new IType[allInterfaces.length];
+ int rootNumber = 0;
+ for (int i = 0; i < allInterfaces.length; i++) {
+ IType[] superInterfaces = getSuperInterfaces(allInterfaces[i]);
+ if (superInterfaces == null || superInterfaces.length == 0) {
+ roots[rootNumber++] = allInterfaces[i];
+ }
}
-
- /**
- * Returns an array of subtypes for the given type - will never return null.
- */
- private IType[] getSubtypesForType(IType type) {
- TypeVector vector = (TypeVector) fTypeToSubtypes.get(type);
- if (vector == null)
+ IType[] result = new IType[rootNumber];
+ if (result.length > 0) {
+ System.arraycopy(roots, 0, result, 0, rootNumber);
+ }
+ return result;
+}
+/**
+ * @see ITypeHierarchy
+ */
+public IType[] getSubclasses(IType type) {
+ try {
+ if (type.isInterface()) {
return fgEmpty;
- else
- return vector.elements();
+ }
+ } catch (JavaModelException npe) {
+ return new IType[] {};
}
-
- /**
- * @see ITypeHierarchy
- */
- public IType getSuperclass(IType type) {
- try {
- if (type.isInterface()) {
- return null;
- }
- return (IType) fClassToSuperclass.get(type);
-
- } catch (JavaModelException npe) {
+ TypeVector vector = (TypeVector)fTypeToSubtypes.get(type);
+ if (vector == null)
+ return fgEmpty;
+ else
+ return vector.elements();
+}
+/**
+ * @see ITypeHierarchy
+ */
+public IType[] getSubtypes(IType type) {
+ return getSubtypesForType(type);
+}
+/**
+ * Returns an array of subtypes for the given type - will never return null.
+ */
+private IType[] getSubtypesForType(IType type) {
+ TypeVector vector = (TypeVector)fTypeToSubtypes.get(type);
+ if (vector == null)
+ return fgEmpty;
+ else
+ return vector.elements();
+}
+/**
+ * @see ITypeHierarchy
+ */
+public IType getSuperclass(IType type) {
+ try {
+ if (type.isInterface()) {
return null;
}
- }
+ return (IType) fClassToSuperclass.get(type);
- /**
- * @see ITypeHierarchy
- */
- public IType[] getSuperInterfaces(IType type) {
- IType[] interfaces = (IType[]) fTypeToSuperInterfaces.get(type);
- if (interfaces == null) {
- return fgEmpty;
- }
- return interfaces;
+ } catch (JavaModelException npe) {
+ return null;
}
-
- /**
- * @see ITypeHierarchy
- */
- public IType[] getSupertypes(IType type) {
- IType superclass = getSuperclass(type);
- if (superclass == null) {
- return getSuperInterfaces(type);
- } else {
- TypeVector superTypes = new TypeVector(getSuperInterfaces(type));
- superTypes.add(superclass);
- return superTypes.elements();
- }
+}
+/**
+ * @see ITypeHierarchy
+ */
+public IType[] getSuperInterfaces(IType type) {
+ IType[] interfaces = (IType[]) fTypeToSuperInterfaces.get(type);
+ if (interfaces == null) {
+ return fgEmpty;
}
-
- /**
- * @see ITypeHierarchy
- */
- public IType getType() {
- return fType;
+ return interfaces;
+}
+/**
+ * @see ITypeHierarchy
+ */
+public IType[] getSupertypes(IType type) {
+ IType superclass = getSuperclass(type);
+ if (superclass == null) {
+ return getSuperInterfaces(type);
+ } else {
+ TypeVector superTypes = new TypeVector(getSuperInterfaces(type));
+ superTypes.add(superclass);
+ return superTypes.elements();
}
-
- /**
- * Adds the new elements to a new array that contains all of the elements of the old array.
- * Returns the new array.
- */
- protected IType[] growAndAddToArray(IType[] array, IType[] additions) {
- if (array == null || array.length == 0) {
- return additions;
- }
- IType[] old = array;
- array = new IType[old.length + additions.length];
- System.arraycopy(old, 0, array, 0, old.length);
- System.arraycopy(additions, 0, array, old.length, additions.length);
- return array;
+}
+/**
+ * @see ITypeHierarchy
+ */
+public IType getType() {
+ return fType;
+}
+/**
+ * Adds the new elements to a new array that contains all of the elements of the old array.
+ * Returns the new array.
+ */
+protected IType[] growAndAddToArray(IType[] array, IType[] additions) {
+ if (array == null || array.length == 0) {
+ return additions;
+ }
+ IType[] old = array;
+ array = new IType[old.length + additions.length];
+ System.arraycopy(old, 0, array, 0, old.length);
+ System.arraycopy(additions, 0, array, old.length, additions.length);
+ return array;
+}
+/**
+ * Adds the new element to a new array that contains all of the elements of the old array.
+ * Returns the new array.
+ */
+protected IType[] growAndAddToArray(IType[] array, IType addition) {
+ if (array == null || array.length == 0) {
+ return new IType[] {addition};
+ }
+ IType[] old = array;
+ array = new IType[old.length + 1];
+ System.arraycopy(old, 0, array, 0, old.length);
+ array[old.length] = addition;
+ return array;
+}
+/**
+ * Returns whether one of the subtypes in this hierarchy has the given simple name
+ * or this type has the given simple name.
+ */
+private boolean hasSubtypeNamed(String simpleName) {
+ if (fType.getElementName().equals(simpleName)) {
+ return true;
}
-
- /**
- * Adds the new element to a new array that contains all of the elements of the old array.
- * Returns the new array.
- */
- protected IType[] growAndAddToArray(IType[] array, IType addition) {
- if (array == null || array.length == 0) {
- return new IType[] { addition };
+ IType[] types = this.getAllSubtypes(fType);
+ for (int i = 0, length = types.length; i < length; i++) {
+ if (types[i].getElementName().equals(simpleName)) {
+ return true;
}
- IType[] old = array;
- array = new IType[old.length + 1];
- System.arraycopy(old, 0, array, 0, old.length);
- array[old.length] = addition;
- return array;
}
-
- /**
- * Returns whether one of the subtypes in this hierarchy has the given simple name
- * or this type has the given simple name.
- */
- private boolean hasSubtypeNamed(String simpleName) {
- if (fType.getElementName().equals(simpleName)) {
+ return false;
+}
+/**
+ * Returns whether the given delta (a compilation unit delta or a class file delta)
+ * indicates that one of the supertypes has changed or one of the imports has changed.
+ */
+private boolean hasSuperTypeOrImportChange(IJavaElementDelta delta) {
+ IJavaElementDelta[] children = delta.getAffectedChildren();
+ for (int i = 0, length = children.length; i < length; i++) {
+ IJavaElementDelta child = children[i];
+ if ((child.getFlags() & IJavaElementDelta.F_SUPER_TYPES) > 0) {
return true;
}
- IType[] types = this.getAllSubtypes(fType);
- for (int i = 0, length = types.length; i < length; i++) {
- if (types[i].getElementName().equals(simpleName)) {
- return true;
- }
+ if (child.getElement() instanceof ImportContainer) {
+ return true;
}
- return false;
}
-
- /**
- * Returns whether the given delta (a compilation unit delta or a class file delta)
- * indicates that one of the supertypes has changed or one of the imports has changed.
- */
- private boolean hasSuperTypeOrImportChange(IJavaElementDelta delta) {
- IJavaElementDelta[] children = delta.getAffectedChildren();
- for (int i = 0, length = children.length; i < length; i++) {
- IJavaElementDelta child = children[i];
- if ((child.getFlags() & IJavaElementDelta.F_SUPER_TYPES) > 0) {
- return true;
- }
- if (child.getElement() instanceof ImportContainer) {
- return true;
- }
+ return false;
+}
+/**
+ * Returns whether one of the types in this hierarchy has the given simple name.
+ */
+private boolean hasTypeNamed(String simpleName) {
+ IType[] types = this.getAllTypes();
+ for (int i = 0, length = types.length; i < length; i++) {
+ if (types[i].getElementName().equals(simpleName)) {
+ return true;
}
- return false;
}
-
- /**
- * Returns whether one of the types in this hierarchy has the given simple name.
- */
- private boolean hasTypeNamed(String simpleName) {
- IType[] types = this.getAllTypes();
- for (int i = 0, length = types.length; i < length; i++) {
- if (types[i].getElementName().equals(simpleName)) {
- return true;
- }
+ return false;
+}
+/**
+ * Returns whether the given delta (a compilation unit delta or a class file delta)
+ * indicates that one of its types has a visibility change.
+ */
+private boolean hasVisibilityChange(IJavaElementDelta delta) {
+ IJavaElementDelta[] children = delta.getAffectedChildren();
+ for (int i = 0, length = children.length; i < length; i++) {
+ IJavaElementDelta child = children[i];
+ if ((child.getFlags() & IJavaElementDelta.F_MODIFIERS) > 0) {
+ return true;
}
- return false;
}
-
- /**
- * Returns whether the given delta (a compilation unit delta or a class file delta)
- * indicates that one of its types has a visibility change.
- */
- private boolean hasVisibilityChange(IJavaElementDelta delta) {
- IJavaElementDelta[] children = delta.getAffectedChildren();
- for (int i = 0, length = children.length; i < length; i++) {
- IJavaElementDelta child = children[i];
- if ((child.getFlags() & IJavaElementDelta.F_MODIFIERS) > 0) {
- return true;
- }
+ return false;
+}
+/**
+ * Returns whether the simple name of a supertype of the given type is
+ * the simple name of one of the types in this hierarchy.
+ */
+private boolean includesSupertypeOf(IType type) {
+ IType[] supertypes = getSupertypes(type);
+ for (int i = 0, length = supertypes.length; i < length; i++) {
+ if (hasTypeNamed(supertypes[i].getElementName())) {
+ return true;
}
- return false;
}
-
- /**
- * Returns whether the simple name of a supertype of the given type is
- * the simple name of one of the types in this hierarchy.
- */
- private boolean includesSupertypeOf(IType type) {
- IType[] supertypes = getSupertypes(type);
- for (int i = 0, length = supertypes.length; i < length; i++) {
- if (hasTypeNamed(supertypes[i].getElementName())) {
+ return false;
+}
+/**
+ * Initializes this hierarchy's internal tables with the given size.
+ */
+protected void initialize(int size) {
+ if (size < 10) {
+ size = 10;
+ }
+ int smallSize = (size / 2);
+ fClassToSuperclass = new Hashtable(size);
+ fTypeToSubtypes = new Hashtable(smallSize);
+ fTypeToSuperInterfaces = new Hashtable(smallSize);
+}
+/**
+ * Returns true if this hierarchy is actively tracking changes
+ * in the Java Model.
+ */
+protected boolean isActivated() {
+ return fIsActivated;
+}
+/**
+ * Returns true if the given delta could change this type hierarchy
+ */
+private boolean isAffected(IJavaElementDelta delta) {
+ IJavaElement element= delta.getElement();
+ switch (element.getElementType()) {
+ case IJavaElement.JAVA_MODEL:
+ return isAffectedByJavaModel(delta, element);
+ case IJavaElement.JAVA_PROJECT:
+ return isAffectedByJavaProject(delta, element);
+ case IJavaElement.PACKAGE_FRAGMENT_ROOT:
+ return isAffectedByPackageFragmentRoot(delta, element);
+ case IJavaElement.PACKAGE_FRAGMENT:
+ return isAffectedByPackageFragment(delta, element);
+ case IJavaElement.CLASS_FILE:
+ case IJavaElement.COMPILATION_UNIT:
+ return isAffectedByType(delta, element);
+ }
+ return false;
+}
+/**
+ * Returns true if any of the children of a project, package
+ * fragment root, or package fragment have changed in a way that
+ * effects this type hierarchy.
+ */
+private boolean isAffectedByChildren(IJavaElementDelta delta) {
+ if ((delta.getFlags() & IJavaElementDelta.F_CHILDREN) > 0) {
+ IJavaElementDelta[] children= delta.getAffectedChildren();
+ for (int i= 0; i < children.length; i++) {
+ if (isAffected(children[i])) {
return true;
}
}
- return false;
- }
-
- /**
- * Initializes this hierarchy's internal tables with the given size.
- */
- protected void initialize(int size) {
- if (size < 10) {
- size = 10;
- }
- int smallSize = (size / 2);
- fClassToSuperclass = new Hashtable(size);
- fTypeToSubtypes = new Hashtable(smallSize);
- fTypeToSuperInterfaces = new Hashtable(smallSize);
- }
-
- /**
- * Returns true if this hierarchy is actively tracking changes
- * in the Java Model.
- */
- protected boolean isActivated() {
- return fIsActivated;
- }
-
- /**
- * Returns true if the given delta could change this type hierarchy
- */
- private boolean isAffected(IJavaElementDelta delta) {
- IJavaElement element = delta.getElement();
- switch (element.getElementType()) {
- case IJavaElement.JAVA_MODEL :
- return isAffectedByJavaModel(delta, element);
- case IJavaElement.JAVA_PROJECT :
- return isAffectedByJavaProject(delta, element);
- case IJavaElement.PACKAGE_FRAGMENT_ROOT :
- return isAffectedByPackageFragmentRoot(delta, element);
- case IJavaElement.PACKAGE_FRAGMENT :
- return isAffectedByPackageFragment(delta, element);
- case IJavaElement.CLASS_FILE :
- case IJavaElement.COMPILATION_UNIT :
- return isAffectedByType(delta, element);
- }
- return false;
- }
-
- /**
- * Returns true if any of the children of a project, package
- * fragment root, or package fragment have changed in a way that
- * effects this type hierarchy.
- */
- private boolean isAffectedByChildren(IJavaElementDelta delta) {
- if ((delta.getFlags() & IJavaElementDelta.F_CHILDREN) > 0) {
- IJavaElementDelta[] children = delta.getAffectedChildren();
- for (int i = 0; i < children.length; i++) {
- if (isAffected(children[i])) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Returns true if the given java model delta could affect this type hierarchy
- */
- private boolean isAffectedByJavaModel(
- IJavaElementDelta delta,
- IJavaElement element) {
- switch (delta.getKind()) {
- case IJavaElementDelta.ADDED :
- case IJavaElementDelta.REMOVED :
- return element.equals(this.javaProject().getJavaModel());
- case IJavaElementDelta.CHANGED :
- return isAffectedByChildren(delta);
- }
- return false;
}
-
- /**
- * Returns true if the given java project delta could affect this type hierarchy
- */
- private boolean isAffectedByJavaProject(
- IJavaElementDelta delta,
- IJavaElement element) {
- switch (delta.getKind()) {
- case IJavaElementDelta.ADDED :
- try {
- // if the added project is on the classpath, then the hierarchy has changed
- IClasspathEntry[] classpath = this.javaProject().getResolvedClasspath(true);
- for (int i = 0; i < classpath.length; i++) {
- if (classpath[i].getEntryKind() == IClasspathEntry.CPE_PROJECT
+ return false;
+}
+/**
+ * Returns true if the given java model delta could affect this type hierarchy
+ */
+private boolean isAffectedByJavaModel(IJavaElementDelta delta, IJavaElement element) {
+ switch (delta.getKind()) {
+ case IJavaElementDelta.ADDED :
+ case IJavaElementDelta.REMOVED :
+ return element.equals(this.javaProject().getJavaModel());
+ case IJavaElementDelta.CHANGED :
+ return isAffectedByChildren(delta);
+ }
+ return false;
+}
+/**
+ * Returns true if the given java project delta could affect this type hierarchy
+ */
+private boolean isAffectedByJavaProject(IJavaElementDelta delta, IJavaElement element) {
+ switch (delta.getKind()) {
+ case IJavaElementDelta.ADDED :
+ try {
+ // if the added project is on the classpath, then the hierarchy has changed
+ IClasspathEntry[] classpath = this.javaProject().getResolvedClasspath(true);
+ for (int i = 0; i < classpath.length; i++) {
+ if (classpath[i].getEntryKind() == IClasspathEntry.CPE_PROJECT
&& classpath[i].getPath().equals(element.getUnderlyingResource().getFullPath())) {
- return true;
- }
- }
- return false;
- } catch (JavaModelException e) {
- return false;
- }
- case IJavaElementDelta.REMOVED :
- // removed project - if it contains packages we are interested in
- // then the type hierarchy has changed
- IJavaElement[] pkgs = fPackageRegion.getElements();
- for (int i = 0; i < pkgs.length; i++) {
- IJavaProject project = pkgs[i].getJavaProject();
- if (project != null && project.equals(element)) {
return true;
}
}
return false;
- case IJavaElementDelta.CHANGED :
- return isAffectedByChildren(delta);
- }
- return false;
- }
-
- /**
- * Returns true if the given package fragment delta could affect this type hierarchy
- */
- private boolean isAffectedByPackageFragment(
- IJavaElementDelta delta,
- IJavaElement element) {
- switch (delta.getKind()) {
- case IJavaElementDelta.ADDED :
- // if the package fragment is in the projects being considered, this could
- // introduce new types, changing the hierarchy
- return fProjectRegion.contains(element);
- case IJavaElementDelta.REMOVED :
- // is a change if the package fragment contains types in this hierarchy
- return packageRegionContainsSamePackageFragment(element);
- case IJavaElementDelta.CHANGED :
- // look at the files in the package fragment
- return isAffectedByChildren(delta);
- }
- return false;
- }
-
- /**
- * Returns true if the given package fragment root delta could affect this type hierarchy
- */
- private boolean isAffectedByPackageFragmentRoot(
- IJavaElementDelta delta,
- IJavaElement element) {
- switch (delta.getKind()) {
- case IJavaElementDelta.ADDED :
- return fProjectRegion.contains(element);
- case IJavaElementDelta.REMOVED :
- case IJavaElementDelta.CHANGED :
- if ((delta.getFlags() & IJavaElementDelta.F_REMOVED_FROM_CLASSPATH) > 0
- || (delta.getFlags() & IJavaElementDelta.F_CONTENT) > 0) {
- // 1. removed from classpath - if it contains packages we are interested in
- // the the type hierarchy has changed
- // 2. content of a jar changed - if it contains packages we are interested in
- // the the type hierarchy has changed
- IJavaElement[] pkgs = fPackageRegion.getElements();
- for (int i = 0; i < pkgs.length; i++) {
- if (pkgs[i].getParent().equals(element)) {
- return true;
- }
- }
- return false;
- }
- }
- return isAffectedByChildren(delta);
- }
-
- /**
- * Returns true if the given type delta (a compilation unit delta or a class file delta)
- * could affect this type hierarchy.
- *
- * The rules are:
- * - if the delta is an added type X, then the hierarchy is changed
- * . if one of the types in this hierarchy has a supertype whose simple name is the
- * simple name of X
- * . if the simple name of a supertype of X is the simple name of one of
- * the subtypes in this hierarchy (X will be added as one of the subtypes)
- * - if the delta is a changed type X, then the hierarchy is changed
- * . if the visibility of X has changed and if one of the types in this hierarchy has a
- * supertype whose simple name is the simple name of X
- * . if one of the supertypes of X has changed or one of the imports has changed,
- * and if the simple name of a supertype of X is the simple name of one of
- * the types in this hierarchy
- * - if the delta is a removed type X, then the hierarchy is changed
- * . if the given element is part of this hierarchy (note we cannot acces the types
- * because the element has been removed)
- */
- protected boolean isAffectedByType(
- IJavaElementDelta delta,
- IJavaElement element) {
- // ignore changes to working copies
- if (element instanceof CompilationUnit
- && ((CompilationUnit) element).isWorkingCopy()) {
- return false;
- }
-
- int kind = delta.getKind();
- if (kind == IJavaElementDelta.REMOVED) {
- return this.files.get(element) != null;
- } else {
- IType[] types = null;
- try {
- types =
- (element instanceof CompilationUnit)
- ? ((CompilationUnit) element).getAllTypes()
- : new IType[] {((org.eclipse.jdt.internal.core.ClassFile) element).getType()};
} catch (JavaModelException e) {
- e.printStackTrace();
return false;
}
- if (kind == IJavaElementDelta.ADDED) {
- for (int i = 0, length = types.length; i < length; i++) {
- IType type = types[i];
- if (typeHasSupertype(type) || subtypesIncludeSupertypeOf(type)) {
- return true;
- }
+ case IJavaElementDelta.REMOVED :
+ // removed project - if it contains packages we are interested in
+ // then the type hierarchy has changed
+ IJavaElement[] pkgs = fPackageRegion.getElements();
+ for (int i = 0; i < pkgs.length; i++) {
+ IJavaProject project = pkgs[i].getJavaProject();
+ if (project != null && project.equals(element)) {
+ return true;
}
- } else { // kind == IJavaElementDelta.CHANGED :
- boolean hasSupertypeChange = hasSuperTypeOrImportChange(delta);
- boolean hasVisibilityChange = hasVisibilityChange(delta);
- for (int i = 0, length = types.length; i < length; i++) {
- IType type = types[i];
- if ((hasVisibilityChange && typeHasSupertype(type))
- || (hasSupertypeChange && includesSupertypeOf(type))) {
+ }
+ return false;
+ case IJavaElementDelta.CHANGED :
+ return isAffectedByChildren(delta);
+ }
+ return false;
+}
+/**
+ * Returns true if the given package fragment delta could affect this type hierarchy
+ */
+private boolean isAffectedByPackageFragment(IJavaElementDelta delta, IJavaElement element) {
+ switch (delta.getKind()) {
+ case IJavaElementDelta.ADDED :
+ // if the package fragment is in the projects being considered, this could
+ // introduce new types, changing the hierarchy
+ return fProjectRegion.contains(element);
+ case IJavaElementDelta.REMOVED :
+ // is a change if the package fragment contains types in this hierarchy
+ return packageRegionContainsSamePackageFragment(element);
+ case IJavaElementDelta.CHANGED :
+ // look at the files in the package fragment
+ return isAffectedByChildren(delta);
+ }
+ return false;
+}
+/**
+ * Returns true if the given package fragment root delta could affect this type hierarchy
+ */
+private boolean isAffectedByPackageFragmentRoot(IJavaElementDelta delta, IJavaElement element) {
+ switch (delta.getKind()) {
+ case IJavaElementDelta.ADDED :
+ return fProjectRegion.contains(element);
+ case IJavaElementDelta.REMOVED :
+ case IJavaElementDelta.CHANGED :
+ if ((delta.getFlags() & IJavaElementDelta.F_REMOVED_FROM_CLASSPATH) > 0 || (delta.getFlags() & IJavaElementDelta.F_CONTENT) > 0) {
+ // 1. removed from classpath - if it contains packages we are interested in
+ // the the type hierarchy has changed
+ // 2. content of a jar changed - if it contains packages we are interested in
+ // the the type hierarchy has changed
+ IJavaElement[] pkgs = fPackageRegion.getElements();
+ for (int i = 0; i < pkgs.length; i++) {
+ if (pkgs[i].getParent().equals(element)) {
return true;
}
}
+ return false;
}
- }
- return false;
- }
-
- /**
- * Returns the java project this hierarchy was created in.
- */
- public IJavaProject javaProject() {
- return fType.getJavaProject();
}
-
- /**
- * Returns <code>true</code> if an equivalent package fragment is included in the package
- * region. Package fragments are equivalent if they both have the same name.
- */
- protected boolean packageRegionContainsSamePackageFragment(IJavaElement element) {
- IJavaElement[] pkgs = fPackageRegion.getElements();
- for (int i = 0; i < pkgs.length; i++) {
- if (pkgs[i].getElementName().equals(element.getElementName())) {
- return true;
- }
- }
+ return isAffectedByChildren(delta);
+}
+/**
+ * Returns true if the given type delta (a compilation unit delta or a class file delta)
+ * could affect this type hierarchy.
+ *
+ * The rules are:
+ * - if the delta is an added type X, then the hierarchy is changed
+ * . if one of the types in this hierarchy has a supertype whose simple name is the
+ * simple name of X
+ * . if the simple name of a supertype of X is the simple name of one of
+ * the subtypes in this hierarchy (X will be added as one of the subtypes)
+ * - if the delta is a changed type X, then the hierarchy is changed
+ * . if the visibility of X has changed and if one of the types in this hierarchy has a
+ * supertype whose simple name is the simple name of X
+ * . if one of the supertypes of X has changed or one of the imports has changed,
+ * and if the simple name of a supertype of X is the simple name of one of
+ * the types in this hierarchy
+ * - if the delta is a removed type X, then the hierarchy is changed
+ * . if the given element is part of this hierarchy (note we cannot acces the types
+ * because the element has been removed)
+ */
+protected boolean isAffectedByType(IJavaElementDelta delta, IJavaElement element) {
+ // ignore changes to working copies
+ if (element instanceof CompilationUnit && ((CompilationUnit)element).isWorkingCopy()) {
return false;
}
-
- /**
- * Prunes this type hierarchy to only contain the branch to the given type,
- * and its subtree. Pruning is only done for classes.
- */
- protected void pruneTypeHierarchy(IType type, IProgressMonitor monitor)
- throws JavaModelException {
- if (type.isClass()) {
- IType[] supers = getAllSuperclasses(type);
-
- if (supers.length == 0) {
- // nothing to prune if this is a root - unless there are other roots
- return;
+
+ int kind = delta.getKind();
+ if (kind == IJavaElementDelta.REMOVED) {
+ return this.files.get(element) != null;
+ } else {
+ IType[] types = null;
+ try {
+ types = (element instanceof CompilationUnit) ?
+ ((CompilationUnit)element).getAllTypes() :
+ new IType[] {((org.eclipse.jdt.internal.core.ClassFile)element).getType()};
+ } catch (JavaModelException e) {
+ e.printStackTrace();
+ return false;
+ }
+ if (kind == IJavaElementDelta.ADDED) {
+ for (int i = 0, length = types.length; i < length; i++) {
+ IType type = types[i];
+ if (typeHasSupertype(type) || subtypesIncludeSupertypeOf(type)) {
+ return true;
+ }
}
-
- IType[] branch = new IType[supers.length + 1];
- System.arraycopy(supers, 0, branch, 1, supers.length);
- branch[0] = type;
- // Branch is a list from the root to our type
- // Walk the branch pruning all other subtrees
- for (int i = branch.length - 1; i > 0; i--) {
- IType[] subtrees = getSubtypes(branch[i]);
- for (int j = 0; j < subtrees.length; j++) {
- if (!subtrees[j].equals(branch[i - 1])) {
- removeType(subtrees[j]);
- }
- this.worked(1);
+ } else { // kind == IJavaElementDelta.CHANGED :
+ boolean hasSupertypeChange = hasSuperTypeOrImportChange(delta);
+ boolean hasVisibilityChange = hasVisibilityChange(delta);
+ for (int i = 0, length = types.length; i < length; i++) {
+ IType type = types[i];
+ if ((hasVisibilityChange && typeHasSupertype(type))
+ || (hasSupertypeChange && includesSupertypeOf(type))) {
+ return true;
}
- fTypeToSubtypes.put(branch[i], new TypeVector(branch[i - 1]));
}
}
}
-
- /**
- * @see ITypeHierarchy
- */
- public void refresh(IProgressMonitor monitor) throws JavaModelException {
- try {
- boolean reactivate = isActivated();
- Vector listeners = fChangeListeners;
- if (reactivate) {
- deactivate();
- }
- fProgressMonitor = monitor;
- if (monitor != null) {
- monitor.beginTask("Creating type hierarchy...", IProgressMonitor.UNKNOWN);
- }
- compute();
- if (fType != null) {
- //prune the hierarchy tree to only include branch and subtree for the type
- pruneTypeHierarchy(fType, monitor);
- }
- if (reactivate) {
- activate();
- fChangeListeners = listeners;
- }
- if (monitor != null) {
- monitor.done();
- }
- fProgressMonitor = null;
- } catch (JavaModelException e) {
- fProgressMonitor = null;
- throw e;
- } catch (CoreException e) {
- fProgressMonitor = null;
- throw new JavaModelException(e);
- } catch (OperationCanceledException oce) {
- refreshCancelled(oce);
+ return false;
+}
+/**
+ * Returns the java project this hierarchy was created in.
+ */
+public IJavaProject javaProject() {
+ return fType.getJavaProject();
+}
+/**
+ * Returns <code>true</code> if an equivalent package fragment is included in the package
+ * region. Package fragments are equivalent if they both have the same name.
+ */
+protected boolean packageRegionContainsSamePackageFragment(IJavaElement element) {
+ IJavaElement[] pkgs = fPackageRegion.getElements();
+ for (int i = 0; i < pkgs.length; i++) {
+ if (pkgs[i].getElementName().equals(element.getElementName())) {
+ return true;
}
}
-
- /**
- * The refresh of this type hierarchy has been cancelled.
- * Cleanup the state of this now invalid type hierarchy.
- */
- protected void refreshCancelled(OperationCanceledException oce)
- throws JavaModelException {
- destroy();
- fProgressMonitor = null;
- throw oce;
- }
-
- /**
- * Removes all the subtypes of the given type from the type hierarchy,
- * and removes its superclass entry.
- */
- protected void removeType(IType type) throws JavaModelException {
- IType[] subtypes = getSubtypes(type);
- fTypeToSubtypes.remove(type);
- fClassToSuperclass.remove(type);
- if (subtypes != null) {
- for (int i = 0; i < subtypes.length; i++) {
- removeType(subtypes[i]);
+ return false;
+}
+/**
+ * Prunes this type hierarchy to only contain the branch to the given type,
+ * and its subtree. Pruning is only done for classes.
+ */
+protected void pruneTypeHierarchy(IType type, IProgressMonitor monitor) throws JavaModelException {
+ if (type.isClass()) {
+ IType[] supers= getAllSuperclasses(type);
+
+ if (supers.length == 0) {
+ // nothing to prune if this is a root - unless there are other roots
+ return;
+ }
+
+ IType[] branch= new IType[supers.length + 1];
+ System.arraycopy(supers, 0, branch, 1, supers.length);
+ branch[0]= type;
+ // Branch is a list from the root to our type
+ // Walk the branch pruning all other subtrees
+ for (int i= branch.length - 1; i > 0; i--) {
+ IType[] subtrees= getSubtypes(branch[i]);
+ for (int j= 0; j < subtrees.length; j++) {
+ if (!subtrees[j].equals(branch[i - 1])) {
+ removeType(subtrees[j]);
+ }
+ this.worked(1);
}
+ fTypeToSubtypes.put(branch[i], new TypeVector(branch[i - 1]));
}
}
-
- /**
- * @see ITypeHierarchy
- */
- public void removeTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener) {
- if (fChangeListeners == null) {
- return;
- }
- fChangeListeners.removeElement(listener);
- if (fChangeListeners.isEmpty()) {
+}
+/**
+ * @see ITypeHierarchy
+ */
+public void refresh(IProgressMonitor monitor) throws JavaModelException {
+ try {
+ boolean reactivate = isActivated();
+ Vector listeners = fChangeListeners;
+ if (reactivate) {
deactivate();
}
- }
-
- /**
- * Returns whether the simple name of a supertype of the given type is
- * the simple name of one of the subtypes in this hierarchy or the
- * simple name of this type.
- */
- private boolean subtypesIncludeSupertypeOf(IType type) {
- // look for superclass
- String superclassName = null;
- try {
- superclassName = type.getSuperclassName();
- } catch (JavaModelException e) {
- e.printStackTrace();
- return false;
+ fProgressMonitor = monitor;
+ if (monitor != null) {
+ monitor.beginTask("Creating type hierarchy...", IProgressMonitor.UNKNOWN);
}
- if (superclassName == null) {
- superclassName = "Object";
+ compute();
+ if (fType != null) {
+ //prune the hierarchy tree to only include branch and subtree for the type
+ pruneTypeHierarchy(fType, monitor);
}
- int dot = -1;
- String simpleSuper =
- (dot = superclassName.lastIndexOf('.')) > -1
- ? superclassName.substring(dot + 1)
- : superclassName;
- if (hasSubtypeNamed(simpleSuper)) {
- return true;
+ if (reactivate) {
+ activate();
+ fChangeListeners = listeners;
}
-
- // look for super interfaces
- String[] interfaceNames = null;
- try {
- interfaceNames = type.getSuperInterfaceNames();
- } catch (JavaModelException e) {
- e.printStackTrace();
- return false;
+ if (monitor != null) {
+ monitor.done();
}
- for (int i = 0, length = interfaceNames.length; i < length; i++) {
- dot = -1;
- String interfaceName = interfaceNames[i];
- String simpleInterface =
- (dot = interfaceName.lastIndexOf('.')) > -1
- ? interfaceName.substring(dot)
- : interfaceName;
- if (hasSubtypeNamed(simpleInterface)) {
- return true;
- }
+ fProgressMonitor = null;
+ } catch (JavaModelException e) {
+ fProgressMonitor = null;
+ throw e;
+ } catch (CoreException e) {
+ fProgressMonitor = null;
+ throw new JavaModelException(e);
+ } catch (OperationCanceledException oce) {
+ refreshCancelled(oce);
+ }
+}
+/**
+ * The refresh of this type hierarchy has been cancelled.
+ * Cleanup the state of this now invalid type hierarchy.
+ */
+protected void refreshCancelled(OperationCanceledException oce) throws JavaModelException {
+ destroy();
+ fProgressMonitor = null;
+ throw oce;
+}
+/**
+ * Removes all the subtypes of the given type from the type hierarchy,
+ * and removes its superclass entry.
+ */
+protected void removeType(IType type) throws JavaModelException {
+ IType[] subtypes= getSubtypes(type);
+ fTypeToSubtypes.remove(type);
+ fClassToSuperclass.remove(type);
+ if (subtypes != null) {
+ for (int i= 0; i < subtypes.length; i++) {
+ removeType(subtypes[i]);
}
-
+ }
+}
+/**
+ * @see ITypeHierarchy
+ */
+public void removeTypeHierarchyChangedListener(ITypeHierarchyChangedListener listener) {
+ if (fChangeListeners == null) {
+ return;
+ }
+ fChangeListeners.removeElement(listener);
+ if (fChangeListeners.isEmpty()) {
+ deactivate();
+ }
+}
+/**
+ * Returns whether the simple name of a supertype of the given type is
+ * the simple name of one of the subtypes in this hierarchy or the
+ * simple name of this type.
+ */
+private boolean subtypesIncludeSupertypeOf(IType type) {
+ // look for superclass
+ String superclassName = null;
+ try {
+ superclassName = type.getSuperclassName();
+ } catch (JavaModelException e) {
+ e.printStackTrace();
return false;
}
-
- /**
- * @see ITypeHierarchy
- */
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append("Focus: ");
- buffer.append(fType == null ? "<NONE>" : fType.getFullyQualifiedName());
- buffer.append("\n");
- if (exists()) {
- if (fType != null) {
- buffer.append("Super types:\n");
- toString(buffer, fType, 1, true);
- buffer.append("Sub types:\n");
- toString(buffer, fType, 1, false);
- } else {
- buffer.append("Sub types of root classes:\n");
- IType[] roots = getRootClasses();
- for (int i = 0; i < roots.length; i++) {
- toString(buffer, roots[i], 1, false);
- }
- }
- } else {
- buffer.append("(Hierarchy became stale)");
- }
- return buffer.toString();
+ if (superclassName == null) {
+ superclassName = "Object";
+ }
+ int dot = -1;
+ String simpleSuper = (dot = superclassName.lastIndexOf('.')) > -1 ?
+ superclassName.substring(dot + 1) :
+ superclassName;
+ if (hasSubtypeNamed(simpleSuper)) {
+ return true;
}
- /**
- * Append a String to the given buffer representing the hierarchy for the type,
- * beginning with the specified indentation level.
- * If ascendant, shows the super types, otherwise show the sub types.
- */
- private void toString(
- StringBuffer buffer,
- IType type,
- int indent,
- boolean ascendant) {
- for (int i = 0; i < indent; i++) {
- buffer.append(" ");
- }
- buffer.append(type.getFullyQualifiedName());
- buffer.append('\n');
-
- IType[] types = ascendant ? getSupertypes(type) : getSubtypes(type);
- for (int i = 0; i < types.length; i++) {
- toString(buffer, types[i], indent + 1, ascendant);
+ // look for super interfaces
+ String[] interfaceNames = null;
+ try {
+ interfaceNames = type.getSuperInterfaceNames();
+ } catch (JavaModelException e) {
+ e.printStackTrace();
+ return false;
+ }
+ for (int i = 0, length = interfaceNames.length; i < length; i++) {
+ dot = -1;
+ String interfaceName = interfaceNames[i];
+ String simpleInterface = (dot = interfaceName.lastIndexOf('.')) > -1 ?
+ interfaceName.substring(dot) :
+ interfaceName;
+ if (hasSubtypeNamed(simpleInterface)) {
+ return true;
}
-
}
-
- /**
- * Returns whether one of the types in this hierarchy has a supertype whose simple
- * name is the simple name of the given type.
- */
- private boolean typeHasSupertype(IType type) {
- String simpleName = type.getElementName();
- Enumeration enum = fClassToSuperclass.elements();
- while (enum.hasMoreElements()) {
- IType superType = (IType) enum.nextElement();
- if (superType.getElementName().equals(simpleName)) {
- return true;
+
+ return false;
+}
+/**
+ * @see ITypeHierarchy
+ */
+public String toString() {
+ StringBuffer buffer = new StringBuffer();
+ buffer.append("Focus: ");
+ buffer.append(fType == null ? "<NONE>" : fType.getFullyQualifiedName());
+ buffer.append("\n");
+ if (exists()) {
+ if (fType != null) {
+ buffer.append("Super types:\n");
+ toString(buffer, fType, 1, true);
+ buffer.append("Sub types:\n");
+ toString(buffer, fType, 1, false);
+ } else {
+ buffer.append("Sub types of root classes:\n");
+ IType[] roots= getRootClasses();
+ for (int i= 0; i < roots.length; i++) {
+ toString(buffer, roots[i], 1, false);
}
}
- return false;
+ } else {
+ buffer.append("(Hierarchy became stale)");
}
+ return buffer.toString();
+}
+/**
+ * Append a String to the given buffer representing the hierarchy for the type,
+ * beginning with the specified indentation level.
+ * If ascendant, shows the super types, otherwise show the sub types.
+ */
+private void toString(StringBuffer buffer, IType type, int indent, boolean ascendant) {
+ for (int i= 0; i < indent; i++) {
+ buffer.append(" ");
+ }
+ buffer.append(type.getFullyQualifiedName());
+ buffer.append('\n');
- /**
- * @see IProgressMonitor
- */
- protected void worked(int work) {
- if (fProgressMonitor != null) {
- fProgressMonitor.worked(work);
- checkCanceled();
- }
+ IType[] types= ascendant ? getSupertypes(type) : getSubtypes(type);
+ for (int i= 0; i < types.length; i++) {
+ toString(buffer, types[i], indent + 1, ascendant);
}
}
+/**
+ * Returns whether one of the types in this hierarchy has a supertype whose simple
+ * name is the simple name of the given type.
+ */
+private boolean typeHasSupertype(IType type) {
+ String simpleName = type.getElementName();
+ Enumeration enum = fClassToSuperclass.elements();
+ while (enum.hasMoreElements()) {
+ IType superType = (IType)enum.nextElement();
+ if (superType.getElementName().equals(simpleName)) {
+ return true;
+ }
+ }
+ return false;
+}
+/**
+ * @see IProgressMonitor
+ */
+protected void worked(int work) {
+ if (fProgressMonitor != null) {
+ fProgressMonitor.worked(work);
+ checkCanceled();
+ }
+}
+}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/AbstractDOMBuilder.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/AbstractDOMBuilder.java
index 0d4683b32f..75da54c1a6 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/AbstractDOMBuilder.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/AbstractDOMBuilder.java
@@ -14,15 +14,13 @@ import java.util.Stack;
/**
* An abstract DOM builder that contains shared functionality of DOMBuilder and SimpleDOMBuilder.
*/
-public class AbstractDOMBuilder
- extends ReferenceInfoAdapter
- implements ILineStartFinder {
+public class AbstractDOMBuilder extends ReferenceInfoAdapter implements ILineStartFinder {
/**
* Set to true when an error is encounterd while
* fuzzy parsing
*/
protected boolean fAbort;
-
+
/**
* True when a compilation unit is being constructed.
* False when any other type of document fragment is
@@ -35,13 +33,13 @@ public class AbstractDOMBuilder
* constructed. False when any other type of document
* fragment is being constructed.
*/
- protected boolean fBuildingType = false;
+ protected boolean fBuildingType= false;
/**
* The String on which the JDOM is being created.
*/
- protected char[] fDocument = null;
-
+ protected char[] fDocument= null;
+
/**
* The source positions of all of the line separators in the document.
*/
@@ -52,7 +50,7 @@ public class AbstractDOMBuilder
* a compilation unit or type. The top of the stack
* is the document fragment that children are added to.
*/
- protected Stack fStack = null;
+ protected Stack fStack = null;
/**
* The number of fields constructed in the current
@@ -66,163 +64,145 @@ public class AbstractDOMBuilder
* The current node being constructed.
*/
protected DOMNode fNode;
- /**
- * AbstractDOMBuilder constructor.
- */
- public AbstractDOMBuilder() {
- super();
- }
-
- /**
- * Accepts the line separator table and converts it into a line start table.
- *
- * <p>A line separator might corresponds to several characters in the source.
- *
- * @see IDocumentElementRequestor#acceptLineSeparatorPositions
- */
- public void acceptLineSeparatorPositions(int[] positions) {
- if (positions != null) {
- int length = positions.length;
- if (length > 0) {
- fLineStartPositions = new int[length + 1];
- fLineStartPositions[0] = 0;
- int documentLength = fDocument.length;
- for (int i = 0; i < length; i++) {
- int iPlusOne = i + 1;
- int positionPlusOne = positions[i] + 1;
- if (positionPlusOne < documentLength) {
- if (iPlusOne < length) {
- // more separators
- fLineStartPositions[iPlusOne] = positionPlusOne;
+/**
+ * AbstractDOMBuilder constructor.
+ */
+public AbstractDOMBuilder() {
+ super();
+}
+/**
+ * Accepts the line separator table and converts it into a line start table.
+ *
+ * <p>A line separator might corresponds to several characters in the source.
+ *
+ * @see IDocumentElementRequestor#acceptLineSeparatorPositions
+ */
+public void acceptLineSeparatorPositions(int[] positions) {
+ if (positions != null) {
+ int length = positions.length;
+ if (length > 0) {
+ fLineStartPositions = new int[length + 1];
+ fLineStartPositions[0] = 0;
+ int documentLength = fDocument.length;
+ for (int i = 0; i < length; i++) {
+ int iPlusOne = i + 1;
+ int positionPlusOne = positions[i] + 1;
+ if (positionPlusOne < documentLength) {
+ if (iPlusOne < length) {
+ // more separators
+ fLineStartPositions[iPlusOne] = positionPlusOne;
+ } else {
+ // no more separators
+ if (fDocument[positionPlusOne] == '\n') {
+ fLineStartPositions[iPlusOne] = positionPlusOne + 1;
} else {
- // no more separators
- if (fDocument[positionPlusOne] == '\n') {
- fLineStartPositions[iPlusOne] = positionPlusOne + 1;
- } else {
- fLineStartPositions[iPlusOne] = positionPlusOne;
- }
+ fLineStartPositions[iPlusOne] = positionPlusOne;
}
- } else {
- fLineStartPositions[iPlusOne] = positionPlusOne;
}
+ } else {
+ fLineStartPositions[iPlusOne] = positionPlusOne;
}
}
}
}
-
- /**
- * Does nothing.
- */
- public void acceptProblem(IProblem problem) {
- }
-
- /**
- * Adds the given node to the current enclosing scope, building the JDOM
- * tree. Nodes are only added to an enclosing scope when a compilation unit or type
- * is being built (since those are the only nodes that have children).
- *
- * <p>NOTE: nodes are added to the JDOM via the method #basicAddChild such that
- * the nodes in the newly created JDOM are not fragmented.
- */
- protected void addChild(IDOMNode child) {
- if (fStack.size() > 0) {
- DOMNode parent = (DOMNode) fStack.peek();
- if (fBuildingCU || fBuildingType) {
- parent.basicAddChild(child);
- }
- }
- }
-
- /**
- * @see IDOMFactory#createCompilationUnit(String)
- */
- public IDOMCompilationUnit createCompilationUnit(
- char[] contents,
- char[] name) {
- return createCompilationUnit(new CompilationUnit(contents, name));
- }
-
- /**
- * @see IDOMFactory#createCompilationUnit(String)
- */
- public IDOMCompilationUnit createCompilationUnit(ICompilationUnit compilationUnit) {
- if (fAbort) {
- return null;
- }
- fNode.normalize(this);
- return (IDOMCompilationUnit) fNode;
- }
-
- /**
- * @see IDocumentElementRequestor#enterClass
- */
- public void enterCompilationUnit() {
- if (fBuildingCU) {
- IDOMCompilationUnit cu =
- new DOMCompilationUnit(fDocument, new int[] { 0, fDocument.length - 1 });
- fStack.push(cu);
+}
+/**
+ * Does nothing.
+ */
+public void acceptProblem(IProblem problem) {}
+/**
+ * Adds the given node to the current enclosing scope, building the JDOM
+ * tree. Nodes are only added to an enclosing scope when a compilation unit or type
+ * is being built (since those are the only nodes that have children).
+ *
+ * <p>NOTE: nodes are added to the JDOM via the method #basicAddChild such that
+ * the nodes in the newly created JDOM are not fragmented.
+ */
+protected void addChild(IDOMNode child) {
+ if (fStack.size() > 0) {
+ DOMNode parent = (DOMNode) fStack.peek();
+ if (fBuildingCU || fBuildingType) {
+ parent.basicAddChild(child);
}
}
-
- /**
- * Finishes the configuration of the compilation unit DOM object which
- * was created by a previous enterCompilationUnit call.
- *
- * @see IDocumentElementRequestor#exitCompilationUnit
- */
- public void exitCompilationUnit(int declarationEnd) {
- DOMCompilationUnit cu = (DOMCompilationUnit) fStack.pop();
- cu.setSourceRangeEnd(declarationEnd);
- fNode = cu;
- }
-
- /**
- * Finishes the configuration of the class and interface DOM objects.
- *
- * @param bodyEnd - a source position corresponding to the closing bracket of the class
- * @param declarationEnd - a source position corresponding to the end of the class
- * declaration. This can include whitespace and comments following the closing bracket.
- */
- protected void exitType(int bodyEnd, int declarationEnd) {
- DOMType type = (DOMType) fStack.pop();
- type.setSourceRangeEnd(declarationEnd);
- type.setCloseBodyRangeStart(bodyEnd);
- type.setCloseBodyRangeEnd(bodyEnd);
- fNode = type;
- }
-
- /**
- * @see ILineSeparatorFinder
- */
- public int getLineStart(int position) {
- int lineSeparatorCount = fLineStartPositions.length;
- // reverse traversal intentional.
- for (int i = lineSeparatorCount - 1; i >= 0; i--) {
- if (fLineStartPositions[i] <= position)
- return fLineStartPositions[i];
- }
- return 0;
+}
+/**
+ * @see IDOMFactory#createCompilationUnit(String)
+ */
+public IDOMCompilationUnit createCompilationUnit(char[] contents, char[] name) {
+ return createCompilationUnit(new CompilationUnit(contents, name));
+}
+/**
+ * @see IDOMFactory#createCompilationUnit(String)
+ */
+public IDOMCompilationUnit createCompilationUnit(ICompilationUnit compilationUnit) {
+ if (fAbort) {
+ return null;
}
-
- /**
- * Initializes the builder to create a document fragment.
- *
- * @param sourceCode - the document containing the source code to be analyzed
- * @param buildingCompilationUnit - true if a the document is being analyzed to
- * create a compilation unit, otherwise false
- * @param buildingType - true if the document is being analyzed to create a
- * type or compilation unit
- */
- protected void initializeBuild(
- char[] sourceCode,
- boolean buildingCompilationUnit,
- boolean buildingType) {
- fBuildingCU = buildingCompilationUnit;
- fBuildingType = buildingType;
- fStack = new Stack();
- fDocument = sourceCode;
- fFieldCount = 0;
- fAbort = false;
+ fNode.normalize(this);
+ return (IDOMCompilationUnit)fNode;
+}
+/**
+ * @see IDocumentElementRequestor#enterClass
+ */
+public void enterCompilationUnit() {
+ if (fBuildingCU) {
+ IDOMCompilationUnit cu= new DOMCompilationUnit(fDocument, new int[] {0, fDocument.length - 1});
+ fStack.push(cu);
+ }
+}
+/**
+ * Finishes the configuration of the compilation unit DOM object which
+ * was created by a previous enterCompilationUnit call.
+ *
+ * @see IDocumentElementRequestor#exitCompilationUnit
+ */
+public void exitCompilationUnit(int declarationEnd) {
+ DOMCompilationUnit cu = (DOMCompilationUnit) fStack.pop();
+ cu.setSourceRangeEnd(declarationEnd);
+ fNode = cu;
+}
+/**
+ * Finishes the configuration of the class and interface DOM objects.
+ *
+ * @param bodyEnd - a source position corresponding to the closing bracket of the class
+ * @param declarationEnd - a source position corresponding to the end of the class
+ * declaration. This can include whitespace and comments following the closing bracket.
+ */
+protected void exitType(int bodyEnd, int declarationEnd) {
+ DOMType type = (DOMType)fStack.pop();
+ type.setSourceRangeEnd(declarationEnd);
+ type.setCloseBodyRangeStart(bodyEnd);
+ type.setCloseBodyRangeEnd(bodyEnd);
+ fNode = type;
+}
+/**
+ * @see ILineSeparatorFinder
+ */
+public int getLineStart(int position) {
+ int lineSeparatorCount = fLineStartPositions.length;
+ // reverse traversal intentional.
+ for(int i = lineSeparatorCount - 1; i >= 0; i--) {
+ if (fLineStartPositions[i] <= position)
+ return fLineStartPositions[i];
}
-
+ return 0;
+}
+/**
+ * Initializes the builder to create a document fragment.
+ *
+ * @param sourceCode - the document containing the source code to be analyzed
+ * @param buildingCompilationUnit - true if a the document is being analyzed to
+ * create a compilation unit, otherwise false
+ * @param buildingType - true if the document is being analyzed to create a
+ * type or compilation unit
+ */
+protected void initializeBuild(char[] sourceCode, boolean buildingCompilationUnit, boolean buildingType) {
+ fBuildingCU = buildingCompilationUnit;
+ fBuildingType = buildingType;
+ fStack = new Stack();
+ fDocument = sourceCode;
+ fFieldCount = 0;
+ fAbort = false;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/CompilationUnit.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/CompilationUnit.java
index 3b968fc434..4583cd92e2 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/CompilationUnit.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/CompilationUnit.java
@@ -17,36 +17,31 @@ public class CompilationUnit implements ICompilationUnit {
protected char[] fContents;
protected char[] fFileName;
protected char[] fMainTypeName;
- public CompilationUnit(char[] contents, char[] filename) {
- fContents = contents;
- fFileName = filename;
+public CompilationUnit(char[] contents, char[] filename) {
+ fContents = contents;
+ fFileName = filename;
- String file = new String(filename);
- int start = file.lastIndexOf("/") + 1;
- if (start == 0 || start < file.lastIndexOf("\\"))
- start = file.lastIndexOf("\\") + 1;
+ String file = new String(filename);
+ int start = file.lastIndexOf("/") + 1;
+ if (start == 0 || start < file.lastIndexOf("\\"))
+ start = file.lastIndexOf("\\") + 1;
- int end = file.lastIndexOf(".");
- if (end == -1)
- end = file.length();
-
- fMainTypeName = file.substring(start, end).toCharArray();
- }
-
- public char[] getContents() {
- return fContents;
- }
-
- public char[] getFileName() {
- return fFileName;
- }
-
- public char[] getMainTypeName() {
- return fMainTypeName;
- }
-
- public String toString() {
- return "CompilationUnit[" + new String(fFileName) + "]";
- }
+ int end = file.lastIndexOf(".");
+ if (end == -1)
+ end = file.length();
+ fMainTypeName = file.substring(start, end).toCharArray();
+}
+public char[] getContents() {
+ return fContents;
+}
+public char[] getFileName() {
+ return fFileName;
+}
+public char[] getMainTypeName() {
+ return fMainTypeName;
+}
+public String toString() {
+ return "CompilationUnit[" + new String(fFileName) + "]";
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMBuilder.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMBuilder.java
index 18414cb1f0..f5c1b11564 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMBuilder.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMBuilder.java
@@ -22,868 +22,597 @@ import java.util.Vector;
*
*/
-public class DOMBuilder
- extends AbstractDOMBuilder
- implements IDocumentElementRequestor {
-
+public class DOMBuilder extends AbstractDOMBuilder implements IDocumentElementRequestor {
+
/**
* True when parsing a single member - ignore any problems
* encountered after the member.
*/
- protected boolean fBuildingSingleMember = false;
-
+ protected boolean fBuildingSingleMember= false;
+
/**
* True when the single member being built has been
* exited.
*/
- protected boolean fFinishedSingleMember = false;
+ protected boolean fFinishedSingleMember = false;
/**
* Collection of multiple fields in one declaration
*/
protected Vector fFields;
- /**
- * Creates a new DOMBuilder
- */
- public DOMBuilder() {
- }
-
- /**
- * @see IDocumentElementRequestor.acceptImport(...);
- */
- public void acceptImport(
- int declarationStart,
- int declarationEnd,
- int[] javaDocPositions,
- char[] name,
- int nameStart,
- boolean onDemand) {
- int[] sourceRange = { declarationStart, declarationEnd };
- int[] nameRange = { nameStart, declarationEnd - 1 };
-
- /* See 1FVII1P */
- String importName =
- CharArrayOps.substring(
- fDocument,
- nameRange[0],
- nameRange[1] + 1 - nameRange[0]);
-
- fNode = new DOMImport(fDocument, sourceRange, importName, nameRange, onDemand);
- addChild(fNode);
- if (fBuildingSingleMember) {
- fFinishedSingleMember = true;
- }
- }
-
- /**
- * @see IDocumentElementRequestor.acceptInitializer(...);
- */
- public void acceptInitializer(
- int declarationStart,
- int declarationEnd,
- int[] javaDocPositions,
- int modifiers,
- int modifiersStart,
- int bodyStart,
- int bodyEnd) {
- int[] sourceRange = { declarationStart, declarationEnd };
- int[] commentRange = { -1, -1 };
- if (javaDocPositions != null) {
- int length = javaDocPositions.length;
- commentRange[0] = javaDocPositions[length - 2];
- commentRange[1] = javaDocPositions[length - 1];
- }
-
- int[] modifiersRange = { -1, -1 };
- if (modifiersStart > declarationStart) {
- modifiersRange[0] = modifiersStart;
- modifiersRange[1] = bodyStart - 1;
- }
- fNode =
- new DOMInitializer(
- fDocument,
- sourceRange,
- commentRange,
- modifiers,
- modifiersRange,
- bodyStart);
- addChild(fNode);
- if (fBuildingSingleMember) {
- fFinishedSingleMember = true;
- }
- }
- /**
- * @see IDocumentElementRequestor.acceptPackage(...);
- */
- public void acceptPackage(
- int declarationStart,
- int declarationEnd,
- int[] javaDocPositions,
- char[] name,
- int nameStartPosition) {
- int[] sourceRange = { declarationStart, declarationEnd };
- int[] nameRange = { nameStartPosition, declarationEnd - 1 };
- fNode =
- new DOMPackage(
- fDocument,
- sourceRange,
- CharArrayOps.charToString(name),
- nameRange);
- addChild(fNode);
- if (fBuildingSingleMember) {
- fFinishedSingleMember = true;
- }
- }
-
- /**
- * Sets the abort flag to true. The parser has encountered an error
- * in the current document. If we are only building a single member, and
- * we are done with the member - don't worry about the error.
- *
- * @see IDocumentElementRequestor
- */
- public void acceptProblem(IProblem problem) {
- if (fBuildingSingleMember && fFinishedSingleMember) {
- return;
- }
- fAbort = true;
- }
-
- /**
- * Adds the given node to the current enclosing scope, building the JDOM
- * tree. Nodes are only added to an enclosing scope when a compilation unit or type
- * is being built (since those are the only nodes that have children).
- *
- * <p>NOTE: nodes are added to the JDOM via the method #basicAddChild such that
- * the nodes in the newly created JDOM are not fragmented.
- */
- protected void addChild(IDOMNode child) {
- super.addChild(child);
- if (fStack.isEmpty() && fFields != null) {
- fFields.addElement(child);
- }
- }
-
- /**
- * @see IDOMFactory#createCompilationUnit()
- */
- public IDOMCompilationUnit createCompilationUnit() {
- return new DOMCompilationUnit();
- }
-
- /**
- * @see IDOMFactory#createCompilationUnit(String)
- */
- public IDOMCompilationUnit createCompilationUnit(ICompilationUnit compilationUnit) {
- initializeBuild(compilationUnit.getContents(), true, true, false);
- getParser().parseCompilationUnit(compilationUnit);
- return super.createCompilationUnit(compilationUnit);
- }
-
- /**
- * @see IDOMFactory#createField(char[])
- */
- public IDOMField createField(char[] sourceCode) {
- initializeBuild(sourceCode, false, false, true);
- getParser().parseField(sourceCode);
- if (fAbort) {
- return null;
- }
-
- // we only accept field declarations with one field
- if (fFieldCount > 1) {
- return null;
- }
-
- fNode.normalize(this);
- return (IDOMField) fNode;
+/**
+ * Creates a new DOMBuilder
+ */
+public DOMBuilder() {}
+/**
+ * @see IDocumentElementRequestor.acceptImport(...);
+ */
+public void acceptImport(int declarationStart, int declarationEnd, int[] javaDocPositions, char[] name,
+ int nameStart, boolean onDemand) {
+ int[] sourceRange = {declarationStart, declarationEnd};
+ int[] nameRange = {nameStart, declarationEnd - 1};
+
+ /* See 1FVII1P */
+ String importName = CharArrayOps.substring(fDocument, nameRange[0], nameRange[1] + 1 - nameRange[0]);
+
+ fNode= new DOMImport(fDocument, sourceRange, importName, nameRange, onDemand);
+ addChild(fNode);
+ if (fBuildingSingleMember) {
+ fFinishedSingleMember= true;
}
-
- /**
- *
- */
- public IDOMField[] createFields(char[] sourceCode) {
- initializeBuild(sourceCode, false, false, false);
- fFields = new Vector();
- getParser().parseField(sourceCode);
- if (fAbort) {
- return null;
- }
-
- IDOMField[] fields = new IDOMField[fFields.size()];
- fFields.copyInto(fields);
- for (int i = 0; i < fields.length; i++) {
- DOMNode node = (DOMNode) fields[i];
- if (i < (fields.length - 1)) {
- DOMNode next = (DOMNode) fields[i + 1];
- node.fNextNode = next;
- next.fPreviousNode = node;
- }
- ((DOMNode) fields[i]).normalize(this);
- }
- return fields;
+}
+/**
+ * @see IDocumentElementRequestor.acceptInitializer(...);
+ */
+public void acceptInitializer(int declarationStart, int declarationEnd, int[] javaDocPositions, int modifiers,
+ int modifiersStart, int bodyStart, int bodyEnd) {
+ int[] sourceRange = {declarationStart, declarationEnd};
+ int[] commentRange = {-1, -1};
+ if (javaDocPositions != null) {
+ int length = javaDocPositions.length;
+ commentRange[0] = javaDocPositions[length - 2];
+ commentRange[1] = javaDocPositions[length - 1];
+ }
+
+ int[] modifiersRange = {-1, -1};
+ if (modifiersStart > declarationStart) {
+ modifiersRange[0] = modifiersStart;
+ modifiersRange[1] = bodyStart - 1;
+ }
+ fNode = new DOMInitializer(fDocument, sourceRange, commentRange, modifiers,
+ modifiersRange, bodyStart);
+ addChild(fNode);
+ if (fBuildingSingleMember) {
+ fFinishedSingleMember= true;
}
-
- /**
- * @see IDOMFactory#createImport()
- */
- public IDOMImport createImport() {
- return new DOMImport();
+}
+/**
+ * @see IDocumentElementRequestor.acceptPackage(...);
+ */
+public void acceptPackage(int declarationStart, int declarationEnd, int[] javaDocPositions, char[] name,
+ int nameStartPosition) {
+ int[] sourceRange = {declarationStart, declarationEnd};
+ int[] nameRange = {nameStartPosition, declarationEnd - 1};
+ fNode= new DOMPackage(fDocument, sourceRange, CharArrayOps.charToString(name), nameRange);
+ addChild(fNode);
+ if (fBuildingSingleMember) {
+ fFinishedSingleMember= true;
}
-
- /**
- * @see IDOMFactory#createImport(char[])
- */
- public IDOMImport createImport(char[] sourceCode) {
- initializeBuild(sourceCode, false, false, true);
- getParser().parseImport(sourceCode);
- if (fAbort || fNode == null) {
- return null;
- }
- fNode.normalize(this);
- return (IDOMImport) fNode;
+}
+/**
+ * Sets the abort flag to true. The parser has encountered an error
+ * in the current document. If we are only building a single member, and
+ * we are done with the member - don't worry about the error.
+ *
+ * @see IDocumentElementRequestor
+ */
+public void acceptProblem(IProblem problem){
+ if (fBuildingSingleMember && fFinishedSingleMember) {
+ return;
}
-
- /**
- * Creates an INITIALIZER document fragment from the given source.
- *
- * @see IDOMFactory#createInitializer(char[])
- */
- public IDOMInitializer createInitializer(char[] sourceCode) {
- initializeBuild(sourceCode, false, false, true);
- getParser().parseInitializer(sourceCode);
- if (fAbort || fNode == null || !(fNode instanceof IDOMInitializer)) {
- return null;
- }
- fNode.normalize(this);
- return (IDOMInitializer) fNode;
+ fAbort= true;
+}
+/**
+ * Adds the given node to the current enclosing scope, building the JDOM
+ * tree. Nodes are only added to an enclosing scope when a compilation unit or type
+ * is being built (since those are the only nodes that have children).
+ *
+ * <p>NOTE: nodes are added to the JDOM via the method #basicAddChild such that
+ * the nodes in the newly created JDOM are not fragmented.
+ */
+protected void addChild(IDOMNode child) {
+ super.addChild(child);
+ if (fStack.isEmpty() && fFields != null) {
+ fFields.addElement(child);
}
-
- /**
- * @see IDOMFactory#createMethod(char[])
- */
- public IDOMMethod createMethod(char[] sourceCode) {
- initializeBuild(sourceCode, false, false, true);
- getParser().parseMethod(sourceCode);
- if (fAbort) {
- return null;
- }
- fNode.normalize(this);
- return (IDOMMethod) fNode;
+}
+/**
+ * @see IDOMFactory#createCompilationUnit()
+ */
+public IDOMCompilationUnit createCompilationUnit() {
+ return new DOMCompilationUnit();
+}
+/**
+ * @see IDOMFactory#createCompilationUnit(String)
+ */
+public IDOMCompilationUnit createCompilationUnit(ICompilationUnit compilationUnit) {
+ initializeBuild(compilationUnit.getContents(), true, true, false);
+ getParser().parseCompilationUnit(compilationUnit);
+ return super.createCompilationUnit(compilationUnit);
+}
+/**
+ * @see IDOMFactory#createField(char[])
+ */
+public IDOMField createField(char[] sourceCode) {
+ initializeBuild(sourceCode, false, false, true);
+ getParser().parseField(sourceCode);
+ if (fAbort) {
+ return null;
}
- /**
- * @see IDOMFactory#createPackage()
- */
- public IDOMPackage createPackage() {
- return new DOMPackage();
+ // we only accept field declarations with one field
+ if (fFieldCount > 1) {
+ return null;
}
-
- /**
- * @see IDOMFactory#createPackage(char[])
- */
- public IDOMPackage createPackage(char[] sourceCode) {
- initializeBuild(sourceCode, false, false, true);
- getParser().parsePackage(sourceCode);
- if (fAbort || fNode == null) {
- return null;
+
+ fNode.normalize(this);
+ return (IDOMField)fNode;
+}
+/**
+ *
+ */
+public IDOMField[] createFields(char[] sourceCode) {
+ initializeBuild(sourceCode, false, false, false);
+ fFields= new Vector();
+ getParser().parseField(sourceCode);
+ if (fAbort) {
+ return null;
+ }
+
+ IDOMField[] fields= new IDOMField[fFields.size()];
+ fFields.copyInto(fields);
+ for (int i= 0; i < fields.length; i++) {
+ DOMNode node= (DOMNode)fields[i];
+ if (i < (fields.length - 1)) {
+ DOMNode next= (DOMNode)fields[i + 1];
+ node.fNextNode= next;
+ next.fPreviousNode= node;
}
- fNode.normalize(this);
- return (IDOMPackage) fNode;
+ ((DOMNode)fields[i]).normalize(this);
}
-
- /**
- * @see IDOMFactory#createType(char[])
- */
- public IDOMType createType(char[] sourceCode) {
- initializeBuild(sourceCode, false, true, false);
- getParser().parseType(sourceCode);
- if (fAbort) {
- return null;
+ return fields;
+}
+/**
+ * @see IDOMFactory#createImport()
+ */
+public IDOMImport createImport() {
+ return new DOMImport();
+}
+/**
+ * @see IDOMFactory#createImport(char[])
+ */
+public IDOMImport createImport(char[] sourceCode) {
+ initializeBuild(sourceCode, false, false, true);
+ getParser().parseImport(sourceCode);
+ if (fAbort || fNode == null) {
+ return null;
+ }
+ fNode.normalize(this);
+ return (IDOMImport)fNode;
+}
+/**
+ * Creates an INITIALIZER document fragment from the given source.
+ *
+ * @see IDOMFactory#createInitializer(char[])
+ */
+public IDOMInitializer createInitializer(char[] sourceCode) {
+ initializeBuild(sourceCode, false, false, true);
+ getParser().parseInitializer(sourceCode);
+ if (fAbort || fNode == null || !(fNode instanceof IDOMInitializer)) {
+ return null;
+ }
+ fNode.normalize(this);
+ return (IDOMInitializer)fNode;
+}
+/**
+ * @see IDOMFactory#createMethod(char[])
+ */
+public IDOMMethod createMethod(char[] sourceCode) {
+ initializeBuild(sourceCode, false, false, true);
+ getParser().parseMethod(sourceCode);
+ if (fAbort) {
+ return null;
+ }
+ fNode.normalize(this);
+ return (IDOMMethod)fNode;
+}
+/**
+ * @see IDOMFactory#createPackage()
+ */
+public IDOMPackage createPackage() {
+ return new DOMPackage();
+}
+/**
+ * @see IDOMFactory#createPackage(char[])
+ */
+public IDOMPackage createPackage(char[] sourceCode) {
+ initializeBuild(sourceCode, false, false, true);
+ getParser().parsePackage(sourceCode);
+ if (fAbort || fNode == null) {
+ return null;
+ }
+ fNode.normalize(this);
+ return (IDOMPackage)fNode;
+}
+/**
+ * @see IDOMFactory#createType(char[])
+ */
+public IDOMType createType(char[] sourceCode) {
+ initializeBuild(sourceCode, false, true, false);
+ getParser().parseType(sourceCode);
+ if (fAbort) {
+ return null;
+ }
+ fNode.normalize(this);
+ return (IDOMType)fNode;
+}
+/**
+ * Creates a new DOMMethod and inizializes.
+ *
+ * @param declarationStart - a source position corresponding to the first character
+ * of this constructor declaration
+ * @param modifiers - the modifiers for this constructor converted to a flag
+ * @param modifiersStart - a source position corresponding to the first character of the
+ * textual modifiers
+ * @param returnType - the name of the return type
+ * @param returnTypeStart - a source position corresponding to the first character
+ * of the return type
+ * @param returnTypeEnd - a source position corresponding to the last character
+ * of the return type
+ * @param returnTypeDimensionCount - the array dimension count as supplied on the
+ * return type, i.e. public int[] foo() {}
+ * @param name - the name of this constructor
+ * @param nameStart - a source position corresponding to the first character of the name
+ * @param nameEnd - a source position corresponding to the last character of the name
+ * @param parameterTypes - a list of parameter type names
+ * @param parameterTypeStarts - a list of source positions corresponding to the
+ * first character of each parameter type name
+ * @param parameterTypeEnds - a list of source positions corresponding to the
+ * last character of each parameter type name
+ * @param parameterNames - a list of the names of the parameters
+ * @param parametersEnd - a source position corresponding to the last character of the
+ * parameter list
+ * @extendedReturnTypeDimensionCount - the array dimension count as supplied on the
+ * end of the parameter list, i.e. public int foo()[] {}
+ * @extendedReturnTypeDimensionEnd - a source position corresponding to the last character
+ * of the extended return type dimension
+ * @param exceptionTypes - a list of the exception types
+ * @param exceptionTypeStarts - a list of source positions corresponding to the first
+ * character of the respective exception types
+ * @param exceptionTypeEnds - a list of source positions corresponding to the last
+ * character of the respective exception types
+ * @param bodyStart - a source position corresponding to the start of this
+ * constructor's body
+ */
+protected void enterAbstractMethod(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart,
+ char[] returnType, int returnTypeStart, int returnTypeEnd, int returnTypeDimensionCount,
+ char[] name, int nameStart, int nameEnd, char[][] parameterTypes, int[] parameterTypeStarts,
+ int[] parameterTypeEnds, char[][] parameterNames, int[] parameterNameStarts,
+ int[] parameterNameEnds, int parametersEnd, int extendedReturnTypeDimensionCount,
+ int extendedReturnTypeDimensionEnd, char[][] exceptionTypes, int[] exceptionTypeStarts,
+ int[] exceptionTypeEnds, int bodyStart, boolean isConstructor) {
+ int[] sourceRange = {declarationStart, -1}; // will be fixed up on exit
+ int[] nameRange = {nameStart, nameEnd};
+ int[] commentRange = {-1, -1};
+ if (javaDocPositions != null) {
+ int length = javaDocPositions.length;
+ commentRange[0] = javaDocPositions[0];
+ commentRange[1] = javaDocPositions[length - 1];
+ }
+ int[] modifiersRange = {-1, -1};
+ if (modifiersStart > -1) {
+ modifiersRange[0] = modifiersStart;
+ if (isConstructor) {
+ modifiersRange[1] = nameStart - 1;
+ } else {
+ modifiersRange[1] = returnTypeStart - 1;
}
- fNode.normalize(this);
- return (IDOMType) fNode;
}
-
- /**
- * Creates a new DOMMethod and inizializes.
- *
- * @param declarationStart - a source position corresponding to the first character
- * of this constructor declaration
- * @param modifiers - the modifiers for this constructor converted to a flag
- * @param modifiersStart - a source position corresponding to the first character of the
- * textual modifiers
- * @param returnType - the name of the return type
- * @param returnTypeStart - a source position corresponding to the first character
- * of the return type
- * @param returnTypeEnd - a source position corresponding to the last character
- * of the return type
- * @param returnTypeDimensionCount - the array dimension count as supplied on the
- * return type, i.e. public int[] foo() {}
- * @param name - the name of this constructor
- * @param nameStart - a source position corresponding to the first character of the name
- * @param nameEnd - a source position corresponding to the last character of the name
- * @param parameterTypes - a list of parameter type names
- * @param parameterTypeStarts - a list of source positions corresponding to the
- * first character of each parameter type name
- * @param parameterTypeEnds - a list of source positions corresponding to the
- * last character of each parameter type name
- * @param parameterNames - a list of the names of the parameters
- * @param parametersEnd - a source position corresponding to the last character of the
- * parameter list
- * @extendedReturnTypeDimensionCount - the array dimension count as supplied on the
- * end of the parameter list, i.e. public int foo()[] {}
- * @extendedReturnTypeDimensionEnd - a source position corresponding to the last character
- * of the extended return type dimension
- * @param exceptionTypes - a list of the exception types
- * @param exceptionTypeStarts - a list of source positions corresponding to the first
- * character of the respective exception types
- * @param exceptionTypeEnds - a list of source positions corresponding to the last
- * character of the respective exception types
- * @param bodyStart - a source position corresponding to the start of this
- * constructor's body
- */
- protected void enterAbstractMethod(
- int declarationStart,
- int[] javaDocPositions,
- int modifiers,
- int modifiersStart,
- char[] returnType,
- int returnTypeStart,
- int returnTypeEnd,
- int returnTypeDimensionCount,
- char[] name,
- int nameStart,
- int nameEnd,
- char[][] parameterTypes,
- int[] parameterTypeStarts,
- int[] parameterTypeEnds,
- char[][] parameterNames,
- int[] parameterNameStarts,
- int[] parameterNameEnds,
- int parametersEnd,
- int extendedReturnTypeDimensionCount,
- int extendedReturnTypeDimensionEnd,
- char[][] exceptionTypes,
- int[] exceptionTypeStarts,
- int[] exceptionTypeEnds,
- int bodyStart,
- boolean isConstructor) {
- int[] sourceRange = { declarationStart, -1 }; // will be fixed up on exit
- int[] nameRange = { nameStart, nameEnd };
- int[] commentRange = { -1, -1 };
+ int[] returnTypeRange = null;
+
+ if (extendedReturnTypeDimensionCount > 0)
+ returnTypeRange = new int[] {returnTypeStart, returnTypeEnd,
+ parametersEnd + 1, extendedReturnTypeDimensionEnd};
+ else
+ returnTypeRange = new int[] {returnTypeStart, returnTypeEnd};
+ int[] parameterRange = {nameEnd + 1, parametersEnd};
+ int[] exceptionRange = {-1, -1};
+ if (exceptionTypes != null && exceptionTypes.length > 0) {
+ int exceptionCount = exceptionTypes.length;
+ exceptionRange[0] = exceptionTypeStarts[0];
+ exceptionRange[1] = exceptionTypeEnds[exceptionCount - 1];
+ }
+ int[] bodyRange = null;
+ if (exceptionRange[1] > -1) {
+ bodyRange = new int[] {exceptionRange[1] + 1, -1}; // will be fixed up on exit
+ } else {
+ bodyRange = new int[] {parametersEnd + 1, -1};
+ }
+ fNode = new DOMMethod(fDocument, sourceRange, CharArrayOps.charToString(name), nameRange, commentRange, modifiers,
+ modifiersRange, isConstructor, CharArrayOps.charToString(returnType), returnTypeRange,
+ CharArrayOps.charcharToString(parameterTypes),
+ CharArrayOps.charcharToString(parameterNames),
+ parameterRange, CharArrayOps.charcharToString(exceptionTypes), exceptionRange, bodyRange);
+ addChild(fNode);
+ fStack.push(fNode);
+}
+/**
+ * @see IDocumentElementRequestor.enterClass(...);
+ */
+public void enterClass(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart, int keywordStart,
+ char[] name, int nameStart, int nameEnd, char[] superclass, int superclassStart,
+ int superclassEnd, char[][] superinterfaces, int[] superinterfaceStarts,
+ int[] superinterfaceEnds, int bodyStart) {
+
+ enterType(declarationStart, javaDocPositions, modifiers, modifiersStart, keywordStart,
+ name, nameStart, nameEnd, superclass, superclassStart,
+ superclassEnd, superinterfaces, superinterfaceStarts,
+ superinterfaceEnds, bodyStart, true);
+}
+/**
+ * @see IDocumentElementRequestor.enterConstructor(...);
+ */
+public void enterConstructor(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart,
+ char[] name, int nameStart, int nameEnd, char[][] parameterTypes,
+ int[] parameterTypeStarts, int[] parameterTypeEnds, char[][] parameterNames,
+ int[] parameterNameStarts, int[] parameterNameEnds, int parametersEnd,
+ char[][] exceptionTypes, int[] exceptionTypeStarts, int[] exceptionTypeEnds,
+ int bodyStart) {
+
+ /* see 1FVIIQZ */
+ String nameString = new String(fDocument, nameStart, nameEnd - nameStart);
+ int openParenPosition = nameString.indexOf('(');
+ if (openParenPosition > -1)
+ nameEnd = nameStart + openParenPosition - 1;
+
+ enterAbstractMethod(declarationStart, javaDocPositions, modifiers, modifiersStart,
+ null, -1, -1, 0,
+ name, nameStart, nameEnd, parameterTypes, parameterTypeStarts,
+ parameterTypeEnds, parameterNames, parameterNameStarts,
+ parameterNameEnds, parametersEnd, 0,
+ -1, exceptionTypes, exceptionTypeStarts,
+ exceptionTypeEnds, bodyStart,true);
+}
+/**
+ * @see IDocumentElementRequestor.enterField(...);
+ */
+public void enterField(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart,
+ char[] type, int typeStart, int typeEnd, int typeDimensionCount, char[] name,
+ int nameStart, int nameEnd, int extendedTypeDimensionCount,
+ int extendedTypeDimensionEnd) {
+ int[] sourceRange = {declarationStart,
+ (extendedTypeDimensionEnd > nameEnd) ? extendedTypeDimensionEnd : nameEnd};
+ int[] nameRange = {nameStart, nameEnd};
+ int[] commentRange = {-1, -1};
if (javaDocPositions != null) {
int length = javaDocPositions.length;
commentRange[0] = javaDocPositions[0];
commentRange[1] = javaDocPositions[length - 1];
}
- int[] modifiersRange = { -1, -1 };
- if (modifiersStart > -1) {
- modifiersRange[0] = modifiersStart;
- if (isConstructor) {
- modifiersRange[1] = nameStart - 1;
- } else {
- modifiersRange[1] = returnTypeStart - 1;
- }
- }
- int[] returnTypeRange = null;
-
- if (extendedReturnTypeDimensionCount > 0)
- returnTypeRange =
- new int[] {
- returnTypeStart,
- returnTypeEnd,
- parametersEnd + 1,
- extendedReturnTypeDimensionEnd };
- else
- returnTypeRange = new int[] { returnTypeStart, returnTypeEnd };
- int[] parameterRange = { nameEnd + 1, parametersEnd };
- int[] exceptionRange = { -1, -1 };
- if (exceptionTypes != null && exceptionTypes.length > 0) {
- int exceptionCount = exceptionTypes.length;
- exceptionRange[0] = exceptionTypeStarts[0];
- exceptionRange[1] = exceptionTypeEnds[exceptionCount - 1];
- }
- int[] bodyRange = null;
- if (exceptionRange[1] > -1) {
- bodyRange = new int[] { exceptionRange[1] + 1, -1 };
- // will be fixed up on exit
- } else {
- bodyRange = new int[] { parametersEnd + 1, -1 };
- }
- fNode =
- new DOMMethod(
- fDocument,
- sourceRange,
- CharArrayOps.charToString(name),
- nameRange,
- commentRange,
- modifiers,
- modifiersRange,
- isConstructor,
- CharArrayOps.charToString(returnType),
- returnTypeRange,
- CharArrayOps.charcharToString(parameterTypes),
- CharArrayOps.charcharToString(parameterNames),
- parameterRange,
- CharArrayOps.charcharToString(exceptionTypes),
- exceptionRange,
- bodyRange);
- addChild(fNode);
- fStack.push(fNode);
- }
-
- /**
- * @see IDocumentElementRequestor.enterClass(...);
- */
- public void enterClass(
- int declarationStart,
- int[] javaDocPositions,
- int modifiers,
- int modifiersStart,
- int keywordStart,
- char[] name,
- int nameStart,
- int nameEnd,
- char[] superclass,
- int superclassStart,
- int superclassEnd,
- char[][] superinterfaces,
- int[] superinterfaceStarts,
- int[] superinterfaceEnds,
- int bodyStart) {
-
- enterType(
- declarationStart,
- javaDocPositions,
- modifiers,
- modifiersStart,
- keywordStart,
- name,
- nameStart,
- nameEnd,
- superclass,
- superclassStart,
- superclassEnd,
- superinterfaces,
- superinterfaceStarts,
- superinterfaceEnds,
- bodyStart,
- true);
- }
-
- /**
- * @see IDocumentElementRequestor.enterConstructor(...);
- */
- public void enterConstructor(
- int declarationStart,
- int[] javaDocPositions,
- int modifiers,
- int modifiersStart,
- char[] name,
- int nameStart,
- int nameEnd,
- char[][] parameterTypes,
- int[] parameterTypeStarts,
- int[] parameterTypeEnds,
- char[][] parameterNames,
- int[] parameterNameStarts,
- int[] parameterNameEnds,
- int parametersEnd,
- char[][] exceptionTypes,
- int[] exceptionTypeStarts,
- int[] exceptionTypeEnds,
- int bodyStart) {
-
- /* see 1FVIIQZ */
- String nameString = new String(fDocument, nameStart, nameEnd - nameStart);
- int openParenPosition = nameString.indexOf('(');
- if (openParenPosition > -1)
- nameEnd = nameStart + openParenPosition - 1;
-
- enterAbstractMethod(
- declarationStart,
- javaDocPositions,
- modifiers,
- modifiersStart,
- null,
- -1,
- -1,
- 0,
- name,
- nameStart,
- nameEnd,
- parameterTypes,
- parameterTypeStarts,
- parameterTypeEnds,
- parameterNames,
- parameterNameStarts,
- parameterNameEnds,
- parametersEnd,
- 0,
- -1,
- exceptionTypes,
- exceptionTypeStarts,
- exceptionTypeEnds,
- bodyStart,
- true);
- }
+ int[] modifiersRange = {-1, -1};
+ if (modifiersStart > -1) {
+ modifiersRange[0] = modifiersStart;
+ modifiersRange[1] = typeStart - 1;
+ }
+ int[] typeRange = {typeStart, typeEnd};
+ boolean hasInitializer = false; // fixed on exitField
+ int[] initializerRange = {-1, -1}; // fixed on exitField
+ boolean isVariableDeclarator = false;
+ if (fNode instanceof DOMField) {
+ DOMField field = (DOMField)fNode;
+ if (field.fTypeRange[0] == typeStart)
+ isVariableDeclarator = true;
+ }
+ fNode = new DOMField(fDocument, sourceRange, CharArrayOps.charToString(name), nameRange, commentRange,
+ modifiers, modifiersRange, typeRange, CharArrayOps.charToString(type), hasInitializer,
+ initializerRange, isVariableDeclarator);
+ addChild(fNode);
+ fStack.push(fNode);
+}
+/**
+ * @see IDocumentElementRequestor.enterInterface(...);
+ */
+public void enterInterface(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart, int keywordStart,
+ char[] name, int nameStart, int nameEnd, char[][] superinterfaces,
+ int[] superinterfaceStarts, int[] superinterfaceEnds, int bodyStart) {
- /**
- * @see IDocumentElementRequestor.enterField(...);
- */
- public void enterField(
- int declarationStart,
- int[] javaDocPositions,
- int modifiers,
- int modifiersStart,
- char[] type,
- int typeStart,
- int typeEnd,
- int typeDimensionCount,
- char[] name,
- int nameStart,
- int nameEnd,
- int extendedTypeDimensionCount,
- int extendedTypeDimensionEnd) {
- int[] sourceRange =
- {
- declarationStart,
- (extendedTypeDimensionEnd > nameEnd) ? extendedTypeDimensionEnd : nameEnd };
- int[] nameRange = { nameStart, nameEnd };
- int[] commentRange = { -1, -1 };
+ enterType(declarationStart, javaDocPositions, modifiers, modifiersStart, keywordStart,
+ name, nameStart, nameEnd, null, -1, -1, superinterfaces,
+ superinterfaceStarts, superinterfaceEnds, bodyStart, false);
+}
+/**
+ * @see IDocumentElementRequestor.enterMethod(...);
+ */
+public void enterMethod(int declarationStart, int[] javaDocPositions, int modifiers, int modifiersStart,
+ char[] returnType, int returnTypeStart, int returnTypeEnd, int returnTypeDimensionCount,
+ char[] name, int nameStart, int nameEnd, char[][] parameterTypes, int[] parameterTypeStarts,
+ int[] parameterTypeEnds, char[][] parameterNames, int[] parameterNameStarts,
+ int[] parameterNameEnds, int parametersEnd, int extendedReturnTypeDimensionCount,
+ int extendedReturnTypeDimensionEnd, char[][] exceptionTypes, int[] exceptionTypeStarts,
+ int[] exceptionTypeEnds, int bodyStart) {
+ enterAbstractMethod(declarationStart, javaDocPositions, modifiers, modifiersStart,
+ returnType, returnTypeStart, returnTypeEnd, returnTypeDimensionCount,
+ name, nameStart, nameEnd, parameterTypes, parameterTypeStarts,
+ parameterTypeEnds, parameterNames, parameterNameStarts,
+ parameterNameEnds, parametersEnd, extendedReturnTypeDimensionCount,
+ extendedReturnTypeDimensionEnd, exceptionTypes, exceptionTypeStarts,
+ exceptionTypeEnds, bodyStart,false);
+}
+/**
+ * @see IDocumentElementRequestor.enterType(...);
+ */
+protected void enterType(int declarationStart, int[] javaDocPositions,
+ int modifiers, int modifiersStart, int keywordStart, char[] name,
+ int nameStart, int nameEnd, char[] superclass, int superclassStart,
+ int superclassEnd, char[][] superinterfaces, int[] superinterfaceStarts,
+ int[] superinterfaceEnds, int bodyStart, boolean isClass) {
+ if (fBuildingType) {
+ int[] sourceRange = {declarationStart, -1}; // will be fixed in the exit
+ int[] commentRange = {-1, -1};
if (javaDocPositions != null) {
int length = javaDocPositions.length;
commentRange[0] = javaDocPositions[0];
commentRange[1] = javaDocPositions[length - 1];
}
- int[] modifiersRange = { -1, -1 };
+ int[] modifiersRange = {-1, -1};
if (modifiersStart > -1) {
modifiersRange[0] = modifiersStart;
- modifiersRange[1] = typeStart - 1;
- }
- int[] typeRange = { typeStart, typeEnd };
- boolean hasInitializer = false; // fixed on exitField
- int[] initializerRange = { -1, -1 }; // fixed on exitField
- boolean isVariableDeclarator = false;
- if (fNode instanceof DOMField) {
- DOMField field = (DOMField) fNode;
- if (field.fTypeRange[0] == typeStart)
- isVariableDeclarator = true;
+ modifiersRange[1] = (modifiersStart > -1) ? keywordStart - 1 : -1;
}
- fNode =
- new DOMField(
- fDocument,
- sourceRange,
- CharArrayOps.charToString(name),
- nameRange,
- commentRange,
- modifiers,
- modifiersRange,
- typeRange,
- CharArrayOps.charToString(type),
- hasInitializer,
- initializerRange,
- isVariableDeclarator);
- addChild(fNode);
- fStack.push(fNode);
- }
-
- /**
- * @see IDocumentElementRequestor.enterInterface(...);
- */
- public void enterInterface(
- int declarationStart,
- int[] javaDocPositions,
- int modifiers,
- int modifiersStart,
- int keywordStart,
- char[] name,
- int nameStart,
- int nameEnd,
- char[][] superinterfaces,
- int[] superinterfaceStarts,
- int[] superinterfaceEnds,
- int bodyStart) {
-
- enterType(
- declarationStart,
- javaDocPositions,
- modifiers,
- modifiersStart,
- keywordStart,
- name,
- nameStart,
- nameEnd,
- null,
- -1,
- -1,
- superinterfaces,
- superinterfaceStarts,
- superinterfaceEnds,
- bodyStart,
- false);
- }
-
- /**
- * @see IDocumentElementRequestor.enterMethod(...);
- */
- public void enterMethod(
- int declarationStart,
- int[] javaDocPositions,
- int modifiers,
- int modifiersStart,
- char[] returnType,
- int returnTypeStart,
- int returnTypeEnd,
- int returnTypeDimensionCount,
- char[] name,
- int nameStart,
- int nameEnd,
- char[][] parameterTypes,
- int[] parameterTypeStarts,
- int[] parameterTypeEnds,
- char[][] parameterNames,
- int[] parameterNameStarts,
- int[] parameterNameEnds,
- int parametersEnd,
- int extendedReturnTypeDimensionCount,
- int extendedReturnTypeDimensionEnd,
- char[][] exceptionTypes,
- int[] exceptionTypeStarts,
- int[] exceptionTypeEnds,
- int bodyStart) {
- enterAbstractMethod(
- declarationStart,
- javaDocPositions,
- modifiers,
- modifiersStart,
- returnType,
- returnTypeStart,
- returnTypeEnd,
- returnTypeDimensionCount,
- name,
- nameStart,
- nameEnd,
- parameterTypes,
- parameterTypeStarts,
- parameterTypeEnds,
- parameterNames,
- parameterNameStarts,
- parameterNameEnds,
- parametersEnd,
- extendedReturnTypeDimensionCount,
- extendedReturnTypeDimensionEnd,
- exceptionTypes,
- exceptionTypeStarts,
- exceptionTypeEnds,
- bodyStart,
- false);
- }
-
- /**
- * @see IDocumentElementRequestor.enterType(...);
- */
- protected void enterType(
- int declarationStart,
- int[] javaDocPositions,
- int modifiers,
- int modifiersStart,
- int keywordStart,
- char[] name,
- int nameStart,
- int nameEnd,
- char[] superclass,
- int superclassStart,
- int superclassEnd,
- char[][] superinterfaces,
- int[] superinterfaceStarts,
- int[] superinterfaceEnds,
- int bodyStart,
- boolean isClass) {
- if (fBuildingType) {
- int[] sourceRange = { declarationStart, -1 }; // will be fixed in the exit
- int[] commentRange = { -1, -1 };
- if (javaDocPositions != null) {
- int length = javaDocPositions.length;
- commentRange[0] = javaDocPositions[0];
- commentRange[1] = javaDocPositions[length - 1];
- }
- int[] modifiersRange = { -1, -1 };
- if (modifiersStart > -1) {
- modifiersRange[0] = modifiersStart;
- modifiersRange[1] = (modifiersStart > -1) ? keywordStart - 1 : -1;
+ int[] typeKeywordRange = {keywordStart, nameStart - 1};
+ int[] nameRange = new int[] {nameStart, nameEnd};
+ int[] extendsKeywordRange = {-1, -1};
+ int[] superclassRange = {-1, -1};
+ int[] implementsKeywordRange = {-1, -1};
+ int[] interfacesRange = {-1, -1};
+ if (isClass) {
+ if (superclass != null) {
+ extendsKeywordRange[0] = nameEnd + 1;
+ extendsKeywordRange[1] = superclassStart - 1;
+ superclassRange[0] = superclassStart;
+ superclassRange[1] = bodyStart - 1;
}
- int[] typeKeywordRange = { keywordStart, nameStart - 1 };
- int[] nameRange = new int[] { nameStart, nameEnd };
- int[] extendsKeywordRange = { -1, -1 };
- int[] superclassRange = { -1, -1 };
- int[] implementsKeywordRange = { -1, -1 };
- int[] interfacesRange = { -1, -1 };
- if (isClass) {
- if (superclass != null) {
- extendsKeywordRange[0] = nameEnd + 1;
- extendsKeywordRange[1] = superclassStart - 1;
- superclassRange[0] = superclassStart;
- superclassRange[1] = bodyStart - 1;
- }
- if (superinterfaces != null && superinterfaces.length > 0) {
- superclassRange[1] = superclassEnd;
- if (superclassEnd > -1) {
- implementsKeywordRange[0] = superclassEnd + 1;
- } else {
- implementsKeywordRange[0] = nameEnd + 1;
- }
- implementsKeywordRange[1] = superinterfaceStarts[0] - 1;
- interfacesRange[0] = superinterfaceStarts[0];
- interfacesRange[1] = bodyStart - 1;
- }
- } else {
- if (superinterfaces != null && superinterfaces.length > 0) {
- extendsKeywordRange[0] = nameEnd + 1;
- extendsKeywordRange[1] = superinterfaceStarts[0] - 1;
- interfacesRange[0] = superinterfaceStarts[0];
- interfacesRange[1] = bodyStart - 1;
+ if (superinterfaces != null && superinterfaces.length > 0) {
+ superclassRange[1] = superclassEnd;
+ if (superclassEnd > -1) {
+ implementsKeywordRange[0] = superclassEnd + 1;
+ } else {
+ implementsKeywordRange[0] = nameEnd + 1;
}
+ implementsKeywordRange[1] = superinterfaceStarts[0] - 1;
+ interfacesRange[0] = superinterfaceStarts[0];
+ interfacesRange[1] = bodyStart - 1;
+ }
+ } else {
+ if (superinterfaces != null && superinterfaces.length > 0) {
+ extendsKeywordRange[0] = nameEnd + 1;
+ extendsKeywordRange[1] = superinterfaceStarts[0] - 1;
+ interfacesRange[0] = superinterfaceStarts[0];
+ interfacesRange[1] = bodyStart - 1;
}
- int[] openBodyRange = { bodyStart, -1 }; // fixed by setTypeRanges(DOMNode)
- int[] closeBodyRange = { -1, -1 }; // will be fixed in exit
- fNode =
- new DOMType(
- fDocument,
- sourceRange,
- new String(name),
- nameRange,
- commentRange,
- modifiers,
- modifiersRange,
- typeKeywordRange,
- superclassRange,
- extendsKeywordRange,
- CharArrayOps.charcharToString(superinterfaces),
- interfacesRange,
- implementsKeywordRange,
- openBodyRange,
- closeBodyRange,
- isClass);
- addChild(fNode);
- fStack.push(fNode);
- }
- }
-
- /**
- * Finishes the configuration of the constructors and methods.
- *
- * @param bodyEnd - a source position corresponding to the closing bracket of the method
- * @param declarationEnd - a source position corresponding to the end of the method
- * declaration. This can include whitespace and comments following the closing bracket.
- */
- protected void exitAbstractMethod(int bodyEnd, int declarationEnd) {
- DOMMethod method = (DOMMethod) fStack.pop();
- method.setSourceRangeEnd(declarationEnd);
- method.setBodyRangeEnd(bodyEnd + 1);
- fNode = method;
- if (fBuildingSingleMember) {
- fFinishedSingleMember = true;
}
+ int[] openBodyRange = {bodyStart, -1}; // fixed by setTypeRanges(DOMNode)
+ int[] closeBodyRange = {-1, -1}; // will be fixed in exit
+ fNode = new DOMType(fDocument, sourceRange, new String(name), nameRange, commentRange,
+ modifiers, modifiersRange, typeKeywordRange, superclassRange, extendsKeywordRange,
+ CharArrayOps.charcharToString(superinterfaces), interfacesRange,
+ implementsKeywordRange, openBodyRange,
+ closeBodyRange, isClass);
+ addChild(fNode);
+ fStack.push(fNode);
}
-
- /**
- * Finishes the configuration of the class DOM object which
- * was created by a previous enterClass call.
- *
- * @see IDocumentElementRequestor.exitClass(...);
- */
- public void exitClass(int bodyEnd, int declarationEnd) {
- exitType(bodyEnd, declarationEnd);
- }
-
- /**
- * Finishes the configuration of the method DOM object which
- * was created by a previous enterConstructor call.
- *
- * @see IDocumentElementRequestor.exitConstructor(...);
- */
- public void exitConstructor(int bodyEnd, int declarationEnd) {
- exitAbstractMethod(bodyEnd, declarationEnd);
+}
+/**
+ * Finishes the configuration of the constructors and methods.
+ *
+ * @param bodyEnd - a source position corresponding to the closing bracket of the method
+ * @param declarationEnd - a source position corresponding to the end of the method
+ * declaration. This can include whitespace and comments following the closing bracket.
+ */
+protected void exitAbstractMethod(int bodyEnd, int declarationEnd) {
+ DOMMethod method = (DOMMethod) fStack.pop();
+ method.setSourceRangeEnd(declarationEnd);
+ method.setBodyRangeEnd(bodyEnd + 1);
+ fNode = method;
+ if (fBuildingSingleMember) {
+ fFinishedSingleMember= true;
}
-
- /**
- * Finishes the configuration of the field DOM object which
- * was created by a previous enterField call.
- *
- * @see IDocumentElementRequestor.exitField(...);
- */
- public void exitField(int bodyEnd, int declarationEnd) {
- DOMField field = (DOMField) fStack.pop();
- if (field.getEndPosition() < declarationEnd) {
- field.setSourceRangeEnd(declarationEnd);
- int nameEnd = field.fNameRange[1];
- if (nameEnd < bodyEnd) {
- /* see 1FVIIV8 - obtain initializer range */
- String initializer = new String(fDocument, nameEnd + 1, bodyEnd - nameEnd);
- int index = initializer.indexOf('=');
- if (index > -1) {
- field.setHasInitializer(true);
- field.setInitializerRange(nameEnd + index + 2, bodyEnd);
- }
+}
+/**
+ * Finishes the configuration of the class DOM object which
+ * was created by a previous enterClass call.
+ *
+ * @see IDocumentElementRequestor.exitClass(...);
+ */
+public void exitClass(int bodyEnd, int declarationEnd) {
+ exitType(bodyEnd, declarationEnd);
+}
+/**
+ * Finishes the configuration of the method DOM object which
+ * was created by a previous enterConstructor call.
+ *
+ * @see IDocumentElementRequestor.exitConstructor(...);
+ */
+public void exitConstructor(int bodyEnd, int declarationEnd) {
+ exitAbstractMethod(bodyEnd, declarationEnd);
+}
+/**
+ * Finishes the configuration of the field DOM object which
+ * was created by a previous enterField call.
+ *
+ * @see IDocumentElementRequestor.exitField(...);
+ */
+public void exitField(int bodyEnd, int declarationEnd) {
+ DOMField field = (DOMField)fStack.pop();
+ if (field.getEndPosition() < declarationEnd) {
+ field.setSourceRangeEnd(declarationEnd);
+ int nameEnd = field.fNameRange[1];
+ if (nameEnd < bodyEnd) {
+ /* see 1FVIIV8 - obtain initializer range */
+ String initializer = new String(fDocument, nameEnd + 1, bodyEnd - nameEnd);
+ int index = initializer.indexOf('=');
+ if (index > -1) {
+ field.setHasInitializer(true);
+ field.setInitializerRange(nameEnd + index + 2, bodyEnd);
}
}
- fFieldCount++;
- fNode = field;
- if (fBuildingSingleMember) {
- fFinishedSingleMember = true;
- }
}
-
- /**
- * Finishes the configuration of the interface DOM object which
- * was created by a previous enterInterface call.
- *
- * @see IDocumentElementRequestor.exitInterface(...);
- */
- public void exitInterface(int bodyEnd, int declarationEnd) {
- exitType(bodyEnd, declarationEnd);
- }
-
- /**
- * Finishes the configuration of the method DOM object which
- * was created by a previous enterMethod call.
- *
- * @see IDocumentElementRequestor.exitMethod(...);
- */
- public void exitMethod(int bodyEnd, int declarationEnd) {
- exitAbstractMethod(bodyEnd, declarationEnd);
- }
-
- /**
- * Creates a new parser.
- */
- protected DocumentElementParser getParser() {
- return new DocumentElementParser(this, new NullProblemFactory());
- }
-
- /**
- * Initializes the builder to create a document fragment.
- *
- * @param sourceCode - the document containing the source code to be analyzed
- * @param buildingCompilationUnit - true if a the document is being analyzed to
- * create a compilation unit, otherwise false
- * @param buildingType - true if the document is being analyzed to create a
- * type or compilation unit
- * @param singleMember - true if building a single member
- */
- protected void initializeBuild(
- char[] sourceCode,
- boolean buildingCompilationUnit,
- boolean buildingType,
- boolean singleMember) {
- super.initializeBuild(sourceCode, buildingCompilationUnit, buildingType);
- fBuildingSingleMember = singleMember;
- fFinishedSingleMember = false;
-
+ fFieldCount++;
+ fNode = field;
+ if (fBuildingSingleMember) {
+ fFinishedSingleMember= true;
}
+}
+/**
+ * Finishes the configuration of the interface DOM object which
+ * was created by a previous enterInterface call.
+ *
+ * @see IDocumentElementRequestor.exitInterface(...);
+ */
+public void exitInterface(int bodyEnd, int declarationEnd) {
+ exitType(bodyEnd, declarationEnd);
+}
+/**
+ * Finishes the configuration of the method DOM object which
+ * was created by a previous enterMethod call.
+ *
+ * @see IDocumentElementRequestor.exitMethod(...);
+ */
+public void exitMethod(int bodyEnd, int declarationEnd) {
+ exitAbstractMethod(bodyEnd, declarationEnd);
+}
+/**
+ * Creates a new parser.
+ */
+protected DocumentElementParser getParser() {
+ return new DocumentElementParser(this, new NullProblemFactory());
+}
+/**
+ * Initializes the builder to create a document fragment.
+ *
+ * @param sourceCode - the document containing the source code to be analyzed
+ * @param buildingCompilationUnit - true if a the document is being analyzed to
+ * create a compilation unit, otherwise false
+ * @param buildingType - true if the document is being analyzed to create a
+ * type or compilation unit
+ * @param singleMember - true if building a single member
+ */
+protected void initializeBuild(char[] sourceCode, boolean buildingCompilationUnit, boolean buildingType, boolean singleMember) {
+ super.initializeBuild(sourceCode, buildingCompilationUnit, buildingType);
+ fBuildingSingleMember= singleMember;
+ fFinishedSingleMember= false;
}
+}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMCompilationUnit.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMCompilationUnit.java
index 2c66a4c5be..b78a0dfcbb 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMCompilationUnit.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMCompilationUnit.java
@@ -28,171 +28,151 @@ class DOMCompilationUnit extends DOMNode implements IDOMCompilationUnit {
* unit.
*/
protected String fHeader;
- /**
- * Creates a new empty COMPILATION_UNIT document fragment.
- */
- DOMCompilationUnit() {
- fHeader = "";
- }
-
- /**
- * Creates a new COMPILATION_UNIT on the given range of the document.
- *
- * @param document - the document containing this node's original contents
- * @param sourceRange - a two element array of integers describing the
- * entire inclusive source range of this node within its document.
- * A compilation unit's source range is the entire document - i.e.
- * the first integer is zero, and the second integer is the position
- * of the last character in the document.
- */
- DOMCompilationUnit(char[] document, int[] sourceRange) {
- super(document, sourceRange, null, new int[] { -1, -1 });
- fHeader = "";
- }
-
- /**
- * @see DOMNode#appendContents(CharArrayBuffer)
- */
- protected void appendFragmentedContents(CharArrayBuffer buffer) {
- buffer.append(getHeader());
- appendContentsOfChildren(buffer);
- }
-
- /**
- * @see IDOMNode#canHaveChildren()
- */
- public boolean canHaveChildren() {
- return true;
- }
-
- /**
- * @see IDOMCompilationUnit#getHeader()
- */
- public String getHeader() {
- return fHeader;
- }
-
- /**
- * @see IDOMNode#getJavaElement
- */
- public IJavaElement getJavaElement(IJavaElement parent)
- throws IllegalArgumentException {
- if (parent.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
- return ((IPackageFragment) parent).getCompilationUnit(getName());
- } else {
- throw new IllegalArgumentException("Illegal parent argument");
- }
+/**
+ * Creates a new empty COMPILATION_UNIT document fragment.
+ */
+DOMCompilationUnit() {
+ fHeader="";
+}
+/**
+ * Creates a new COMPILATION_UNIT on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * A compilation unit's source range is the entire document - i.e.
+ * the first integer is zero, and the second integer is the position
+ * of the last character in the document.
+ */
+DOMCompilationUnit(char[] document, int[] sourceRange) {
+ super(document, sourceRange, null, new int[]{-1, -1});
+ fHeader = "";
+}
+/**
+ * @see DOMNode#appendContents(CharArrayBuffer)
+ */
+protected void appendFragmentedContents(CharArrayBuffer buffer) {
+ buffer.append(getHeader());
+ appendContentsOfChildren(buffer);
+}
+/**
+ * @see IDOMNode#canHaveChildren()
+ */
+public boolean canHaveChildren() {
+ return true;
+}
+/**
+ * @see IDOMCompilationUnit#getHeader()
+ */
+public String getHeader() {
+ return fHeader;
+}
+/**
+ * @see IDOMNode#getJavaElement
+ */
+public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException {
+ if (parent.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
+ return ((IPackageFragment)parent).getCompilationUnit(getName());
+ } else {
+ throw new IllegalArgumentException("Illegal parent argument");
}
-
- /**
- * @see IDOMCompilationUnit#getName()
- */
- public String getName() {
- IDOMType topLevelType = null;
- IDOMType firstType = null;
- IDOMNode child = fFirstChild;
- while (child != null) {
- if (child.getNodeType() == IDOMNode.TYPE) {
- IDOMType type = (IDOMType) child;
- if (firstType == null) {
- firstType = type;
- }
- if (Flags.isPublic(type.getFlags())) {
- topLevelType = type;
- break;
- }
+}
+/**
+ * @see IDOMCompilationUnit#getName()
+ */
+public String getName() {
+ IDOMType topLevelType= null;
+ IDOMType firstType= null;
+ IDOMNode child= fFirstChild;
+ while (child != null) {
+ if (child.getNodeType() == IDOMNode.TYPE) {
+ IDOMType type= (IDOMType)child;
+ if (firstType == null) {
+ firstType= type;
}
- child = child.getNextNode();
- }
- if (topLevelType == null) {
- topLevelType = firstType;
- }
- if (topLevelType != null) {
- return topLevelType.getName() + ".java";
- } else {
- return null;
- }
- }
-
- /**
- * @see IDOMNode#getNodeType()
- */
- public int getNodeType() {
- return IDOMNode.COMPILATION_UNIT;
- }
-
- /**
- * Sets the header
- */
- protected void initalizeHeader() {
- DOMNode child = (DOMNode) getFirstChild();
- if (child != null) {
- int childStart = child.getStartPosition();
- if (childStart > 1) {
- setHeader(CharArrayOps.substring(fDocument, 0, childStart));
+ if (Flags.isPublic(type.getFlags())) {
+ topLevelType= type;
+ break;
}
}
+ child= child.getNextNode();
}
-
- /**
- * @see IDOMNode#isAllowableChild(IDOMNode)
- */
- public boolean isAllowableChild(IDOMNode node) {
- if (node != null) {
- int type = node.getNodeType();
- return type == IDOMNode.PACKAGE
- || type == IDOMNode.IMPORT
- || type == IDOMNode.TYPE;
- } else {
- return false;
- }
-
+ if (topLevelType == null) {
+ topLevelType= firstType;
}
-
- /**
- * @see DOMNode
- */
- protected DOMNode newDOMNode() {
- return new DOMCompilationUnit();
+ if (topLevelType != null) {
+ return topLevelType.getName() + ".java";
+ } else {
+ return null;
}
-
- /**
- * Normalizes this <code>DOMNode</code>'s source positions to include whitespace preceeding
- * the node on the line on which the node starts, and all whitespace after the node up to
- * the next node's start
- */
- void normalize(ILineStartFinder finder) {
- super.normalize(finder);
- initalizeHeader();
- }
-
- /**
- * @see IDOMCompilationUnit@setHeader(String)
- */
- public void setHeader(String comment) {
- fHeader = comment;
- fragment();
- }
-
- /**
- * @see IDOMCompilationUnit#setName(String)
- */
- public void setName(String name) {
- }
-
- /**
- * @see DOMNode#shareContents(DOMNode)
- */
- protected void shareContents(DOMNode node) {
- super.shareContents(node);
- fHeader = ((DOMCompilationUnit) node).fHeader;
- }
-
- /**
- * @see IDOMNode#toString()
- */
- public String toString() {
- return "COMPILATION_UNIT: " + getName();
+}
+/**
+ * @see IDOMNode#getNodeType()
+ */
+public int getNodeType() {
+ return IDOMNode.COMPILATION_UNIT;
+}
+/**
+ * Sets the header
+ */
+protected void initalizeHeader() {
+ DOMNode child = (DOMNode)getFirstChild();
+ if (child != null) {
+ int childStart = child.getStartPosition();
+ if (childStart > 1) {
+ setHeader(CharArrayOps.substring(fDocument, 0, childStart));
+ }
}
-
+}
+/**
+ * @see IDOMNode#isAllowableChild(IDOMNode)
+ */
+public boolean isAllowableChild(IDOMNode node) {
+ if (node != null) {
+ int type= node.getNodeType();
+ return type == IDOMNode.PACKAGE || type == IDOMNode.IMPORT || type == IDOMNode.TYPE;
+ } else {
+ return false;
+ }
+
+}
+/**
+ * @see DOMNode
+ */
+protected DOMNode newDOMNode() {
+ return new DOMCompilationUnit();
+}
+/**
+ * Normalizes this <code>DOMNode</code>'s source positions to include whitespace preceeding
+ * the node on the line on which the node starts, and all whitespace after the node up to
+ * the next node's start
+ */
+void normalize(ILineStartFinder finder) {
+ super.normalize(finder);
+ initalizeHeader();
+}
+/**
+ * @see IDOMCompilationUnit@setHeader(String)
+ */
+public void setHeader(String comment) {
+ fHeader= comment;
+ fragment();
+}
+/**
+ * @see IDOMCompilationUnit#setName(String)
+ */
+public void setName(String name) {}
+/**
+ * @see DOMNode#shareContents(DOMNode)
+ */
+protected void shareContents(DOMNode node) {
+ super.shareContents(node);
+ fHeader= ((DOMCompilationUnit)node).fHeader;
+}
+/**
+ * @see IDOMNode#toString()
+ */
+public String toString() {
+ return "COMPILATION_UNIT: " + getName();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMField.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMField.java
index 22a94e68a5..07554b0b72 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMField.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMField.java
@@ -23,7 +23,7 @@ import java.util.Enumeration;
* @see DOMNode
*/
class DOMField extends DOMMember implements IDOMField {
-
+
/**
* Contains the type of the field when the type
* has been altered from the contents in the
@@ -36,7 +36,7 @@ class DOMField extends DOMMember implements IDOMField {
* field's type in the document.
*/
protected int[] fTypeRange;
-
+
/**
* The contents of the initializer when the
* initializer has been altered from the
@@ -51,659 +51,558 @@ class DOMField extends DOMMember implements IDOMField {
*/
protected int[] fInitializerRange;
- /**
- * Constructs an empty field node.
- */
- DOMField() {
- }
-
- /**
- * Creates a new detailed FIELD document fragment on the given range of the document.
- *
- * @param document - the document containing this node's original contents
- * @param sourceRange - a two element array of integers describing the
- * entire inclusive source range of this node within its document.
- * Contents start on and include the character at the first position.
- * Contents end on and include the character at the last position.
- * An array of -1's indicates this node's contents do not exist
- * in the document.
- * @param name - the identifier portion of the name of this field,
- * corresponding to VariableDeclaratorId (JLS 8.3).
- * @param nameRange - a two element array of integers describing the
- * entire inclusive source range of this node's name within its document,
- * including any array qualifiers that might follow the name.
- * @param commentRange - a two element array describing the comments that precede
- * the member declaration. The first matches the start of this node's
- * sourceRange, and the second is the new-line or first non-whitespace
- * character following the last comment. If no comments are present,
- * this array contains two -1's.
- * @param flags - an integer representing the modifiers for this member. The
- * integer can be analyzed with org.eclipse.jdt.core.Flags
- * @param modifierRange - a two element array describing the location of
- * modifiers for this member within its source range. The first integer
- * is the first character of the first modifier for this member, and
- * the second integer is the last whitespace character preceeding the
- * next part of this member declaration. If there are no modifiers present
- * in this node's source code (i.e. default protection), this array
- * contains two -1's.
- * @param typeRange- a two element array describing the location of the
- * typeName in the document - the positions of the first and last characters
- * of the typeName.
- * @param type - the type of the field, in normalized form, as defined in
- * Type in Field Declaration (JLS 8.3)
- * @param hasInitializer - true if this field declaration includes an initializer,
- * otherwise false
- * @param initRange - a two element array describing the location of the initializer
- * in the declaration. The first integer is the position of the character
- * following the equals sign, and the position of the last character is the last
- * in the initializer. If this field has no initializer, this array contains
- * two -1's.
- * @param isVariableDeclarator - true if the field is a seconday variable declarator
- * for a previous field declaration.
- */
- DOMField(
- char[] document,
- int[] sourceRange,
- String name,
- int[] nameRange,
- int[] commentRange,
- int flags,
- int[] modifierRange,
- int[] typeRange,
- String type,
- boolean hasInitializer,
- int[] initRange,
- boolean isVariableDeclarator) {
- super(
- document,
- sourceRange,
- name,
- nameRange,
- commentRange,
- flags,
- modifierRange);
-
- fType = type;
- fTypeRange = typeRange;
- setHasInitializer(hasInitializer);
- fInitializerRange = initRange;
- setIsVariableDeclarator(isVariableDeclarator);
- setMask(MASK_DETAILED_SOURCE_INDEXES, true);
-
- }
-
- /**
- * Creates a new simple FIELD document fragment on the given range of the document.
- *
- * @param document - the document containing this node's original contents
- * @param sourceRange - a two element array of integers describing the
- * entire inclusive source range of this node within its document.
- * Contents start on and include the character at the first position.
- * Contents end on and include the character at the last position.
- * An array of -1's indicates this node's contents do not exist
- * in the document.
- * @param name - the identifier portion of the name of this field,
- * corresponding to VariableDeclaratorId (JLS 8.3).
- * @param nameRange - a two element array of integers describing the
- * entire inclusive source range of this node's name within its document,
- * including any array qualifiers that might follow the name.
- * @param flags - an integer representing the modifiers for this member. The
- * integer can be analyzed with org.eclipse.jdt.core.Flags
- * @param type - the type of the field, in normalized form, as defined in
- * Type in Field Declaration (JLS 8.3)
- * @param isVariableDeclarator - true if the field is a seconday variable declarator
- * for a previous field declaration.
- */
- DOMField(
- char[] document,
- int[] sourceRange,
- String name,
- int[] nameRange,
- int flags,
- String type,
- boolean isVariableDeclarator) {
- this(
- document,
- sourceRange,
- name,
- nameRange,
- new int[] { -1, -1 },
- flags,
- new int[] { -1, -1 },
- new int[] { -1, -1 },
- type,
- false,
- new int[] { -1, -1 },
- isVariableDeclarator);
- setMask(MASK_DETAILED_SOURCE_INDEXES, false);
- }
-
- /**
- * Appends this member's body contents to the given CharArrayBuffer.
- * Body contents include the member body and any trailing whitespace.
- *
- * <p>A field does not have a body.
- *
- * @see DOMMember#appendMemberBodyContents(CharArrayBuffer)
- */
- protected void appendMemberBodyContents(CharArrayBuffer buffer) {
- }
+/**
+ * Constructs an empty field node.
+ */
+DOMField() {
+}
+/**
+ * Creates a new detailed FIELD document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this field,
+ * corresponding to VariableDeclaratorId (JLS 8.3).
+ * @param nameRange - a two element array of integers describing the
+ * entire inclusive source range of this node's name within its document,
+ * including any array qualifiers that might follow the name.
+ * @param commentRange - a two element array describing the comments that precede
+ * the member declaration. The first matches the start of this node's
+ * sourceRange, and the second is the new-line or first non-whitespace
+ * character following the last comment. If no comments are present,
+ * this array contains two -1's.
+ * @param flags - an integer representing the modifiers for this member. The
+ * integer can be analyzed with org.eclipse.jdt.core.Flags
+ * @param modifierRange - a two element array describing the location of
+ * modifiers for this member within its source range. The first integer
+ * is the first character of the first modifier for this member, and
+ * the second integer is the last whitespace character preceeding the
+ * next part of this member declaration. If there are no modifiers present
+ * in this node's source code (i.e. default protection), this array
+ * contains two -1's.
+ * @param typeRange- a two element array describing the location of the
+ * typeName in the document - the positions of the first and last characters
+ * of the typeName.
+ * @param type - the type of the field, in normalized form, as defined in
+ * Type in Field Declaration (JLS 8.3)
+ * @param hasInitializer - true if this field declaration includes an initializer,
+ * otherwise false
+ * @param initRange - a two element array describing the location of the initializer
+ * in the declaration. The first integer is the position of the character
+ * following the equals sign, and the position of the last character is the last
+ * in the initializer. If this field has no initializer, this array contains
+ * two -1's.
+ * @param isVariableDeclarator - true if the field is a seconday variable declarator
+ * for a previous field declaration.
+ */
+DOMField(char[] document, int[] sourceRange, String name, int[] nameRange, int[] commentRange, int flags, int[] modifierRange, int[] typeRange, String type, boolean hasInitializer, int[] initRange, boolean isVariableDeclarator) {
+ super(document, sourceRange, name, nameRange, commentRange, flags, modifierRange);
- /**
- * @see DOMMember#appendMemberDeclarationContents(CharArrayBuffer)
- */
- protected void appendMemberDeclarationContents(CharArrayBuffer buffer) {
+ fType= type;
+ fTypeRange= typeRange;
+ setHasInitializer(hasInitializer);
+ fInitializerRange= initRange;
+ setIsVariableDeclarator(isVariableDeclarator);
+ setMask(MASK_DETAILED_SOURCE_INDEXES, true);
- if (isVariableDeclarator()) {
- buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]);
- } else {
- buffer.append(getTypeContents()).append(
- fDocument,
- fTypeRange[1] + 1,
- fNameRange[0] - fTypeRange[1] - 1);
- }
+}
+/**
+ * Creates a new simple FIELD document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this field,
+ * corresponding to VariableDeclaratorId (JLS 8.3).
+ * @param nameRange - a two element array of integers describing the
+ * entire inclusive source range of this node's name within its document,
+ * including any array qualifiers that might follow the name.
+ * @param flags - an integer representing the modifiers for this member. The
+ * integer can be analyzed with org.eclipse.jdt.core.Flags
+ * @param type - the type of the field, in normalized form, as defined in
+ * Type in Field Declaration (JLS 8.3)
+ * @param isVariableDeclarator - true if the field is a seconday variable declarator
+ * for a previous field declaration.
+ */
+DOMField(char[] document, int[] sourceRange, String name, int[] nameRange, int flags, String type, boolean isVariableDeclarator) {
+ this(document, sourceRange, name, nameRange, new int[] {-1, -1}, flags, new int[] {-1, -1}, new int[] {-1, -1}, type, false, new int[] {-1, -1}, isVariableDeclarator);
+ setMask(MASK_DETAILED_SOURCE_INDEXES, false);
+}
+/**
+ * Appends this member's body contents to the given CharArrayBuffer.
+ * Body contents include the member body and any trailing whitespace.
+ *
+ * <p>A field does not have a body.
+ *
+ * @see DOMMember#appendMemberBodyContents(CharArrayBuffer)
+ */
+protected void appendMemberBodyContents(CharArrayBuffer buffer) {}
+/**
+ * @see DOMMember#appendMemberDeclarationContents(CharArrayBuffer)
+ */
+protected void appendMemberDeclarationContents(CharArrayBuffer buffer) {
- buffer.append(getNameContents());
- if (hasInitializer()) {
- if (fInitializerRange[0] < 0) {
- buffer.append("=").append(fInitializer).append(
- fDocument,
- fNameRange[1] + 1,
- fSourceRange[1] - fNameRange[1]);
- } else {
- buffer
- .append(fDocument, fNameRange[1] + 1, fInitializerRange[0] - fNameRange[1] - 1)
- .append(getInitializer())
- .append(
- fDocument,
- fInitializerRange[1] + 1,
- fSourceRange[1] - fInitializerRange[1]);
- }
+ if (isVariableDeclarator()) {
+ buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]);
+ } else {
+ buffer
+ .append(getTypeContents())
+ .append(fDocument, fTypeRange[1] + 1, fNameRange[0] - fTypeRange[1] - 1);
+ }
+
+ buffer.append(getNameContents());
+ if (hasInitializer()) {
+ if (fInitializerRange[0] < 0) {
+ buffer
+ .append("=")
+ .append(fInitializer)
+ .append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]);
} else {
- if (fInitializerRange[0] < 0) {
- buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]);
- } else {
- buffer.append(
- fDocument,
- fInitializerRange[1] + 1,
- fSourceRange[1] - fInitializerRange[1]);
- }
+ buffer
+ .append(fDocument, fNameRange[1] + 1, fInitializerRange[0] - fNameRange[1] - 1)
+ .append(getInitializer())
+ .append(fDocument, fInitializerRange[1] + 1, fSourceRange[1] - fInitializerRange[1]);
}
-
- }
-
- /**
- * Appends this member's header contents to the given CharArrayBuffer.
- * Header contents include any preceding comments and modifiers.
- *
- * <p>If this field is a secondary variable declarator, there is no header.
- *
- * @see DOMMember#appendMemberHeaderFragment(CharArrayBuffer)
- */
- protected void appendMemberHeaderFragment(CharArrayBuffer buffer) {
-
- if (isVariableDeclarator()) {
- return;
+ } else {
+ if (fInitializerRange[0] < 0) {
+ buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]);
} else {
- super.appendMemberHeaderFragment(buffer);
+ buffer.append(fDocument, fInitializerRange[1] + 1, fSourceRange[1] - fInitializerRange[1]);
}
-
- }
-
- /**
- * @see DOMMember#appendSimpleContents(CharArrayBuffer)
- */
- protected void appendSimpleContents(CharArrayBuffer buffer) {
- // append eveything before my name
- buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]);
- // append my name
- buffer.append(fName);
- // append everything after my name
- buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]);
}
- /**
- * Generates detailed source indexes for this node if possible.
- *
- * @exception DOMException if unable to generate detailed source indexes
- * for this node
- */
- protected void becomeDetailed() throws DOMException {
- if (!isDetailed()) {
- if (isVariableDeclarator() || hasMultipleVariableDeclarators()) {
- DOMNode first = getFirstFieldDeclaration();
- DOMNode last = getLastFieldDeclaration();
- DOMNode node = first;
- String source = first.getContents();
- while (node != last) {
- node = node.fNextNode;
- source += node.getContents();
- }
- DOMBuilder builder = new DOMBuilder();
- IDOMField[] details = builder.createFields(source.toCharArray());
- if (details.length == 0) {
- throw new DOMException("Unable to generate detailed source indexes.");
- } else {
- node = this;
- for (int i = 0; i < details.length; i++) {
- node.shareContents((DOMNode) details[i]);
- node = node.fNextNode;
- }
- }
- } else {
- super.becomeDetailed();
- }
-
- }
- }
+}
+/**
+ * Appends this member's header contents to the given CharArrayBuffer.
+ * Header contents include any preceding comments and modifiers.
+ *
+ * <p>If this field is a secondary variable declarator, there is no header.
+ *
+ * @see DOMMember#appendMemberHeaderFragment(CharArrayBuffer)
+ */
+protected void appendMemberHeaderFragment(CharArrayBuffer buffer) {
- /**
- * @see IDOMNode#clone()
- */
- public Object clone() {
- if (isVariableDeclarator() || hasMultipleVariableDeclarators()) {
- return getFactory().createField(
- new String(getSingleVariableDeclaratorContents()));
- } else {
- return super.clone();
- }
+ if (isVariableDeclarator()) {
+ return;
+ } else {
+ super.appendMemberHeaderFragment(buffer);
}
- /**
- * Expands all variable declarators in this field declaration into
- * stand-alone field declarations.
- */
- protected void expand() {
+}
+/**
+ * @see DOMMember#appendSimpleContents(CharArrayBuffer)
+ */
+protected void appendSimpleContents(CharArrayBuffer buffer) {
+ // append eveything before my name
+ buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]);
+ // append my name
+ buffer.append(fName);
+ // append everything after my name
+ buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]);
+}
+/**
+ * Generates detailed source indexes for this node if possible.
+ *
+ * @exception DOMException if unable to generate detailed source indexes
+ * for this node
+ */
+protected void becomeDetailed() throws DOMException {
+ if (!isDetailed()) {
if (isVariableDeclarator() || hasMultipleVariableDeclarators()) {
- Enumeration siblings = new SiblingEnumeration(getFirstFieldDeclaration());
- DOMField field = (DOMField) siblings.nextElement();
- DOMNode next = field.fNextNode;
- while (siblings.hasMoreElements()
- && (next instanceof DOMField)
- && (((DOMField) next).isVariableDeclarator())) {
- field.localizeContents();
- if (field.fParent != null) {
- field.fParent.fragment();
- }
- field = (DOMField) siblings.nextElement();
- next = field.fNextNode;
+ DOMNode first = getFirstFieldDeclaration();
+ DOMNode last = getLastFieldDeclaration();
+ DOMNode node= first;
+ String source= first.getContents();
+ while (node != last) {
+ node= node.fNextNode;
+ source+=node.getContents();
}
- field.localizeContents();
- }
- }
-
- /**
- * @see DOMNode#getDetailedNode()
- */
- protected DOMNode getDetailedNode() {
- if (isVariableDeclarator() || hasMultipleVariableDeclarators()) {
- return (DOMNode) getFactory().createField(
- new String(getSingleVariableDeclaratorContents()));
- } else {
- return (DOMNode) getFactory().createField(getContents());
- }
- }
-
- /**
- * Returns the first field document fragment that defines
- * the type for this variable declarator.
- */
- protected DOMField getFirstFieldDeclaration() {
- if (isVariableDeclarator()) {
- return ((DOMField) fPreviousNode).getFirstFieldDeclaration();
- } else {
- return this;
- }
- }
-
- /**
- * @see IDOMField#getInitializer()
- */
- public String getInitializer() {
- becomeDetailed();
- if (hasInitializer()) {
- if (fInitializer != null) {
- return fInitializer;
+ DOMBuilder builder = new DOMBuilder();
+ IDOMField[] details= builder.createFields(source.toCharArray());
+ if (details.length == 0) {
+ throw new DOMException("Unable to generate detailed source indexes.");
} else {
- return CharArrayOps.substring(
- fDocument,
- fInitializerRange[0],
- fInitializerRange[1] + 1 - fInitializerRange[0]);
+ node= this;
+ for (int i= 0; i < details.length; i++) {
+ node.shareContents((DOMNode)details[i]);
+ node= node.fNextNode;
+ }
}
} else {
- return null;
+ super.becomeDetailed();
}
- }
- /**
- * @see IDOMNode#getJavaElement
- */
- public IJavaElement getJavaElement(IJavaElement parent)
- throws IllegalArgumentException {
- if (parent.getElementType() == IJavaElement.TYPE) {
- return ((IType) parent).getField(getName());
- } else {
- throw new IllegalArgumentException("Illegal parent argument");
- }
}
-
- /**
- * Returns the last field document fragment in this muli-declarator statement.
- */
- protected DOMField getLastFieldDeclaration() {
- DOMField field = this;
- while (field.isVariableDeclarator()
- || field.hasMultipleVariableDeclarators()) {
- if (field.fNextNode instanceof DOMField
- && ((DOMField) field.fNextNode).isVariableDeclarator()) {
- field = (DOMField) field.fNextNode;
- } else {
- break;
+}
+/**
+ * @see IDOMNode#clone()
+ */
+public Object clone() {
+ if (isVariableDeclarator() || hasMultipleVariableDeclarators()) {
+ return getFactory().createField(new String(getSingleVariableDeclaratorContents()));
+ } else {
+ return super.clone();
+ }
+}
+/**
+ * Expands all variable declarators in this field declaration into
+ * stand-alone field declarations.
+ */
+protected void expand() {
+ if (isVariableDeclarator() || hasMultipleVariableDeclarators()) {
+ Enumeration siblings= new SiblingEnumeration(getFirstFieldDeclaration());
+ DOMField field= (DOMField)siblings.nextElement();
+ DOMNode next= field.fNextNode;
+ while (siblings.hasMoreElements() && (next instanceof DOMField) && (((DOMField)next).isVariableDeclarator())) {
+ field.localizeContents();
+ if (field.fParent != null) {
+ field.fParent.fragment();
}
+ field= (DOMField)siblings.nextElement();
+ next= field.fNextNode;
}
- return field;
+ field.localizeContents();
}
-
- /**
- * @see DOMMember#getMemberDeclarationStartPosition()
- */
- protected int getMemberDeclarationStartPosition() {
- return fTypeRange[0];
+}
+/**
+ * @see DOMNode#getDetailedNode()
+ */
+protected DOMNode getDetailedNode() {
+ if (isVariableDeclarator() || hasMultipleVariableDeclarators()) {
+ return (DOMNode)getFactory().createField(new String(getSingleVariableDeclaratorContents()));
+ } else {
+ return (DOMNode)getFactory().createField(getContents());
}
-
- /**
- * @see IDOMNode#getNodeType()
- */
- public int getNodeType() {
- return IDOMNode.FIELD;
+}
+/**
+ * Returns the first field document fragment that defines
+ * the type for this variable declarator.
+ */
+protected DOMField getFirstFieldDeclaration() {
+ if (isVariableDeclarator()) {
+ return ((DOMField)fPreviousNode).getFirstFieldDeclaration();
+ } else {
+ return this;
}
-
- /**
- * Returns a String representing this field declaration as a field
- * declaration with one variable declarator.
- */
- protected char[] getSingleVariableDeclaratorContents() {
-
- CharArrayBuffer buffer = new CharArrayBuffer();
- DOMField first = getFirstFieldDeclaration();
- if (first.isDetailed()) {
- first.appendMemberHeaderFragment(buffer);
- buffer.append(getType());
- if (isVariableDeclarator()) {
- buffer.append(" ");
- } else {
- buffer.append(fDocument, fTypeRange[1] + 1, fNameRange[0] - fTypeRange[1] - 1);
- }
- } else {
- buffer.append(
- first.fDocument,
- first.fSourceRange[0],
- first.fNameRange[0] - first.fSourceRange[0]);
- }
-
- buffer.append(getName());
- if (hasInitializer()) {
- if (fInitializerRange[0] < 0) {
- buffer.append("=").append(fInitializer).append(';').append(
- JavaModelManager.LINE_SEPARATOR);
- } else {
- buffer
- .append(fDocument, fNameRange[1] + 1, fInitializerRange[0] - fNameRange[1] - 1)
- .append(getInitializer())
- .append(';')
- .append(JavaModelManager.LINE_SEPARATOR);
- }
+}
+/**
+ * @see IDOMField#getInitializer()
+ */
+public String getInitializer() {
+ becomeDetailed();
+ if (hasInitializer()) {
+ if (fInitializer != null) {
+ return fInitializer;
} else {
- buffer.append(';').append(JavaModelManager.LINE_SEPARATOR);
+ return CharArrayOps.substring(fDocument, fInitializerRange[0], fInitializerRange[1] + 1 - fInitializerRange[0]);
}
- return buffer.getContents();
+ } else {
+ return null;
}
-
- /**
- * @see IDOMField#getType()
- */
- public String getType() {
- return fType;
+}
+/**
+ * @see IDOMNode#getJavaElement
+ */
+public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException {
+ if (parent.getElementType() == IJavaElement.TYPE) {
+ return ((IType)parent).getField(getName());
+ } else {
+ throw new IllegalArgumentException("Illegal parent argument");
}
-
- /**
- * Returns the souce code to be used for this
- * field's type.
- */
- protected char[] getTypeContents() {
- if (isTypeAltered()) {
- return fType.toCharArray();
+}
+/**
+ * Returns the last field document fragment in this muli-declarator statement.
+ */
+protected DOMField getLastFieldDeclaration() {
+ DOMField field = this;
+ while (field.isVariableDeclarator() || field.hasMultipleVariableDeclarators()) {
+ if (field.fNextNode instanceof DOMField && ((DOMField)field.fNextNode).isVariableDeclarator()) {
+ field= (DOMField)field.fNextNode;
} else {
- return CharArrayOps.subarray(
- fDocument,
- fTypeRange[0],
- fTypeRange[1] + 1 - fTypeRange[0]);
+ break;
}
}
+ return field;
+}
+/**
+ * @see DOMMember#getMemberDeclarationStartPosition()
+ */
+protected int getMemberDeclarationStartPosition() {
+ return fTypeRange[0];
+}
+/**
+ * @see IDOMNode#getNodeType()
+ */
+public int getNodeType() {
+ return IDOMNode.FIELD;
+}
+/**
+ * Returns a String representing this field declaration as a field
+ * declaration with one variable declarator.
+ */
+protected char[] getSingleVariableDeclaratorContents() {
- /**
- * Returns true if this field has an initializer expression,
- * otherwise false.
- */
- protected boolean hasInitializer() {
- return getMask(MASK_FIELD_HAS_INITIALIZER);
- }
-
- /**
- * Returns true is this field declarations has more than one
- * variable declarator, otherwise false;
- */
- protected boolean hasMultipleVariableDeclarators() {
- return fNextNode != null
- && (fNextNode instanceof DOMField)
- && ((DOMField) fNextNode).isVariableDeclarator();
- }
- /**
- * Inserts the given un-parented node as a sibling of this node, immediately before
- * this node. Once inserted, the sibling is only dependent on this document fragment.
- *
- * <p>When a sibling is inserted before a variable declarator, it must first
- * be expanded.
- *
- * @see IDOMNode#insertSibling(IDOMNode)
- */
- public void insertSibling(IDOMNode sibling)
- throws IllegalArgumentException, DOMException {
+ CharArrayBuffer buffer= new CharArrayBuffer();
+ DOMField first= getFirstFieldDeclaration();
+ if (first.isDetailed()) {
+ first.appendMemberHeaderFragment(buffer);
+ buffer.append(getType());
if (isVariableDeclarator()) {
- expand();
- }
- super.insertSibling(sibling);
- }
-
- /**
- * Returns true if this field's type has been altered
- * from the original document contents.
- */
- protected boolean isTypeAltered() {
- return getMask(MASK_FIELD_TYPE_ALTERED);
- }
-
- /**
- * Returns true if this field is declared as a secondary variable
- * declarator for a previous field declaration.
- */
- protected boolean isVariableDeclarator() {
- return getMask(MASK_FIELD_IS_VARIABLE_DECLARATOR);
- }
-
- /**
- * @see DOMNode
- */
- protected DOMNode newDOMNode() {
- return new DOMField();
- }
-
- /**
- * Normalizes this <code>DOMNode</code>'s end position.
- */
- void normalizeEndPosition(ILineStartFinder finder, DOMNode next) {
- if (next == null) {
- // this node's end position includes all of the characters up
- // to the end of the enclosing node
- DOMNode parent = (DOMNode) getParent();
- if (parent == null || parent instanceof DOMCompilationUnit) {
- setSourceRangeEnd(fDocument.length - 1);
- } else {
- // parent is a type
- setSourceRangeEnd(((DOMType) parent).getCloseBodyPosition() - 1);
- }
+ buffer.append(" ");
} else {
- // this node's end position is just before the start of the next node
- // unless the next node is a field that is declared along with this one
- next.normalizeStartPosition(getEndPosition(), finder);
- if (next instanceof DOMField) {
- DOMField field = (DOMField) next;
- if (field.isVariableDeclarator() && fTypeRange[0] == field.fTypeRange[0])
- return;
- }
- setSourceRangeEnd(next.getStartPosition() - 1);
+ buffer.append(fDocument, fTypeRange[1] + 1, fNameRange[0] - fTypeRange[1] - 1);
}
- }
-
- /**
- * Normalizes this <code>DOMNode</code>'s start position.
- */
- void normalizeStartPosition(int endPosition, ILineStartFinder finder) {
- if (isVariableDeclarator()) {
- // start position is end of last element
- setStartPosition(fPreviousNode.getEndPosition() + 1);
+ } else {
+ buffer.append(first.fDocument, first.fSourceRange[0], first.fNameRange[0] - first.fSourceRange[0]);
+ }
+
+ buffer.append(getName());
+ if (hasInitializer()) {
+ if (fInitializerRange[0] < 0) {
+ buffer
+ .append("=")
+ .append(fInitializer)
+ .append(';')
+ .append(JavaModelManager.LINE_SEPARATOR);
} else {
- super.normalizeStartPosition(endPosition, finder);
+ buffer
+ .append(fDocument, fNameRange[1] + 1, fInitializerRange[0] - fNameRange[1] - 1)
+ .append(getInitializer())
+ .append(';')
+ .append(JavaModelManager.LINE_SEPARATOR);
}
+ } else {
+ buffer.append(';').append(JavaModelManager.LINE_SEPARATOR);
}
-
- /**
- * Offsets all the source indexes in this node by the given amount.
- */
- protected void offset(int offset) {
- super.offset(offset);
- offsetRange(fInitializerRange, offset);
- offsetRange(fTypeRange, offset);
- }
-
- /**
- * Separates this node from its parent and siblings, maintaining any ties that
- * this node has to the underlying document fragment.
- *
- * <p>When a field with multiple declarators is removed, its declaration
- * must first be expanded.
- *
- * @see IDOMNode#remove()
- */
- public void remove() {
- expand();
- super.remove();
- }
-
- /**
- * @see IDOMMember#setComment(String)
- */
- public void setComment(String comment) {
- expand();
- super.setComment(comment);
+ return buffer.getContents();
+}
+/**
+ * @see IDOMField#getType()
+ */
+public String getType() {
+ return fType;
+}
+/**
+ * Returns the souce code to be used for this
+ * field's type.
+ */
+protected char[] getTypeContents() {
+ if (isTypeAltered()) {
+ return fType.toCharArray();
+ } else {
+ return CharArrayOps.subarray(fDocument, fTypeRange[0], fTypeRange[1] + 1 - fTypeRange[0]);
}
-
- /**
- * @see IDOMMember#setFlags(int)
- */
- public void setFlags(int flags) {
+}
+/**
+ * Returns true if this field has an initializer expression,
+ * otherwise false.
+ */
+protected boolean hasInitializer() {
+ return getMask(MASK_FIELD_HAS_INITIALIZER);
+}
+/**
+ * Returns true is this field declarations has more than one
+ * variable declarator, otherwise false;
+ */
+protected boolean hasMultipleVariableDeclarators() {
+ return fNextNode != null && (fNextNode instanceof DOMField) &&
+ ((DOMField)fNextNode).isVariableDeclarator();
+}
+/**
+ * Inserts the given un-parented node as a sibling of this node, immediately before
+ * this node. Once inserted, the sibling is only dependent on this document fragment.
+ *
+ * <p>When a sibling is inserted before a variable declarator, it must first
+ * be expanded.
+ *
+ * @see IDOMNode#insertSibling(IDOMNode)
+ */
+public void insertSibling(IDOMNode sibling) throws IllegalArgumentException, DOMException {
+ if (isVariableDeclarator()) {
expand();
- super.setFlags(flags);
- }
-
- /**
- * Sets the state of this field declaration as having
- * an initializer expression.
- */
- protected void setHasInitializer(boolean hasInitializer) {
- setMask(MASK_FIELD_HAS_INITIALIZER, hasInitializer);
- }
-
- /**
- * @see IDOMField#setInitializer(char[])
- */
- public void setInitializer(String initializer) {
- becomeDetailed();
- fragment();
- setHasInitializer(initializer != null);
- fInitializer = initializer;
- }
-
- /**
- * Sets the initializer range.
- */
- void setInitializerRange(int start, int end) {
- fInitializerRange[0] = start;
- fInitializerRange[1] = end;
- }
-
- /**
- * Sets the state of this field declaration as being a
- * secondary variable declarator for a previous field
- * declaration.
- */
- protected void setIsVariableDeclarator(boolean isVariableDeclarator) {
- setMask(MASK_FIELD_IS_VARIABLE_DECLARATOR, isVariableDeclarator);
- }
-
- /**
- * @see IDOMField#setName(char[])
- */
- public void setName(String name) throws IllegalArgumentException {
- if (name == null) {
- throw new IllegalArgumentException("illegal to set name to null");
+ }
+ super.insertSibling(sibling);
+}
+/**
+ * Returns true if this field's type has been altered
+ * from the original document contents.
+ */
+protected boolean isTypeAltered() {
+ return getMask(MASK_FIELD_TYPE_ALTERED);
+}
+/**
+ * Returns true if this field is declared as a secondary variable
+ * declarator for a previous field declaration.
+ */
+protected boolean isVariableDeclarator() {
+ return getMask(MASK_FIELD_IS_VARIABLE_DECLARATOR);
+}
+/**
+ * @see DOMNode
+ */
+protected DOMNode newDOMNode() {
+ return new DOMField();
+}
+/**
+ * Normalizes this <code>DOMNode</code>'s end position.
+ */
+void normalizeEndPosition(ILineStartFinder finder, DOMNode next) {
+ if (next == null) {
+ // this node's end position includes all of the characters up
+ // to the end of the enclosing node
+ DOMNode parent = (DOMNode) getParent();
+ if (parent == null || parent instanceof DOMCompilationUnit) {
+ setSourceRangeEnd(fDocument.length - 1);
} else {
- super.setName(name);
- setTypeAltered(true);
+ // parent is a type
+ setSourceRangeEnd(((DOMType)parent).getCloseBodyPosition() - 1);
}
- }
-
- /**
- * @see IDOMField#setType(char[])
- */
- public void setType(String typeName) throws IllegalArgumentException {
- if (typeName == null) {
- throw new IllegalArgumentException("Illegal to set field type to null");
+ } else {
+ // this node's end position is just before the start of the next node
+ // unless the next node is a field that is declared along with this one
+ next.normalizeStartPosition(getEndPosition(), finder);
+ if (next instanceof DOMField) {
+ DOMField field = (DOMField) next;
+ if (field.isVariableDeclarator() && fTypeRange[0] == field.fTypeRange[0])
+ return;
}
- becomeDetailed();
- expand();
- fragment();
- setTypeAltered(true);
- setNameAltered(true);
- fType = typeName;
+ setSourceRangeEnd(next.getStartPosition() - 1);
}
-
- /**
- * Sets the state of this field declaration as having
- * the field type altered from the original document.
- */
- protected void setTypeAltered(boolean typeAltered) {
- setMask(MASK_FIELD_TYPE_ALTERED, typeAltered);
- }
-
- /**
- * @see DOMNode#shareContents(DOMNode)
- */
- protected void shareContents(DOMNode node) {
- super.shareContents(node);
- DOMField field = (DOMField) node;
- fInitializer = field.fInitializer;
- fInitializerRange = rangeCopy(field.fInitializerRange);
- fType = field.fType;
- fTypeRange = rangeCopy(field.fTypeRange);
+}
+/**
+ * Normalizes this <code>DOMNode</code>'s start position.
+ */
+void normalizeStartPosition(int endPosition, ILineStartFinder finder) {
+ if (isVariableDeclarator()) {
+ // start position is end of last element
+ setStartPosition(fPreviousNode.getEndPosition() + 1);
+ } else {
+ super.normalizeStartPosition(endPosition, finder);
}
-
- /**
- * @see IDOMNode#toString()
- */
- public String toString() {
- return "FIELD: " + getName();
+}
+/**
+ * Offsets all the source indexes in this node by the given amount.
+ */
+protected void offset(int offset) {
+ super.offset(offset);
+ offsetRange(fInitializerRange, offset);
+ offsetRange(fTypeRange, offset);
+}
+/**
+ * Separates this node from its parent and siblings, maintaining any ties that
+ * this node has to the underlying document fragment.
+ *
+ * <p>When a field with multiple declarators is removed, its declaration
+ * must first be expanded.
+ *
+ * @see IDOMNode#remove()
+ */
+public void remove() {
+ expand();
+ super.remove();
+}
+/**
+ * @see IDOMMember#setComment(String)
+ */
+public void setComment(String comment) {
+ expand();
+ super.setComment(comment);
+}
+/**
+ * @see IDOMMember#setFlags(int)
+ */
+public void setFlags(int flags) {
+ expand();
+ super.setFlags(flags);
+}
+/**
+ * Sets the state of this field declaration as having
+ * an initializer expression.
+ */
+protected void setHasInitializer(boolean hasInitializer) {
+ setMask(MASK_FIELD_HAS_INITIALIZER, hasInitializer);
+}
+/**
+ * @see IDOMField#setInitializer(char[])
+ */
+public void setInitializer(String initializer) {
+ becomeDetailed();
+ fragment();
+ setHasInitializer(initializer != null);
+ fInitializer= initializer;
+}
+/**
+ * Sets the initializer range.
+ */
+void setInitializerRange(int start, int end) {
+ fInitializerRange[0] = start;
+ fInitializerRange[1] = end;
+}
+/**
+ * Sets the state of this field declaration as being a
+ * secondary variable declarator for a previous field
+ * declaration.
+ */
+protected void setIsVariableDeclarator(boolean isVariableDeclarator) {
+ setMask(MASK_FIELD_IS_VARIABLE_DECLARATOR, isVariableDeclarator);
+}
+/**
+ * @see IDOMField#setName(char[])
+ */
+public void setName(String name) throws IllegalArgumentException {
+ if (name == null) {
+ throw new IllegalArgumentException("illegal to set name to null");
+ } else {
+ super.setName(name);
+ setTypeAltered(true);
}
-
+}
+/**
+ * @see IDOMField#setType(char[])
+ */
+public void setType(String typeName) throws IllegalArgumentException {
+ if (typeName == null) {
+ throw new IllegalArgumentException("Illegal to set field type to null");
+ }
+ becomeDetailed();
+ expand();
+ fragment();
+ setTypeAltered(true);
+ setNameAltered(true);
+ fType= typeName;
+}
+/**
+ * Sets the state of this field declaration as having
+ * the field type altered from the original document.
+ */
+protected void setTypeAltered(boolean typeAltered) {
+ setMask(MASK_FIELD_TYPE_ALTERED, typeAltered);
+}
+/**
+ * @see DOMNode#shareContents(DOMNode)
+ */
+protected void shareContents(DOMNode node) {
+ super.shareContents(node);
+ DOMField field= (DOMField)node;
+ fInitializer= field.fInitializer;
+ fInitializerRange= rangeCopy(field.fInitializerRange);
+ fType= field.fType;
+ fTypeRange= rangeCopy(field.fTypeRange);
+}
+/**
+ * @see IDOMNode#toString()
+ */
+public String toString() {
+ return "FIELD: " + getName();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMImport.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMImport.java
index 4af1551aa8..759a59e176 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMImport.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMImport.java
@@ -25,146 +25,131 @@ class DOMImport extends DOMNode implements IDOMImport {
* Indicates if this import is an on demand type import
*/
protected boolean fOnDemand;
- /**
- * Creates a new empty IMPORT node.
- */
- DOMImport() {
- fName = "java.lang.*";
- setMask(MASK_DETAILED_SOURCE_INDEXES, true);
- }
-
- /**
- * Creates a new detailed IMPORT document fragment on the given range of the document.
- *
- * @param document - the document containing this node's original contents
- * @param sourceRange - a two element array of integers describing the
- * entire inclusive source range of this node within its document.
- * Contents start on and include the character at the first position.
- * Contents end on and include the character at the last position.
- * An array of -1's indicates this node's contents do not exist
- * in the document.
- * @param name - the identifier portion of the name of this node, or
- * <code>null</code> if this node does not have a name
- * @param nameRange - a two element array of integers describing the
- * entire inclusive source range of this node's name within its document,
- * including any array qualifiers that might immediately follow the name
- * or -1's if this node does not have a name.
- * @param onDemand - indicates if this import is an on demand style import
- */
- DOMImport(
- char[] document,
- int[] sourceRange,
- String name,
- int[] nameRange,
- boolean onDemand) {
- super(document, sourceRange, name, nameRange);
- fOnDemand = onDemand;
- setMask(MASK_DETAILED_SOURCE_INDEXES, true);
- }
-
- /**
- * Creates a new simple IMPORT document fragment on the given range of the document.
- *
- * @param document - the document containing this node's original contents
- * @param sourceRange - a two element array of integers describing the
- * entire inclusive source range of this node within its document.
- * Contents start on and include the character at the first position.
- * Contents end on and include the character at the last position.
- * An array of -1's indicates this node's contents do not exist
- * in the document.
- * @param name - the identifier portion of the name of this node, or
- * <code>null</code> if this node does not have a name
- * @param onDemand - indicates if this import is an on demand style import
- */
- DOMImport(char[] document, int[] sourceRange, String name, boolean onDemand) {
- this(document, sourceRange, name, new int[] { -1, -1 }, onDemand);
- fOnDemand = onDemand;
- setMask(MASK_DETAILED_SOURCE_INDEXES, false);
- }
-
- /**
- * @see DOMNode#appendFragmentedContents(CharArrayBuffer)
- */
- protected void appendFragmentedContents(CharArrayBuffer buffer) {
- if (fNameRange[0] < 0) {
- buffer.append("import ").append(fName).append(';').append(
- JavaModelManager.LINE_SEPARATOR);
- } else {
- buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]);
- //buffer.append(fDocument, fNameRange[0], fNameRange[1] - fNameRange[0] + 1);
- buffer.append(fName);
- buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]);
- }
- }
-
- /**
- * @see IDOMNode#getContents()
- */
- public String getContents() {
- if (fName == null) {
- return null;
- } else {
- return super.getContents();
- }
- }
-
- /**
- * @see DOMNode#getDetailedNode()
- */
- protected DOMNode getDetailedNode() {
- return (DOMNode) getFactory().createImport(getContents());
- }
-
- /**
- * @see IDOMNode#getJavaElement
- */
- public IJavaElement getJavaElement(IJavaElement parent)
- throws IllegalArgumentException {
- if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) {
- return ((ICompilationUnit) parent).getImport(getName());
- } else {
- throw new IllegalArgumentException("Illegal parent argument");
- }
- }
-
- /**
- * @see IDOMNode#getNodeType()
- */
- public int getNodeType() {
- return IDOMNode.IMPORT;
- }
-
- /**
- * @see IDOMImport#isOnDemand()
- */
- public boolean isOnDemand() {
- return fOnDemand;
+/**
+ * Creates a new empty IMPORT node.
+ */
+DOMImport() {
+ fName = "java.lang.*";
+ setMask(MASK_DETAILED_SOURCE_INDEXES, true);
+}
+/**
+ * Creates a new detailed IMPORT document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this node, or
+ * <code>null</code> if this node does not have a name
+ * @param nameRange - a two element array of integers describing the
+ * entire inclusive source range of this node's name within its document,
+ * including any array qualifiers that might immediately follow the name
+ * or -1's if this node does not have a name.
+ * @param onDemand - indicates if this import is an on demand style import
+ */
+DOMImport(char[] document, int[] sourceRange, String name, int[] nameRange, boolean onDemand) {
+ super(document, sourceRange, name, nameRange);
+ fOnDemand = onDemand;
+ setMask(MASK_DETAILED_SOURCE_INDEXES, true);
+}
+/**
+ * Creates a new simple IMPORT document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this node, or
+ * <code>null</code> if this node does not have a name
+ * @param onDemand - indicates if this import is an on demand style import
+ */
+DOMImport(char[] document, int[] sourceRange, String name, boolean onDemand) {
+ this(document, sourceRange, name, new int[] {-1, -1}, onDemand);
+ fOnDemand = onDemand;
+ setMask(MASK_DETAILED_SOURCE_INDEXES, false);
+}
+/**
+ * @see DOMNode#appendFragmentedContents(CharArrayBuffer)
+ */
+protected void appendFragmentedContents(CharArrayBuffer buffer) {
+ if (fNameRange[0] < 0) {
+ buffer
+ .append("import ")
+ .append(fName)
+ .append(';')
+ .append(JavaModelManager.LINE_SEPARATOR);
+ } else {
+ buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]);
+ //buffer.append(fDocument, fNameRange[0], fNameRange[1] - fNameRange[0] + 1);
+ buffer.append(fName);
+ buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]);
}
-
- /**
- * @see DOMNode
- */
- protected DOMNode newDOMNode() {
- return new DOMImport();
+}
+/**
+ * @see IDOMNode#getContents()
+ */
+public String getContents() {
+ if (fName == null) {
+ return null;
+ } else {
+ return super.getContents();
}
-
- /**
- * @see IDOMNode#setName(char[])
- */
- public void setName(String name) {
- if (name == null) {
- throw new IllegalArgumentException("illegal to set name to null");
- }
- becomeDetailed();
- super.setName(name);
- fOnDemand = name.endsWith(".*");
+}
+/**
+ * @see DOMNode#getDetailedNode()
+ */
+protected DOMNode getDetailedNode() {
+ return (DOMNode)getFactory().createImport(getContents());
+}
+/**
+ * @see IDOMNode#getJavaElement
+ */
+public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException {
+ if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) {
+ return ((ICompilationUnit)parent).getImport(getName());
+ } else {
+ throw new IllegalArgumentException("Illegal parent argument");
}
-
- /**
- * @see IDOMNode#toString()
- */
- public String toString() {
- return "IMPORT: " + getName();
+}
+/**
+ * @see IDOMNode#getNodeType()
+ */
+public int getNodeType() {
+ return IDOMNode.IMPORT;
+}
+/**
+ * @see IDOMImport#isOnDemand()
+ */
+public boolean isOnDemand() {
+ return fOnDemand;
+}
+/**
+ * @see DOMNode
+ */
+protected DOMNode newDOMNode() {
+ return new DOMImport();
+}
+/**
+ * @see IDOMNode#setName(char[])
+ */
+public void setName(String name) {
+ if (name == null) {
+ throw new IllegalArgumentException("illegal to set name to null");
}
-
+ becomeDetailed();
+ super.setName(name);
+ fOnDemand = name.endsWith(".*");
+}
+/**
+ * @see IDOMNode#toString()
+ */
+public String toString() {
+ return "IMPORT: " + getName();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMInitializer.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMInitializer.java
index d365b28ec8..55164d926d 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMInitializer.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMInitializer.java
@@ -34,237 +34,193 @@ class DOMInitializer extends DOMMember implements IDOMInitializer {
* The original inclusive source range of the
* body in the document.
*/
- protected int[] fBodyRange;
+ protected int[] fBodyRange;
- /**
- * Constructs an empty initializer node.
- */
- DOMInitializer() {
-
- }
-
- /**
- * Creates a new detailed INITIALIZER document fragment on the given range of the document.
- *
- * @param document - the document containing this node's original contents
- * @param sourceRange - a two element array of integers describing the
- * entire inclusive source range of this node within its document.
- * Contents start on and include the character at the first position.
- * Contents end on and include the character at the last position.
- * An array of -1's indicates this node's contents do not exist
- * in the document.
- * @param commentRange - a two element array describing the comments that precede
- * the member declaration. The first matches the start of this node's
- * sourceRange, and the second is the new-line or first non-whitespace
- * character following the last comment. If no comments are present,
- * this array contains two -1's.
- * @param flags - an integer representing the modifiers for this member. The
- * integer can be analyzed with org.eclipse.jdt.core.Flags
- * @param modifierRange - a two element array describing the location of
- * modifiers for this member within its source range. The first integer
- * is the first character of the first modifier for this member, and
- * the second integer is the last whitespace character preceeding the
- * next part of this member declaration. If there are no modifiers present
- * in this node's source code (i.e. default protection), this array
- * contains two -1's.
- * @param bodyStartPosition - the position of the open brace of the body
- * of this initialzer.
- */
- DOMInitializer(
- char[] document,
- int[] sourceRange,
- int[] commentRange,
- int flags,
- int[] modifierRange,
- int bodyStartPosition) {
- super(
- document,
- sourceRange,
- null,
- new int[] { -1, -1 },
- commentRange,
- flags,
- modifierRange);
- fBodyRange = new int[2];
- fBodyRange[0] = bodyStartPosition;
- fBodyRange[1] = sourceRange[1];
- setHasBody(true);
- setMask(MASK_DETAILED_SOURCE_INDEXES, true);
- }
-
- /**
- * Creates a new simple INITIALIZER document fragment on the given range of the document.
- *
- * @param document - the document containing this node's original contents
- * @param sourceRange - a two element array of integers describing the
- * entire inclusive source range of this node within its document.
- * Contents start on and include the character at the first position.
- * Contents end on and include the character at the last position.
- * An array of -1's indicates this node's contents do not exist
- * in the document.
- * @param flags - an integer representing the modifiers for this member. The
- * integer can be analyzed with org.eclipse.jdt.core.Flags
- */
- DOMInitializer(char[] document, int[] sourceRange, int flags) {
- this(
- document,
- sourceRange,
- new int[] { -1, -1 },
- flags,
- new int[] { -1, -1 },
- -1);
- setMask(MASK_DETAILED_SOURCE_INDEXES, false);
-
- }
-
- /**
- * @see DOMMember#appendMemberBodyContents(CharArrayBuffer)
- */
- protected void appendMemberBodyContents(CharArrayBuffer buffer) {
- if (hasBody()) {
- buffer.append(getBody()).append(
- fDocument,
- fBodyRange[1] + 1,
- fSourceRange[1] - fBodyRange[1]);
- } else {
- buffer.append("{}").append(JavaModelManager.LINE_SEPARATOR);
- }
- }
-
- /**
- * @see DOMMember#appendMemberDeclarationContents(CharArrayBuffer)
- */
- protected void appendMemberDeclarationContents(CharArrayBuffer buffer) {
- }
+/**
+ * Constructs an empty initializer node.
+ */
+DOMInitializer() {
- /**
- * @see DOMNode#appendSimpleContents(CharArrayBuffer)
- */
- protected void appendSimpleContents(CharArrayBuffer buffer) {
- // append eveything before my name
- buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]);
- // append my name
- buffer.append(fName);
- // append everything after my name
- buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]);
+}
+/**
+ * Creates a new detailed INITIALIZER document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param commentRange - a two element array describing the comments that precede
+ * the member declaration. The first matches the start of this node's
+ * sourceRange, and the second is the new-line or first non-whitespace
+ * character following the last comment. If no comments are present,
+ * this array contains two -1's.
+ * @param flags - an integer representing the modifiers for this member. The
+ * integer can be analyzed with org.eclipse.jdt.core.Flags
+ * @param modifierRange - a two element array describing the location of
+ * modifiers for this member within its source range. The first integer
+ * is the first character of the first modifier for this member, and
+ * the second integer is the last whitespace character preceeding the
+ * next part of this member declaration. If there are no modifiers present
+ * in this node's source code (i.e. default protection), this array
+ * contains two -1's.
+ * @param bodyStartPosition - the position of the open brace of the body
+ * of this initialzer.
+ */
+DOMInitializer(char[] document, int[] sourceRange, int[] commentRange, int flags, int[] modifierRange, int bodyStartPosition) {
+ super(document, sourceRange, null, new int[]{-1, -1}, commentRange, flags, modifierRange);
+ fBodyRange= new int[2];
+ fBodyRange[0]= bodyStartPosition;
+ fBodyRange[1]= sourceRange[1];
+ setHasBody(true);
+ setMask(MASK_DETAILED_SOURCE_INDEXES, true);
+}
+/**
+ * Creates a new simple INITIALIZER document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param flags - an integer representing the modifiers for this member. The
+ * integer can be analyzed with org.eclipse.jdt.core.Flags
+ */
+DOMInitializer(char[] document, int[] sourceRange, int flags) {
+ this(document, sourceRange, new int[] {-1, -1}, flags, new int[] {-1, -1}, -1);
+ setMask(MASK_DETAILED_SOURCE_INDEXES, false);
+
+}
+/**
+ * @see DOMMember#appendMemberBodyContents(CharArrayBuffer)
+ */
+protected void appendMemberBodyContents(CharArrayBuffer buffer) {
+ if (hasBody()) {
+ buffer
+ .append(getBody())
+ .append(fDocument, fBodyRange[1] + 1, fSourceRange[1] - fBodyRange[1]);
+ } else {
+ buffer.append("{}").append(JavaModelManager.LINE_SEPARATOR);
}
-
- /**
- * @see IDOMInitializer#getBody()
- */
- public String getBody() {
- becomeDetailed();
- if (hasBody()) {
- if (fBody != null) {
- return fBody;
- } else {
- return CharArrayOps.substring(
- fDocument,
- fBodyRange[0],
- fBodyRange[1] + 1 - fBodyRange[0]);
- }
+}
+/**
+ * @see DOMMember#appendMemberDeclarationContents(CharArrayBuffer)
+ */
+protected void appendMemberDeclarationContents(CharArrayBuffer buffer) {}
+/**
+ * @see DOMNode#appendSimpleContents(CharArrayBuffer)
+ */
+protected void appendSimpleContents(CharArrayBuffer buffer) {
+ // append eveything before my name
+ buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]);
+ // append my name
+ buffer.append(fName);
+ // append everything after my name
+ buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]);
+}
+/**
+ * @see IDOMInitializer#getBody()
+ */
+public String getBody() {
+ becomeDetailed();
+ if (hasBody()) {
+ if (fBody != null) {
+ return fBody;
} else {
- return null;
+ return CharArrayOps.substring(fDocument, fBodyRange[0], fBodyRange[1] + 1 - fBodyRange[0]);
}
+ } else {
+ return null;
}
-
- /**
- * @see DOMNode#getDetailedNode()
- */
- protected DOMNode getDetailedNode() {
- return (DOMNode) getFactory().createInitializer(getContents());
- }
-
- /**
- * @see IDOMNode#getJavaElement
- */
- public IJavaElement getJavaElement(IJavaElement parent)
- throws IllegalArgumentException {
- if (parent.getElementType() == IJavaElement.TYPE) {
- int count = 1;
- IDOMNode previousNode = getPreviousNode();
- while (previousNode != null) {
- if (previousNode instanceof DOMInitializer) {
- count++;
- }
- previousNode = previousNode.getPreviousNode();
+}
+/**
+ * @see DOMNode#getDetailedNode()
+ */
+protected DOMNode getDetailedNode() {
+ return (DOMNode)getFactory().createInitializer(getContents());
+}
+/**
+ * @see IDOMNode#getJavaElement
+ */
+public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException {
+ if (parent.getElementType() == IJavaElement.TYPE) {
+ int count = 1;
+ IDOMNode previousNode = getPreviousNode();
+ while (previousNode != null) {
+ if (previousNode instanceof DOMInitializer) {
+ count++;
}
- return ((IType) parent).getInitializer(count);
- } else {
- throw new IllegalArgumentException("Illegal parent argument");
+ previousNode = previousNode.getPreviousNode();
}
+ return ((IType) parent).getInitializer(count);
+ } else {
+ throw new IllegalArgumentException("Illegal parent argument");
}
-
- /**
- * @see DOMMember#getMemberDeclarationStartPosition()
- */
- protected int getMemberDeclarationStartPosition() {
- return fBodyRange[0];
- }
-
- /**
- * @see IDOMNode#getNodeType()
- */
- public int getNodeType() {
- return IDOMNode.INITIALIZER;
- }
-
- /**
- * @see IDOMNode#isSigantureEqual(IDOMNode).
- *
- * <p>This method always answers false since an initializer
- * does not have a signature.
- */
- public boolean isSignatureEqual(IDOMNode node) {
- return false;
- }
-
- /**
- * @see DOMNode
- */
- protected DOMNode newDOMNode() {
- return new DOMInitializer();
- }
-
- /**
- * Offsets all the source indexes in this node by the given amount.
- */
- protected void offset(int offset) {
- super.offset(offset);
- offsetRange(fBodyRange, offset);
- }
-
- /**
- * @see IDOMInitializer#setBody(char[])
- */
- public void setBody(String body) {
- becomeDetailed();
- fBody = body;
- setHasBody(body != null);
- fragment();
- }
-
- /**
- * @see IDOMInitializer#setName(String)
- */
- public void setName(String name) {
- }
-
- /**
- * @see DOMNode#shareContents(DOMNode)
- */
- protected void shareContents(DOMNode node) {
- super.shareContents(node);
- DOMInitializer init = (DOMInitializer) node;
- fBody = init.fBody;
- fBodyRange = rangeCopy(init.fBodyRange);
- }
-
- /**
- * @see IDOMNode#toString()
- */
- public String toString() {
- return "INITIALIZER";
- }
-
+}
+/**
+ * @see DOMMember#getMemberDeclarationStartPosition()
+ */
+protected int getMemberDeclarationStartPosition() {
+ return fBodyRange[0];
+}
+/**
+ * @see IDOMNode#getNodeType()
+ */
+public int getNodeType() {
+ return IDOMNode.INITIALIZER;
+}
+/**
+ * @see IDOMNode#isSigantureEqual(IDOMNode).
+ *
+ * <p>This method always answers false since an initializer
+ * does not have a signature.
+ */
+public boolean isSignatureEqual(IDOMNode node) {
+ return false;
+}
+/**
+ * @see DOMNode
+ */
+protected DOMNode newDOMNode() {
+ return new DOMInitializer();
+}
+/**
+ * Offsets all the source indexes in this node by the given amount.
+ */
+protected void offset(int offset) {
+ super.offset(offset);
+ offsetRange(fBodyRange, offset);
+}
+/**
+ * @see IDOMInitializer#setBody(char[])
+ */
+public void setBody(String body) {
+ becomeDetailed();
+ fBody= body;
+ setHasBody(body != null);
+ fragment();
+}
+/**
+ * @see IDOMInitializer#setName(String)
+ */
+public void setName(String name) {}
+/**
+ * @see DOMNode#shareContents(DOMNode)
+ */
+protected void shareContents(DOMNode node) {
+ super.shareContents(node);
+ DOMInitializer init= (DOMInitializer)node;
+ fBody= init.fBody;
+ fBodyRange= rangeCopy(init.fBodyRange);
+}
+/**
+ * @see IDOMNode#toString()
+ */
+public String toString() {
+ return "INITIALIZER";
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMMember.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMMember.java
index ff72589eb3..ebbd1f874f 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMMember.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMMember.java
@@ -24,13 +24,13 @@ abstract class DOMMember extends DOMNode implements IDOMMember {
* The modifier flags for this member that can be
* analyzed with org.eclipse.jdt.core.Flags
*/
- protected int fFlags = 0;
+ protected int fFlags= 0;
/**
* The member's comments when it has been altered from
* the contents in the document, otherwise <code>null</code>.
*/
- protected String fComment = null;
+ protected String fComment= null;
/**
* The original inclusive source range of the
@@ -38,14 +38,15 @@ abstract class DOMMember extends DOMNode implements IDOMMember {
* or -1's if the member did not originally have a
* comment.
*/
- protected int[] fCommentRange;
+ protected int[] fCommentRange;
+
/**
* The member's modifiers textual representation when
* the modifiers (flags) have been altered from
* their original contents, otherwise <code>null</code>.
*/
- protected char[] fModifiers = null;
+ protected char[] fModifiers= null;
/**
* The original inclusive source range of the
@@ -53,324 +54,293 @@ abstract class DOMMember extends DOMNode implements IDOMMember {
* the member did not originally have modifiers in
* the source code (i.e. default protection).
*/
- protected int[] fModifierRange;
+ protected int[] fModifierRange;
- /**
- * Constructs an empty member node.
- */
- DOMMember() {
+/**
+ * Constructs an empty member node.
+ */
+DOMMember() {
+}
+/**
+ * Creates a new member document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this node, or
+ * <code>null</code> if this node does not have a name
+ * @param nameRange - a two element array of integers describing the
+ * entire inclusive source range of this node's name within its document,
+ * including any array qualifiers that might immediately follow the name.
+ * @param commentRange - a two element array describing the comments that precede
+ * the member declaration. The first matches the start of this node's
+ * sourceRange, and the second is the new-line or first non-whitespace
+ * character following the last comment. If no comments are present,
+ * this array contains two -1's.
+ * @param flags - an integer representing the modifiers for this member. The
+ * integer can be analyzed with org.eclipse.jdt.core.Flags
+ * @param modifierRange - a two element array describing the location of
+ * modifiers for this member within its source range. The first integer
+ * is the first character of the first modifier for this member, and
+ * the second integer is the last whitespace character preceeding the
+ * next part of this member declaration. If there are no modifiers present
+ * in this node's source code (i.e. default protection), this array
+ * contains two -1's.
+ */
+DOMMember(char[] document, int[] sourceRange, String name, int[] nameRange, int[] commentRange, int flags, int[] modifierRange) {
+ super(document, sourceRange, name, nameRange);
+ fFlags= flags;
+ fComment= null;
+ fCommentRange= commentRange;
+ fModifierRange= modifierRange;
+ setHasComment(commentRange[0] >= 0);
+}
+/**
+ * Appends the contents of this node to the given CharArrayBuffer, using
+ * the original document and indicies as a form for the current attribute values
+ * of this node.
+ *
+ * <p>To facilitate the implementation of generating contents for members,
+ * the content of members is split into three sections - the header,
+ * declaration, and body sections. The header section includes any preceding
+ * comments and modifiers. The declaration section includes the portion of
+ * the member declaration that follows any modifiers and precedes the
+ * member body. The body section includes the member body and any trailing
+ * whitespace.
+ *
+ * @see DOMNode#appendFragmentedContents(CharArrayBuffer)
+ */
+protected void appendFragmentedContents(CharArrayBuffer buffer) {
+ if (isDetailed()) {
+ appendMemberHeaderFragment(buffer);
+ appendMemberDeclarationContents(buffer);
+ appendMemberBodyContents(buffer);
+ } else {
+ appendSimpleContents(buffer);
}
+}
+/**
+ * Appends this member's body contents to the given CharArrayBuffer.
+ * Body contents include the member body and any trailing whitespace.
+ */
+protected abstract void appendMemberBodyContents(CharArrayBuffer buffer);
+/**
+ * Appends this member's declaration contents to the given CharArrayBuffer.
+ * The declaration contents includes the portion of this member that
+ * appears after any modifiers and precedes the body.
+ */
+protected abstract void appendMemberDeclarationContents(CharArrayBuffer buffer);
+/**
+ * Appends this member's header contents to the given CharArrayBuffer.
+ * Header contents include any preceding comments and modifiers.
+ */
+protected void appendMemberHeaderFragment(CharArrayBuffer buffer) {
- /**
- * Creates a new member document fragment on the given range of the document.
- *
- * @param document - the document containing this node's original contents
- * @param sourceRange - a two element array of integers describing the
- * entire inclusive source range of this node within its document.
- * Contents start on and include the character at the first position.
- * Contents end on and include the character at the last position.
- * An array of -1's indicates this node's contents do not exist
- * in the document.
- * @param name - the identifier portion of the name of this node, or
- * <code>null</code> if this node does not have a name
- * @param nameRange - a two element array of integers describing the
- * entire inclusive source range of this node's name within its document,
- * including any array qualifiers that might immediately follow the name.
- * @param commentRange - a two element array describing the comments that precede
- * the member declaration. The first matches the start of this node's
- * sourceRange, and the second is the new-line or first non-whitespace
- * character following the last comment. If no comments are present,
- * this array contains two -1's.
- * @param flags - an integer representing the modifiers for this member. The
- * integer can be analyzed with org.eclipse.jdt.core.Flags
- * @param modifierRange - a two element array describing the location of
- * modifiers for this member within its source range. The first integer
- * is the first character of the first modifier for this member, and
- * the second integer is the last whitespace character preceeding the
- * next part of this member declaration. If there are no modifiers present
- * in this node's source code (i.e. default protection), this array
- * contains two -1's.
- */
- DOMMember(
- char[] document,
- int[] sourceRange,
- String name,
- int[] nameRange,
- int[] commentRange,
- int flags,
- int[] modifierRange) {
- super(document, sourceRange, name, nameRange);
- fFlags = flags;
- fComment = null;
- fCommentRange = commentRange;
- fModifierRange = modifierRange;
- setHasComment(commentRange[0] >= 0);
- }
+ int spaceStart, spaceEnd;
- /**
- * Appends the contents of this node to the given CharArrayBuffer, using
- * the original document and indicies as a form for the current attribute values
- * of this node.
- *
- * <p>To facilitate the implementation of generating contents for members,
- * the content of members is split into three sections - the header,
- * declaration, and body sections. The header section includes any preceding
- * comments and modifiers. The declaration section includes the portion of
- * the member declaration that follows any modifiers and precedes the
- * member body. The body section includes the member body and any trailing
- * whitespace.
- *
- * @see DOMNode#appendFragmentedContents(CharArrayBuffer)
- */
- protected void appendFragmentedContents(CharArrayBuffer buffer) {
- if (isDetailed()) {
- appendMemberHeaderFragment(buffer);
- appendMemberDeclarationContents(buffer);
- appendMemberBodyContents(buffer);
- } else {
- appendSimpleContents(buffer);
+ // space before comment
+ if (hasComment()) {
+ spaceStart= fSourceRange[0];
+ spaceEnd= fCommentRange[0];
+ if (spaceEnd > 0) {
+ buffer.append(fDocument, spaceStart, spaceEnd - spaceStart);
}
}
-
- /**
- * Appends this member's body contents to the given CharArrayBuffer.
- * Body contents include the member body and any trailing whitespace.
- */
- protected abstract void appendMemberBodyContents(CharArrayBuffer buffer);
- /**
- * Appends this member's declaration contents to the given CharArrayBuffer.
- * The declaration contents includes the portion of this member that
- * appears after any modifiers and precedes the body.
- */
- protected abstract void appendMemberDeclarationContents(CharArrayBuffer buffer);
- /**
- * Appends this member's header contents to the given CharArrayBuffer.
- * Header contents include any preceding comments and modifiers.
- */
- protected void appendMemberHeaderFragment(CharArrayBuffer buffer) {
-
- int spaceStart, spaceEnd;
-
- // space before comment
- if (hasComment()) {
- spaceStart = fSourceRange[0];
- spaceEnd = fCommentRange[0];
- if (spaceEnd > 0) {
- buffer.append(fDocument, spaceStart, spaceEnd - spaceStart);
- }
- }
-
- String fragment = getComment();
- if (fragment != null) {
- buffer.append(fragment);
- }
-
- if (fCommentRange[1] >= 0) {
- spaceStart = fCommentRange[1] + 1;
- } else {
- spaceStart = fSourceRange[0];
- }
- if (fModifierRange[0] >= 0) {
- spaceEnd = fModifierRange[0] - 1;
- } else {
- spaceEnd = getMemberDeclarationStartPosition() - 1;
- }
-
- if (spaceEnd >= spaceStart) {
- buffer.append(fDocument, spaceStart, spaceEnd + 1 - spaceStart);
- }
- buffer.append(getModifiersText());
-
+
+ String fragment= getComment();
+ if (fragment != null) {
+ buffer.append(fragment);
}
- /**
- * Appends the contents of this node to the given CharArrayBuffer, using
- * the original document and indicies as a form for the current attribute values
- * of this node. This method is called when this node is know not to have
- * detailed source indexes.
- */
- protected abstract void appendSimpleContents(CharArrayBuffer buffer);
- /**
- * Returns a copy of the given array with the new element appended
- * to the end of the array.
- */
- protected String[] appendString(String[] list, String element) {
- String[] copy = new String[list.length + 1];
- System.arraycopy(list, 0, copy, 0, list.length);
- copy[list.length] = element;
- return copy;
+ if (fCommentRange[1] >= 0) {
+ spaceStart= fCommentRange[1] + 1;
+ } else {
+ spaceStart= fSourceRange[0];
}
-
- /**
- * Returns a <code>String</code> describing the modifiers for this member,
- * ending with whitespace (if not empty). This value serves as a replacement
- * value for the member's modifier range when the modifiers have been altered
- * from their original contents.
- */
- protected char[] generateFlags() {
- char[] flags = Flags.toString(getFlags()).toCharArray();
- if (flags.length == 0) {
- return flags;
- } else {
- return CharArrayOps.concat(flags, new char[] { ' ' });
- }
+ if (fModifierRange[0] >= 0) {
+ spaceEnd= fModifierRange[0] - 1;
+ } else {
+ spaceEnd= getMemberDeclarationStartPosition() - 1;
}
- /**
- * @see IDOMMember#getComment()
- */
- public String getComment() {
- becomeDetailed();
- if (hasComment()) {
- if (fComment != null) {
- return fComment;
- } else {
- return CharArrayOps.substring(
- fDocument,
- fCommentRange[0],
- fCommentRange[1] + 1 - fCommentRange[0]);
- }
- } else {
- return null;
- }
+ if (spaceEnd >= spaceStart) {
+ buffer.append(fDocument, spaceStart, spaceEnd + 1 - spaceStart);
}
+ buffer.append(getModifiersText());
- /**
- * @see IDOMMember#getFlags()
- */
- public int getFlags() {
- return fFlags;
+}
+/**
+ * Appends the contents of this node to the given CharArrayBuffer, using
+ * the original document and indicies as a form for the current attribute values
+ * of this node. This method is called when this node is know not to have
+ * detailed source indexes.
+ */
+protected abstract void appendSimpleContents(CharArrayBuffer buffer);
+/**
+ * Returns a copy of the given array with the new element appended
+ * to the end of the array.
+ */
+protected String[] appendString(String[] list, String element) {
+ String[] copy= new String[list.length + 1];
+ System.arraycopy(list, 0, copy, 0, list.length);
+ copy[list.length]= element;
+ return copy;
+}
+/**
+ * Returns a <code>String</code> describing the modifiers for this member,
+ * ending with whitespace (if not empty). This value serves as a replacement
+ * value for the member's modifier range when the modifiers have been altered
+ * from their original contents.
+ */
+protected char[] generateFlags() {
+ char[] flags= Flags.toString(getFlags()).toCharArray();
+ if (flags.length == 0) {
+ return flags;
+ } else {
+ return CharArrayOps.concat(flags, new char[] {' '});
}
-
- /**
- * Returns the location of the first character in the member's declaration
- * section.
- *
- * @see DOMMember#getMemberDeclarationContents()
- * @see DOMMember#getFragmentedContents()
- */
- protected abstract int getMemberDeclarationStartPosition();
- /**
- * Returns the String to be used for this member's flags when
- * generating contents - either the original contents in the document
- * or the replacement value.
- */
- protected char[] getModifiersText() {
- if (fModifiers == null) {
- if (fModifierRange[0] < 0) {
- return null;
- } else {
- return CharArrayOps.subarray(
- fDocument,
- fModifierRange[0],
- fModifierRange[1] + 1 - fModifierRange[0]);
- }
+}
+/**
+ * @see IDOMMember#getComment()
+ */
+public String getComment() {
+ becomeDetailed();
+ if (hasComment()) {
+ if (fComment != null) {
+ return fComment;
} else {
- return fModifiers;
+ return CharArrayOps.substring(fDocument, fCommentRange[0], fCommentRange[1] + 1 - fCommentRange[0]);
}
+ } else {
+ return null;
}
-
- /**
- * Returns true if this member currently has a body.
- */
- protected boolean hasBody() {
- return getMask(MASK_HAS_BODY);
- }
-
- /**
- * Returns true if this member currently has a comment.
- */
- protected boolean hasComment() {
- return getMask(MASK_HAS_COMMENT);
- }
-
- /**
- * Offsets all the source indexes in this node by the given amount.
- */
- protected void offset(int offset) {
- super.offset(offset);
- offsetRange(fCommentRange, offset);
- offsetRange(fModifierRange, offset);
- }
-
- /**
- * @see IDOMMember#setComment(String)
- */
- public void setComment(String comment) {
- becomeDetailed();
- fComment = comment;
- fragment();
- setHasComment(comment != null);
- /* see 1FVIJAH */
- if (comment != null) {
- String commentString = new String(comment);
- if (commentString.indexOf("@deprecated") >= 0) {
- fFlags = fFlags | IConstants.AccDeprecated;
- return;
- }
-
- }
- fFlags = fFlags & (~IConstants.AccDeprecated);
-
- }
-
- /**
- * @see IDOMMember#setFlags(int)
- */
- public void setFlags(int flags) {
- becomeDetailed();
- if (Flags.isDeprecated(fFlags)) {
- fFlags = flags | IConstants.AccDeprecated;
+}
+/**
+ * @see IDOMMember#getFlags()
+ */
+public int getFlags() {
+ return fFlags;
+}
+/**
+ * Returns the location of the first character in the member's declaration
+ * section.
+ *
+ * @see DOMMember#getMemberDeclarationContents()
+ * @see DOMMember#getFragmentedContents()
+ */
+protected abstract int getMemberDeclarationStartPosition();
+/**
+ * Returns the String to be used for this member's flags when
+ * generating contents - either the original contents in the document
+ * or the replacement value.
+ */
+protected char[] getModifiersText() {
+ if (fModifiers == null) {
+ if (fModifierRange[0] < 0) {
+ return null;
} else {
- fFlags = flags & (~IConstants.AccDeprecated);
+ return CharArrayOps.subarray(fDocument, fModifierRange[0], fModifierRange[1] + 1 - fModifierRange[0]);
}
- fragment();
- fModifiers = generateFlags();
- }
-
- /**
- * Sets the state of this member declaration as having
- * a body.
- */
- protected void setHasBody(boolean hasBody) {
- setMask(MASK_HAS_BODY, hasBody);
+ } else {
+ return fModifiers;
}
+}
+/**
+ * Returns true if this member currently has a body.
+ */
+protected boolean hasBody() {
+ return getMask(MASK_HAS_BODY);
+}
+/**
+ * Returns true if this member currently has a comment.
+ */
+protected boolean hasComment() {
+ return getMask(MASK_HAS_COMMENT);
+}
+/**
+ * Offsets all the source indexes in this node by the given amount.
+ */
+protected void offset(int offset) {
+ super.offset(offset);
+ offsetRange(fCommentRange, offset);
+ offsetRange(fModifierRange, offset);
+}
+/**
+ * @see IDOMMember#setComment(String)
+ */
+public void setComment(String comment) {
+ becomeDetailed();
+ fComment= comment;
+ fragment();
+ setHasComment(comment != null);
+ /* see 1FVIJAH */
+ if (comment != null) {
+ String commentString = new String(comment);
+ if (commentString.indexOf("@deprecated") >= 0) {
+ fFlags= fFlags | IConstants.AccDeprecated;
+ return;
+ }
- /**
- * Sets the state of this member declaration as having
- * a preceding comment.
- */
- protected void setHasComment(boolean hasComment) {
- setMask(MASK_HAS_COMMENT, hasComment);
}
+ fFlags= fFlags & (~IConstants.AccDeprecated);
- /**
- * Sets the original position of the first character of this node's contents
- * in its document. This method is only used during DOM creation while
- * normalizing the source range of each node.
- *
- * Synchronize the start of the comment position with the start of the
- * node.
- */
- protected void setStartPosition(int start) {
- if (fCommentRange[0] >= 0) {
- fCommentRange[0] = start;
- }
- super.setStartPosition(start);
+}
+/**
+ * @see IDOMMember#setFlags(int)
+ */
+public void setFlags(int flags) {
+ becomeDetailed();
+ if (Flags.isDeprecated(fFlags)) {
+ fFlags= flags | IConstants.AccDeprecated;
+ } else {
+ fFlags= flags & (~IConstants.AccDeprecated);
}
-
- /**
- * @see DOMNode#shareContents(DOMNode)
- */
- protected void shareContents(DOMNode node) {
- super.shareContents(node);
- DOMMember member = (DOMMember) node;
- fComment = member.fComment;
- fCommentRange = rangeCopy(member.fCommentRange);
- fFlags = member.fFlags;
- fModifiers = member.fModifiers;
- fModifierRange = rangeCopy(member.fModifierRange);
+ fragment();
+ fModifiers= generateFlags();
+}
+/**
+ * Sets the state of this member declaration as having
+ * a body.
+ */
+protected void setHasBody(boolean hasBody) {
+ setMask(MASK_HAS_BODY, hasBody);
+}
+/**
+ * Sets the state of this member declaration as having
+ * a preceding comment.
+ */
+protected void setHasComment(boolean hasComment) {
+ setMask(MASK_HAS_COMMENT, hasComment);
+}
+/**
+ * Sets the original position of the first character of this node's contents
+ * in its document. This method is only used during DOM creation while
+ * normalizing the source range of each node.
+ *
+ * Synchronize the start of the comment position with the start of the
+ * node.
+ */
+protected void setStartPosition(int start) {
+ if (fCommentRange[0] >= 0) {
+ fCommentRange[0]= start;
}
-
+ super.setStartPosition(start);
+}
+/**
+ * @see DOMNode#shareContents(DOMNode)
+ */
+protected void shareContents(DOMNode node) {
+ super.shareContents(node);
+ DOMMember member= (DOMMember)node;
+ fComment= member.fComment;
+ fCommentRange= rangeCopy(member.fCommentRange);
+ fFlags= member.fFlags;
+ fModifiers= member.fModifiers;
+ fModifierRange= rangeCopy(member.fModifierRange);
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
index d7350a1ca6..58a3665657 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMMethod.java
@@ -21,7 +21,7 @@ import org.eclipse.jdt.internal.core.util.*;
* @see IDOMMethod
* @see DOMNode
*/
-
+
class DOMMethod extends DOMMember implements IDOMMethod {
/**
@@ -41,7 +41,7 @@ class DOMMethod extends DOMMember implements IDOMMethod {
* of the array are the inclusive source range of
* the array qualifiers.
*/
- protected int[] fReturnTypeRange;
+ protected int[] fReturnTypeRange;
/**
* Contains the textual representation of the method's
@@ -55,7 +55,7 @@ class DOMMethod extends DOMMember implements IDOMMethod {
* The original inclusive source range of the
* method's parameter list in the document.
*/
- protected int[] fParameterRange;
+ protected int[] fParameterRange;
/**
* Contains the textual representation of the method's
@@ -71,8 +71,8 @@ class DOMMethod extends DOMMember implements IDOMMethod {
* The original inclusive source range of the
* method's exception list in the document.
*/
- protected int[] fExceptionRange;
-
+ protected int[] fExceptionRange;
+
/**
* Contains the method's body when the body has
* been altered from the contents in the document,
@@ -86,7 +86,8 @@ class DOMMethod extends DOMMember implements IDOMMethod {
* The original inclusive source range of the
* method's body.
*/
- protected int[] fBodyRange;
+ protected int[] fBodyRange;
+
/**
* Names of parameters in the method parameter list,
@@ -106,723 +107,608 @@ class DOMMethod extends DOMMember implements IDOMMethod {
*/
protected String[] fExceptions;
- /**
- * Constructs an empty method node.
- */
- DOMMethod() {
-
- }
-
- /**
- * Creates a new detailed METHOD document fragment on the given range of the document.
- *
- * @param document - the document containing this node's original contents
- * @param sourceRange - a two element array of integers describing the
- * entire inclusive source range of this node within its document.
- * Contents start on and include the character at the first position.
- * Contents end on and include the character at the last position.
- * An array of -1's indicates this node's contents do not exist
- * in the document.
- * @param name - the identifier portion of the name of this node, or
- * <code>null</code> if this node does not have a name
- * @param nameRange - a two element array of integers describing the
- * entire inclusive source range of this node's name within its document,
- * including any array qualifiers that might immediately follow the name
- * or -1's if this node does not have a name.
- * @param commentRange - a two element array describing the comments that precede
- * the member declaration. The first matches the start of this node's
- * sourceRange, and the second is the new-line or first non-whitespace
- * character following the last comment. If no comments are present,
- * this array contains two -1's.
- * @param flags - an integer representing the modifiers for this member. The
- * integer can be analyzed with org.eclipse.jdt.core.Flags
- * @param modifierRange - a two element array describing the location of
- * modifiers for this member within its source range. The first integer
- * is the first character of the first modifier for this member, and
- * the second integer is the last whitespace character preceeding the
- * next part of this member declaration. If there are no modifiers present
- * in this node's source code (i.e. default protection), this array
- * contains two -1's.
- * @param isConstructor - true if the method is a contructor, otherwise false
- * @param returnType - the normalized return type of this method
- * @param returnTypeRange - a two element array describing the location of the
- * return type within the method's source range. The first integer is is
- * the position of the first character in the return type, and the second
- * integer is the position of the last character in the return type.
- * For constructors, the contents of this array are -1's.
- * If the return type of this method is qualified with '[]' following the
- * parameter list, this array has four entries. In this case, the last
- * two entries of the array are the inclusive source range of the array
- * qualifiers.
- * @param parameterTypes - an array of parameter types in the method declaration
- * or <code>null</code> if the method has no parameters
- * @param parameterNames - an array of parameter names in the method declaration
- * or <code>null</code> if the method has no parameters
- * @param parameterRange - a two element array describing the location of the
- * parameter list in the method. The first integer is the location of the
- * open parenthesis and the second integer is the location of the closing
- * parenthesis.
- * @param exceptions - an array of the names of exceptions thrown by this method
- * or <code>null</code> if the method throws no exceptions
- * @param exceptionRange - a two element array describing the location of the
- * exception list in the method declaration. The first integer is the position
- * of the first character in the first exception the method throws, and the
- * second integer is the position of the last character of the last exception
- * this method throws.
- * @param bodyRange - a two element array describing the location of the method's body.
- * The first integer is the first character following the method's
- * parameter list, or exception list (if present). The second integer is the location
- * of the last character in the method's source range.
- */
- DOMMethod(
- char[] document,
- int[] sourceRange,
- String name,
- int[] nameRange,
- int[] commentRange,
- int flags,
- int[] modifierRange,
- boolean isConstructor,
- String returnType,
- int[] returnTypeRange,
- String[] parameterTypes,
- String[] parameterNames,
- int[] parameterRange,
- String[] exceptions,
- int[] exceptionRange,
- int[] bodyRange) {
- super(
- document,
- sourceRange,
- name,
- nameRange,
- commentRange,
- flags,
- modifierRange);
-
- setMask(MASK_IS_CONSTRUCTOR, isConstructor);
- fReturnType = returnType;
- fReturnTypeRange = returnTypeRange;
- fParameterTypes = parameterTypes;
- fParameterNames = parameterNames;
- fParameterRange = parameterRange;
- fExceptionRange = exceptionRange;
- fExceptions = exceptions;
- setHasBody(true);
- fBodyRange = bodyRange;
- setMask(MASK_DETAILED_SOURCE_INDEXES, true);
-
- }
+
+/**
+ * Constructs an empty method node.
+ */
+DOMMethod() {
- /**
- * Creates a new simple METHOD document fragment on the given range of the document.
- *
- * @param document - the document containing this node's original contents
- * @param sourceRange - a two element array of integers describing the
- * entire inclusive source range of this node within its document.
- * Contents start on and include the character at the first position.
- * Contents end on and include the character at the last position.
- * An array of -1's indicates this node's contents do not exist
- * in the document.
- * @param name - the identifier portion of the name of this node, or
- * <code>null</code> if this node does not have a name
- * @param nameRange - a two element array of integers describing the
- * entire inclusive source range of this node's name within its document,
- * including any array qualifiers that might immediately follow the name
- * or -1's if this node does not have a name.
- * @param flags - an integer representing the modifiers for this member. The
- * integer can be analyzed with org.eclipse.jdt.core.Flags
- * @param isConstructor - true if the method is a contructor, otherwise false
- * @param returnType - the normalized return type of this method
- * @param parameterTypes - an array of parameter types in the method declaration
- * or <code>null</code> if the method has no parameters
- * @param parameterNames - an array of parameter names in the method declaration
- * or <code>null</code> if the method has no parameters
- * @param exceptions - an array of the names of exceptions thrown by this method
- * or <code>null</code> if the method throws no exceptions
- */
- DOMMethod(
- char[] document,
- int[] sourceRange,
- String name,
- int[] nameRange,
- int flags,
- boolean isConstructor,
- String returnType,
- String[] parameterTypes,
- String[] parameterNames,
- String[] exceptions) {
- this(
- document,
- sourceRange,
- name,
- nameRange,
- new int[] { -1, -1 },
- flags,
- new int[] { -1, -1 },
- isConstructor,
- returnType,
- new int[] { -1, -1 },
- parameterTypes,
- parameterNames,
- new int[] { -1, -1 },
- exceptions,
- new int[] { -1, -1 },
- new int[] { -1, -1 });
- setMask(MASK_DETAILED_SOURCE_INDEXES, false);
+}
+/**
+ * Creates a new detailed METHOD document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this node, or
+ * <code>null</code> if this node does not have a name
+ * @param nameRange - a two element array of integers describing the
+ * entire inclusive source range of this node's name within its document,
+ * including any array qualifiers that might immediately follow the name
+ * or -1's if this node does not have a name.
+ * @param commentRange - a two element array describing the comments that precede
+ * the member declaration. The first matches the start of this node's
+ * sourceRange, and the second is the new-line or first non-whitespace
+ * character following the last comment. If no comments are present,
+ * this array contains two -1's.
+ * @param flags - an integer representing the modifiers for this member. The
+ * integer can be analyzed with org.eclipse.jdt.core.Flags
+ * @param modifierRange - a two element array describing the location of
+ * modifiers for this member within its source range. The first integer
+ * is the first character of the first modifier for this member, and
+ * the second integer is the last whitespace character preceeding the
+ * next part of this member declaration. If there are no modifiers present
+ * in this node's source code (i.e. default protection), this array
+ * contains two -1's.
+ * @param isConstructor - true if the method is a contructor, otherwise false
+ * @param returnType - the normalized return type of this method
+ * @param returnTypeRange - a two element array describing the location of the
+ * return type within the method's source range. The first integer is is
+ * the position of the first character in the return type, and the second
+ * integer is the position of the last character in the return type.
+ * For constructors, the contents of this array are -1's.
+ * If the return type of this method is qualified with '[]' following the
+ * parameter list, this array has four entries. In this case, the last
+ * two entries of the array are the inclusive source range of the array
+ * qualifiers.
+ * @param parameterTypes - an array of parameter types in the method declaration
+ * or <code>null</code> if the method has no parameters
+ * @param parameterNames - an array of parameter names in the method declaration
+ * or <code>null</code> if the method has no parameters
+ * @param parameterRange - a two element array describing the location of the
+ * parameter list in the method. The first integer is the location of the
+ * open parenthesis and the second integer is the location of the closing
+ * parenthesis.
+ * @param exceptions - an array of the names of exceptions thrown by this method
+ * or <code>null</code> if the method throws no exceptions
+ * @param exceptionRange - a two element array describing the location of the
+ * exception list in the method declaration. The first integer is the position
+ * of the first character in the first exception the method throws, and the
+ * second integer is the position of the last character of the last exception
+ * this method throws.
+ * @param bodyRange - a two element array describing the location of the method's body.
+ * The first integer is the first character following the method's
+ * parameter list, or exception list (if present). The second integer is the location
+ * of the last character in the method's source range.
+ */
+DOMMethod(char[] document, int[] sourceRange, String name, int[] nameRange, int[] commentRange, int flags, int[] modifierRange, boolean isConstructor, String returnType, int[] returnTypeRange, String[] parameterTypes, String[] parameterNames, int[] parameterRange, String[] exceptions, int[] exceptionRange, int[] bodyRange) {
+ super(document, sourceRange, name, nameRange, commentRange, flags, modifierRange);
+
+ setMask(MASK_IS_CONSTRUCTOR, isConstructor);
+ fReturnType= returnType;
+ fReturnTypeRange= returnTypeRange;
+ fParameterTypes= parameterTypes;
+ fParameterNames= parameterNames;
+ fParameterRange= parameterRange;
+ fExceptionRange= exceptionRange;
+ fExceptions= exceptions;
+ setHasBody(true);
+ fBodyRange= bodyRange;
+ setMask(MASK_DETAILED_SOURCE_INDEXES, true);
+
+}
+/**
+ * Creates a new simple METHOD document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this node, or
+ * <code>null</code> if this node does not have a name
+ * @param nameRange - a two element array of integers describing the
+ * entire inclusive source range of this node's name within its document,
+ * including any array qualifiers that might immediately follow the name
+ * or -1's if this node does not have a name.
+ * @param flags - an integer representing the modifiers for this member. The
+ * integer can be analyzed with org.eclipse.jdt.core.Flags
+ * @param isConstructor - true if the method is a contructor, otherwise false
+ * @param returnType - the normalized return type of this method
+ * @param parameterTypes - an array of parameter types in the method declaration
+ * or <code>null</code> if the method has no parameters
+ * @param parameterNames - an array of parameter names in the method declaration
+ * or <code>null</code> if the method has no parameters
+ * @param exceptions - an array of the names of exceptions thrown by this method
+ * or <code>null</code> if the method throws no exceptions
+ */
+DOMMethod(char[] document, int[] sourceRange, String name, int[] nameRange, int flags, boolean isConstructor, String returnType, String[] parameterTypes, String[] parameterNames, String[] exceptions) {
+ this(document, sourceRange, name, nameRange, new int[] {-1, -1}, flags, new int[] {-1, -1}, isConstructor, returnType, new int[] {-1, -1}, parameterTypes, parameterNames, new int[] {-1, -1}, exceptions, new int[] {-1, -1}, new int[] {-1, -1});
+ setMask(MASK_DETAILED_SOURCE_INDEXES, false);
+}
+/**
+ * @see IDOMMethod#addException(String)
+ */
+public void addException(String name) throws IllegalArgumentException {
+ if (name == null) {
+ throw new IllegalArgumentException("Cannot add null exception");
}
-
- /**
- * @see IDOMMethod#addException(String)
- */
- public void addException(String name) throws IllegalArgumentException {
- if (name == null) {
- throw new IllegalArgumentException("Cannot add null exception");
- }
- if (fExceptions == null) {
- fExceptions = new String[1];
- fExceptions[0] = name;
- } else {
- fExceptions = appendString(fExceptions, name);
- }
- setExceptions(fExceptions);
+ if (fExceptions == null) {
+ fExceptions= new String[1];
+ fExceptions[0]= name;
+ } else {
+ fExceptions= appendString(fExceptions, name);
}
-
- /**
- * @see IDOMMethod#addParameter(String, String)
- */
- public void addParameter(String type, String name)
- throws IllegalArgumentException {
- if (type == null) {
- throw new IllegalArgumentException("Cannot add parameter with null type");
- }
- if (name == null) {
- throw new IllegalArgumentException("Cannot add parameter with null name");
- }
- if (fParameterNames == null) {
- fParameterNames = new String[1];
- fParameterNames[0] = name;
- } else {
- fParameterNames = appendString(fParameterNames, name);
- }
- if (fParameterTypes == null) {
- fParameterTypes = new String[1];
- fParameterTypes[0] = type;
- } else {
- fParameterTypes = appendString(fParameterTypes, type);
- }
- setParameters(fParameterTypes, fParameterNames);
- }
-
- /**
- * @see DOMMember#appendMemberBodyContents(CharArrayBuffer)
- */
- protected void appendMemberBodyContents(CharArrayBuffer buffer) {
- if (fBody != null) {
- buffer.append(fBody);
- } else {
- buffer.append(fDocument, fBodyRange[0], fBodyRange[1] + 1 - fBodyRange[0]);
- }
+ setExceptions(fExceptions);
+}
+/**
+ * @see IDOMMethod#addParameter(String, String)
+ */
+public void addParameter(String type, String name) throws IllegalArgumentException {
+ if (type == null) {
+ throw new IllegalArgumentException("Cannot add parameter with null type");
+ }
+ if (name == null) {
+ throw new IllegalArgumentException("Cannot add parameter with null name");
+ }
+ if (fParameterNames == null) {
+ fParameterNames= new String[1];
+ fParameterNames[0]= name;
+ } else {
+ fParameterNames= appendString(fParameterNames, name);
+ }
+ if (fParameterTypes == null) {
+ fParameterTypes= new String[1];
+ fParameterTypes[0]= type;
+ } else {
+ fParameterTypes= appendString(fParameterTypes, type);
+ }
+ setParameters(fParameterTypes, fParameterNames);
+}
+/**
+ * @see DOMMember#appendMemberBodyContents(CharArrayBuffer)
+ */
+protected void appendMemberBodyContents(CharArrayBuffer buffer) {
+ if (fBody != null) {
+ buffer.append(fBody);
+ } else {
+ buffer.append(fDocument, fBodyRange[0], fBodyRange[1] + 1 - fBodyRange[0]);
}
-
- /**
- * @see DOMMember#appendMemberDeclarationContents(CharArrayBuffer)
- */
- protected void appendMemberDeclarationContents(CharArrayBuffer buffer) {
-
- if (isConstructor()) {
- buffer.append(getConstructorName()).append(
- fDocument,
- fNameRange[1] + 1,
- fParameterRange[0] - fNameRange[1] - 1);
- } else {
- buffer.append(getReturnTypeContents());
- if (fReturnTypeRange[0] >= 0) {
- buffer.append(
- fDocument,
- fReturnTypeRange[1] + 1,
- fNameRange[0] - fReturnTypeRange[1] - 1);
- } else {
- buffer.append(" ");
- }
- buffer.append(getNameContents()).append(
- fDocument,
- fNameRange[1] + 1,
- fParameterRange[0] - fNameRange[1] - 1);
- }
- if (fParameterList != null) {
- buffer.append(fParameterList);
+}
+/**
+ * @see DOMMember#appendMemberDeclarationContents(CharArrayBuffer)
+ */
+protected void appendMemberDeclarationContents(CharArrayBuffer buffer) {
+
+ if (isConstructor()) {
+ buffer
+ .append(getConstructorName())
+ .append(fDocument, fNameRange[1] + 1, fParameterRange[0] - fNameRange[1] - 1);
+ } else {
+ buffer.append(getReturnTypeContents());
+ if (fReturnTypeRange[0] >= 0) {
+ buffer.append(fDocument, fReturnTypeRange[1] + 1, fNameRange[0] - fReturnTypeRange[1] - 1);
} else {
- buffer.append(
- fDocument,
- fParameterRange[0],
- fParameterRange[1] + 1 - fParameterRange[0]);
+ buffer.append(" ");
}
- int start;
- if (hasTrailingArrayQualifier() && isReturnTypeAltered()) {
- start = fReturnTypeRange[3] + 1;
+ buffer
+ .append(getNameContents())
+ .append(fDocument, fNameRange[1] + 1, fParameterRange[0] - fNameRange[1] - 1);
+ }
+ if (fParameterList != null) {
+ buffer.append(fParameterList);
+ } else {
+ buffer.append(fDocument, fParameterRange[0], fParameterRange[1] + 1 - fParameterRange[0]);
+ }
+ int start;
+ if (hasTrailingArrayQualifier() && isReturnTypeAltered()) {
+ start= fReturnTypeRange[3] + 1;
+ } else {
+ start= fParameterRange[1] + 1;
+ }
+ if (fExceptions != null) {
+ // add 'throws' keyword
+ if (fExceptionRange[0] >= 0) {
+ buffer.append(fDocument, start, fExceptionRange[0] - start);
} else {
- start = fParameterRange[1] + 1;
+ buffer.append(" throws ");
}
- if (fExceptions != null) {
- // add 'throws' keyword
- if (fExceptionRange[0] >= 0) {
- buffer.append(fDocument, start, fExceptionRange[0] - start);
- } else {
- buffer.append(" throws ");
- }
- // add exception list
- if (fExceptionList != null) {
- buffer.append(fExceptionList);
- // add space before body
- if (fExceptionRange[0] >= 0) {
- buffer.append(
- fDocument,
- fExceptionRange[1] + 1,
- fBodyRange[0] - fExceptionRange[1] - 1);
- } else {
- buffer.append(
- fDocument,
- fParameterRange[1] + 1,
- fBodyRange[0] - fParameterRange[1] - 1);
- }
- } else {
- // add list and space before body
- buffer.append(
- fDocument,
- fExceptionRange[0],
- fBodyRange[0] - fExceptionRange[0]);
- }
- } else {
+ // add exception list
+ if (fExceptionList != null) {
+ buffer.append(fExceptionList);
// add space before body
if (fExceptionRange[0] >= 0) {
- buffer.append(
- fDocument,
- fExceptionRange[1] + 1,
- fBodyRange[0] - fExceptionRange[1] - 1);
+ buffer.append(fDocument, fExceptionRange[1] + 1, fBodyRange[0] - fExceptionRange[1] - 1);
} else {
- buffer.append(fDocument, start, fBodyRange[0] - start);
+ buffer.append(fDocument, fParameterRange[1] + 1, fBodyRange[0] - fParameterRange[1] - 1);
}
- }
-
- }
-
- /**
- * @see DOMNode#appendSimpleContents(CharArrayBuffer)
- */
- protected void appendSimpleContents(CharArrayBuffer buffer) {
- // append eveything before my name
- buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]);
- // append my name
- if (isConstructor()) {
- buffer.append(getConstructorName());
} else {
- buffer.append(fName);
+ // add list and space before body
+ buffer.append(fDocument, fExceptionRange[0], fBodyRange[0] - fExceptionRange[0]);
}
- // append everything after my name
- buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]);
- }
-
- /**
- * @see IDOMMethod#getBody()
- */
- public String getBody() {
- becomeDetailed();
- if (hasBody()) {
- if (fBody != null) {
- return fBody;
- } else {
- return CharArrayOps.substring(
- fDocument,
- fBodyRange[0],
- fBodyRange[1] + 1 - fBodyRange[0]);
- }
+ } else {
+ // add space before body
+ if (fExceptionRange[0] >= 0) {
+ buffer.append(fDocument, fExceptionRange[1] + 1, fBodyRange[0] - fExceptionRange[1] - 1);
} else {
- return null;
+ buffer.append(fDocument, start, fBodyRange[0] - start);
}
}
-
- /**
- * Returns the simple name of the enclsoing type for this constructor.
- * If the constuctor is not currently enclosed in a type, the original
- * name of the constructor as found in the documnent is returned.
- */
- protected String getConstructorName() {
-
- if (isConstructor()) {
- if (getParent() != null) {
- return getParent().getName();
- } else {
- // If there is no parent use the original name
- return new String(getNameContents());
- }
+
+}
+/**
+ * @see DOMNode#appendSimpleContents(CharArrayBuffer)
+ */
+protected void appendSimpleContents(CharArrayBuffer buffer) {
+ // append eveything before my name
+ buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]);
+ // append my name
+ if (isConstructor()) {
+ buffer.append(getConstructorName());
+ } else {
+ buffer.append(fName);
+ }
+ // append everything after my name
+ buffer.append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]);
+}
+/**
+ * @see IDOMMethod#getBody()
+ */
+public String getBody() {
+ becomeDetailed();
+ if (hasBody()) {
+ if (fBody != null) {
+ return fBody;
} else {
- return null;
+ return CharArrayOps.substring(fDocument, fBodyRange[0], fBodyRange[1] + 1 - fBodyRange[0]);
}
-
- }
-
- /**
- * @see DOMNode#getDetailedNode()
- */
- protected DOMNode getDetailedNode() {
- return (DOMNode) getFactory().createMethod(getContents());
- }
-
- /**
- * @see IDOMMethod#getExceptions()
- */
- public String[] getExceptions() {
- return fExceptions;
+ } else {
+ return null;
}
+}
+/**
+ * Returns the simple name of the enclsoing type for this constructor.
+ * If the constuctor is not currently enclosed in a type, the original
+ * name of the constructor as found in the documnent is returned.
+ */
+protected String getConstructorName() {
- /**
- * @see IDOMNode#getJavaElement
- */
- public IJavaElement getJavaElement(IJavaElement parent)
- throws IllegalArgumentException {
- if (parent.getElementType() == IJavaElement.TYPE) {
- // translate parameter types to signatures
- String[] sigs = null;
- if (fParameterTypes != null) {
- sigs = new String[fParameterTypes.length];
- int i;
- for (i = 0; i < fParameterTypes.length; i++) {
- sigs[i] =
- Signature.createTypeSignature(fParameterTypes[i].toCharArray(), false);
- }
- }
- String name = null;
- if (isConstructor()) {
- name = getConstructorName();
- } else {
- name = getName();
- }
- return ((IType) parent).getMethod(name, sigs);
+ if (isConstructor()) {
+ if (getParent() != null) {
+ return getParent().getName();
} else {
- throw new IllegalArgumentException("Illegal parent argument");
+ // If there is no parent use the original name
+ return new String(getNameContents());
}
+ } else {
+ return null;
}
-
- /**
- * @see DOMMember#getMemberDeclarationStartPosition()
- */
- protected int getMemberDeclarationStartPosition() {
- if (fReturnTypeRange[0] >= 0) {
- return fReturnTypeRange[0];
- } else {
- return fNameRange[0];
+
+}
+/**
+ * @see DOMNode#getDetailedNode()
+ */
+protected DOMNode getDetailedNode() {
+ return (DOMNode)getFactory().createMethod(getContents());
+}
+/**
+ * @see IDOMMethod#getExceptions()
+ */
+public String[] getExceptions() {
+ return fExceptions;
+}
+/**
+ * @see IDOMNode#getJavaElement
+ */
+public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException {
+ if (parent.getElementType() == IJavaElement.TYPE) {
+ // translate parameter types to signatures
+ String[] sigs= null;
+ if (fParameterTypes != null) {
+ sigs= new String[fParameterTypes.length];
+ int i;
+ for (i= 0; i < fParameterTypes.length; i++) {
+ sigs[i]= Signature.createTypeSignature(fParameterTypes[i].toCharArray(), false);
+ }
}
- }
-
- /**
- * @see IDOMNode#getName()
- */
- public String getName() {
+ String name= null;
if (isConstructor()) {
- return null;
+ name= getConstructorName();
} else {
- return super.getName();
+ name= getName();
}
+ return ((IType)parent).getMethod(name, sigs);
+ } else {
+ throw new IllegalArgumentException("Illegal parent argument");
}
-
- /**
- * @see IDOMNode#getNodeType()
- */
- public int getNodeType() {
- return IDOMNode.METHOD;
- }
-
- /**
- * @see IDOMMethod#getParameterNames()
- */
- public String[] getParameterNames() {
- return fParameterNames;
+}
+/**
+ * @see DOMMember#getMemberDeclarationStartPosition()
+ */
+protected int getMemberDeclarationStartPosition() {
+ if (fReturnTypeRange[0] >= 0) {
+ return fReturnTypeRange[0];
+ } else {
+ return fNameRange[0];
}
-
- /**
- * @see IDOMMethod#getParameterTypes()
- */
- public String[] getParameterTypes() {
- return fParameterTypes;
+}
+/**
+ * @see IDOMNode#getName()
+ */
+public String getName() {
+ if (isConstructor()) {
+ return null;
+ } else {
+ return super.getName();
}
-
- /**
- * @see IDOMMethod#getReturnType()
- */
- public String getReturnType() {
- if (isConstructor()) {
- return null;
- } else {
- return fReturnType;
- }
+}
+/**
+ * @see IDOMNode#getNodeType()
+ */
+public int getNodeType() {
+ return IDOMNode.METHOD;
+}
+/**
+ * @see IDOMMethod#getParameterNames()
+ */
+public String[] getParameterNames() {
+ return fParameterNames;
+}
+/**
+ * @see IDOMMethod#getParameterTypes()
+ */
+public String[] getParameterTypes() {
+ return fParameterTypes;
+}
+/**
+ * @see IDOMMethod#getReturnType()
+ */
+public String getReturnType() {
+ if (isConstructor()) {
+ return null;
+ } else {
+ return fReturnType;
}
-
- /**
- * Returns the source code to be used for this method's return type
- */
- protected char[] getReturnTypeContents() {
- if (isConstructor()) {
- return null;
+}
+/**
+ * Returns the source code to be used for this method's return type
+ */
+protected char[] getReturnTypeContents() {
+ if (isConstructor()) {
+ return null;
+ } else {
+ if (isReturnTypeAltered()) {
+ return fReturnType.toCharArray();
} else {
- if (isReturnTypeAltered()) {
- return fReturnType.toCharArray();
- } else {
- return CharArrayOps.subarray(
- fDocument,
- fReturnTypeRange[0],
- fReturnTypeRange[1] + 1 - fReturnTypeRange[0]);
- }
-
+ return CharArrayOps.subarray(fDocument, fReturnTypeRange[0], fReturnTypeRange[1] + 1 - fReturnTypeRange[0]);
}
- }
-
- /**
- * Returns true if this method's return type has
- * array qualifiers ('[]') following the parameter list.
- */
- protected boolean hasTrailingArrayQualifier() {
- return fReturnTypeRange.length > 2;
- }
-
- /**
- * @see IDOMMethod#isConstructor()
- */
- public boolean isConstructor() {
- return getMask(MASK_IS_CONSTRUCTOR);
- }
- /**
- * Returns true if this method's return type has been altered
- * from the original document contents.
- */
- protected boolean isReturnTypeAltered() {
- return getMask(MASK_RETURN_TYPE_ALTERED);
}
-
- /**
- * @see IDOMNode#isSigantureEqual(IDOMNode).
- *
- * <p>Two methods have equal signatures if there names are the same
- * and their parameter types are the same.
- */
- public boolean isSignatureEqual(IDOMNode node) {
- boolean ok = node.getNodeType() == getNodeType();
- if (ok) {
- IDOMMethod method = (IDOMMethod) node;
- ok =
- (isConstructor() && method.isConstructor())
- || (!isConstructor() && !method.isConstructor());
- if (ok && !isConstructor()) {
- ok = getName().equals(method.getName());
+}
+/**
+ * Returns true if this method's return type has
+ * array qualifiers ('[]') following the parameter list.
+ */
+protected boolean hasTrailingArrayQualifier() {
+ return fReturnTypeRange.length > 2;
+}
+/**
+ * @see IDOMMethod#isConstructor()
+ */
+public boolean isConstructor() {
+ return getMask(MASK_IS_CONSTRUCTOR);
+}
+/**
+ * Returns true if this method's return type has been altered
+ * from the original document contents.
+ */
+protected boolean isReturnTypeAltered() {
+ return getMask(MASK_RETURN_TYPE_ALTERED);
+}
+/**
+ * @see IDOMNode#isSigantureEqual(IDOMNode).
+ *
+ * <p>Two methods have equal signatures if there names are the same
+ * and their parameter types are the same.
+ */
+public boolean isSignatureEqual(IDOMNode node) {
+ boolean ok= node.getNodeType() == getNodeType();
+ if (ok) {
+ IDOMMethod method= (IDOMMethod)node;
+ ok = (isConstructor() && method.isConstructor()) ||
+ (!isConstructor() && !method.isConstructor());
+ if (ok && !isConstructor()) {
+ ok= getName().equals(method.getName());
+ }
+ if (!ok) {
+ return false;
+ }
+
+ String[] types= method.getParameterTypes();
+ if (fParameterTypes == null || fParameterTypes.length == 0) {
+ // this method has no parameters
+ if (types == null || types.length == 0) {
+ // the other method has no parameters either
+ return true;
}
- if (!ok) {
+ } else {
+ // this method has parameters
+ if (types == null || types.length == 0) {
+ // the other method has no parameters
return false;
}
-
- String[] types = method.getParameterTypes();
- if (fParameterTypes == null || fParameterTypes.length == 0) {
- // this method has no parameters
- if (types == null || types.length == 0) {
- // the other method has no parameters either
- return true;
- }
- } else {
- // this method has parameters
- if (types == null || types.length == 0) {
- // the other method has no parameters
- return false;
- }
- if (fParameterTypes.length != types.length) {
- // the methods have a different number of parameters
+ if (fParameterTypes.length != types.length) {
+ // the methods have a different number of parameters
+ return false;
+ }
+ int i;
+ for (i= 0; i < types.length; i++) {
+ if (!fParameterTypes[i].equals(types[i])) {
return false;
}
- int i;
- for (i = 0; i < types.length; i++) {
- if (!fParameterTypes[i].equals(types[i])) {
- return false;
- }
- }
- return true;
}
+ return true;
}
- return false;
-
- }
-
- /**
- * @see DOMNode
- */
- protected DOMNode newDOMNode() {
- return new DOMMethod();
}
-
- /**
- * Offsets all the source indexes in this node by the given amount.
- */
- protected void offset(int offset) {
- super.offset(offset);
- offsetRange(fBodyRange, offset);
- offsetRange(fExceptionRange, offset);
- offsetRange(fParameterRange, offset);
- offsetRange(fReturnTypeRange, offset);
+ return false;
+
+}
+/**
+ * @see DOMNode
+ */
+protected DOMNode newDOMNode() {
+ return new DOMMethod();
+}
+/**
+ * Offsets all the source indexes in this node by the given amount.
+ */
+protected void offset(int offset) {
+ super.offset(offset);
+ offsetRange(fBodyRange, offset);
+ offsetRange(fExceptionRange, offset);
+ offsetRange(fParameterRange, offset);
+ offsetRange(fReturnTypeRange, offset);
+}
+/**
+ * @see IDOMMethod#setBody
+ */
+public void setBody(String body) {
+ becomeDetailed();
+ fragment();
+ fBody= body;
+ setHasBody(body != null);
+ if (!hasBody()) {
+ fBody= ";"+JavaModelManager.LINE_SEPARATOR;
}
-
- /**
- * @see IDOMMethod#setBody
- */
- public void setBody(String body) {
- becomeDetailed();
- fragment();
- fBody = body;
- setHasBody(body != null);
- if (!hasBody()) {
- fBody = ";" + JavaModelManager.LINE_SEPARATOR;
+}
+/**
+ * Sets the end of the body range
+ */
+void setBodyRangeEnd(int end) {
+ fBodyRange[1] = end;
+}
+/**
+ * @see IDOMMethod#setConstructor(boolean)
+ */
+public void setConstructor(boolean b) {
+ becomeDetailed();
+ setMask(MASK_IS_CONSTRUCTOR, b);
+ fragment();
+}
+/**
+ * @see IDOMMethod#setExceptions(char[][])
+ */
+public void setExceptions(String[] names) {
+ becomeDetailed();
+ if (names == null || names.length == 0) {
+ fExceptions= null;
+ } else {
+ fExceptions= names;
+ CharArrayBuffer buffer = new CharArrayBuffer();
+ char[] comma = new char[] {',', ' '};
+ for (int i = 0, length = names.length; i < length; i++) {
+ if (i > 0)
+ buffer.append(comma);
+ buffer.append(names[i]);
}
+ fExceptionList= buffer.getContents();
}
-
- /**
- * Sets the end of the body range
- */
- void setBodyRangeEnd(int end) {
- fBodyRange[1] = end;
- }
-
- /**
- * @see IDOMMethod#setConstructor(boolean)
- */
- public void setConstructor(boolean b) {
- becomeDetailed();
- setMask(MASK_IS_CONSTRUCTOR, b);
- fragment();
- }
-
- /**
- * @see IDOMMethod#setExceptions(char[][])
- */
- public void setExceptions(String[] names) {
- becomeDetailed();
- if (names == null || names.length == 0) {
- fExceptions = null;
- } else {
- fExceptions = names;
- CharArrayBuffer buffer = new CharArrayBuffer();
- char[] comma = new char[] { ',', ' ' };
- for (int i = 0, length = names.length; i < length; i++) {
- if (i > 0)
- buffer.append(comma);
- buffer.append(names[i]);
- }
- fExceptionList = buffer.getContents();
- }
- fragment();
+ fragment();
+}
+/**
+ * @see IDOMMethod#setName
+ */
+public void setName(String name) {
+ if (name == null) {
+ throw new IllegalArgumentException("illegal to set method name to null");
+ } else {
+ super.setName(name);
}
-
- /**
- * @see IDOMMethod#setName
- */
- public void setName(String name) {
- if (name == null) {
- throw new IllegalArgumentException("illegal to set method name to null");
+}
+/**
+ * @see IDOMMethod#setParameters(char[][], char[][])
+ */
+public void setParameters(String[] types, String[] names) throws IllegalArgumentException {
+ becomeDetailed();
+ if (types== null || names == null) {
+ if (types == null && names == null) {
+ fParameterTypes= null;
+ fParameterNames= null;
+ fParameterList= new char[] {'(',')'};
} else {
- super.setName(name);
+ throw new IllegalArgumentException("types and names must have identical length");
}
- }
-
- /**
- * @see IDOMMethod#setParameters(char[][], char[][])
- */
- public void setParameters(String[] types, String[] names)
- throws IllegalArgumentException {
- becomeDetailed();
- if (types == null || names == null) {
- if (types == null && names == null) {
- fParameterTypes = null;
- fParameterNames = null;
- fParameterList = new char[] { '(', ')' };
- } else {
- throw new IllegalArgumentException("types and names must have identical length");
+ } else if (names.length != types.length) {
+ throw new IllegalArgumentException("types and names must have identical length");
+ } else if (names.length == 0) {
+ setParameters(null, null);
+ } else {
+ fParameterNames= names;
+ fParameterTypes= types;
+ CharArrayBuffer parametersBuffer = new CharArrayBuffer();
+ parametersBuffer.append("(");
+ char[] comma = new char[] {',', ' '};
+ for (int i = 0; i < names.length; i++) {
+ if (i > 0) {
+ parametersBuffer.append(comma);
}
- } else
- if (names.length != types.length) {
- throw new IllegalArgumentException("types and names must have identical length");
- } else
- if (names.length == 0) {
- setParameters(null, null);
- } else {
- fParameterNames = names;
- fParameterTypes = types;
- CharArrayBuffer parametersBuffer = new CharArrayBuffer();
- parametersBuffer.append("(");
- char[] comma = new char[] { ',', ' ' };
- for (int i = 0; i < names.length; i++) {
- if (i > 0) {
- parametersBuffer.append(comma);
- }
- parametersBuffer.append(types[i]).append(" ").append(names[i]);
- }
- parametersBuffer.append(")");
- fParameterList = parametersBuffer.getContents();
- }
- fragment();
- }
-
- /**
- * @see IDOMMethod#setReturnType(char[])
- */
- public void setReturnType(String name) throws IllegalArgumentException {
- if (name == null) {
- throw new IllegalArgumentException("illegal return type of null");
+ parametersBuffer
+ .append(types[i])
+ .append(" ")
+ .append(names[i]);
}
- becomeDetailed();
- fragment();
- setReturnTypeAltered(true);
- fReturnType = name;
- }
-
- /**
- * Sets the state of this method declaration as having
- * the return type altered from the original document.
- */
- protected void setReturnTypeAltered(boolean typeAltered) {
- setMask(MASK_RETURN_TYPE_ALTERED, typeAltered);
- }
-
- /**
- */
- protected void setSourceRangeEnd(int end) {
- super.setSourceRangeEnd(end);
- fBodyRange[1] = end;
- }
-
- /**
- * @see DOMNode#shareContents(DOMNode)
- */
- protected void shareContents(DOMNode node) {
- super.shareContents(node);
- DOMMethod method = (DOMMethod) node;
- fBody = method.fBody;
- fBodyRange = rangeCopy(method.fBodyRange);
- fExceptionList = method.fExceptionList;
- fExceptionRange = rangeCopy(method.fExceptionRange);
- fExceptions = method.fExceptions;
- fParameterList = method.fParameterList;
- fParameterNames = method.fParameterNames;
- fParameterRange = rangeCopy(method.fParameterRange);
- fParameterTypes = method.fParameterTypes;
- fReturnType = method.fReturnType;
- fReturnTypeRange = rangeCopy(method.fReturnTypeRange);
+ parametersBuffer.append(")");
+ fParameterList= parametersBuffer.getContents();
}
-
- /**
- * @see IDOMNode#toString()
- */
- public String toString() {
- if (isConstructor()) {
- return "CONSTRUCTOR";
- } else {
- return "METHOD: " + getName();
- }
+ fragment();
+}
+/**
+ * @see IDOMMethod#setReturnType(char[])
+ */
+public void setReturnType(String name) throws IllegalArgumentException {
+ if (name == null) {
+ throw new IllegalArgumentException("illegal return type of null");
+ }
+ becomeDetailed();
+ fragment();
+ setReturnTypeAltered(true);
+ fReturnType= name;
+}
+/**
+ * Sets the state of this method declaration as having
+ * the return type altered from the original document.
+ */
+protected void setReturnTypeAltered(boolean typeAltered) {
+ setMask(MASK_RETURN_TYPE_ALTERED, typeAltered);
+}
+/**
+ */
+protected void setSourceRangeEnd(int end) {
+ super.setSourceRangeEnd(end);
+ fBodyRange[1]= end;
+}
+/**
+ * @see DOMNode#shareContents(DOMNode)
+ */
+protected void shareContents(DOMNode node) {
+ super.shareContents(node);
+ DOMMethod method= (DOMMethod)node;
+ fBody= method.fBody;
+ fBodyRange= rangeCopy(method.fBodyRange);
+ fExceptionList= method.fExceptionList;
+ fExceptionRange= rangeCopy(method.fExceptionRange);
+ fExceptions= method.fExceptions;
+ fParameterList= method.fParameterList;
+ fParameterNames= method.fParameterNames;
+ fParameterRange= rangeCopy(method.fParameterRange);
+ fParameterTypes= method.fParameterTypes;
+ fReturnType= method.fReturnType;
+ fReturnTypeRange= rangeCopy(method.fReturnTypeRange);
+}
+/**
+ * @see IDOMNode#toString()
+ */
+public String toString() {
+ if (isConstructor()) {
+ return "CONSTRUCTOR";
+ } else {
+ return "METHOD: " + getName();
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMNode.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
index d60e83c20f..d3a1181038 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMNode.java
@@ -50,7 +50,7 @@ public abstract class DOMNode implements IDOMNode {
* when this node has no children. (Children of a node
* are implemented as a doubly linked list).
*/
- protected DOMNode fFirstChild = null;
+ protected DOMNode fFirstChild= null;
/**
* The last child of this node - <code>null</code>
@@ -58,26 +58,26 @@ public abstract class DOMNode implements IDOMNode {
* access to the last child when adding new children
* at the end of the linked list of children.
*/
- protected DOMNode fLastChild = null;
+ protected DOMNode fLastChild= null;
/**
* The sibling node following this node - <code>null</code>
* for the last node in the sibling list.
*/
- protected DOMNode fNextNode = null;
+ protected DOMNode fNextNode= null;
/**
* The parent of this node. A <code>null</code>
* parent indicates that this node is a root
* node of a document fragment.
*/
- protected DOMNode fParent = null;
+ protected DOMNode fParent= null;
/**
* The sibling node preceding this node - <code>null</code>
* for the first node in the sibling list.
*/
- protected DOMNode fPreviousNode = null;
+ protected DOMNode fPreviousNode= null;
/**
* True when this node has attributes that have
@@ -88,7 +88,7 @@ public abstract class DOMNode implements IDOMNode {
* consistent with the content of the shared
* document.
*/
- protected boolean fIsFragmented = false;
+ protected boolean fIsFragmented= false;
/**
* The name of this node. For efficiency, the
@@ -96,21 +96,21 @@ public abstract class DOMNode implements IDOMNode {
* on creation, rather than always having to fetch
* the name from the shared document.
*/
- protected String fName = null;
+ protected String fName= null;
/**
* The original inclusive indicies of this node's name in
* the shared document. Values of -1 indiciate the name
* does not exist in the document.
*/
- protected int[] fNameRange;
+ protected int[] fNameRange;
/**
* The shared document that the contents for this node
* are contained in. Attribute indicies are positions
* in this character array.
*/
- protected char[] fDocument = null;
+ protected char[] fDocument= null;
/**
* The original entire inclusive range of this node's contents
@@ -128,881 +128,820 @@ public abstract class DOMNode implements IDOMNode {
* @see #setMask
* @see #getMask
*/
- protected int fStateMask = 0;
+ protected int fStateMask= 0;
/**
* A bit mask indicating this field has an initializer
* expression
*/
- protected static final int MASK_FIELD_HAS_INITIALIZER = 0x00000001;
-
+ protected static final int MASK_FIELD_HAS_INITIALIZER= 0x00000001;
+
/**
* A bit mask indicating this field is a secondary variable
* declarator for a previous field declaration.
*/
- protected static final int MASK_FIELD_IS_VARIABLE_DECLARATOR = 0x00000002;
+ protected static final int MASK_FIELD_IS_VARIABLE_DECLARATOR= 0x00000002;
/**
* A bit mask indicating this field's type has been
* altered from its original contents in the document.
*/
- protected static final int MASK_FIELD_TYPE_ALTERED = 0x00000004;
+ protected static final int MASK_FIELD_TYPE_ALTERED= 0x00000004;
/**
* A bit mask indicating this node's name has been
* altered from its original contents in the document.
*/
- protected static final int MASK_NAME_ALTERED = 0x00000008;
+ protected static final int MASK_NAME_ALTERED= 0x00000008;
/**
* A bit mask indicating this node currently has a
* body.
*/
- protected static final int MASK_HAS_BODY = 0x00000010;
-
+ protected static final int MASK_HAS_BODY= 0x00000010;
+
/**
* A bit mask indicating this node currently has a
* preceding comment.
*/
- protected static final int MASK_HAS_COMMENT = 0x00000020;
+ protected static final int MASK_HAS_COMMENT= 0x00000020;
/**
* A bit mask indicating this method is a constructor.
*/
- protected static final int MASK_IS_CONSTRUCTOR = 0x00000040;
+ protected static final int MASK_IS_CONSTRUCTOR= 0x00000040;
/**
* A bit mask indicating this type is a class.
*/
- protected static final int MASK_TYPE_IS_CLASS = 0x00000080;
+ protected static final int MASK_TYPE_IS_CLASS= 0x00000080;
/**
* A bit mask indicating this type has a superclass
* (requires or has an 'extends' clause).
*/
- protected static final int MASK_TYPE_HAS_SUPERCLASS = 0x00000100;
+ protected static final int MASK_TYPE_HAS_SUPERCLASS= 0x00000100;
/**
* A bit mask indicating this type implements
* or extends some interfaces
*/
- protected static final int MASK_TYPE_HAS_INTERFACES = 0x00000200;
+ protected static final int MASK_TYPE_HAS_INTERFACES= 0x00000200;
/**
* A bit mask indicating this return type of this method has
* been altered from the original contents.
*/
- protected static final int MASK_RETURN_TYPE_ALTERED = 0x00000400;
+ protected static final int MASK_RETURN_TYPE_ALTERED= 0x00000400;
/**
* A bit mask indicating this node has detailed source indexes
*/
protected static final int MASK_DETAILED_SOURCE_INDEXES = 0x00000800;
- /**
- * Creates a new empty document fragment.
- */
- DOMNode() {
- fName = null;
- fDocument = null;
- fSourceRange = new int[] { -1, -1 };
- fNameRange = new int[] { -1, -1 };
- fragment();
- }
-
- /**
- * Creates a new document fragment on the given range of the document.
- *
- * @param document - the document containing this node's original contents
- * @param sourceRange - a two element array of integers describing the
- * entire inclusive source range of this node within its document.
- * Contents start on and include the character at the first position.
- * Contents end on and include the character at the last position.
- * An array of -1's indicates this node's contents do not exist
- * in the document.
- * @param name - the identifier portion of the name of this node, or
- * <code>null</code> if this node does not have a name
- * @param nameRange - a two element array of integers describing the
- * entire inclusive source range of this node's name within its document,
- * including any array qualifiers that might immediately follow the name
- * or -1's if this node does not have a name.
- */
- DOMNode(char[] document, int[] sourceRange, String name, int[] nameRange) {
- super();
- fDocument = document;
- fSourceRange = sourceRange;
- fName = name;
- fNameRange = nameRange;
-
- }
+/**
+ * Creates a new empty document fragment.
+ */
+DOMNode() {
+ fName= null;
+ fDocument= null;
+ fSourceRange= new int[]{-1, -1};
+ fNameRange= new int[]{-1, -1};
+ fragment();
+}
+/**
+ * Creates a new document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this node, or
+ * <code>null</code> if this node does not have a name
+ * @param nameRange - a two element array of integers describing the
+ * entire inclusive source range of this node's name within its document,
+ * including any array qualifiers that might immediately follow the name
+ * or -1's if this node does not have a name.
+ */
+DOMNode(char[] document, int[] sourceRange, String name, int[] nameRange) {
+ super();
+ fDocument= document;
+ fSourceRange= sourceRange;
+ fName= name;
+ fNameRange= nameRange;
- /**
- * Adds the given un-parented node (document fragment) as the last child of
- * this node.
- *
- * <p>When a child is added, this node must be considered fragmented such that
- * the contents of this node are properly generated.
- *
- * @see IDOMNode#addChild(IDOMNode)
- */
- public void addChild(IDOMNode child)
- throws IllegalArgumentException, DOMException {
- basicAddChild(child);
-
- // if the node is a constructor, it must also be fragmented to update the constructor's name
- if (child.getNodeType() == IDOMNode.METHOD
- && ((IDOMMethod) child).isConstructor()) {
- ((DOMNode) child).fragment();
- } else {
- fragment();
- }
+}
+/**
+ * Adds the given un-parented node (document fragment) as the last child of
+ * this node.
+ *
+ * <p>When a child is added, this node must be considered fragmented such that
+ * the contents of this node are properly generated.
+ *
+ * @see IDOMNode#addChild(IDOMNode)
+ */
+public void addChild(IDOMNode child) throws IllegalArgumentException, DOMException {
+ basicAddChild(child);
+
+ // if the node is a constructor, it must also be fragmented to update the constructor's name
+ if (child.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)child).isConstructor()) {
+ ((DOMNode)child).fragment();
+ } else {
+ fragment();
}
-
- /**
- * Appends the current contents of this document fragment
- * to the given <code>CharArrayBuffer</code>.
- *
- * <p>If this node is fragmented, contents must be generated by
- * using the original document and indicies as a form for the current
- * attribute values of this node. If this node not fragmented, the
- * contents can be obtained from the document.
- *
- */
- protected void appendContents(CharArrayBuffer buffer) {
- if (isFragmented()) {
- appendFragmentedContents(buffer);
- } else {
- buffer.append(
- fDocument,
- fSourceRange[0],
- fSourceRange[1] + 1 - fSourceRange[0]);
- }
+}
+/**
+ * Appends the current contents of this document fragment
+ * to the given <code>CharArrayBuffer</code>.
+ *
+ * <p>If this node is fragmented, contents must be generated by
+ * using the original document and indicies as a form for the current
+ * attribute values of this node. If this node not fragmented, the
+ * contents can be obtained from the document.
+ *
+ */
+protected void appendContents(CharArrayBuffer buffer) {
+ if (isFragmented()) {
+ appendFragmentedContents(buffer);
+ } else {
+ buffer.append(fDocument, fSourceRange[0], fSourceRange[1] + 1 - fSourceRange[0]);
}
-
- /**
- * Appends the contents of all children of this node to the
- * given <code>CharArrayBuffer</code>.
- *
- * <p>This algorithm used minimizes String generation by merging
- * adjacent unfragmented children into one substring operation.
- *
- */
- protected void appendContentsOfChildren(CharArrayBuffer buffer) {
- DOMNode child = fFirstChild;
- DOMNode sibling;
-
- int start = 0, end = 0;
- if (child != null) {
- start = child.getStartPosition();
- end = child.getEndPosition();
- }
- while (child != null) {
- sibling = child.fNextNode;
- if (sibling != null) {
- if (sibling.isContentMergableWith(child)) {
- end = sibling.getEndPosition();
- } else {
- if (child.isFragmented()) {
- child.appendContents(buffer);
- } else {
- buffer.append(child.getDocument(), start, end + 1 - start);
- }
- start = sibling.getStartPosition();
- end = sibling.getEndPosition();
- }
+}
+/**
+ * Appends the contents of all children of this node to the
+ * given <code>CharArrayBuffer</code>.
+ *
+ * <p>This algorithm used minimizes String generation by merging
+ * adjacent unfragmented children into one substring operation.
+ *
+ */
+protected void appendContentsOfChildren(CharArrayBuffer buffer) {
+ DOMNode child= fFirstChild;
+ DOMNode sibling;
+
+ int start= 0, end= 0;
+ if (child != null) {
+ start= child.getStartPosition();
+ end= child.getEndPosition();
+ }
+ while (child != null) {
+ sibling= child.fNextNode;
+ if (sibling != null) {
+ if (sibling.isContentMergableWith(child)) {
+ end= sibling.getEndPosition();
} else {
if (child.isFragmented()) {
child.appendContents(buffer);
} else {
buffer.append(child.getDocument(), start, end + 1 - start);
}
+ start= sibling.getStartPosition();
+ end= sibling.getEndPosition();
}
- child = sibling;
- }
- }
-
- /**
- * Appends the contents of this node to the given <code>CharArrayBufer</code>, using
- * the original document and indicies as a form for the current attribute
- * values of this node.
- */
- protected abstract void appendFragmentedContents(CharArrayBuffer buffer);
- /**
- * Adds the given un-parented node (document fragment) as the last child of
- * this node without setting this node's 'fragmented' flag. This
- * method is only used by the <code>DOMBuilder</code> when creating a new DOM such
- * that a new DOM is unfragmented.
- */
- void basicAddChild(IDOMNode child)
- throws IllegalArgumentException, DOMException {
- // verify child may be added
- if (!canHaveChildren()) {
- throw new DOMException("attempt to add child to node that cannot have children");
- }
- if (child == null) {
- throw new IllegalArgumentException("attempt to add null child");
- }
- if (!isAllowableChild(child)) {
- throw new DOMException("attempt to add child of incompatible type");
- }
- if (child.getParent() != null) {
- throw new DOMException("attempt to add child that is already parented");
- }
- /* NOTE: To test if the child is an ancestor of this node, we
- * need only test if the root of this node is the child (the child
- * is already a root since we have just guarenteed it has no parent).
- */
- if (child == getRoot()) {
- throw new DOMException("attempt to add ancestor as child");
- }
-
- DOMNode node = (DOMNode) child;
-
- // if the child is not already part of this document, localize its contents
- // before adding it to the tree
- if (node.getDocument() != getDocument()) {
- node.localizeContents();
- }
-
- // add the child last
- if (fFirstChild == null) {
- // this is the first and only child
- fFirstChild = node;
} else {
- fLastChild.fNextNode = node;
- node.fPreviousNode = fLastChild;
- }
- fLastChild = node;
- node.fParent = this;
- }
-
- /**
- * Generates detailed source indexes for this node if possible.
- *
- * @exception DOMException if unable to generate detailed source indexes
- * for this node
- */
- protected void becomeDetailed() throws DOMException {
- if (!isDetailed()) {
- DOMNode detailed = getDetailedNode();
- if (detailed == null) {
- throw new DOMException("Unable to generate detailed source indexes.");
- }
- if (detailed != this) {
- shareContents(detailed);
+ if (child.isFragmented()) {
+ child.appendContents(buffer);
+ } else {
+ buffer.append(child.getDocument(), start, end + 1 - start);
}
}
+ child= sibling;
}
-
- /**
- * Returns true if this node is allowed to have children, otherwise false.
- *
- * <p>Default implementation of <code>IDOMNode</code> interface method returns false; this
- * method must be overridden by subclasses that implement nodes that allow
- * children.
- *
- * @see IDOMNode#canHaveChildren()
- */
- public boolean canHaveChildren() {
- return false;
- }
-
- /**
- * @see IDOMNode#clone()
- */
- public Object clone() {
-
- // create a new buffer with all my contents and children contents
- int length = 0;
- char[] buffer = null;
- int offset = fSourceRange[0];
-
- if (offset >= 0) {
- length = fSourceRange[1] - offset + 1;
- buffer = new char[length];
- System.arraycopy(fDocument, offset, buffer, 0, length);
- }
- DOMNode clone = newDOMNode();
- clone.shareContents(this);
- clone.fDocument = buffer;
-
- if (offset > 0) {
- clone.offset(0 - offset);
+}
+/**
+ * Appends the contents of this node to the given <code>CharArrayBufer</code>, using
+ * the original document and indicies as a form for the current attribute
+ * values of this node.
+ */
+protected abstract void appendFragmentedContents(CharArrayBuffer buffer);
+/**
+ * Adds the given un-parented node (document fragment) as the last child of
+ * this node without setting this node's 'fragmented' flag. This
+ * method is only used by the <code>DOMBuilder</code> when creating a new DOM such
+ * that a new DOM is unfragmented.
+ */
+void basicAddChild(IDOMNode child) throws IllegalArgumentException, DOMException {
+ // verify child may be added
+ if (!canHaveChildren()) {
+ throw new DOMException("attempt to add child to node that cannot have children");
+ }
+ if (child == null) {
+ throw new IllegalArgumentException("attempt to add null child");
+ }
+ if (!isAllowableChild(child)) {
+ throw new DOMException("attempt to add child of incompatible type");
+ }
+ if (child.getParent() != null) {
+ throw new DOMException("attempt to add child that is already parented");
+ }
+ /* NOTE: To test if the child is an ancestor of this node, we
+ * need only test if the root of this node is the child (the child
+ * is already a root since we have just guarenteed it has no parent).
+ */
+ if (child == getRoot()) {
+ throw new DOMException("attempt to add ancestor as child");
+ }
+
+ DOMNode node= (DOMNode)child;
+
+ // if the child is not already part of this document, localize its contents
+ // before adding it to the tree
+ if (node.getDocument() != getDocument()) {
+ node.localizeContents();
+ }
+
+ // add the child last
+ if (fFirstChild == null) {
+ // this is the first and only child
+ fFirstChild= node;
+ } else {
+ fLastChild.fNextNode= node;
+ node.fPreviousNode= fLastChild;
+ }
+ fLastChild= node;
+ node.fParent= this;
+}
+/**
+ * Generates detailed source indexes for this node if possible.
+ *
+ * @exception DOMException if unable to generate detailed source indexes
+ * for this node
+ */
+protected void becomeDetailed() throws DOMException {
+ if (!isDetailed()) {
+ DOMNode detailed= getDetailedNode();
+ if (detailed == null) {
+ throw new DOMException("Unable to generate detailed source indexes.");
}
-
- // clone my children
- if (canHaveChildren()) {
- Enumeration children = getChildren();
- while (children.hasMoreElements()) {
- DOMNode child = (DOMNode) children.nextElement();
- if (child.fDocument == fDocument) {
- DOMNode childClone = child.cloneSharingDocument(buffer, offset);
- clone.basicAddChild(childClone);
- } else {
- DOMNode childClone = (DOMNode) child.clone();
- clone.addChild(childClone);
- }
-
- }
+ if (detailed != this) {
+ shareContents(detailed);
}
-
- return clone;
}
-
- private DOMNode cloneSharingDocument(char[] document, int rootOffset) {
-
- int length = 0;
- int offset = fSourceRange[0];
-
- DOMNode clone = newDOMNode();
- clone.shareContents(this);
- clone.fDocument = document;
- if (rootOffset > 0) {
- clone.offset(0 - rootOffset);
- }
-
- if (canHaveChildren()) {
- Enumeration children = getChildren();
- while (children.hasMoreElements()) {
- DOMNode child = (DOMNode) children.nextElement();
- if (child.fDocument == fDocument) {
- DOMNode childClone = child.cloneSharingDocument(document, rootOffset);
- clone.basicAddChild(childClone);
- } else {
- DOMNode childClone = (DOMNode) child.clone();
- clone.addChild(childClone);
- }
+}
+/**
+ * Returns true if this node is allowed to have children, otherwise false.
+ *
+ * <p>Default implementation of <code>IDOMNode</code> interface method returns false; this
+ * method must be overridden by subclasses that implement nodes that allow
+ * children.
+ *
+ * @see IDOMNode#canHaveChildren()
+ */
+public boolean canHaveChildren() {
+ return false;
+}
+/**
+ * @see IDOMNode#clone()
+ */
+public Object clone() {
+
+ // create a new buffer with all my contents and children contents
+ int length= 0;
+ char[] buffer= null;
+ int offset= fSourceRange[0];
+
+ if (offset >= 0) {
+ length= fSourceRange[1] - offset + 1;
+ buffer= new char[length];
+ System.arraycopy(fDocument, offset, buffer, 0, length);
+ }
+ DOMNode clone= newDOMNode();
+ clone.shareContents(this);
+ clone.fDocument = buffer;
+
+ if (offset > 0) {
+ clone.offset(0 - offset);
+ }
+
+ // clone my children
+ if (canHaveChildren()) {
+ Enumeration children= getChildren();
+ while (children.hasMoreElements()) {
+ DOMNode child= (DOMNode)children.nextElement();
+ if (child.fDocument == fDocument) {
+ DOMNode childClone= child.cloneSharingDocument(buffer, offset);
+ clone.basicAddChild(childClone);
+ } else {
+ DOMNode childClone= (DOMNode)child.clone();
+ clone.addChild(childClone);
}
+
}
- return clone;
}
-
- /**
- * Sets this node's fragmented flag and all ancestor fragmented flags
- * to <code>true<code>. This happens when an attribute of this node or a descendant
- * node has been altered. When a node is fragmented, its contents must
- * be generated from its attributes and original "form" rather than
- * from the original contents in the document.
- */
- protected void fragment() {
- if (!isFragmented()) {
- fIsFragmented = true;
- if (fParent != null) {
- fParent.fragment();
+
+ return clone;
+}
+private DOMNode cloneSharingDocument(char[] document, int rootOffset) {
+
+ int length = 0;
+ int offset = fSourceRange[0];
+
+ DOMNode clone = newDOMNode();
+ clone.shareContents(this);
+ clone.fDocument = document;
+ if (rootOffset > 0) {
+ clone.offset(0 - rootOffset);
+ }
+
+ if (canHaveChildren()) {
+ Enumeration children = getChildren();
+ while (children.hasMoreElements()) {
+ DOMNode child = (DOMNode) children.nextElement();
+ if (child.fDocument == fDocument) {
+ DOMNode childClone= child.cloneSharingDocument(document, rootOffset);
+ clone.basicAddChild(childClone);
+ } else {
+ DOMNode childClone= (DOMNode)child.clone();
+ clone.addChild(childClone);
}
}
}
-
- /**
- * @see IDOMNode#getCharacters()
- */
- public char[] getCharacters() {
- CharArrayBuffer buffer = new CharArrayBuffer();
- appendContents(buffer);
- return buffer.getContents();
- }
-
- /**
- * @see IDOMNode#getChild(String)
- */
- public IDOMNode getChild(String name) {
- DOMNode child = fFirstChild;
- while (child != null) {
- String n = child.getName();
- if (n != null && n.equals(name)) {
- return child;
- }
- child = child.fNextNode;
+ return clone;
+}
+/**
+ * Sets this node's fragmented flag and all ancestor fragmented flags
+ * to <code>true<code>. This happens when an attribute of this node or a descendant
+ * node has been altered. When a node is fragmented, its contents must
+ * be generated from its attributes and original "form" rather than
+ * from the original contents in the document.
+ */
+protected void fragment() {
+ if (!isFragmented()) {
+ fIsFragmented= true;
+ if (fParent != null) {
+ fParent.fragment();
}
- return null;
- }
-
- /**
- * @see IDOMNode#getChildren()
- */
- public Enumeration getChildren() {
- return new SiblingEnumeration(fFirstChild);
- }
-
- /**
- * Returns the current contents of this document fragment,
- * or <code>null</code> if this node has no contents.
- *
- * <p>If this node is fragmented, contents must be generated by
- * using the original document and indicies as a form for the current
- * attribute values of this node. If this node not fragmented, the
- * contents can be obtained from the document.
- *
- * @see IDOMNode#getContents()
- */
- public String getContents() {
- CharArrayBuffer buffer = new CharArrayBuffer();
- appendContents(buffer);
- return buffer.toString();
- }
-
- /**
- * Returns a new document fragment representing this node with
- * detailed source indexes. Subclasses that provide a detailed
- * implementation must override this method.
- */
- protected DOMNode getDetailedNode() {
- return this;
- }
-
- /**
- * Returns the document containing this node's original contents.
- * The document may be shared by other nodes.
- */
- protected char[] getDocument() {
- return fDocument;
- }
-
- /**
- * Returns the original position of the last character of this
- * node's contents in its document.
- */
- public int getEndPosition() {
- return fSourceRange[1];
- }
-
- /**
- * Returns a factory with which to create new document fragments.
- */
- protected IDOMFactory getFactory() {
- return new DOMFactory();
- }
-
- /**
- * @see IDOMNode#getFirstChild()
- */
- public IDOMNode getFirstChild() {
- return fFirstChild;
- }
-
- /**
- * Returns the position at which the first child of this node should be inserted.
- */
- public int getInsertionPosition() {
- return getEndPosition();
- }
-
- /**
- * Returns <code>true</code> if the given mask of this node's state flag
- * is turned on, otherwise <code>false</code>.
- */
- protected boolean getMask(int mask) {
- return (fStateMask & mask) > 0;
}
-
- /**
- * @see IDOMNode#getName()
- */
- public String getName() {
- return fName;
+}
+/**
+ * @see IDOMNode#getCharacters()
+ */
+public char[] getCharacters() {
+ CharArrayBuffer buffer= new CharArrayBuffer();
+ appendContents(buffer);
+ return buffer.getContents();
+}
+/**
+ * @see IDOMNode#getChild(String)
+ */
+public IDOMNode getChild(String name) {
+ DOMNode child= fFirstChild;
+ while (child != null) {
+ String n= child.getName();
+ if (n != null && n.equals(name)) {
+ return child;
+ }
+ child= child.fNextNode;
}
-
- /**
- * Returns the source code to be used for this node's name.
- */
- protected char[] getNameContents() {
- if (isNameAltered()) {
- return fName.toCharArray();
+ return null;
+}
+/**
+ * @see IDOMNode#getChildren()
+ */
+public Enumeration getChildren() {
+ return new SiblingEnumeration(fFirstChild);
+}
+/**
+ * Returns the current contents of this document fragment,
+ * or <code>null</code> if this node has no contents.
+ *
+ * <p>If this node is fragmented, contents must be generated by
+ * using the original document and indicies as a form for the current
+ * attribute values of this node. If this node not fragmented, the
+ * contents can be obtained from the document.
+ *
+ * @see IDOMNode#getContents()
+ */
+public String getContents() {
+ CharArrayBuffer buffer= new CharArrayBuffer();
+ appendContents(buffer);
+ return buffer.toString();
+}
+/**
+ * Returns a new document fragment representing this node with
+ * detailed source indexes. Subclasses that provide a detailed
+ * implementation must override this method.
+ */
+protected DOMNode getDetailedNode() {
+ return this;
+}
+/**
+ * Returns the document containing this node's original contents.
+ * The document may be shared by other nodes.
+ */
+protected char[] getDocument() {
+ return fDocument;
+}
+/**
+ * Returns the original position of the last character of this
+ * node's contents in its document.
+ */
+public int getEndPosition() {
+ return fSourceRange[1];
+}
+/**
+ * Returns a factory with which to create new document fragments.
+ */
+protected IDOMFactory getFactory() {
+ return new DOMFactory();
+}
+/**
+ * @see IDOMNode#getFirstChild()
+ */
+public IDOMNode getFirstChild() {
+ return fFirstChild;
+}
+/**
+ * Returns the position at which the first child of this node should be inserted.
+ */
+public int getInsertionPosition() {
+ return getEndPosition();
+}
+/**
+ * Returns <code>true</code> if the given mask of this node's state flag
+ * is turned on, otherwise <code>false</code>.
+ */
+protected boolean getMask(int mask) {
+ return (fStateMask & mask) > 0;
+}
+/**
+ * @see IDOMNode#getName()
+ */
+public String getName() {
+ return fName;
+}
+/**
+ * Returns the source code to be used for this node's name.
+ */
+protected char[] getNameContents() {
+ if (isNameAltered()) {
+ return fName.toCharArray();
+ } else {
+ if (fName == null || fNameRange[0] < 0) {
+ return null;
} else {
- if (fName == null || fNameRange[0] < 0) {
- return null;
- } else {
- int length = fNameRange[1] + 1 - fNameRange[0];
- char[] result = new char[length];
- System.arraycopy(fDocument, fNameRange[0], result, 0, length);
- return result;
- }
+ int length = fNameRange[1] + 1 - fNameRange[0];
+ char[] result = new char[length];
+ System.arraycopy(fDocument, fNameRange[0], result, 0, length);
+ return result;
}
}
-
- /**
- * @see IDOMNode#getNextNode()
- */
- public IDOMNode getNextNode() {
- return fNextNode;
- }
-
- /**
- * @see IDOMNode#getParent()
- */
- public IDOMNode getParent() {
- return fParent;
- }
-
- /**
- * Answers a source position which corresponds to the end of the parent
- * element's declaration.
- */
- protected int getParentEndDeclaration() {
- IDOMNode parent = getParent();
- if (parent == null) {
+}
+/**
+ * @see IDOMNode#getNextNode()
+ */
+public IDOMNode getNextNode() {
+ return fNextNode;
+}
+/**
+ * @see IDOMNode#getParent()
+ */
+public IDOMNode getParent() {
+ return fParent;
+}
+/**
+ * Answers a source position which corresponds to the end of the parent
+ * element's declaration.
+ */
+protected int getParentEndDeclaration() {
+ IDOMNode parent = getParent();
+ if (parent == null) {
+ return 0;
+ } else {
+ if (parent instanceof IDOMCompilationUnit) {
return 0;
} else {
- if (parent instanceof IDOMCompilationUnit) {
- return 0;
- } else {
- return ((DOMType) parent).getOpenBodyEnd();
- }
+ return ((DOMType)parent).getOpenBodyEnd();
}
}
-
- /**
- * @see IDOMNode#getPreviousNode()
- */
- public IDOMNode getPreviousNode() {
- return fPreviousNode;
- }
-
- /**
- * Returns the root node of this document fragment.
- */
- protected IDOMNode getRoot() {
- if (fParent == null) {
- return this;
- } else {
- return fParent.getRoot();
- }
+}
+/**
+ * @see IDOMNode#getPreviousNode()
+ */
+public IDOMNode getPreviousNode() {
+ return fPreviousNode;
+}
+/**
+ * Returns the root node of this document fragment.
+ */
+protected IDOMNode getRoot() {
+ if (fParent == null) {
+ return this;
+ } else {
+ return fParent.getRoot();
}
-
- /**
- * Returns the original position of the first character of this
- * node's contents in its document.
- */
- public int getStartPosition() {
- return fSourceRange[0];
+}
+/**
+ * Returns the original position of the first character of this
+ * node's contents in its document.
+ */
+public int getStartPosition() {
+ return fSourceRange[0];
+}
+/**
+ * @see IDOMNode#insertSibling(IDOMNode)
+ */
+public void insertSibling(IDOMNode sibling) throws IllegalArgumentException, DOMException {
+ // verify sibling may be added
+ if (sibling == null) {
+ throw new IllegalArgumentException("attempt to insert null sibling");
}
-
- /**
- * @see IDOMNode#insertSibling(IDOMNode)
- */
- public void insertSibling(IDOMNode sibling)
- throws IllegalArgumentException, DOMException {
- // verify sibling may be added
- if (sibling == null) {
- throw new IllegalArgumentException("attempt to insert null sibling");
- }
- if (fParent == null) {
- throw new DOMException("attempt to insert sibling before root node");
- }
- if (!fParent.isAllowableChild(sibling)) {
- throw new DOMException("attempt to insert sibling of incompatible type");
- }
- if (sibling.getParent() != null) {
- throw new DOMException("attempt to insert sibling that is already parented");
- }
- /* NOTE: To test if the sibling is an ancestor of this node, we
- * need only test if the root of this node is the child (the sibling
- * is already a root since we have just guaranteed it has no parent).
- */
- if (sibling == getRoot()) {
- throw new DOMException("attempt to insert ancestor as sibling");
- }
-
- DOMNode node = (DOMNode) sibling;
-
- // if the sibling is not already part of this document, localize its contents
- // before inserting it into the tree
- if (node.getDocument() != getDocument()) {
- node.localizeContents();
- }
-
- // insert the node
- if (fPreviousNode == null) {
- fParent.fFirstChild = node;
- } else {
- fPreviousNode.fNextNode = node;
- }
- node.fParent = fParent;
- node.fPreviousNode = fPreviousNode;
- node.fNextNode = this;
- fPreviousNode = node;
-
- // if the node is a constructor, it must also be fragmented to update the constructor's name
- if (node.getNodeType() == IDOMNode.METHOD
- && ((IDOMMethod) node).isConstructor()) {
- node.fragment();
- } else {
- fParent.fragment();
- }
+ if (fParent == null) {
+ throw new DOMException("attempt to insert sibling before root node");
}
-
- /**
- * @see IDOMNode
- */
- public boolean isAllowableChild(IDOMNode node) {
- return false;
+ if (!fParent.isAllowableChild(sibling)) {
+ throw new DOMException("attempt to insert sibling of incompatible type");
}
-
- /**
- * Returns <code>true</code> if the contents of this node are from the same document as
- * the given node, the contents of this node immediately follow the contents
- * of the given node, and neither this node or the given node are fragmented -
- * otherwise <code>false</code>.
- */
- protected boolean isContentMergableWith(DOMNode node) {
- return !node.isFragmented()
- && !isFragmented()
- && node.getDocument() == getDocument()
- && node.getEndPosition() + 1 == getStartPosition();
+ if (sibling.getParent() != null) {
+ throw new DOMException("attempt to insert sibling that is already parented");
}
-
- /**
- * Returns <code>true</code> if this node has detailed source index information,
- * or <code>false</code> if this node has limited source index information. To
- * perform some manipulations, detailed indexes are required.
+ /* NOTE: To test if the sibling is an ancestor of this node, we
+ * need only test if the root of this node is the child (the sibling
+ * is already a root since we have just guaranteed it has no parent).
*/
- protected boolean isDetailed() {
- return getMask(MASK_DETAILED_SOURCE_INDEXES);
+ if (sibling == getRoot()) {
+ throw new DOMException("attempt to insert ancestor as sibling");
}
- /**
- * Returns <code>true</code> if this node's or a descendant node's contents
- * have been altered since this node was created. This indicates
- * that the contents of this node are no longer consistent with
- * the contents of this node's document.
- */
- protected boolean isFragmented() {
- return fIsFragmented;
+ DOMNode node= (DOMNode)sibling;
+
+ // if the sibling is not already part of this document, localize its contents
+ // before inserting it into the tree
+ if (node.getDocument() != getDocument()) {
+ node.localizeContents();
}
- /**
- * Returns <code>true</code> if this noed's name has been altered
- * from the original document contents.
- */
- protected boolean isNameAltered() {
- return getMask(MASK_NAME_ALTERED);
+ // insert the node
+ if (fPreviousNode == null) {
+ fParent.fFirstChild= node;
+ } else {
+ fPreviousNode.fNextNode= node;
}
+ node.fParent= fParent;
+ node.fPreviousNode= fPreviousNode;
+ node.fNextNode= this;
+ fPreviousNode= node;
- /**
- * @see IDOMNode#isSignatureEqual(IDOMNode).
- *
- * <p>By default, the signatures of two nodes are equal if their
- * type and names are equal. Node types that have other requirements
- * for equality must override this method.
- */
- public boolean isSignatureEqual(IDOMNode node) {
- return getNodeType() == node.getNodeType() && getName().equals(node.getName());
+ // if the node is a constructor, it must also be fragmented to update the constructor's name
+ if (node.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)node).isConstructor()) {
+ node.fragment();
+ } else {
+ fParent.fragment();
}
+}
+/**
+ * @see IDOMNode
+ */
+public boolean isAllowableChild(IDOMNode node) {
+ return false;
+}
+/**
+ * Returns <code>true</code> if the contents of this node are from the same document as
+ * the given node, the contents of this node immediately follow the contents
+ * of the given node, and neither this node or the given node are fragmented -
+ * otherwise <code>false</code>.
+ */
+protected boolean isContentMergableWith(DOMNode node) {
+ return !node.isFragmented() && !isFragmented() && node.getDocument() == getDocument() &&
+ node.getEndPosition() + 1 == getStartPosition();
+}
+/**
+ * Returns <code>true</code> if this node has detailed source index information,
+ * or <code>false</code> if this node has limited source index information. To
+ * perform some manipulations, detailed indexes are required.
+ */
+protected boolean isDetailed() {
+ return getMask(MASK_DETAILED_SOURCE_INDEXES);
+}
+/**
+ * Returns <code>true</code> if this node's or a descendant node's contents
+ * have been altered since this node was created. This indicates
+ * that the contents of this node are no longer consistent with
+ * the contents of this node's document.
+ */
+protected boolean isFragmented() {
+ return fIsFragmented;
+}
+/**
+ * Returns <code>true</code> if this noed's name has been altered
+ * from the original document contents.
+ */
+protected boolean isNameAltered() {
+ return getMask(MASK_NAME_ALTERED);
+}
+/**
+ * @see IDOMNode#isSignatureEqual(IDOMNode).
+ *
+ * <p>By default, the signatures of two nodes are equal if their
+ * type and names are equal. Node types that have other requirements
+ * for equality must override this method.
+ */
+public boolean isSignatureEqual(IDOMNode node) {
+ return getNodeType() == node.getNodeType() && getName().equals(node.getName());
+}
+/**
+ * Localizes the contents of this node and all descendant nodes,
+ * such that this node is no longer dependent on its original
+ * document in order to generate its contents. This node and all
+ * descendant nodes become unfragmented and share a new
+ * document.
+ */
+protected void localizeContents() {
- /**
- * Localizes the contents of this node and all descendant nodes,
- * such that this node is no longer dependent on its original
- * document in order to generate its contents. This node and all
- * descendant nodes become unfragmented and share a new
- * document.
- */
- protected void localizeContents() {
+ DOMNode clone= (DOMNode)clone();
+ shareContents(clone);
- DOMNode clone = (DOMNode) clone();
- shareContents(clone);
+}
+/**
+ * Returns a new empty <code>DOMNode</code> for this instance.
+ */
+protected abstract DOMNode newDOMNode();
+/**
+ * Normalizes this <code>DOMNode</code>'s source positions to include whitespace preceeding
+ * the node on the line on which the node starts, and all whitespace after the node up to
+ * the next node's start
+ */
+void normalize(ILineStartFinder finder) {
+ if (getPreviousNode() == null)
+ normalizeStartPosition(getParentEndDeclaration(), finder);
+ // Set the children's position
+ if (canHaveChildren()) {
+ Enumeration children = getChildren();
+ while(children.hasMoreElements())
+ ((DOMNode)children.nextElement()).normalize(finder);
}
- /**
- * Returns a new empty <code>DOMNode</code> for this instance.
- */
- protected abstract DOMNode newDOMNode();
- /**
- * Normalizes this <code>DOMNode</code>'s source positions to include whitespace preceeding
- * the node on the line on which the node starts, and all whitespace after the node up to
- * the next node's start
- */
- void normalize(ILineStartFinder finder) {
- if (getPreviousNode() == null)
- normalizeStartPosition(getParentEndDeclaration(), finder);
-
- // Set the children's position
- if (canHaveChildren()) {
- Enumeration children = getChildren();
- while (children.hasMoreElements())
- ((DOMNode) children.nextElement()).normalize(finder);
+ normalizeEndPosition(finder, (DOMNode)getNextNode());
+}
+/**
+ * Normalizes this <code>DOMNode</code>'s end position.
+ */
+void normalizeEndPosition(ILineStartFinder finder, DOMNode next) {
+ if (next == null) {
+ // this node's end position includes all of the characters up
+ // to the end of the enclosing node
+ DOMNode parent = (DOMNode) getParent();
+ if (parent == null || parent instanceof DOMCompilationUnit) {
+ setSourceRangeEnd(fDocument.length - 1);
+ } else {
+ // parent is a type
+ setSourceRangeEnd(((DOMType)parent).getCloseBodyPosition() - 1);
}
-
- normalizeEndPosition(finder, (DOMNode) getNextNode());
+ } else {
+ // this node's end position is just before the start of the next node
+ next.normalizeStartPosition(getEndPosition(), finder);
+ setSourceRangeEnd(next.getStartPosition() - 1);
}
-
- /**
- * Normalizes this <code>DOMNode</code>'s end position.
- */
- void normalizeEndPosition(ILineStartFinder finder, DOMNode next) {
- if (next == null) {
- // this node's end position includes all of the characters up
- // to the end of the enclosing node
- DOMNode parent = (DOMNode) getParent();
- if (parent == null || parent instanceof DOMCompilationUnit) {
- setSourceRangeEnd(fDocument.length - 1);
- } else {
- // parent is a type
- setSourceRangeEnd(((DOMType) parent).getCloseBodyPosition() - 1);
- }
- } else {
- // this node's end position is just before the start of the next node
- next.normalizeStartPosition(getEndPosition(), finder);
- setSourceRangeEnd(next.getStartPosition() - 1);
+}
+/**
+ * Normalizes this <code>DOMNode</code>'s start position.
+ */
+void normalizeStartPosition(int previousEnd, ILineStartFinder finder) {
+ int nodeStart = getStartPosition();
+ int lineStart = finder.getLineStart(nodeStart);
+ if (nodeStart > lineStart && (lineStart > previousEnd || (previousEnd == 0 && lineStart == 0)))
+ setStartPosition(lineStart);
+}
+/**
+ * Offsets all the source indexes in this node by the given amount.
+ */
+protected void offset(int offset) {
+ offsetRange(fNameRange, offset);
+ offsetRange(fSourceRange, offset);
+}
+/**
+ * Offsets the source range by the given amount
+ */
+protected void offsetRange(int[] range, int offset) {
+ for (int i= 0; i < range.length; i++) {
+ range[i]+=offset;
+ if (range[i] < 0) {
+ range[i]= -1;
}
}
-
- /**
- * Normalizes this <code>DOMNode</code>'s start position.
- */
- void normalizeStartPosition(int previousEnd, ILineStartFinder finder) {
- int nodeStart = getStartPosition();
- int lineStart = finder.getLineStart(nodeStart);
- if (nodeStart > lineStart
- && (lineStart > previousEnd || (previousEnd == 0 && lineStart == 0)))
- setStartPosition(lineStart);
+}
+/**
+ * Returns a copy of the given range.
+ */
+protected int[] rangeCopy(int[] range) {
+ int[] copy= new int[range.length];
+ for (int i= 0; i < range.length; i++) {
+ copy[i]= range[i];
}
+ return copy;
+}
+/**
+ * Separates this node from its parent and siblings, maintaining any ties that
+ * this node has to the underlying document fragment.
+ *
+ * <p>When a child is removed, its parent is fragmented such that it properly
+ * generates its contents.
+ *
+ * @see IDOMNode#remove()
+ */
+public void remove() {
- /**
- * Offsets all the source indexes in this node by the given amount.
- */
- protected void offset(int offset) {
- offsetRange(fNameRange, offset);
- offsetRange(fSourceRange, offset);
+ if (fParent != null) {
+ fParent.fragment();
}
-
- /**
- * Offsets the source range by the given amount
- */
- protected void offsetRange(int[] range, int offset) {
- for (int i = 0; i < range.length; i++) {
- range[i] += offset;
- if (range[i] < 0) {
- range[i] = -1;
- }
- }
+
+ // link siblings
+ if (fNextNode != null) {
+ fNextNode.fPreviousNode= fPreviousNode;
}
-
- /**
- * Returns a copy of the given range.
- */
- protected int[] rangeCopy(int[] range) {
- int[] copy = new int[range.length];
- for (int i = 0; i < range.length; i++) {
- copy[i] = range[i];
- }
- return copy;
+ if (fPreviousNode != null) {
+ fPreviousNode.fNextNode= fNextNode;
}
-
- /**
- * Separates this node from its parent and siblings, maintaining any ties that
- * this node has to the underlying document fragment.
- *
- * <p>When a child is removed, its parent is fragmented such that it properly
- * generates its contents.
- *
- * @see IDOMNode#remove()
- */
- public void remove() {
-
- if (fParent != null) {
- fParent.fragment();
+ // fix parent's pointers
+ if (fParent != null) {
+ if (fParent.fFirstChild == this) {
+ fParent.fFirstChild= fNextNode;
}
-
- // link siblings
- if (fNextNode != null) {
- fNextNode.fPreviousNode = fPreviousNode;
+ if (fParent.fLastChild == this) {
+ fParent.fLastChild= fPreviousNode;
}
- if (fPreviousNode != null) {
- fPreviousNode.fNextNode = fNextNode;
- }
- // fix parent's pointers
- if (fParent != null) {
- if (fParent.fFirstChild == this) {
- fParent.fFirstChild = fNextNode;
- }
- if (fParent.fLastChild == this) {
- fParent.fLastChild = fPreviousNode;
- }
- }
- // remove myself
- fParent = null;
- fNextNode = null;
- fPreviousNode = null;
- }
-
- /**
- * Sets the specified mask of this node's state mask on or off
- * based on the boolean value - true -> on, false -> off.
- */
- protected void setMask(int mask, boolean on) {
- if (on) {
- fStateMask |= mask;
- } else {
- fStateMask &= ~mask;
- }
- }
-
- /**
- * @see IDOMNode#setName
- */
- public void setName(String name) {
- fName = name;
- setNameAltered(true);
- fragment();
- }
-
- /**
- * Sets the state of this node as having
- * its name attribute altered from the original
- * document contents.
- */
- protected void setNameAltered(boolean altered) {
- setMask(MASK_NAME_ALTERED, altered);
- }
-
- /**
- * Sets the original position of the last character of this node's contents
- * in its document. This method is only used during DOM creation while
- * normalizing the source range of each node.
- */
- protected void setSourceRangeEnd(int end) {
- fSourceRange[1] = end;
}
-
- /**
- * Sets the original position of the first character of this node's contents
- * in its document. This method is only used during DOM creation while
- * normalizing the source range of each node.
- */
- protected void setStartPosition(int start) {
- fSourceRange[0] = start;
+ // remove myself
+ fParent= null;
+ fNextNode= null;
+ fPreviousNode= null;
+}
+/**
+ * Sets the specified mask of this node's state mask on or off
+ * based on the boolean value - true -> on, false -> off.
+ */
+protected void setMask(int mask, boolean on) {
+ if (on) {
+ fStateMask |= mask;
+ } else {
+ fStateMask &= ~mask;
}
-
- /**
- * Sets the contents of this node and descendant nodes to be the
- * (identical) contents of the given node and its descendants. This
- * does not effect this node's parent and sibling configuration,
- * only the contents of this node. This is used only to localize
- * the contents of this node.
- */
- protected void shareContents(DOMNode node) {
- fDocument = node.fDocument;
- fIsFragmented = node.fIsFragmented;
- fName = node.fName;
- fNameRange = rangeCopy(node.fNameRange);
- fSourceRange = rangeCopy(node.fSourceRange);
- fStateMask = node.fStateMask;
-
- if (canHaveChildren()) {
- Enumeration myChildren = getChildren();
- Enumeration otherChildren = node.getChildren();
- DOMNode myChild, otherChild;
- while (myChildren.hasMoreElements()) {
- myChild = (DOMNode) myChildren.nextElement();
- otherChild = (DOMNode) otherChildren.nextElement();
- myChild.shareContents(otherChild);
- }
+}
+/**
+ * @see IDOMNode#setName
+ */
+public void setName(String name) {
+ fName= name;
+ setNameAltered(true);
+ fragment();
+}
+/**
+ * Sets the state of this node as having
+ * its name attribute altered from the original
+ * document contents.
+ */
+protected void setNameAltered(boolean altered) {
+ setMask(MASK_NAME_ALTERED, altered);
+}
+/**
+ * Sets the original position of the last character of this node's contents
+ * in its document. This method is only used during DOM creation while
+ * normalizing the source range of each node.
+ */
+protected void setSourceRangeEnd(int end) {
+ fSourceRange[1]= end;
+}
+/**
+ * Sets the original position of the first character of this node's contents
+ * in its document. This method is only used during DOM creation while
+ * normalizing the source range of each node.
+ */
+protected void setStartPosition(int start) {
+ fSourceRange[0]= start;
+}
+/**
+ * Sets the contents of this node and descendant nodes to be the
+ * (identical) contents of the given node and its descendants. This
+ * does not effect this node's parent and sibling configuration,
+ * only the contents of this node. This is used only to localize
+ * the contents of this node.
+ */
+protected void shareContents(DOMNode node) {
+ fDocument= node.fDocument;
+ fIsFragmented= node.fIsFragmented;
+ fName= node.fName;
+ fNameRange= rangeCopy(node.fNameRange);
+ fSourceRange= rangeCopy(node.fSourceRange);
+ fStateMask= node.fStateMask;
+
+
+ if (canHaveChildren()) {
+ Enumeration myChildren= getChildren();
+ Enumeration otherChildren= node.getChildren();
+ DOMNode myChild, otherChild;
+ while (myChildren.hasMoreElements()) {
+ myChild= (DOMNode)myChildren.nextElement();
+ otherChild= (DOMNode)otherChildren.nextElement();
+ myChild.shareContents(otherChild);
}
}
-
- /**
- * Returns a <code>String</code> representing this node - for Debug purposes only.
- */
- public abstract String toString();
+}
+/**
+ * Returns a <code>String</code> representing this node - for Debug purposes only.
+ */
+public abstract String toString();
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMPackage.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMPackage.java
index d0698c20ac..ca015deea4 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMPackage.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMPackage.java
@@ -22,125 +22,116 @@ import org.eclipse.jdt.internal.core.util.*;
*/
class DOMPackage extends DOMNode implements IDOMPackage {
- /**
- * Creates an empty PACKAGE node.
- */
- DOMPackage() {
- setMask(MASK_DETAILED_SOURCE_INDEXES, true);
- }
-
- /**
- * Creates a new simple PACKAGE document fragment on the given range of the document.
- *
- * @param document - the document containing this node's original contents
- * @param sourceRange - a two element array of integers describing the
- * entire inclusive source range of this node within its document.
- * Contents start on and include the character at the first position.
- * Contents end on and include the character at the last position.
- * An array of -1's indicates this node's contents do not exist
- * in the document.
- * @param name - the identifier portion of the name of this node, or
- * <code>null</code> if this node does not have a name
- */
- DOMPackage(char[] document, int[] sourceRange, String name) {
- super(document, sourceRange, name, new int[] { -1, -1 });
- setMask(MASK_DETAILED_SOURCE_INDEXES, false);
- }
-
- /**
- * Creates a new detailed PACKAGE document fragment on the given range of the document.
- *
- * @param document - the document containing this node's original contents
- * @param sourceRange - a two element array of integers describing the
- * entire inclusive source range of this node within its document.
- * Contents start on and include the character at the first position.
- * Contents end on and include the character at the last position.
- * An array of -1's indicates this node's contents do not exist
- * in the document.
- * @param name - the identifier portion of the name of this node, or
- * <code>null</code> if this node does not have a name
- * @param nameRange - a two element array of integers describing the
- * entire inclusive source range of this node's name within its document,
- * including any array qualifiers that might immediately follow the name
- * or -1's if this node does not have a name.
- */
- DOMPackage(char[] document, int[] sourceRange, String name, int[] nameRange) {
- super(document, sourceRange, name, nameRange);
- setMask(MASK_DETAILED_SOURCE_INDEXES, true);
- }
-
- /**
- * @see DOMNode#appendFragmentedContents(CharArrayBuffer)
- */
- protected void appendFragmentedContents(CharArrayBuffer buffer) {
- if (fNameRange[0] < 0) {
- buffer.append("package ").append(fName).append(';').append(
- JavaModelManager.LINE_SEPARATOR);
- } else {
- buffer
- .append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0])
- .append(fName)
- .append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]);
- }
- }
-
- /**
- * @see IDOMNode#getContents()
- */
- public String getContents() {
- if (fName == null) {
- return null;
- } else {
- return super.getContents();
- }
- }
-
- /**
- * @see DOMNode#getDetailedNode()
- */
- protected DOMNode getDetailedNode() {
- return (DOMNode) getFactory().createPackage(getContents());
- }
-
- /**
- * @see IDOMNode#getJavaElement
- */
- public IJavaElement getJavaElement(IJavaElement parent)
- throws IllegalArgumentException {
- if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) {
- return ((ICompilationUnit) parent).getPackageDeclaration(getName());
- } else {
- throw new IllegalArgumentException("Illegal parent argument");
- }
- }
-
- /**
- * @see IDOMNode#getNodeType()
- */
- public int getNodeType() {
- return IDOMNode.PACKAGE;
- }
-
- /**
- * @see DOMNode
- */
- protected DOMNode newDOMNode() {
- return new DOMPackage();
+/**
+ * Creates an empty PACKAGE node.
+ */
+DOMPackage() {
+ setMask(MASK_DETAILED_SOURCE_INDEXES, true);
+}
+/**
+ * Creates a new simple PACKAGE document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this node, or
+ * <code>null</code> if this node does not have a name
+ */
+DOMPackage(char[] document, int[] sourceRange, String name) {
+ super(document, sourceRange, name, new int[] {-1, -1});
+ setMask(MASK_DETAILED_SOURCE_INDEXES, false);
+}
+/**
+ * Creates a new detailed PACKAGE document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this node, or
+ * <code>null</code> if this node does not have a name
+ * @param nameRange - a two element array of integers describing the
+ * entire inclusive source range of this node's name within its document,
+ * including any array qualifiers that might immediately follow the name
+ * or -1's if this node does not have a name.
+ */
+DOMPackage(char[] document, int[] sourceRange, String name, int[] nameRange) {
+ super(document, sourceRange, name, nameRange);
+ setMask(MASK_DETAILED_SOURCE_INDEXES, true);
+}
+/**
+ * @see DOMNode#appendFragmentedContents(CharArrayBuffer)
+ */
+protected void appendFragmentedContents(CharArrayBuffer buffer) {
+ if (fNameRange[0] < 0) {
+ buffer
+ .append("package ")
+ .append(fName)
+ .append(';')
+ .append(JavaModelManager.LINE_SEPARATOR);
+ } else {
+ buffer
+ .append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0])
+ .append(fName)
+ .append(fDocument, fNameRange[1] + 1, fSourceRange[1] - fNameRange[1]);
}
-
- /**
- * @see IDOMNode#setName
- */
- public void setName(String name) {
- becomeDetailed();
- super.setName(name);
+}
+/**
+ * @see IDOMNode#getContents()
+ */
+public String getContents() {
+ if (fName == null) {
+ return null;
+ } else {
+ return super.getContents();
}
-
- /**
- * @see IDOMNode#toString()
- */
- public String toString() {
- return "PACKAGE: " + getName();
+}
+/**
+ * @see DOMNode#getDetailedNode()
+ */
+protected DOMNode getDetailedNode() {
+ return (DOMNode)getFactory().createPackage(getContents());
+}
+/**
+ * @see IDOMNode#getJavaElement
+ */
+public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException {
+ if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) {
+ return ((ICompilationUnit)parent).getPackageDeclaration(getName());
+ } else {
+ throw new IllegalArgumentException("Illegal parent argument");
}
-
+}
+/**
+ * @see IDOMNode#getNodeType()
+ */
+public int getNodeType() {
+ return IDOMNode.PACKAGE;
+}
+/**
+ * @see DOMNode
+ */
+protected DOMNode newDOMNode() {
+ return new DOMPackage();
+}
+/**
+ * @see IDOMNode#setName
+ */
+public void setName(String name) {
+ becomeDetailed();
+ super.setName(name);
+}
+/**
+ * @see IDOMNode#toString()
+ */
+public String toString() {
+ return "PACKAGE: " + getName();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMType.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMType.java
index 035be3ddcf..f4631c72c8 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMType.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/DOMType.java
@@ -24,9 +24,8 @@ import java.util.Enumeration;
* @see IDOMType
* @see DOMNode
*/
-
-/* package */
-class DOMType extends DOMMember implements IDOMType {
+
+/* package */ class DOMType extends DOMMember implements IDOMType {
/**
* The 'class' or 'interface' keyword if altered
@@ -38,7 +37,7 @@ class DOMType extends DOMMember implements IDOMType {
* The original inclusive source range of the 'class'
* or 'interface' keyword in the document.
*/
- protected int[] fTypeRange;
+ protected int[] fTypeRange;
/**
* The superclass name for the class declaration
@@ -53,21 +52,22 @@ class DOMType extends DOMMember implements IDOMType {
* name in the document, or -1's of no superclass was
* specified in the document.
*/
- protected int[] fSuperclassRange;
+ protected int[] fSuperclassRange;
+
/**
* The original inclusive souce range of the 'extends' keyword
* in the document, including surrounding whitespace, or -1's if
* the keyword was not present in the document.
*/
- protected int[] fExtendsRange;
+ protected int[] fExtendsRange;
/**
* The original inclusive souce range of the 'implements' keyword
* in the document, including surrounding whitespace, or -1's if
* the keyword was not present in the document.
- */
- protected int[] fImplementsRange;
+ */
+ protected int[] fImplementsRange;
/**
* The comma delimited list of interfaces this type implements
@@ -82,14 +82,16 @@ class DOMType extends DOMMember implements IDOMType {
* type implements or extends, not including any surrouding whitespace.
* If the document did not specify interfaces, this array contains -1's.
*/
- protected int[] fInterfacesRange;
+ protected int[] fInterfacesRange;
+
+
/**
* The original source range of the first character following the
* type name superclass name, or interface list, up to and including
* the first character before the first type member.
- */
- protected int[] fOpenBodyRange;
+ */
+ protected int[] fOpenBodyRange;
/**
* The original source range of the first new line or non whitespace
@@ -97,668 +99,542 @@ class DOMType extends DOMMember implements IDOMType {
* and including the first character before the next node (if there are
* no following nodes, the range ends at the position of the last
* charater in the document).
- */
- protected int[] fCloseBodyRange;
+ */
+ protected int[] fCloseBodyRange;
+
/**
* A list of interfaces this type extends or implements.
* <code>null</code> when this type does not extend
* or implement any interfaces.
*/
- protected String[] fSuperInterfaces = new String[0];
- /**
- * Constructs an empty type node.
- */
- DOMType() {
-
- }
-
- /**
- * Creates a new detailed TYPE document fragment on the given range of the document.
- *
- * @param document - the document containing this node's original contents
- * @param sourceRange - a two element array of integers describing the
- * entire inclusive source range of this node within its document.
- * Contents start on and include the character at the first position.
- * Contents end on and include the character at the last position.
- * An array of -1's indicates this node's contents do not exist
- * in the document.
- * @param name - the identifier portion of the name of this node, or
- * <code>null</code> if this node does not have a name
- * @param nameRange - a two element array of integers describing the
- * entire inclusive source range of this node's name within its document,
- * including any array qualifiers that might immediately follow the name
- * or -1's if this node does not have a name.
- * @param commentRange - a two element array describing the comments that precede
- * the member declaration. The first matches the start of this node's
- * sourceRange, and the second is the new-line or first non-whitespace
- * character following the last comment. If no comments are present,
- * this array contains two -1's.
- * @param flags - an integer representing the modifiers for this member. The
- * integer can be analyzed with org.eclipse.jdt.core.Flags
- * @param modifierRange - a two element array describing the location of
- * modifiers for this member within its source range. The first integer
- * is the first character of the first modifier for this member, and
- * the second integer is the last whitespace character preceeding the
- * next part of this member declaration. If there are no modifiers present
- * in this node's source code (i.e. default protection), this array
- * contains two -1's.
- * @param typeRange - a two element array describing the location of the 'class'
- * or 'interface' keyword in the type declaration - first and last character
- * positions.
- * @param superclassRange - a two element array describing the location of the
- * superclass name in the type declaration - first and last character
- * positions or two -1's if a superclass is not present in the document.
- * @param extendsRange - a two element array describing the location of the
- * 'extends' keyword in the type declaration, including any surrounding
- * whitespace, or -1's if the 'extends' keyword is not present in the document.
- * @param implementsList - an array of names of the interfaces this type implements
- * or extends, or <code>null</code> if this type does not implement or extend
- * any interfaces.
- * @param implementsRange - a two element array describing the location of the
- * comment delimited list of interfaces this type implements or extends,
- * not including any surrounding whitespace, or -1's if no interface list
- * is present in the document.
- * @param implementsKeywordRange - a two element array describing the location of the
- * 'implements' keyword, including any surrounding whitespace, or -1's if no
- * 'implements' keyword is present in the document.
- * @param openBodyRange - a two element array describing the location of the
- * open brace of the type's body and whitespace following the type declaration
- * and preceeding the first member in the type.
- * @param closeBodyRange - a two element array describing the source range of the
- * first new line or non whitespace character preceeding the close brace of the
- * type's body, up to the close brace
- * @param isClass - true is the type is a class, false if it is an interface
- */
- DOMType(
- char[] document,
- int[] sourceRange,
- String name,
- int[] nameRange,
- int[] commentRange,
- int flags,
- int[] modifierRange,
- int[] typeRange,
- int[] superclassRange,
- int[] extendsRange,
- String[] implementsList,
- int[] implementsRange,
- int[] implementsKeywordRange,
- int[] openBodyRange,
- int[] closeBodyRange,
- boolean isClass) {
- super(
- document,
- sourceRange,
- name,
- nameRange,
- commentRange,
- flags,
- modifierRange);
-
- fTypeRange = typeRange;
- setMask(MASK_TYPE_IS_CLASS, isClass);
+ protected String[] fSuperInterfaces= new String[0];
+/**
+ * Constructs an empty type node.
+ */
+DOMType() {
- fExtendsRange = extendsRange;
- fImplementsRange = implementsKeywordRange;
- fSuperclassRange = superclassRange;
- fInterfacesRange = implementsRange;
- fCloseBodyRange = closeBodyRange;
- setMask(MASK_TYPE_HAS_SUPERCLASS, superclassRange[0] > 0);
- setMask(MASK_TYPE_HAS_INTERFACES, implementsList != null);
- fSuperInterfaces = implementsList;
- fOpenBodyRange = openBodyRange;
- fCloseBodyRange = closeBodyRange;
- setMask(MASK_DETAILED_SOURCE_INDEXES, true);
+}
+/**
+ * Creates a new detailed TYPE document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this node, or
+ * <code>null</code> if this node does not have a name
+ * @param nameRange - a two element array of integers describing the
+ * entire inclusive source range of this node's name within its document,
+ * including any array qualifiers that might immediately follow the name
+ * or -1's if this node does not have a name.
+ * @param commentRange - a two element array describing the comments that precede
+ * the member declaration. The first matches the start of this node's
+ * sourceRange, and the second is the new-line or first non-whitespace
+ * character following the last comment. If no comments are present,
+ * this array contains two -1's.
+ * @param flags - an integer representing the modifiers for this member. The
+ * integer can be analyzed with org.eclipse.jdt.core.Flags
+ * @param modifierRange - a two element array describing the location of
+ * modifiers for this member within its source range. The first integer
+ * is the first character of the first modifier for this member, and
+ * the second integer is the last whitespace character preceeding the
+ * next part of this member declaration. If there are no modifiers present
+ * in this node's source code (i.e. default protection), this array
+ * contains two -1's.
+ * @param typeRange - a two element array describing the location of the 'class'
+ * or 'interface' keyword in the type declaration - first and last character
+ * positions.
+ * @param superclassRange - a two element array describing the location of the
+ * superclass name in the type declaration - first and last character
+ * positions or two -1's if a superclass is not present in the document.
+ * @param extendsRange - a two element array describing the location of the
+ * 'extends' keyword in the type declaration, including any surrounding
+ * whitespace, or -1's if the 'extends' keyword is not present in the document.
+ * @param implementsList - an array of names of the interfaces this type implements
+ * or extends, or <code>null</code> if this type does not implement or extend
+ * any interfaces.
+ * @param implementsRange - a two element array describing the location of the
+ * comment delimited list of interfaces this type implements or extends,
+ * not including any surrounding whitespace, or -1's if no interface list
+ * is present in the document.
+ * @param implementsKeywordRange - a two element array describing the location of the
+ * 'implements' keyword, including any surrounding whitespace, or -1's if no
+ * 'implements' keyword is present in the document.
+ * @param openBodyRange - a two element array describing the location of the
+ * open brace of the type's body and whitespace following the type declaration
+ * and preceeding the first member in the type.
+ * @param closeBodyRange - a two element array describing the source range of the
+ * first new line or non whitespace character preceeding the close brace of the
+ * type's body, up to the close brace
+ * @param isClass - true is the type is a class, false if it is an interface
+ */
+DOMType(char[] document, int[] sourceRange, String name, int[] nameRange, int[] commentRange, int flags, int[] modifierRange, int[] typeRange, int[] superclassRange, int[] extendsRange, String[] implementsList, int[] implementsRange, int[] implementsKeywordRange, int[] openBodyRange, int[] closeBodyRange, boolean isClass) {
+ super(document, sourceRange, name, nameRange, commentRange, flags, modifierRange);
+
+ fTypeRange= typeRange;
+ setMask(MASK_TYPE_IS_CLASS, isClass);
+
+ fExtendsRange= extendsRange;
+ fImplementsRange= implementsKeywordRange;
+ fSuperclassRange= superclassRange;
+ fInterfacesRange= implementsRange;
+ fCloseBodyRange= closeBodyRange;
+ setMask(MASK_TYPE_HAS_SUPERCLASS, superclassRange[0] > 0);
+ setMask(MASK_TYPE_HAS_INTERFACES, implementsList != null);
+ fSuperInterfaces= implementsList;
+ fOpenBodyRange= openBodyRange;
+ fCloseBodyRange= closeBodyRange;
+ setMask(MASK_DETAILED_SOURCE_INDEXES, true);
+}
+/**
+ * Creates a new simple TYPE document fragment on the given range of the document.
+ *
+ * @param document - the document containing this node's original contents
+ * @param sourceRange - a two element array of integers describing the
+ * entire inclusive source range of this node within its document.
+ * Contents start on and include the character at the first position.
+ * Contents end on and include the character at the last position.
+ * An array of -1's indicates this node's contents do not exist
+ * in the document.
+ * @param name - the identifier portion of the name of this node, or
+ * <code>null</code> if this node does not have a name
+ * @param nameRange - a two element array of integers describing the
+ * entire inclusive source range of this node's name within its document,
+ * including any array qualifiers that might immediately follow the name
+ * or -1's if this node does not have a name.
+ * @param flags - an integer representing the modifiers for this member. The
+ * integer can be analyzed with org.eclipse.jdt.core.Flags
+ * @param implementsList - an array of names of the interfaces this type implements
+ * or extends, or <code>null</code> if this type does not implement or extend
+ * any interfaces.
+ * @param isClass - true is the type is a class, false if it is an interface
+ */
+DOMType(char[] document, int[] sourceRange, String name, int[] nameRange, int flags, String[] implementsList, boolean isClass) {
+ this(document, sourceRange, name, nameRange, new int[] {-1, -1}, flags,
+ new int[] {-1, -1}, new int[] {-1, -1}, new int[] {-1, -1}, new int[] {-1, -1},
+ implementsList, new int[] {-1, -1}, new int[] {-1, -1}, new int[] {-1, -1}, new int[] {sourceRange[1], sourceRange[1]}, isClass);
+ setMask(MASK_DETAILED_SOURCE_INDEXES, false);
+}
+/**
+ * @see IDOMType#addSuperInterface(String)
+ */
+public void addSuperInterface(String name) throws IllegalArgumentException {
+ if (name == null) {
+ throw new IllegalArgumentException("Cannot add null interface");
}
-
- /**
- * Creates a new simple TYPE document fragment on the given range of the document.
- *
- * @param document - the document containing this node's original contents
- * @param sourceRange - a two element array of integers describing the
- * entire inclusive source range of this node within its document.
- * Contents start on and include the character at the first position.
- * Contents end on and include the character at the last position.
- * An array of -1's indicates this node's contents do not exist
- * in the document.
- * @param name - the identifier portion of the name of this node, or
- * <code>null</code> if this node does not have a name
- * @param nameRange - a two element array of integers describing the
- * entire inclusive source range of this node's name within its document,
- * including any array qualifiers that might immediately follow the name
- * or -1's if this node does not have a name.
- * @param flags - an integer representing the modifiers for this member. The
- * integer can be analyzed with org.eclipse.jdt.core.Flags
- * @param implementsList - an array of names of the interfaces this type implements
- * or extends, or <code>null</code> if this type does not implement or extend
- * any interfaces.
- * @param isClass - true is the type is a class, false if it is an interface
- */
- DOMType(
- char[] document,
- int[] sourceRange,
- String name,
- int[] nameRange,
- int flags,
- String[] implementsList,
- boolean isClass) {
- this(
- document,
- sourceRange,
- name,
- nameRange,
- new int[] { -1, -1 },
- flags,
- new int[] { -1, -1 },
- new int[] { -1, -1 },
- new int[] { -1, -1 },
- new int[] { -1, -1 },
- implementsList,
- new int[] { -1, -1 },
- new int[] { -1, -1 },
- new int[] { -1, -1 },
- new int[] { sourceRange[1], sourceRange[1] },
- isClass);
- setMask(MASK_DETAILED_SOURCE_INDEXES, false);
+ if (fSuperInterfaces == null) {
+ fSuperInterfaces= new String[1];
+ fSuperInterfaces[0]= name;
+ } else {
+ fSuperInterfaces= appendString(fSuperInterfaces, name);
}
-
- /**
- * @see IDOMType#addSuperInterface(String)
- */
- public void addSuperInterface(String name) throws IllegalArgumentException {
- if (name == null) {
- throw new IllegalArgumentException("Cannot add null interface");
- }
- if (fSuperInterfaces == null) {
- fSuperInterfaces = new String[1];
- fSuperInterfaces[0] = name;
- } else {
- fSuperInterfaces = appendString(fSuperInterfaces, name);
- }
- setSuperInterfaces(fSuperInterfaces);
- }
-
- /**
- * @see DOMMember#appendMemberBodyContents(CharArrayBuffer)
- */
- protected void appendMemberBodyContents(CharArrayBuffer buffer) {
- buffer.append(
- fDocument,
- fOpenBodyRange[0],
- fOpenBodyRange[1] + 1 - fOpenBodyRange[0]);
- appendContentsOfChildren(buffer);
- buffer.append(
- fDocument,
- fCloseBodyRange[0],
- fCloseBodyRange[1] + 1 - fCloseBodyRange[0]);
- buffer.append(
- fDocument,
- fCloseBodyRange[1] + 1,
- fSourceRange[1] - fCloseBodyRange[1]);
+ setSuperInterfaces(fSuperInterfaces);
+}
+/**
+ * @see DOMMember#appendMemberBodyContents(CharArrayBuffer)
+ */
+protected void appendMemberBodyContents(CharArrayBuffer buffer) {
+ buffer.append(fDocument, fOpenBodyRange[0], fOpenBodyRange[1] + 1 - fOpenBodyRange[0]);
+ appendContentsOfChildren(buffer);
+ buffer.append(fDocument, fCloseBodyRange[0], fCloseBodyRange[1] + 1 - fCloseBodyRange[0]);
+ buffer.append(fDocument, fCloseBodyRange[1] + 1, fSourceRange[1] - fCloseBodyRange[1]);
+}
+/**
+ * @see DOMMember#appendMemberDeclarationContents(CharArrayBuffer )
+ */
+protected void appendMemberDeclarationContents(CharArrayBuffer buffer) {
+
+ if (fTypeKeyword != null) {
+ buffer.append(fTypeKeyword);
+ buffer.append(fDocument, fTypeRange[1], fNameRange[0] - fTypeRange[1] );
+ } else {
+ buffer.append(fDocument, fTypeRange[0], fTypeRange[1] + 1 - fTypeRange[0]);
}
- /**
- * @see DOMMember#appendMemberDeclarationContents(CharArrayBuffer )
- */
- protected void appendMemberDeclarationContents(CharArrayBuffer buffer) {
+ buffer.append(getName());
- if (fTypeKeyword != null) {
- buffer.append(fTypeKeyword);
- buffer.append(fDocument, fTypeRange[1], fNameRange[0] - fTypeRange[1]);
- } else {
- buffer.append(fDocument, fTypeRange[0], fTypeRange[1] + 1 - fTypeRange[0]);
+ if (isClass()) {
+ boolean hasSuperclass = false, hasInterfaces = false;
+ if (getMask(MASK_TYPE_HAS_SUPERCLASS)) {
+ hasSuperclass = true;
+ if (fExtendsRange[0] < 0) {
+ buffer.append(" extends ");
+ } else {
+ buffer.append(fDocument, fExtendsRange[0], fExtendsRange[1] + 1 - fExtendsRange[0]);
+ }
+ if (fSuperclass != null) {
+ buffer.append(fSuperclass);
+ } else {
+ buffer.append(fDocument, fSuperclassRange[0], fSuperclassRange[1] + 1 - fSuperclassRange[0]);
+ }
}
-
- buffer.append(getName());
-
- if (isClass()) {
- boolean hasSuperclass = false, hasInterfaces = false;
- if (getMask(MASK_TYPE_HAS_SUPERCLASS)) {
- hasSuperclass = true;
- if (fExtendsRange[0] < 0) {
- buffer.append(" extends ");
- } else {
- buffer.append(
- fDocument,
- fExtendsRange[0],
- fExtendsRange[1] + 1 - fExtendsRange[0]);
- }
- if (fSuperclass != null) {
- buffer.append(fSuperclass);
- } else {
- buffer.append(
- fDocument,
- fSuperclassRange[0],
- fSuperclassRange[1] + 1 - fSuperclassRange[0]);
- }
+ if (getMask(MASK_TYPE_HAS_INTERFACES)) {
+ hasInterfaces = true;
+ if (fImplementsRange[0] < 0) {
+ buffer.append(" implements ");
+ } else {
+ buffer.append(fDocument, fImplementsRange[0], fImplementsRange[1] + 1 - fImplementsRange[0]);
}
- if (getMask(MASK_TYPE_HAS_INTERFACES)) {
- hasInterfaces = true;
- if (fImplementsRange[0] < 0) {
- buffer.append(" implements ");
- } else {
- buffer.append(
- fDocument,
- fImplementsRange[0],
- fImplementsRange[1] + 1 - fImplementsRange[0]);
- }
- if (fInterfaces != null) {
- buffer.append(fInterfaces);
- } else {
- buffer.append(
- fDocument,
- fInterfacesRange[0],
- fInterfacesRange[1] + 1 - fInterfacesRange[0]);
- }
+ if (fInterfaces != null) {
+ buffer.append(fInterfaces);
+ } else {
+ buffer.append(fDocument, fInterfacesRange[0], fInterfacesRange[1] + 1 - fInterfacesRange[0]);
}
- if (hasInterfaces) {
- if (fImplementsRange[0] < 0) {
- buffer.append(" ");
- } else {
- buffer.append(
- fDocument,
- fInterfacesRange[1] + 1,
- fOpenBodyRange[0] - fInterfacesRange[1] - 1);
- }
+ }
+ if (hasInterfaces) {
+ if (fImplementsRange[0] < 0) {
+ buffer.append(" ");
} else {
- if (hasSuperclass) {
- if (fSuperclassRange[0] < 0) {
- buffer.append(" ");
- } else {
- buffer.append(
- fDocument,
- fSuperclassRange[1] + 1,
- fOpenBodyRange[0] - fSuperclassRange[1] - 1);
- }
- } else {
- buffer.append(
- fDocument,
- fNameRange[1] + 1,
- fOpenBodyRange[0] - fNameRange[1] - 1);
- }
+ buffer.append(fDocument, fInterfacesRange[1] + 1, fOpenBodyRange[0] - fInterfacesRange[1] - 1);
}
} else {
- if (getMask(MASK_TYPE_HAS_INTERFACES)) {
- if (fExtendsRange[0] < 0) {
- buffer.append(" extends ");
- } else {
- buffer.append(
- fDocument,
- fExtendsRange[0],
- fExtendsRange[1] + 1 - fExtendsRange[0]);
- }
- if (fInterfaces != null) {
- buffer.append(fInterfaces);
+ if (hasSuperclass) {
+ if (fSuperclassRange[0] < 0) {
buffer.append(" ");
} else {
- buffer.append(
- fDocument,
- fInterfacesRange[0],
- fInterfacesRange[1] + 1 - fInterfacesRange[0]);
+ buffer.append(fDocument, fSuperclassRange[1] + 1, fOpenBodyRange[0] - fSuperclassRange[1] - 1);
}
} else {
- buffer.append(
- fDocument,
- fNameRange[1] + 1,
- fOpenBodyRange[0] - fNameRange[1] - 1);
+ buffer.append(fDocument, fNameRange[1] + 1, fOpenBodyRange[0] - fNameRange[1] - 1);
}
}
-
- }
-
- /**
- * @see DOMNode#appendSimpleContents(CharArrayBuffer)
- */
- protected void appendSimpleContents(CharArrayBuffer buffer) {
- // append eveything before my name
- buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]);
- // append my name
- buffer.append(fName);
-
- // append everything after my name and before my first child
- buffer.append(fDocument, fNameRange[1] + 1, fOpenBodyRange[1] - fNameRange[1]);
- // append my children
- appendContentsOfChildren(buffer);
- // append from my last child to my end
- buffer.append(
- fDocument,
- fCloseBodyRange[0],
- fSourceRange[1] - fCloseBodyRange[0] + 1);
-
- }
-
- /**
- * @see IDOMNode#canHaveChildren()
- */
- public boolean canHaveChildren() {
- return true;
- }
-
- /**
- * Returns the position of the closing brace for the body of this type.
- * This value this method returns is only valid before the type has
- * been normalized and is present only for normalization.
- */
- int getCloseBodyPosition() {
- return fCloseBodyRange[0];
- }
-
- /**
- * @see DOMNode#getDetailedNode()
- */
- protected DOMNode getDetailedNode() {
- return (DOMNode) getFactory().createType(getContents());
- }
-
- /**
- * @see DOMNode#getInsertionPosition()
- */
- public int getInsertionPosition() {
- return getCloseBodyPosition();
- }
-
- /**
- * @see IDOMNode#getJavaElement
- */
- public IJavaElement getJavaElement(IJavaElement parent)
- throws IllegalArgumentException {
- if (parent.getElementType() == IJavaElement.TYPE) {
- return ((IType) parent).getType(getName());
- } else
- if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) {
- return ((ICompilationUnit) parent).getType(getName());
+ } else {
+ if (getMask(MASK_TYPE_HAS_INTERFACES)) {
+ if (fExtendsRange[0] < 0) {
+ buffer.append(" extends ");
} else {
- throw new IllegalArgumentException("Illegal parent argument");
+ buffer.append(fDocument, fExtendsRange[0], fExtendsRange[1] + 1 - fExtendsRange[0]);
}
- }
-
- /**
- * @see DOMMember#getMemberDeclarationStartPosition()
- */
- protected int getMemberDeclarationStartPosition() {
- return fTypeRange[0];
- }
-
- /**
- * @see IDOMNode#getNodeType()
- */
- public int getNodeType() {
- return IDOMNode.TYPE;
- }
-
- /**
- * Answers the open body range end position.
- */
- int getOpenBodyEnd() {
- return fOpenBodyRange[1];
- }
-
- /**
- * @see IDOMType#getSuperclass()
- */
- public String getSuperclass() {
- becomeDetailed();
- if (getMask(MASK_TYPE_HAS_SUPERCLASS)) {
- if (fSuperclass != null) {
- return fSuperclass;
+ if (fInterfaces != null) {
+ buffer.append(fInterfaces);
+ buffer.append(" ");
} else {
- return CharArrayOps.substring(
- fDocument,
- fSuperclassRange[0],
- fSuperclassRange[1] + 1 - fSuperclassRange[0]);
+ buffer.append(fDocument, fInterfacesRange[0], fInterfacesRange[1] + 1 - fInterfacesRange[0]);
}
} else {
- return null;
+ buffer.append(fDocument, fNameRange[1] + 1, fOpenBodyRange[0] - fNameRange[1] - 1);
}
}
+
+}
+/**
+ * @see DOMNode#appendSimpleContents(CharArrayBuffer)
+ */
+protected void appendSimpleContents(CharArrayBuffer buffer) {
+ // append eveything before my name
+ buffer.append(fDocument, fSourceRange[0], fNameRange[0] - fSourceRange[0]);
+ // append my name
+ buffer.append(fName);
- /**
- * @see IDOMType#getSuperInterfaces()
- */
- public String[] getSuperInterfaces() {
- return fSuperInterfaces;
- }
-
- /**
- * @see IDOMNode
- */
- public boolean isAllowableChild(IDOMNode node) {
- if (node != null) {
- int type = node.getNodeType();
- return type == IDOMNode.TYPE
- || type == IDOMNode.FIELD
- || type == IDOMNode.METHOD
- || type == IDOMNode.INITIALIZER;
- } else {
- return false;
- }
+
+ // append everything after my name and before my first child
+ buffer.append(fDocument, fNameRange[1] + 1, fOpenBodyRange[1] - fNameRange[1]);
+ // append my children
+ appendContentsOfChildren(buffer);
+ // append from my last child to my end
+ buffer.append(fDocument, fCloseBodyRange[0], fSourceRange[1] - fCloseBodyRange[0] + 1);
- }
- /**
- * @see IDOMType#isClass()
- */
- public boolean isClass() {
- return getMask(MASK_TYPE_IS_CLASS);
+}
+/**
+ * @see IDOMNode#canHaveChildren()
+ */
+public boolean canHaveChildren() {
+ return true;
+}
+/**
+ * Returns the position of the closing brace for the body of this type.
+ * This value this method returns is only valid before the type has
+ * been normalized and is present only for normalization.
+ */
+int getCloseBodyPosition() {
+ return fCloseBodyRange[0];
+}
+/**
+ * @see DOMNode#getDetailedNode()
+ */
+protected DOMNode getDetailedNode() {
+ return (DOMNode)getFactory().createType(getContents());
+}
+/**
+ * @see DOMNode#getInsertionPosition()
+ */
+public int getInsertionPosition() {
+ return getCloseBodyPosition();
+}
+/**
+ * @see IDOMNode#getJavaElement
+ */
+public IJavaElement getJavaElement(IJavaElement parent) throws IllegalArgumentException {
+ if (parent.getElementType() == IJavaElement.TYPE) {
+ return ((IType)parent).getType(getName());
+ } else if (parent.getElementType() == IJavaElement.COMPILATION_UNIT) {
+ return ((ICompilationUnit)parent).getType(getName());
+ } else {
+ throw new IllegalArgumentException("Illegal parent argument");
}
-
- /**
- * @see DOMNode
- */
- protected DOMNode newDOMNode() {
- return new DOMType();
+}
+/**
+ * @see DOMMember#getMemberDeclarationStartPosition()
+ */
+protected int getMemberDeclarationStartPosition() {
+ return fTypeRange[0];
+}
+/**
+ * @see IDOMNode#getNodeType()
+ */
+public int getNodeType() {
+ return IDOMNode.TYPE;
+}
+/**
+ * Answers the open body range end position.
+ */
+int getOpenBodyEnd() {
+ return fOpenBodyRange[1];
+}
+/**
+ * @see IDOMType#getSuperclass()
+ */
+public String getSuperclass() {
+ becomeDetailed();
+ if (getMask(MASK_TYPE_HAS_SUPERCLASS)) {
+ if (fSuperclass != null) {
+ return fSuperclass;
+ } else {
+ return CharArrayOps.substring(fDocument, fSuperclassRange[0], fSuperclassRange[1] + 1 - fSuperclassRange[0]);
+ }
+ } else {
+ return null;
}
-
- /**
- * Normalizes this <code>DOMNode</code>'s source positions to include whitespace preceeding
- * the node on the line on which the node starts, and all whitespace after the node up to
- * the next node's start
- */
- void normalize(ILineStartFinder finder) {
- // perform final changes to the open and close body ranges
- int openBodyEnd, closeBodyStart;
- DOMNode first = (DOMNode) getFirstChild();
- closeBodyStart = fCloseBodyRange[1];
- if (isDetailed()) {
- if (first == null) {
- openBodyEnd = fCloseBodyRange[0] - 1;
+}
+/**
+ * @see IDOMType#getSuperInterfaces()
+ */
+public String[] getSuperInterfaces() {
+ return fSuperInterfaces;
+}
+/**
+ * @see IDOMNode
+ */
+public boolean isAllowableChild(IDOMNode node) {
+ if (node != null) {
+ int type= node.getNodeType();
+ return type == IDOMNode.TYPE || type == IDOMNode.FIELD|| type == IDOMNode.METHOD ||
+ type == IDOMNode.INITIALIZER;
+ } else {
+ return false;
+ }
+
+}
+/**
+ * @see IDOMType#isClass()
+ */
+public boolean isClass() {
+ return getMask(MASK_TYPE_IS_CLASS);
+}
+/**
+ * @see DOMNode
+ */
+protected DOMNode newDOMNode() {
+ return new DOMType();
+}
+/**
+ * Normalizes this <code>DOMNode</code>'s source positions to include whitespace preceeding
+ * the node on the line on which the node starts, and all whitespace after the node up to
+ * the next node's start
+ */
+void normalize(ILineStartFinder finder) {
+ // perform final changes to the open and close body ranges
+ int openBodyEnd, closeBodyStart;
+ DOMNode first = (DOMNode) getFirstChild();
+ closeBodyStart = fCloseBodyRange[1];
+ if (isDetailed()) {
+ if (first == null) {
+ openBodyEnd = fCloseBodyRange[0] - 1;
+ } else {
+ openBodyEnd = first.getStartPosition();
+ int lineStart = finder.getLineStart(openBodyEnd);
+ openBodyEnd--;
+ if (lineStart > fOpenBodyRange[0])
+ openBodyEnd = lineStart - 1;
+ }
+ } else {
+ if (first != null) {
+ // look for the open body
+ openBodyEnd= CharArrayOps.indexOf('{', fDocument, fNameRange[1] + 1);
+ if (openBodyEnd < 0 || openBodyEnd >= first.getStartPosition()) {
+ openBodyEnd= first.getStartPosition() - 1;
} else {
- openBodyEnd = first.getStartPosition();
- int lineStart = finder.getLineStart(openBodyEnd);
- openBodyEnd--;
- if (lineStart > fOpenBodyRange[0])
+ int lineStart = finder.getLineStart(first.getStartPosition());
+ if (lineStart > openBodyEnd) {
openBodyEnd = lineStart - 1;
- }
- } else {
- if (first != null) {
- // look for the open body
- openBodyEnd = CharArrayOps.indexOf('{', fDocument, fNameRange[1] + 1);
- if (openBodyEnd < 0 || openBodyEnd >= first.getStartPosition()) {
- openBodyEnd = first.getStartPosition() - 1;
} else {
- int lineStart = finder.getLineStart(first.getStartPosition());
- if (lineStart > openBodyEnd) {
- openBodyEnd = lineStart - 1;
- } else {
- openBodyEnd = first.getStartPosition() - 1;
- }
+ openBodyEnd = first.getStartPosition() - 1;
}
- if (fDocument[closeBodyStart] != '}') {
- // look for the body end
- Scanner scanner = new Scanner();
- scanner.setSourceBuffer(
- CharArrayOps.subarray(
- fDocument,
- fLastChild.getEndPosition() + 1,
- closeBodyStart - fLastChild.getEndPosition() + 1));
-
- try {
- int currentToken = scanner.getNextToken();
- while (currentToken != TerminalSymbols.TokenNameRBRACE
- && currentToken != TerminalSymbols.TokenNameEOF) {
- currentToken = scanner.getNextToken();
- }
- if (currentToken == TerminalSymbols.TokenNameRBRACE) {
- closeBodyStart = fLastChild.getEndPosition() + scanner.currentPosition;
- }
- } catch (InvalidInputException e) {
- // leave closeBodyStart as is
+ }
+ if (fDocument[closeBodyStart] != '}') {
+ // look for the body end
+ Scanner scanner = new Scanner();
+ scanner.setSourceBuffer(CharArrayOps.subarray(fDocument, fLastChild.getEndPosition() + 1, closeBodyStart - fLastChild.getEndPosition() + 1));
+
+ try {
+ int currentToken = scanner.getNextToken();
+ while(currentToken != TerminalSymbols.TokenNameRBRACE &&
+ currentToken != TerminalSymbols.TokenNameEOF) {
+ currentToken = scanner.getNextToken();
+ }
+ if(currentToken == TerminalSymbols.TokenNameRBRACE) {
+ closeBodyStart = fLastChild.getEndPosition() + scanner.currentPosition;
}
-
}
- } else {
- openBodyEnd = fCloseBodyRange[0] - 1;
+ catch(InvalidInputException e) {
+ // leave closeBodyStart as is
+ }
+
}
- }
- setOpenBodyRangeEnd(openBodyEnd);
- setCloseBodyRangeStart(closeBodyStart);
- super.normalize(finder);
- }
-
- /**
- * Offsets all the source indexes in this node by the given amount.
- */
- protected void offset(int offset) {
- super.offset(offset);
- offsetRange(fCloseBodyRange, offset);
- offsetRange(fExtendsRange, offset);
- offsetRange(fImplementsRange, offset);
- offsetRange(fInterfacesRange, offset);
- offsetRange(fOpenBodyRange, offset);
- offsetRange(fSuperclassRange, offset);
- offsetRange(fTypeRange, offset);
- }
-
- /**
- * @see IDOMType#setClass(boolean)
- */
- public void setClass(boolean b) {
- becomeDetailed();
- fragment();
- setMask(MASK_TYPE_IS_CLASS, b);
- if (b) {
- fTypeKeyword = "class";
} else {
- fTypeKeyword = "interface";
- setSuperclass(null);
+ openBodyEnd = fCloseBodyRange[0] - 1;
}
}
-
- /**
- * Sets the end of the close body range
- */
- void setCloseBodyRangeEnd(int end) {
- fCloseBodyRange[1] = end;
- }
-
- /**
- * Sets the start of the close body range
- */
- void setCloseBodyRangeStart(int start) {
- fCloseBodyRange[0] = start;
+ setOpenBodyRangeEnd(openBodyEnd);
+ setCloseBodyRangeStart(closeBodyStart);
+ super.normalize(finder);
+}
+/**
+ * Offsets all the source indexes in this node by the given amount.
+ */
+protected void offset(int offset) {
+ super.offset(offset);
+ offsetRange(fCloseBodyRange, offset);
+ offsetRange(fExtendsRange, offset);
+ offsetRange(fImplementsRange, offset);
+ offsetRange(fInterfacesRange, offset);
+ offsetRange(fOpenBodyRange, offset);
+ offsetRange(fSuperclassRange, offset);
+ offsetRange(fTypeRange, offset);
+}
+/**
+ * @see IDOMType#setClass(boolean)
+ */
+public void setClass(boolean b) {
+ becomeDetailed();
+ fragment();
+ setMask(MASK_TYPE_IS_CLASS, b);
+ if (b) {
+ fTypeKeyword= "class";
+ } else {
+ fTypeKeyword= "interface";
+ setSuperclass(null);
}
-
- /**
- * Sets the name of this node.
- *
- * <p>When the name of a type is set, all of its constructors must be marked
- * as fragmented, since the names of the constructors must reflect the name
- * of this type.
- *
- * @see IDOMNode#setName(char[])
- */
- public void setName(String name) throws IllegalArgumentException {
- if (name == null) {
- throw new IllegalArgumentException("illegal to set type name to null");
- }
- super.setName(name);
- Enumeration children = getChildren();
- while (children.hasMoreElements()) {
- IDOMNode child = (IDOMNode) children.nextElement();
- if (child.getNodeType() == IDOMNode.METHOD
- && ((IDOMMethod) child).isConstructor()) {
- ((DOMNode) child).fragment();
- }
+}
+/**
+ * Sets the end of the close body range
+ */
+void setCloseBodyRangeEnd(int end) {
+ fCloseBodyRange[1] = end;
+}
+/**
+ * Sets the start of the close body range
+ */
+void setCloseBodyRangeStart(int start) {
+ fCloseBodyRange[0] = start;
+}
+/**
+ * Sets the name of this node.
+ *
+ * <p>When the name of a type is set, all of its constructors must be marked
+ * as fragmented, since the names of the constructors must reflect the name
+ * of this type.
+ *
+ * @see IDOMNode#setName(char[])
+ */
+public void setName(String name) throws IllegalArgumentException {
+ if (name == null) {
+ throw new IllegalArgumentException("illegal to set type name to null");
+ }
+ super.setName(name);
+ Enumeration children= getChildren();
+ while (children.hasMoreElements()) {
+ IDOMNode child= (IDOMNode)children.nextElement();
+ if (child.getNodeType() == IDOMNode.METHOD && ((IDOMMethod)child).isConstructor()) {
+ ((DOMNode)child).fragment();
}
}
-
- /**
- * Sets the end of the open body range
- */
- void setOpenBodyRangeEnd(int end) {
- fOpenBodyRange[1] = end;
- }
-
- /**
- * @see IDOMType#setSuperclass(char[])
- */
- public void setSuperclass(String superclassName) {
- becomeDetailed();
- fragment();
- fSuperclass = superclassName;
- setMask(MASK_TYPE_HAS_SUPERCLASS, superclassName != null);
- }
-
- /**
- * @see IDOMType#setSuperInterfaces(String[])
- */
- public void setSuperInterfaces(String[] names) {
- becomeDetailed();
- if (names == null) {
- throw new IllegalArgumentException("illegal to set super interfaces to null");
- }
- fragment();
- fSuperInterfaces = names;
- if (names == null || names.length == 0) {
- fInterfaces = null;
- fSuperInterfaces = null;
- setMask(MASK_TYPE_HAS_INTERFACES, false);
- } else {
- setMask(MASK_TYPE_HAS_INTERFACES, true);
- CharArrayBuffer buffer = new CharArrayBuffer();
- for (int i = 0; i < names.length; i++) {
- if (i > 0) {
- buffer.append(", ");
- }
- buffer.append(names[i]);
+}
+/**
+ * Sets the end of the open body range
+ */
+void setOpenBodyRangeEnd(int end) {
+ fOpenBodyRange[1] = end;
+}
+/**
+ * @see IDOMType#setSuperclass(char[])
+ */
+public void setSuperclass(String superclassName) {
+ becomeDetailed();
+ fragment();
+ fSuperclass= superclassName;
+ setMask(MASK_TYPE_HAS_SUPERCLASS, superclassName != null);
+}
+/**
+ * @see IDOMType#setSuperInterfaces(String[])
+ */
+public void setSuperInterfaces(String[] names) {
+ becomeDetailed();
+ if (names == null) {
+ throw new IllegalArgumentException("illegal to set super interfaces to null");
+ }
+ fragment();
+ fSuperInterfaces= names;
+ if (names == null || names.length == 0) {
+ fInterfaces= null;
+ fSuperInterfaces= null;
+ setMask(MASK_TYPE_HAS_INTERFACES, false);
+ } else {
+ setMask(MASK_TYPE_HAS_INTERFACES, true);
+ CharArrayBuffer buffer = new CharArrayBuffer();
+ for (int i = 0; i < names.length; i++) {
+ if (i > 0) {
+ buffer.append(", ");
}
- fInterfaces = buffer.getContents();
+ buffer.append(names[i]);
}
+ fInterfaces = buffer.getContents();
}
-
- /**
- * Sets the type keyword
- */
- void setTypeKeyword(String keyword) {
- fTypeKeyword = keyword;
- }
-
- /**
- * @see DOMNode#shareContents(DOMNode)
- */
- protected void shareContents(DOMNode node) {
- super.shareContents(node);
- DOMType type = (DOMType) node;
- fCloseBodyRange = rangeCopy(type.fCloseBodyRange);
- fExtendsRange = type.fExtendsRange;
- fImplementsRange = rangeCopy(type.fImplementsRange);
- fInterfaces = type.fInterfaces;
- fInterfacesRange = rangeCopy(type.fInterfacesRange);
- fOpenBodyRange = rangeCopy(type.fOpenBodyRange);
- fSuperclass = type.fSuperclass;
- fSuperclassRange = rangeCopy(type.fSuperclassRange);
- fSuperInterfaces = type.fSuperInterfaces;
- fTypeKeyword = type.fTypeKeyword;
- fTypeRange = rangeCopy(type.fTypeRange);
- }
-
- /**
- * @see IDOMNode#toString()
- */
- public String toString() {
- return "TYPE: " + getName();
- }
-
+}
+/**
+ * Sets the type keyword
+ */
+void setTypeKeyword(String keyword) {
+ fTypeKeyword = keyword;
+}
+/**
+ * @see DOMNode#shareContents(DOMNode)
+ */
+protected void shareContents(DOMNode node) {
+ super.shareContents(node);
+ DOMType type= (DOMType)node;
+ fCloseBodyRange= rangeCopy(type.fCloseBodyRange);
+ fExtendsRange= type.fExtendsRange;
+ fImplementsRange= rangeCopy(type.fImplementsRange);
+ fInterfaces= type.fInterfaces;
+ fInterfacesRange= rangeCopy(type.fInterfacesRange);
+ fOpenBodyRange= rangeCopy(type.fOpenBodyRange);
+ fSuperclass= type.fSuperclass;
+ fSuperclassRange= rangeCopy(type.fSuperclassRange);
+ fSuperInterfaces= type.fSuperInterfaces;
+ fTypeKeyword= type.fTypeKeyword;
+ fTypeRange= rangeCopy(type.fTypeRange);
+}
+/**
+ * @see IDOMNode#toString()
+ */
+public String toString() {
+ return "TYPE: " + getName();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/ILineStartFinder.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/ILineStartFinder.java
index 73fdd88c8b..0c8ee08788 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/ILineStartFinder.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/ILineStartFinder.java
@@ -1,11 +1,11 @@
package org.eclipse.jdt.internal.core.jdom;
interface ILineStartFinder {
- /**
- * Returns the position of the start of the line at or before the given source position.
- *
- * <p>This defaults to zero if the position corresponds to a position on the first line
- * of the source.
- */
- public int getLineStart(int position);
+/**
+ * Returns the position of the start of the line at or before the given source position.
+ *
+ * <p>This defaults to zero if the position corresponds to a position on the first line
+ * of the source.
+ */
+public int getLineStart(int position);
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/NullProblem.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/NullProblem.java
index 4a0e1856d9..4b407d4e7f 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/NullProblem.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/NullProblem.java
@@ -15,7 +15,7 @@ public class NullProblem implements IProblem {
/**
* The filename of the compilation unit which was being processed when this problem occured.
*/
- char[] fFileName;
+ char [] fFileName;
/**
* The problem identification number of this problem.
@@ -41,122 +41,101 @@ public class NullProblem implements IProblem {
/**
* The source position corresponding to the end of the source element which caused
* this problem.
- */
+ */
int fEndPosition;
/**
* The line number in the compilation unit which caused the problem
*/
int fLineNumber;
- /**
- * Creates a NullProblem
- */
- public NullProblem(
- char[] originatingFileName,
- int problemId,
- String[] arguments,
- int severity,
- int startPosition,
- int endPosition,
- int lineNumber) {
- fFileName = originatingFileName;
- fProblemId = problemId;
- fArguements = arguments;
- fSeverity = severity;
- fStartPosition = startPosition;
- fEndPosition = endPosition;
- fLineNumber = lineNumber;
- }
-
- /**
- * @see IProblem
- */
- public String[] getArguments() {
- return fArguements;
- }
-
- /**
- * @see IProblem
- */
- public int getID() {
- return fProblemId;
- }
-
- /**
- * @see IProblem
- */
- public String getMessage() {
- return Integer.toString(fProblemId);
- }
-
- /**
- * @see IProblem
- */
- public char[] getOriginatingFileName() {
- return fFileName;
- }
-
- /**
- * @see IProblem.
- */
- public int getSeverity() {
- return fSeverity;
- }
-
- /**
- * @see IProblem
- */
- public int getSourceEnd() {
- return fEndPosition;
- }
-
- /**
- * @see IProblem
- */
- public int getSourceLineNumber() {
- return fLineNumber;
- }
-
- /**
- * @see IProblem
- */
- public int getSourceStart() {
- return fStartPosition;
- }
-
- /**
- * @see IProblem
- */
- public boolean isError() {
- return true;
- }
-
- /**
- * @see IProblem
- */
- public boolean isWarning() {
- return false;
- }
-
- /**
- * @see IProblem
- */
- public void setSourceEnd(int sourceEnd) {
- fEndPosition = sourceEnd;
- }
-
- /**
- * @see IProblem
- */
- public void setSourceLineNumber(int lineNumber) {
- fLineNumber = lineNumber;
- }
-
- /**
- * @see IProblem
- */
- public void setSourceStart(int sourceStart) {
- fStartPosition = sourceStart;
- }
-
+/**
+ * Creates a NullProblem
+ */
+public NullProblem(char[] originatingFileName, int problemId, String[] arguments, int severity, int startPosition, int endPosition, int lineNumber) {
+ fFileName = originatingFileName;
+ fProblemId = problemId;
+ fArguements = arguments;
+ fSeverity = severity;
+ fStartPosition = startPosition;
+ fEndPosition = endPosition;
+ fLineNumber = lineNumber;
+}
+/**
+ * @see IProblem
+ */
+public String[] getArguments() {
+ return fArguements;
+}
+/**
+ * @see IProblem
+ */
+public int getID() {
+ return fProblemId;
+}
+/**
+ * @see IProblem
+ */
+public String getMessage() {
+ return Integer.toString(fProblemId);
+}
+/**
+ * @see IProblem
+ */
+public char[] getOriginatingFileName() {
+ return fFileName;
+}
+/**
+ * @see IProblem.
+ */
+public int getSeverity() {
+ return fSeverity;
+}
+/**
+ * @see IProblem
+ */
+public int getSourceEnd() {
+ return fEndPosition;
+}
+/**
+ * @see IProblem
+ */
+public int getSourceLineNumber() {
+ return fLineNumber;
+}
+/**
+ * @see IProblem
+ */
+public int getSourceStart() {
+ return fStartPosition;
+}
+/**
+ * @see IProblem
+ */
+public boolean isError() {
+ return true;
+}
+/**
+ * @see IProblem
+ */
+public boolean isWarning() {
+ return false;
+}
+/**
+ * @see IProblem
+ */
+public void setSourceEnd(int sourceEnd) {
+ fEndPosition = sourceEnd;
+}
+/**
+ * @see IProblem
+ */
+public void setSourceLineNumber(int lineNumber) {
+ fLineNumber = lineNumber;
+}
+/**
+ * @see IProblem
+ */
+public void setSourceStart(int sourceStart) {
+ fStartPosition = sourceStart;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/NullProblemFactory.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/NullProblemFactory.java
index 1542e805cc..9eb45674a3 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/NullProblemFactory.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/NullProblemFactory.java
@@ -14,39 +14,22 @@ import java.util.*;
* <code>IProblemFactory</code>s and null <code>IProblem</code>s.
*/
public class NullProblemFactory implements IProblemFactory {
- /**
- * Returns a new <code>NullProblem</code> initialized to the given info.
- */
- public IProblem createProblem(
- char[] originatingFileName,
- int problemId,
- String[] arguments,
- int severity,
- int startPosition,
- int endPosition,
- int lineNumber) {
- return new NullProblem(
- originatingFileName,
- problemId,
- arguments,
- severity,
- startPosition,
- endPosition,
- lineNumber);
- }
-
- /**
- * Returns the default locale
- */
- public Locale getLocale() {
- return Locale.getDefault();
- }
-
- /**
- * Answers a String representation of the problemId.
- */
- public String getLocalizedMessage(int problemId, String[] problemArguments) {
- return Integer.toString(problemId);
- }
-
+/**
+ * Returns a new <code>NullProblem</code> initialized to the given info.
+ */
+public IProblem createProblem(char[] originatingFileName, int problemId, String[] arguments, int severity, int startPosition, int endPosition, int lineNumber) {
+ return new NullProblem(originatingFileName, problemId, arguments, severity, startPosition, endPosition, lineNumber);
+}
+/**
+ * Returns the default locale
+ */
+public Locale getLocale() {
+ return Locale.getDefault();
+}
+/**
+ * Answers a String representation of the problemId.
+ */
+public String getLocalizedMessage(int problemId, String[] problemArguments) {
+ return Integer.toString(problemId);
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/SiblingEnumeration.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/SiblingEnumeration.java
index 2ebbd88f46..80fbbd0d2f 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/SiblingEnumeration.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/SiblingEnumeration.java
@@ -15,38 +15,34 @@ import java.util.Enumeration;
* @see java.util.Enumeration
*/
-/* package */
-class SiblingEnumeration implements Enumeration {
+/* package */ class SiblingEnumeration implements Enumeration {
/**
* The current location in the linked list
* of DOM nodes.
*/
protected IDOMNode fCurrentElement;
- /**
- * Creates an enumeration of silbings starting at the given node.
- * If the given node is <code>null</code> the enumeration is empty.
- */
- SiblingEnumeration(IDOMNode child) {
- fCurrentElement = child;
- }
-
- /**
- * @see java.util.Enumeration#hasMoreElements()
- */
- public boolean hasMoreElements() {
- return fCurrentElement != null;
- }
-
- /**
- * @see java.util.Enumeration#nextElement()
- */
- public Object nextElement() {
- IDOMNode curr = fCurrentElement;
- if (curr != null) {
- fCurrentElement = fCurrentElement.getNextNode();
- }
- return curr;
+/**
+ * Creates an enumeration of silbings starting at the given node.
+ * If the given node is <code>null</code> the enumeration is empty.
+ */
+SiblingEnumeration(IDOMNode child) {
+ fCurrentElement= child;
+}
+/**
+ * @see java.util.Enumeration#hasMoreElements()
+ */
+public boolean hasMoreElements() {
+ return fCurrentElement != null;
+}
+/**
+ * @see java.util.Enumeration#nextElement()
+ */
+public Object nextElement() {
+ IDOMNode curr= fCurrentElement;
+ if (curr != null) {
+ fCurrentElement= fCurrentElement.getNextNode();
}
-
+ return curr;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/SimpleDOMBuilder.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/SimpleDOMBuilder.java
index 05f9977be8..643fe9f04a 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/SimpleDOMBuilder.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/jdom/SimpleDOMBuilder.java
@@ -17,331 +17,201 @@ import java.util.Stack;
/**
* A DOM builder that uses the SourceElementParser
*/
-public class SimpleDOMBuilder
- extends AbstractDOMBuilder
- implements ISourceElementRequestor {
+public class SimpleDOMBuilder extends AbstractDOMBuilder implements ISourceElementRequestor {
+
+
+
+
+
- /**
-
- */
- public void acceptImport(
- int declarationStart,
- int declarationEnd,
- char[] name,
- boolean onDemand) {
- int[] sourceRange = { declarationStart, declarationEnd };
- String importName = new String(name);
- /** name is set to contain the '*' */
- if (onDemand) {
- importName += ".*";
- }
- fNode = new DOMImport(fDocument, sourceRange, importName, onDemand);
- addChild(fNode);
- }
-
- /**
-
- */
- public void acceptInitializer(
- int modifiers,
- int declarationSourceStart,
- int declarationSourceEnd) {
- int[] sourceRange = { declarationSourceStart, declarationSourceEnd };
- fNode = new DOMInitializer(fDocument, sourceRange, modifiers);
- addChild(fNode);
- }
-
- /**
- */
- public void acceptPackage(
- int declarationStart,
- int declarationEnd,
- char[] name) {
- int[] sourceRange = new int[] { declarationStart, declarationEnd };
- fNode = new DOMPackage(fDocument, sourceRange, CharArrayOps.charToString(name));
- addChild(fNode);
- }
-
- /**
- * @see IDOMFactory#createCompilationUnit(String)
- */
- public IDOMCompilationUnit createCompilationUnit(
- String sourceCode,
- String name) {
- return createCompilationUnit(sourceCode.toCharArray(), name.toCharArray());
- }
-
- /**
- * @see IDOMFactory#createCompilationUnit(String)
- */
- public IDOMCompilationUnit createCompilationUnit(ICompilationUnit compilationUnit) {
- initializeBuild(compilationUnit.getContents(), true, true);
- getParser().parseCompilationUnit(compilationUnit, false);
- return super.createCompilationUnit(compilationUnit);
- }
-
- /**
- * Creates a new DOMMethod and inizializes.
- *
- * @param declarationStart - a source position corresponding to the first character
- * of this constructor declaration
- * @param modifiers - the modifiers for this constructor converted to a flag
- * @param returnType - the name of the return type
- * @param name - the name of this constructor
- * @param nameStart - a source position corresponding to the first character of the name
- * @param nameEnd - a source position corresponding to the last character of the name
- * @param parameterTypes - a list of parameter type names
- * @param parameterNames - a list of the names of the parameters
- * @param exceptionTypes - a list of the exception types
- */
- protected void enterAbstractMethod(
- int declarationStart,
- int modifiers,
- char[] returnType,
- char[] name,
- int nameStart,
- int nameEnd,
- char[][] parameterTypes,
- char[][] parameterNames,
- char[][] exceptionTypes,
- boolean isConstructor) {
- int[] sourceRange = { declarationStart, -1 }; // will be fixed up on exit
- int[] nameRange = { nameStart, nameEnd };
- fNode =
- new DOMMethod(
- fDocument,
- sourceRange,
- CharArrayOps.charToString(name),
- nameRange,
- modifiers,
- isConstructor,
- CharArrayOps.charToString(returnType),
- CharArrayOps.charcharToString(parameterTypes),
- CharArrayOps.charcharToString(parameterNames),
- CharArrayOps.charcharToString(exceptionTypes));
- addChild(fNode);
- fStack.push(fNode);
- }
-
- /**
- */
- public void enterClass(
- int declarationStart,
- int modifiers,
- char[] name,
- int nameStart,
- int nameEnd,
- char[] superclass,
- char[][] superinterfaces) {
- enterType(
- declarationStart,
- modifiers,
- name,
- nameStart,
- nameEnd,
- superclass,
- superinterfaces,
- true);
- }
-
- /**
- */
- public void enterConstructor(
- int declarationStart,
- int modifiers,
- char[] name,
- int nameStart,
- int nameEnd,
- char[][] parameterTypes,
- char[][] parameterNames,
- char[][] exceptionTypes) {
- /* see 1FVIIQZ */
- String nameString = new String(fDocument, nameStart, nameEnd - nameStart);
- int openParenPosition = nameString.indexOf('(');
- if (openParenPosition > -1)
- nameEnd = nameStart + openParenPosition - 1;
-
- enterAbstractMethod(
- declarationStart,
- modifiers,
- null,
- name,
- nameStart,
- nameEnd,
- parameterTypes,
- parameterNames,
- exceptionTypes,
- true);
- }
+/**
- /**
- */
- public void enterField(
- int declarationStart,
- int modifiers,
- char[] type,
- char[] name,
- int nameStart,
- int nameEnd) {
+ */
+public void acceptImport(int declarationStart, int declarationEnd, char[] name, boolean onDemand) {
+ int[] sourceRange = {declarationStart, declarationEnd};
+ String importName = new String(name);
+ /** name is set to contain the '*' */
+ if (onDemand) {
+ importName+=".*";
+ }
+ fNode= new DOMImport(fDocument, sourceRange, importName, onDemand);
+ addChild(fNode);
+}
+/**
- int[] sourceRange = { declarationStart, -1 };
- int[] nameRange = { nameStart, nameEnd };
- boolean isSecondary = false;
- if (fNode instanceof DOMField) {
- isSecondary = declarationStart == fNode.fSourceRange[0];
- }
- fNode =
- new DOMField(
- fDocument,
- sourceRange,
- CharArrayOps.charToString(name),
- nameRange,
- modifiers,
- CharArrayOps.charToString(type),
- isSecondary);
+ */
+public void acceptInitializer(int modifiers, int declarationSourceStart, int declarationSourceEnd) {
+ int[] sourceRange = {declarationSourceStart, declarationSourceEnd};
+ fNode = new DOMInitializer(fDocument, sourceRange, modifiers);
+ addChild(fNode);
+}
+/**
+ */
+public void acceptPackage(int declarationStart, int declarationEnd, char[] name) {
+ int[] sourceRange= new int[] {declarationStart, declarationEnd};
+ fNode= new DOMPackage(fDocument, sourceRange, CharArrayOps.charToString(name));
+ addChild(fNode);
+}
+/**
+ * @see IDOMFactory#createCompilationUnit(String)
+ */
+public IDOMCompilationUnit createCompilationUnit(String sourceCode, String name) {
+ return createCompilationUnit(sourceCode.toCharArray(), name.toCharArray());
+}
+/**
+ * @see IDOMFactory#createCompilationUnit(String)
+ */
+public IDOMCompilationUnit createCompilationUnit(ICompilationUnit compilationUnit) {
+ initializeBuild(compilationUnit.getContents(), true, true);
+ getParser().parseCompilationUnit(compilationUnit, false);
+ return super.createCompilationUnit(compilationUnit);
+}
+/**
+ * Creates a new DOMMethod and inizializes.
+ *
+ * @param declarationStart - a source position corresponding to the first character
+ * of this constructor declaration
+ * @param modifiers - the modifiers for this constructor converted to a flag
+ * @param returnType - the name of the return type
+ * @param name - the name of this constructor
+ * @param nameStart - a source position corresponding to the first character of the name
+ * @param nameEnd - a source position corresponding to the last character of the name
+ * @param parameterTypes - a list of parameter type names
+ * @param parameterNames - a list of the names of the parameters
+ * @param exceptionTypes - a list of the exception types
+ */
+protected void enterAbstractMethod(int declarationStart, int modifiers,
+ char[] returnType, char[] name, int nameStart, int nameEnd, char[][] parameterTypes,
+ char[][] parameterNames, char[][] exceptionTypes, boolean isConstructor) {
+
+ int[] sourceRange = {declarationStart, -1}; // will be fixed up on exit
+ int[] nameRange = {nameStart, nameEnd};
+ fNode = new DOMMethod(fDocument, sourceRange, CharArrayOps.charToString(name), nameRange, modifiers,
+ isConstructor, CharArrayOps.charToString(returnType),
+ CharArrayOps.charcharToString(parameterTypes),
+ CharArrayOps.charcharToString(parameterNames),
+ CharArrayOps.charcharToString(exceptionTypes));
+ addChild(fNode);
+ fStack.push(fNode);
+}
+/**
+ */
+public void enterClass(int declarationStart, int modifiers, char[] name, int nameStart, int nameEnd, char[] superclass, char[][] superinterfaces) {
+ enterType(declarationStart, modifiers, name, nameStart, nameEnd, superclass,
+ superinterfaces, true);
+}
+/**
+ */
+public void enterConstructor(int declarationStart, int modifiers, char[] name, int nameStart, int nameEnd, char[][] parameterTypes, char[][] parameterNames, char[][] exceptionTypes) {
+ /* see 1FVIIQZ */
+ String nameString = new String(fDocument, nameStart, nameEnd - nameStart);
+ int openParenPosition = nameString.indexOf('(');
+ if (openParenPosition > -1)
+ nameEnd = nameStart + openParenPosition - 1;
+
+ enterAbstractMethod(declarationStart, modifiers,
+ null, name, nameStart, nameEnd, parameterTypes,
+ parameterNames, exceptionTypes,true);
+}
+/**
+ */
+public void enterField(int declarationStart, int modifiers, char[] type, char[] name, int nameStart, int nameEnd) {
+
+ int[] sourceRange = {declarationStart, -1};
+ int[] nameRange = {nameStart, nameEnd};
+ boolean isSecondary= false;
+ if (fNode instanceof DOMField) {
+ isSecondary = declarationStart == fNode.fSourceRange[0];
+ }
+ fNode = new DOMField(fDocument, sourceRange, CharArrayOps.charToString(name), nameRange,
+ modifiers, CharArrayOps.charToString(type), isSecondary);
+ addChild(fNode);
+ fStack.push(fNode);
+}
+/**
+ */
+public void enterInterface(int declarationStart, int modifiers, char[] name, int nameStart, int nameEnd, char[][] superinterfaces) {
+ enterType(declarationStart, modifiers, name, nameStart, nameEnd, null,
+ superinterfaces, false);
+}
+/**
+ */
+public void enterMethod(int declarationStart, int modifiers, char[] returnType, char[] name, int nameStart, int nameEnd, char[][] parameterTypes, char[][] parameterNames, char[][] exceptionTypes) {
+ enterAbstractMethod(declarationStart, modifiers,
+ null, name, nameStart, nameEnd, parameterTypes,
+ parameterNames, exceptionTypes,false);
+}
+/**
+ */
+protected void enterType(int declarationStart, int modifiers, char[] name,
+ int nameStart, int nameEnd, char[] superclass, char[][] superinterfaces, boolean isClass) {
+ if (fBuildingType) {
+ int[] sourceRange = {declarationStart, -1}; // will be fixed in the exit
+ int[] nameRange = new int[] {nameStart, nameEnd};
+ fNode = new DOMType(fDocument, sourceRange, new String(name), nameRange,
+ modifiers, CharArrayOps.charcharToString(superinterfaces), isClass);
addChild(fNode);
fStack.push(fNode);
}
-
- /**
- */
- public void enterInterface(
- int declarationStart,
- int modifiers,
- char[] name,
- int nameStart,
- int nameEnd,
- char[][] superinterfaces) {
- enterType(
- declarationStart,
- modifiers,
- name,
- nameStart,
- nameEnd,
- null,
- superinterfaces,
- false);
- }
-
- /**
- */
- public void enterMethod(
- int declarationStart,
- int modifiers,
- char[] returnType,
- char[] name,
- int nameStart,
- int nameEnd,
- char[][] parameterTypes,
- char[][] parameterNames,
- char[][] exceptionTypes) {
- enterAbstractMethod(
- declarationStart,
- modifiers,
- null,
- name,
- nameStart,
- nameEnd,
- parameterTypes,
- parameterNames,
- exceptionTypes,
- false);
- }
-
- /**
- */
- protected void enterType(
- int declarationStart,
- int modifiers,
- char[] name,
- int nameStart,
- int nameEnd,
- char[] superclass,
- char[][] superinterfaces,
- boolean isClass) {
- if (fBuildingType) {
- int[] sourceRange = { declarationStart, -1 }; // will be fixed in the exit
- int[] nameRange = new int[] { nameStart, nameEnd };
- fNode =
- new DOMType(
- fDocument,
- sourceRange,
- new String(name),
- nameRange,
- modifiers,
- CharArrayOps.charcharToString(superinterfaces),
- isClass);
- addChild(fNode);
- fStack.push(fNode);
- }
- }
-
- /**
- * Finishes the configuration of the class DOM object which
- * was created by a previous enterClass call.
- *
- * @see ISourceElementRequestor.exitClass(...);
- */
- public void exitClass(int declarationEnd) {
- exitType(declarationEnd);
- }
-
- /**
- * Finishes the configuration of the method DOM object which
- * was created by a previous enterConstructor call.
- *
- * @see ISourceElementRequestor.exitConstructor(...);
- */
- public void exitConstructor(int declarationEnd) {
- exitMember(declarationEnd);
- }
-
- /**
- */
- public void exitField(int declarationEnd) {
- exitMember(declarationEnd);
- }
-
- /**
- */
- public void exitInterface(int declarationEnd) {
- exitType(declarationEnd);
- }
-
- /**
- * Finishes the configuration of the member.
- *
- * @param declarationEnd - a source position corresponding to the end of the method
- * declaration. This can include whitespace and comments following the closing bracket.
- */
- protected void exitMember(int declarationEnd) {
- DOMMember m = (DOMMember) fStack.pop();
- m.setSourceRangeEnd(declarationEnd);
- fNode = m;
- }
-
- /**
- */
- public void exitMethod(int declarationEnd) {
- exitMember(declarationEnd);
- }
-
- /**
- * @see AbstractDOMBuilder#exitType
- *
- * @param declarationEnd - a source position corresponding to the end of the class
- * declaration. This can include whitespace and comments following the closing bracket.
- */
- protected void exitType(int declarationEnd) {
- exitType(declarationEnd, declarationEnd);
- }
-
- /**
- * Creates a new parser.
- */
- protected SourceElementParser getParser() {
- return new SourceElementParser(this, new NullProblemFactory());
- }
-
+}
+/**
+ * Finishes the configuration of the class DOM object which
+ * was created by a previous enterClass call.
+ *
+ * @see ISourceElementRequestor.exitClass(...);
+ */
+public void exitClass(int declarationEnd) {
+ exitType(declarationEnd);
+}
+/**
+ * Finishes the configuration of the method DOM object which
+ * was created by a previous enterConstructor call.
+ *
+ * @see ISourceElementRequestor.exitConstructor(...);
+ */
+public void exitConstructor(int declarationEnd) {
+ exitMember(declarationEnd);
+}
+/**
+ */
+public void exitField(int declarationEnd) {
+ exitMember(declarationEnd);
+}
+/**
+ */
+public void exitInterface(int declarationEnd) {
+ exitType(declarationEnd);
+}
+/**
+ * Finishes the configuration of the member.
+ *
+ * @param declarationEnd - a source position corresponding to the end of the method
+ * declaration. This can include whitespace and comments following the closing bracket.
+ */
+protected void exitMember(int declarationEnd) {
+ DOMMember m= (DOMMember) fStack.pop();
+ m.setSourceRangeEnd(declarationEnd);
+ fNode = m;
+}
+/**
+ */
+public void exitMethod(int declarationEnd) {
+ exitMember(declarationEnd);
+}
+/**
+ * @see AbstractDOMBuilder#exitType
+ *
+ * @param declarationEnd - a source position corresponding to the end of the class
+ * declaration. This can include whitespace and comments following the closing bracket.
+ */
+protected void exitType(int declarationEnd) {
+ exitType(declarationEnd, declarationEnd);
+}
+/**
+ * Creates a new parser.
+ */
+protected SourceElementParser getParser() {
+ return new SourceElementParser(this, new NullProblemFactory());
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/lookup/ReferenceInfo.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/lookup/ReferenceInfo.java
index d01827ad6a..dcbbe0e209 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/lookup/ReferenceInfo.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/lookup/ReferenceInfo.java
@@ -22,42 +22,38 @@ public class ReferenceInfo {
public static final byte REFTYPE_derive = 0x10;
public static final byte REFTYPE_type = 0x20;
public static final byte REFTYPE_class = 0x40;
- public static final byte REFTYPE_constant = (byte) 0x80;
- // public static final byte REFTYPE_label = 256;
-
- /**
- * Creates a new ReferenceInfo object. There should be one per compilation unit.
- */
- public ReferenceInfo(char[][] names, byte[] kinds) {
- fNames = names;
- fKinds = kinds;
- }
-
- /**
- * Returns the reference kinds array.
- */
- public byte[] getKinds() {
- return fKinds;
- }
-
- /**
- * Returns the reference names array.
- */
- public char[][] getNames() {
- return fNames;
- }
-
- /**
- * For debugging only
- */
- public String toString() {
- StringBuffer buf = new StringBuffer("ReferenceInfo(");
- for (int i = 0; i < fNames.length; i++) {
- buf.append(fNames[i]);
- buf.append(" ");
- }
- buf.append(")");
- return buf.toString();
+ public static final byte REFTYPE_constant = (byte)0x80;
+// public static final byte REFTYPE_label = 256;
+
+/**
+ * Creates a new ReferenceInfo object. There should be one per compilation unit.
+ */
+public ReferenceInfo(char [][]names, byte[] kinds) {
+ fNames = names;
+ fKinds = kinds;
+}
+/**
+ * Returns the reference kinds array.
+ */
+public byte[] getKinds() {
+ return fKinds;
+}
+/**
+ * Returns the reference names array.
+ */
+public char[][] getNames() {
+ return fNames;
+}
+/**
+ * For debugging only
+ */
+public String toString() {
+ StringBuffer buf = new StringBuffer("ReferenceInfo(");
+ for (int i = 0; i < fNames.length; i++) {
+ buf.append(fNames[i]);
+ buf.append(" ");
}
-
+ buf.append(")");
+ return buf.toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/AnonymousFileSource.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/AnonymousFileSource.java
index 453602cf92..02bf03fb69 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/AnonymousFileSource.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/AnonymousFileSource.java
@@ -7,128 +7,121 @@ package org.eclipse.jdt.internal.core.util;
import java.io.*;
import java.net.*;
+
/** An anonymous file source creates files in the given directory.
*/
public class AnonymousFileSource {
File fDirectory;
- /**
- * Creates an anonymous file source which creates files in the given directory.
- */
- public AnonymousFileSource(File directory) {
- if (!directory.exists()) {
- directory.mkdirs();
- } else
- if (!directory.isDirectory()) {
- throw new IllegalArgumentException("Directory arguments should be a directory.");
- }
- fDirectory = directory;
- }
-
- /**
- * Allocates and returns a RandomAccessFile in R/W mode on a new anonymous file.
- * Guaranteed to be unallocated.
- */
- synchronized public RandomAccessFile allocateAnonymousFile()
- throws IOException {
-
- File file = getAnonymousFile();
- return new RandomAccessFile(file, "rw");
+/**
+ * Creates an anonymous file source which creates files in the given directory.
+ */
+public AnonymousFileSource(File directory) {
+ if (!directory.exists()) {
+ directory.mkdirs();
+ } else if (!directory.isDirectory()) {
+ throw new IllegalArgumentException("Directory arguments should be a directory.");
}
-
- /**
- * Returns a URL on a newly allocated file with the given initial content.
- * Guaranteed to be unallocated.
- */
- synchronized public URL allocateAnonymousURL(byte[] bytes) throws IOException {
- try {
- byte hasharray[] = java.security.MessageDigest.getInstance("SHA").digest(bytes);
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < hasharray.length; i++) {
- sb.append(Character.forDigit((int) ((hasharray[i] >> 4) & 0x0F), 16));
- sb.append(Character.forDigit((int) (hasharray[i] & 0x0F), 16));
- }
- sb.append(".jnk");
- String fileName = sb.toString();
- File file = fileForName(fileName);
- if (!file.exists()) {
- RandomAccessFile raf = new RandomAccessFile(file, "rw");
- raf.write(bytes);
- raf.close();
- }
- return convertFileToURL(file);
- } catch (java.security.NoSuchAlgorithmException e) {
- throw new IOException(e.getMessage());
+ fDirectory = directory;
+}
+/**
+ * Allocates and returns a RandomAccessFile in R/W mode on a new anonymous file.
+ * Guaranteed to be unallocated.
+ */
+synchronized public RandomAccessFile allocateAnonymousFile() throws IOException {
+
+ File file = getAnonymousFile();
+ return new RandomAccessFile(file, "rw"/*nonNLS*/);
+}
+/**
+ * Returns a URL on a newly allocated file with the given initial content.
+ * Guaranteed to be unallocated.
+ */
+synchronized public URL allocateAnonymousURL(byte[] bytes) throws IOException {
+ try {
+ byte hasharray[] = java.security.MessageDigest.getInstance("SHA"/*nonNLS*/).digest(bytes);
+ StringBuffer sb = new StringBuffer();
+ for (int i = 0; i < hasharray.length; i++) {
+ sb.append(Character.forDigit((int)((hasharray[i] >> 4) & 0x0F), 16));
+ sb.append(Character.forDigit((int)(hasharray[i] & 0x0F), 16));
}
- }
-
- /**
- * Returns a URL using the "file" protocol corresponding to the given File.
- */
- static public URL convertFileToURL(File file) {
- try {
- String path = file.getCanonicalPath().replace(java.io.File.separatorChar, '/');
- return new URL("file", "", "/" + path);
- } catch (IOException ioe) {
- throw new Error();
+ sb.append(".jnk"/*nonNLS*/);
+ String fileName = sb.toString();
+ File file = fileForName(fileName);
+ if (!file.exists()) {
+ RandomAccessFile raf = new RandomAccessFile(file, "rw"/*nonNLS*/);
+ raf.write(bytes);
+ raf.close();
}
+ return convertFileToURL(file);
+ }
+ catch (java.security.NoSuchAlgorithmException e) {
+ throw new IOException(e.getMessage());
}
-
- /**
- * Answer a File to use for the given simple file name.
- */
- File fileForName(String fileName) {
- File dir;
- if (fileName.length() >= 1) {
- String dirName = Integer.toHexString((fileName.hashCode() % 255) & 255);
- dir = new File(fDirectory, dirName);
- dir.mkdirs();
- } else {
- dir = fDirectory;
- }
- return new File(dir, fileName);
+}
+/**
+ * Returns a URL using the "file" protocol corresponding to the given File.
+ */
+static public URL convertFileToURL(File file) {
+ try {
+ String path = file.getCanonicalPath().replace(java.io.File.separatorChar, '/');
+ return new URL("file"/*nonNLS*/, ""/*nonNLS*/, "/"/*nonNLS*/ + path);
}
-
- /**
- * Returns a new anonymous file, but does not allocate it.
- * Not guaranteed to be free when used since it is unallocated.
- */
- synchronized public File getAnonymousFile() {
- File file;
- file = fileForName(getAnonymousFileName());
- while (file.exists()) {
- try {
- Thread.sleep(1);
- } catch (InterruptedException e) {
- }
- file = fileForName(getAnonymousFileName());
- }
- return file;
+ catch (IOException ioe) {
+ throw new Error();
}
-
- /**
- * Returns a new anonymous file name.
- * Not guaranteed to be free since its directory is unknown.
- */
- synchronized public String getAnonymousFileName() {
- return getAnonymousFileName(System.currentTimeMillis());
+}
+/**
+ * Answer a File to use for the given simple file name.
+ */
+File fileForName(String fileName) {
+ File dir;
+ if (fileName.length() >= 1) {
+ String dirName = Integer.toHexString((fileName.hashCode() % 255) & 255);
+ dir = new File(fDirectory, dirName);
+ dir.mkdirs();
+ } else {
+ dir = fDirectory;
}
-
- /**
- * Returns a new anonymous file name based on the given long.
- * Not guaranteed to be free since its directory is unknown.
- */
- synchronized public String getAnonymousFileName(long l) {
- if (l < 0)
- l = -l;
- StringBuffer sb = new StringBuffer();
- sb.append(Character.forDigit((int) (l % 26 + 10), 36));
- l /= 26;
- while (l != 0) {
- sb.append(Character.forDigit((int) (l % 36), 36));
- l /= 36;
+ return new File(dir, fileName);
+}
+/**
+ * Returns a new anonymous file, but does not allocate it.
+ * Not guaranteed to be free when used since it is unallocated.
+ */
+synchronized public File getAnonymousFile() {
+ File file;
+ file = fileForName(getAnonymousFileName());
+ while (file.exists()) {
+ try {
+ Thread.sleep(1);
+ }
+ catch (InterruptedException e) {
}
- sb.append(".jnk");
- return sb.toString();
+ file = fileForName(getAnonymousFileName());
}
-
+ return file;
+}
+/**
+ * Returns a new anonymous file name.
+ * Not guaranteed to be free since its directory is unknown.
+ */
+synchronized public String getAnonymousFileName() {
+ return getAnonymousFileName(System.currentTimeMillis());
+}
+/**
+ * Returns a new anonymous file name based on the given long.
+ * Not guaranteed to be free since its directory is unknown.
+ */
+synchronized public String getAnonymousFileName(long l) {
+ if (l < 0) l = -l;
+ StringBuffer sb = new StringBuffer();
+ sb.append(Character.forDigit((int)(l % 26 + 10), 36));
+ l /= 26;
+ while (l != 0) {
+ sb.append(Character.forDigit((int)(l % 36), 36));
+ l /= 36;
+ }
+ sb.append(".jnk"/*nonNLS*/);
+ return sb.toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/CharArrayBuffer.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/CharArrayBuffer.java
index 8ee7839e1a..00b18b29a3 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/CharArrayBuffer.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/CharArrayBuffer.java
@@ -28,152 +28,142 @@ public class CharArrayBuffer {
* Enables append(char[] array, int start, int end).
*/
protected int[][] fRanges;
- /**
- * Creates a <code>CharArrayBuffer</code> with the default buffer size (10).
- */
- public CharArrayBuffer() {
- this(null, DEFAULT_BUFFER_SIZE);
- }
-
- /**
- * Creates a <code>CharArrayBuffer</code> with the default buffer size,
- * and sets the first element in the buffer to be the given char[].
- *
- * @param first - the first element to be placed in the buffer, ignored if null
- */
- public CharArrayBuffer(char[] first) {
- this(first, DEFAULT_BUFFER_SIZE);
- }
-
- /**
- * Creates a <code>CharArrayBuffer</code> with the given buffer size,
- * and sets the first element in the buffer to be the given char array.
- *
- * @param first - the first element of the buffer, ignored if null.
- * @param size - the buffer size, if less than 1, set to the DEFAULT_BUFFER_SIZE.
- */
- public CharArrayBuffer(char[] first, int size) {
- fSize = (size > 0) ? size : DEFAULT_BUFFER_SIZE;
- fBuffer = new char[fSize][];
- fRanges = new int[fSize][];
- fEnd = 0;
- if (first != null)
- append(first, 0, first.length);
- }
-
- /**
- * Creates a <code>CharArrayBuffer</code> with the given buffer size.
- *
- * @param size - the size of the buffer.
- */
- public CharArrayBuffer(int size) {
- this(null, size);
- }
-
- /**
- * Appends the entire given char array. Given for convenience.
- *
- * @param src - a char array which is appended to the end of the buffer.
- */
- public CharArrayBuffer append(char[] src) {
- if (src != null)
- append(src, 0, src.length);
- return this;
- }
-
- /**
- * Appends a sub array of the given array to the buffer.
- *
- * @param src - the next array of characters to be appended to the buffer, ignored if null
- * @param start - the start index in the src array.
- * @param length - the number of characters from start to be appended
- *
- * @throws ArrayIndexOutOfBoundsException - if arguments specify an array index out of bounds.
- */
- public CharArrayBuffer append(char[] src, int start, int length) {
- if (start < 0)
+/**
+ * Creates a <code>CharArrayBuffer</code> with the default buffer size (10).
+ */
+public CharArrayBuffer() {
+ this(null, DEFAULT_BUFFER_SIZE);
+}
+/**
+ * Creates a <code>CharArrayBuffer</code> with the default buffer size,
+ * and sets the first element in the buffer to be the given char[].
+ *
+ * @param first - the first element to be placed in the buffer, ignored if null
+ */
+public CharArrayBuffer(char[] first) {
+ this(first, DEFAULT_BUFFER_SIZE);
+}
+/**
+ * Creates a <code>CharArrayBuffer</code> with the given buffer size,
+ * and sets the first element in the buffer to be the given char array.
+ *
+ * @param first - the first element of the buffer, ignored if null.
+ * @param size - the buffer size, if less than 1, set to the DEFAULT_BUFFER_SIZE.
+ */
+public CharArrayBuffer(char[] first, int size) {
+ fSize = (size > 0) ? size : DEFAULT_BUFFER_SIZE;
+ fBuffer = new char[fSize][];
+ fRanges = new int[fSize][];
+ fEnd = 0;
+ if (first != null)
+ append(first, 0, first.length);
+}
+/**
+ * Creates a <code>CharArrayBuffer</code> with the given buffer size.
+ *
+ * @param size - the size of the buffer.
+ */
+public CharArrayBuffer(int size) {
+ this(null, size);
+}
+/**
+ * Appends the entire given char array. Given for convenience.
+ *
+ * @param src - a char array which is appended to the end of the buffer.
+ */
+public CharArrayBuffer append(char[] src) {
+ if (src != null)
+ append(src, 0, src.length);
+ return this;
+}
+/**
+ * Appends a sub array of the given array to the buffer.
+ *
+ * @param src - the next array of characters to be appended to the buffer, ignored if null
+ * @param start - the start index in the src array.
+ * @param length - the number of characters from start to be appended
+ *
+ * @throws ArrayIndexOutOfBoundsException - if arguments specify an array index out of bounds.
+ */
+public CharArrayBuffer append(char[] src, int start, int length) {
+ if (start < 0)
+ throw new ArrayIndexOutOfBoundsException();
+ if (length < 0)
+ throw new ArrayIndexOutOfBoundsException();
+ if (src != null) {
+ int srcLength = src.length;
+ if (start > srcLength)
throw new ArrayIndexOutOfBoundsException();
- if (length < 0)
+ if (length + start > srcLength)
throw new ArrayIndexOutOfBoundsException();
- if (src != null) {
- int srcLength = src.length;
- if (start > srcLength)
- throw new ArrayIndexOutOfBoundsException();
- if (length + start > srcLength)
- throw new ArrayIndexOutOfBoundsException();
- /** do length check here to allow exceptions to be thrown */
- if (length > 0) {
- if (fEnd == fSize) {
- int size2 = fSize * 2;
- System.arraycopy(fBuffer, 0, (fBuffer = new char[size2][]), 0, fSize);
- System.arraycopy(fRanges, 0, (fRanges = new int[size2][]), 0, fSize);
- fSize *= 2;
- }
- fBuffer[fEnd] = src;
- fRanges[fEnd] = new int[] { start, length };
- fEnd++;
+ /** do length check here to allow exceptions to be thrown */
+ if (length > 0) {
+ if (fEnd == fSize) {
+ int size2 = fSize * 2;
+ System.arraycopy(fBuffer, 0, (fBuffer = new char[size2][]), 0, fSize);
+ System.arraycopy(fRanges, 0, (fRanges = new int[size2][]), 0, fSize);
+ fSize *= 2;
}
+ fBuffer[fEnd] = src;
+ fRanges[fEnd] = new int[] {start, length};
+ fEnd++;
}
- return this;
}
-
- /**
- * Appends the given char. Given for convenience.
- *
- * @param src - a char which is appended to the end of the buffer.
- */
- public CharArrayBuffer append(char c) {
- append(new char[] { c }, 0, 1);
- return this;
- }
-
- /**
- * Appends the given String to the buffer. Given for convenience, use
- * #append(char[]) if possible
- *
- * @param src - a char array which is appended to the end of the buffer.
- */
- public CharArrayBuffer append(String src) {
- if (src != null)
- append(src.toCharArray(), 0, src.length());
- return this;
- }
-
- /**
- * Returns the entire contents of the buffer as one
- * char[] or null if nothing has been put in the buffer.
- */
- public char[] getContents() {
- if (fEnd == 0)
- return null;
-
- // determine the size of the array
- int size = 0;
- for (int i = 0; i < fEnd; i++)
- size += fRanges[i][1];
-
- if (size > 0) {
- char[] result = new char[size];
- int current = 0;
- // copy the results
- for (int i = 0; i < fEnd; i++) {
- int[] range = fRanges[i];
- int length = range[1];
- System.arraycopy(fBuffer[i], range[0], result, current, length);
- current += length;
- }
- return result;
- }
+ return this;
+}
+/**
+ * Appends the given char. Given for convenience.
+ *
+ * @param src - a char which is appended to the end of the buffer.
+ */
+public CharArrayBuffer append(char c) {
+ append(new char[] {c}, 0, 1);
+ return this;
+}
+/**
+ * Appends the given String to the buffer. Given for convenience, use
+ * #append(char[]) if possible
+ *
+ * @param src - a char array which is appended to the end of the buffer.
+ */
+public CharArrayBuffer append(String src) {
+ if (src != null)
+ append(src.toCharArray(), 0, src.length());
+ return this;
+}
+/**
+ * Returns the entire contents of the buffer as one
+ * char[] or null if nothing has been put in the buffer.
+ */
+public char[] getContents() {
+ if (fEnd == 0)
return null;
- }
- /**
- * Returns the contents of the buffer as a String, or
- * <code>null</code> if the buffer is empty.
- */
- public String toString() {
- char[] contents = getContents();
- return (contents != null) ? new String(contents) : null;
+ // determine the size of the array
+ int size = 0;
+ for (int i = 0; i < fEnd; i++)
+ size += fRanges[i][1];
+
+ if (size > 0) {
+ char[] result = new char[size];
+ int current = 0;
+ // copy the results
+ for(int i = 0; i < fEnd; i++) {
+ int[] range = fRanges[i];
+ int length = range[1];
+ System.arraycopy(fBuffer[i], range[0], result, current, length);
+ current += length;
+ }
+ return result;
}
-
+ return null;
+}
+/**
+ * Returns the contents of the buffer as a String, or
+ * <code>null</code> if the buffer is empty.
+ */
+public String toString() {
+ char[] contents = getContents();
+ return (contents != null) ? new String(contents) : null;
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/CharArrayOps.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/CharArrayOps.java
index 4a883d89ba..f8c98a9c9c 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/CharArrayOps.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/CharArrayOps.java
@@ -1,138 +1,131 @@
package org.eclipse.jdt.internal.core.util;
public class CharArrayOps {
- /**
- * Returns the char arrays as an array of Strings
- */
- public static String[] charcharToString(char[][] charchar) {
- if (charchar == null) {
- return null;
- }
- String[] strings = new String[charchar.length];
- for (int i = 0; i < charchar.length; i++) {
- strings[i] = new String(charchar[i]);
- }
- return strings;
+/**
+ * Returns the char arrays as an array of Strings
+ */
+public static String[] charcharToString(char[][] charchar) {
+ if (charchar == null) {
+ return null;
}
-
- /**
- * Returns the char array as a String
- */
- public static String charToString(char[] chars) {
- if (chars == null) {
- return null;
- } else {
- return new String(chars);
- }
+ String[] strings= new String[charchar.length];
+ for (int i= 0; i < charchar.length; i++) {
+ strings[i]= new String(charchar[i]);
}
-
- /**
- * Concatinates the two arrays into one big array.
- * If the first array is null, returns the second array.
- * If the second array is null, returns the first array.
- *
- * @param first - the array which the other array is concatinated onto
- * @param second - the array which is to be concatinated onto the first array
- */
- public static char[] concat(char[] first, char[] second) {
- if (first == null)
- return second;
- if (second == null)
- return first;
-
- int length1 = first.length;
- int length2 = second.length;
- char[] result = new char[length1 + length2];
- System.arraycopy(first, 0, result, 0, length1);
- System.arraycopy(second, 0, result, length1, length2);
- return result;
+ return strings;
+}
+/**
+ * Returns the char array as a String
+ */
+public static String charToString(char[] chars) {
+ if (chars == null) {
+ return null;
+ } else {
+ return new String(chars);
}
+}
+/**
+ * Concatinates the two arrays into one big array.
+ * If the first array is null, returns the second array.
+ * If the second array is null, returns the first array.
+ *
+ * @param first - the array which the other array is concatinated onto
+ * @param second - the array which is to be concatinated onto the first array
+ */
+public static char[] concat(char[] first, char[] second) {
+ if (first == null)
+ return second;
+ if (second == null)
+ return first;
- /**
- * Checks the two character arrays for equality.
- *
- * @param first - one of the arrays to be compared
- * @param second - the other array which is to be compared
- */
- public static boolean equals(char[] first, char[] second) {
- if (first == second)
- return true;
- if (first == null || second == null)
- return false;
- if (first.length != second.length)
- return false;
-
- for (int i = 0, length = first.length; i < length; i++)
- if (first[i] != second[i])
- return false;
+ int length1 = first.length;
+ int length2 = second.length;
+ char[] result = new char[length1 + length2];
+ System.arraycopy(first, 0, result, 0, length1);
+ System.arraycopy(second, 0, result, length1, length2);
+ return result;
+}
+/**
+ * Checks the two character arrays for equality.
+ *
+ * @param first - one of the arrays to be compared
+ * @param second - the other array which is to be compared
+ */
+public static boolean equals(char[] first, char[] second) {
+ if (first == second)
return true;
- }
+ if (first == null || second == null)
+ return false;
+ if (first.length != second.length)
+ return false;
- /**
- * Returns the index of the first occurrence of character in buffer,
- * starting from offset, or -1 if not found.
- */
- public static int indexOf(char character, char[] buffer, int offset) {
- for (int i = offset; i < buffer.length; i++) {
- if (buffer[i] == character) {
- return i;
- }
+ for (int i = 0, length = first.length; i < length; i++)
+ if (first[i] != second[i])
+ return false;
+ return true;
+}
+/**
+ * Returns the index of the first occurrence of character in buffer,
+ * starting from offset, or -1 if not found.
+ */
+public static int indexOf(char character, char[] buffer, int offset) {
+ for (int i= offset; i < buffer.length; i++) {
+ if (buffer[i] == character) {
+ return i;
}
- return -1;
- }
-
- /**
- * Extracts a sub-array from the given array, starting
- * at the given startIndex and proceeding for length characters.
- * Returns null if:
- * 1. the src array is null
- * 2. the start index is out of bounds
- * 3. the length parameter specifies a end point which is out of bounds
- * Does not return a copy of the array if possible, i.e. if start is zero
- * and length equals the length of the src array.
- *
- * @param src - the array from which elements need to be copied
- * @param start - the start index in the src array
- * @param length - the number of characters to copy
- */
- public static char[] subarray(char[] src, int start, int length) {
- if (src == null)
- return null;
- int srcLength = src.length;
- if (start < 0 || start >= srcLength)
- return null;
- if (length < 0 || start + length > srcLength)
- return null;
- if (srcLength == length && start == 0)
- return src;
-
- char[] result = new char[length];
- if (length > 0)
- System.arraycopy(src, start, result, 0, length);
- return result;
}
-
- /**
- * Extracts a substring from the given array, starting
- * at the given startIndex and proceeding for length characters.
- * Returns null if:
- * 1. the src array is null
- * 2. the start index is out of bounds
- * 3. the length parameter specifies a end point which is out of bounds
- * Does not return a copy of the array if possible, i.e. if start is zero
- * and length equals the length of the src array.
- *
- * @param src - the array from which elements need to be copied
- * @param start - the start index in the src array
- * @param length - the number of characters to copy
- */
- public static String substring(char[] src, int start, int length) {
- char[] chars = subarray(src, start, length);
- if (chars != null) {
- return new String(chars);
- } else {
- return null;
- }
+ return -1;
+}
+/**
+ * Extracts a sub-array from the given array, starting
+ * at the given startIndex and proceeding for length characters.
+ * Returns null if:
+ * 1. the src array is null
+ * 2. the start index is out of bounds
+ * 3. the length parameter specifies a end point which is out of bounds
+ * Does not return a copy of the array if possible, i.e. if start is zero
+ * and length equals the length of the src array.
+ *
+ * @param src - the array from which elements need to be copied
+ * @param start - the start index in the src array
+ * @param length - the number of characters to copy
+ */
+public static char[] subarray(char[] src, int start, int length) {
+ if (src == null)
+ return null;
+ int srcLength = src.length;
+ if (start < 0 || start >= srcLength)
+ return null;
+ if (length < 0 || start + length > srcLength)
+ return null;
+ if (srcLength == length && start == 0)
+ return src;
+
+ char[] result = new char[length];
+ if (length > 0)
+ System.arraycopy(src, start, result, 0, length);
+ return result;
+}
+/**
+ * Extracts a substring from the given array, starting
+ * at the given startIndex and proceeding for length characters.
+ * Returns null if:
+ * 1. the src array is null
+ * 2. the start index is out of bounds
+ * 3. the length parameter specifies a end point which is out of bounds
+ * Does not return a copy of the array if possible, i.e. if start is zero
+ * and length equals the length of the src array.
+ *
+ * @param src - the array from which elements need to be copied
+ * @param start - the start index in the src array
+ * @param length - the number of characters to copy
+ */
+public static String substring(char[] src, int start, int length) {
+ char[] chars= subarray(src, start, length);
+ if (chars != null) {
+ return new String(chars);
+ } else {
+ return null;
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/DiskCache.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/DiskCache.java
index c97ce31b08..dd1ba41135 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/DiskCache.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/DiskCache.java
@@ -4,6 +4,8 @@ package org.eclipse.jdt.internal.core.util;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
+import org.eclipse.jdt.internal.core.Util;
+
import java.io.*;
import java.util.*;
@@ -31,7 +33,7 @@ public class DiskCache {
* Max size of the cache in K.
*/
int fSpaceLimit;
-
+
/**
* Used for creating cache entry files.
*/
@@ -42,7 +44,7 @@ public class DiskCache {
* or because file is still open.
*/
Vector fFilesToBeDeleted = new Vector();
-
+
/**
* Extends the LRU cache entry to add extra fields needed by disk cache.
* We could avoided overriding the cache entry class by creating another object
@@ -51,19 +53,13 @@ public class DiskCache {
* It is static because it doesn't require an outer instance.
*/
protected static class Entry extends LRUCache.LRUCacheEntry {
-
+
long fLastAccess;
byte[] fExtraInfo;
int fFlags;
static final int F_COMPLETE = 1;
-
- Entry(
- String key,
- int size,
- String fileName,
- long lastAccess,
- byte[] extraInfo,
- int flags) {
+
+ Entry(String key, int size, String fileName, long lastAccess, byte[] extraInfo, int flags) {
// use super's key, value and space fields for our key, fileName and size.
super(key, fileName, size);
fLastAccess = lastAccess;
@@ -72,15 +68,10 @@ public class DiskCache {
}
DiskCacheEntry asDiskCacheEntry() {
- return new DiskCacheEntry(
- (String) _fKey,
- _fSpace,
- (String) _fValue,
- fLastAccess,
- fExtraInfo);
+ return new DiskCacheEntry((String)_fKey, _fSpace, (String)_fValue, fLastAccess, fExtraInfo);
}
}
-
+
/**
* The maximum size of the cache, in number of K.
*/
@@ -99,21 +90,20 @@ public class DiskCache {
* An item is being removed from the cache. Delete its file.
*/
protected void privateNotifyDeletionFromCache(LRUCacheEntry entry) {
- String fileName = (String) entry._fValue;
- if ((((Entry) entry).fFlags & Entry.F_COMPLETE) != 0) {
+ String fileName = (String)entry._fValue;
+ if ((((Entry)entry).fFlags & Entry.F_COMPLETE) != 0) {
/* Entry has been complete written, so we can delete it. */
boolean success = deleteFile(fileName);
- if (success)
- return;
+ if (success) return;
/* If success == false, then it is inconsistent with the flag's
* F_COMPLETE mask. Something is wrong. */
- }
+ }
/* Otherwise, or if file deletion failed (probably due to
* a stream on it still being open), mark the file for deletion later
* (at save or reload time) checking again to see if it's closed. */
- rememberToDelete(fileName);
+ rememberToDelete(fileName);
}
-
+
/**
* Lookup an entry. Expose the Entry object.
*/
@@ -122,7 +112,7 @@ public class DiskCache {
if (entry == null) {
return null;
}
- updateTimestamp(entry);
+ updateTimestamp (entry);
return entry;
}
@@ -134,16 +124,16 @@ public class DiskCache {
if (entry == null) {
return null;
}
- this.privateRemoveEntry(entry, false);
+ this.privateRemoveEntry (entry, false);
return entry;
}
-
+
/**
* Updates the timestamp for the given entry, ensuring that the queue is
* kept in correct order. The entry must exist
*/
- protected void updateTimestamp(LRUCacheEntry entry) {
- ((Entry) entry).fLastAccess = System.currentTimeMillis();
+ protected void updateTimestamp (LRUCacheEntry entry) {
+ ((Entry)entry).fLastAccess = System.currentTimeMillis();
super.updateTimestamp(entry);
}
@@ -161,18 +151,18 @@ public class DiskCache {
public Enumeration getEntries() {
return new Enumeration() {
- Entry current = (Entry) fEntryQueue;
-
+ Entry current = (Entry)fEntryQueue;
+
public boolean hasMoreElements() {
return current != null;
}
-
+
public Object nextElement() {
if (current == null) {
throw new NoSuchElementException();
}
Entry result = current;
- current = (Entry) current._fNext;
+ current = (Entry)current._fNext;
return result;
}
};
@@ -181,9 +171,9 @@ public class DiskCache {
EntryCache fEntryCache;
- static final String CONTENTS_FILE_NAME = "contents";
- static final String TEMP_CONTENTS_FILE_NAME = "tempcont";
- static final String CONTENTS_VERSION = "DiskCache.V1.0";
+ static final String CONTENTS_FILE_NAME = "contents"/*nonNLS*/;
+ static final String TEMP_CONTENTS_FILE_NAME = "tempcont"/*nonNLS*/;
+ static final String CONTENTS_VERSION = "DiskCache.V1.0"/*nonNLS*/;
/**
* Set to true when cache is modified, cleared when saved.
@@ -199,23 +189,23 @@ public class DiskCache {
* Interval for periodic save checks, in ms. 5 sec by default.
*/
int fPeriodicSaveInterval = 60000;
-
- /**
- * Create a disk cache which uses the given filesystem directory
- * and has the given space limit (in kilobytes).
- */
- public DiskCache(File directory, int spaceLimit) {
- fDirectory = directory;
- fFileSource = new AnonymousFileSource(directory);
- fSpaceLimit = spaceLimit;
- createEntryCache();
- try {
- read();
- deleteFilesToBeDeleted();
- } catch (IOException e) {
- }
+
+/**
+ * Create a disk cache which uses the given filesystem directory
+ * and has the given space limit (in kilobytes).
+ */
+public DiskCache(File directory, int spaceLimit) {
+ fDirectory = directory;
+ fFileSource = new AnonymousFileSource(directory);
+ fSpaceLimit = spaceLimit;
+ createEntryCache();
+ try {
+ read();
+ deleteFilesToBeDeleted();
}
-
+ catch (IOException e) {
+ }
+}
/**
* Add an entry to the cache. The size of the entry in bytes must be given.
* Extra information in the form of a byte array may optionally be associated
@@ -225,15 +215,14 @@ public class DiskCache {
*
* @throws IOException if a file for the entry's contents could not be created
*/
- public OutputStream add(final String key, int size, byte[] extraInfo)
- throws IOException {
- if (size > fSpaceLimit * 1024) {
+ public OutputStream add(final String key, int size, byte[] extraInfo) throws IOException {
+ if (size > fSpaceLimit*1024) {
throw new IOException("Entry size greater than cache size");
}
final File file;
OutputStream output;
// Allocate the file first. If errors occur, no entry is added.
- synchronized (fFileSource) {
+ synchronized(fFileSource) {
file = fFileSource.getAnonymousFile();
output = new FileOutputStream(file);
}
@@ -241,9 +230,8 @@ public class DiskCache {
if (extraInfo != null && extraInfo.length == 0) {
extraInfo = null;
}
- final Entry entry =
- new Entry(key, size, file.getName(), lastAccess, extraInfo, 0);
- synchronized (fEntryCache) {
+ final Entry entry = new Entry(key, size, file.getName(), lastAccess, extraInfo, 0);
+ synchronized(fEntryCache) {
// Only use the simple file name.
fEntryCache.add(entry);
}
@@ -252,57 +240,55 @@ public class DiskCache {
// Hopefully the content is received before the periodic save interval,
// so state is saved at most once for this entry.
modified();
-
+
// Return a filter stream which sets the complete flag when the stream is closed.
return new FilterOutputStream(output) {
public void write(byte b[], int off, int len) throws IOException {
out.write(b, off, len);
}
-
+
private void closeHelper() throws IOException {
super.close();
// Ensure entry is still valid.
// It may have been removed or replaced in the interim.
- synchronized (fEntryCache) {
+ synchronized(fEntryCache) {
if (fEntryCache.get(key) != entry) {
- String fileName = (String) entry._fValue;
+ String fileName = (String)entry._fValue;
boolean success = deleteFile(fileName);
if (!success) {
rememberToDelete(fileName);
}
}
}
- modified();
+ modified();
}
-
+
public void close() throws IOException {
entry.fFlags |= Entry.F_COMPLETE;
closeHelper();
}
-
- public void finalize() throws Throwable {
+
+ public void finalize() throws Throwable {
closeHelper();
super.finalize();
}
-
+
/* For debugging/testing ONLY. Do not use outside of test suites.*/
public String toString() {
return file.toString();
}
};
}
-
/**
* Clear the cache. All entries are removed and their associated files are deleted.
*/
public void clearCache() {
- synchronized (fEntryCache) {
+ synchronized(fEntryCache) {
fEntryCache.flush();
}
// Be sure to save the cleared contents.
- modified();
+ modified();
}
-
/**
* Close the cache.
* Flush incomplete entries, save volatile state if needed, and halt periodic saves.
@@ -311,7 +297,8 @@ public class DiskCache {
if (fIsDirty || flushIncompleteEntries()) {
try {
save();
- } catch (IOException e) {
+ }
+ catch (IOException e) {
// Ignore
}
}
@@ -322,15 +309,13 @@ public class DiskCache {
thread.interrupt();
}
}
-
/**
* Internal - (Re)create the internal entry cache.
*/
protected void createEntryCache() {
fEntryCache = new EntryCache();
- fEntryCache.setSpaceLimit(fSpaceLimit * 1024);
+ fEntryCache.setSpaceLimit(fSpaceLimit*1024);
}
-
/**
* Internal - Delete the file for an entry. Returns the
* "success flag" result from java.io.File's delete().
@@ -340,29 +325,27 @@ public class DiskCache {
fileToDelete.delete();
// Could have already been deleted.
boolean success = !fileToDelete.exists();
- if (success && fFilesToBeDeleted.contains(fileName))
+ if(success && fFilesToBeDeleted.contains(fileName))
fFilesToBeDeleted.removeElement(fileName);
- return success;
+ return success;
}
-
- /**
- * Internal - Deletes the files that have been flagged for deletion. Returns
- * the number of flagged files that remain undeleted.
- */
- public int deleteFilesToBeDeleted() {
- synchronized (fFilesToBeDeleted) {
- Vector clone = (Vector) fFilesToBeDeleted.clone();
- Enumeration e = clone.elements();
- while (e.hasMoreElements()) {
- String fileName = (String) e.nextElement();
- boolean success = deleteFile(fileName);
- if (success)
- fFilesToBeDeleted.removeElement(fileName);
- }
- return fFilesToBeDeleted.size();
+/**
+ * Internal - Deletes the files that have been flagged for deletion. Returns
+ * the number of flagged files that remain undeleted.
+ */
+public int deleteFilesToBeDeleted() {
+ synchronized (fFilesToBeDeleted) {
+ Vector clone = (Vector) fFilesToBeDeleted.clone();
+ Enumeration e = clone.elements();
+ while(e.hasMoreElements()) {
+ String fileName = (String) e.nextElement();
+ boolean success = deleteFile(fileName);
+ if (success)
+ fFilesToBeDeleted.removeElement(fileName);
}
+ return fFilesToBeDeleted.size();
}
-
+}
/**
* Flush all incomplete entries from the cache.
* Returns true if some were flushed.
@@ -370,61 +353,54 @@ public class DiskCache {
protected boolean flushIncompleteEntries() {
Vector v = new Vector();
for (Enumeration e = fEntryCache.getEntries(); e.hasMoreElements();) {
- Entry entry = (Entry) e.nextElement();
+ Entry entry = (Entry)e.nextElement();
if ((entry.fFlags & Entry.F_COMPLETE) == 0) {
v.addElement(entry._fKey);
}
}
for (int i = 0, size = v.size(); i < size; ++i) {
- fEntryCache.removeKey((String) v.elementAt(i));
+ fEntryCache.removeKey((String)v.elementAt(i));
}
return v.size() > 0;
}
-
/**
* Returns the directory which holds the cache.
*/
public File getDirectory() {
return fDirectory;
}
-
- /**
- * For debugging/testing purposes.
- */
- public int getNumberOfFilesToBeDeleted() {
- return fFilesToBeDeleted.size();
- }
-
+/**
+ * For debugging/testing purposes.
+ */
+public int getNumberOfFilesToBeDeleted() {
+ return fFilesToBeDeleted.size();
+}
/**
* Return the number of entries in the cache.
*/
public int getNumEntries() {
return fEntryCache.getNumEntries();
}
-
/**
* Returns the delay in milliseconds between periodic saves.
*/
public int getPeriodicSaveInterval() {
return fPeriodicSaveInterval;
}
-
/**
* Returns the space limit of the cache, in Kilobytes.
*/
public int getSpaceLimit() {
return fSpaceLimit;
}
-
/**
* Returns the space used by the cache, in Kilobytes.
*/
public int getSpaceUsed() {
- synchronized (fEntryCache) {
+ synchronized(fEntryCache) {
return (fEntryCache.getCurrentSpace() + 1023) / 1024; // Take ceiling.
}
}
-
/**
* Returns an enumeration on the keys (Strings)
* of the entries in the cache.
@@ -432,7 +408,6 @@ public class DiskCache {
public Enumeration keys() {
return fEntryCache.keys();
}
-
/**
* Look up an entry in the cache. Answer the entry if found, or null if not found.
* If the contents are to be retrieved, use the <code>open</code> method rather than
@@ -442,19 +417,19 @@ public class DiskCache {
*/
public DiskCacheEntry lookup(String key) {
Entry entry;
- synchronized (fEntryCache) {
+ synchronized(fEntryCache) {
entry = fEntryCache.get(key);
}
if (entry == null || (entry.fFlags & Entry.F_COMPLETE) == 0) {
return null;
- } else {
+ }
+ else {
// If the entry was found, then the contents should be
// resaved because the order of items in it has changed.
modified();
return entry.asDiskCacheEntry();
}
}
-
/**
* Internal - The cache has been modified. Remember to save the state.
* Method is synchronized to protect fPeriodicSaveThread from concurrent access.
@@ -465,7 +440,6 @@ public class DiskCache {
startPeriodicSaveThread();
}
}
-
/**
* Open an input stream on the contents of the given entry.
* The passed entry must be the result of a previous lookup operation.
@@ -483,9 +457,9 @@ public class DiskCache {
if (finalEntry == null || !fileName.equals((String) finalEntry._fValue)) {
throw new FileNotFoundException();
}
-
+
final File file = fFileSource.fileForName(fileName);
-
+
class DiskCachePrivateFileInputStream extends FileInputStream {
DiskCachePrivateFileInputStream(File file) throws FileNotFoundException {
super(file);
@@ -494,7 +468,7 @@ public class DiskCache {
super.close();
// Ensure entry is still valid.
// It may have been removed or replaced in the interim.
- synchronized (fEntryCache) {
+ synchronized(fEntryCache) {
if (fEntryCache.get(key) != finalEntry) {
boolean success = deleteFile(fileName);
if (!success) {
@@ -502,9 +476,9 @@ public class DiskCache {
}
}
}
- modified();
+ modified();
}
- protected void finalize() throws IOException {
+ protected void finalize() throws IOException {
close();
super.finalize();
}
@@ -515,7 +489,8 @@ public class DiskCache {
};
try {
return new DiskCachePrivateFileInputStream(file);
- } catch (FileNotFoundException e) {
+ }
+ catch (FileNotFoundException e) {
// If there's an error while opening the file,
// delete the entry and the file from the cache.
remove(key);
@@ -524,7 +499,6 @@ public class DiskCache {
throw e;
}
}
-
/**
* Read the cache state from persistent storage.
* Any undeleted entry files left at the last save the cach now tries to delete.
@@ -534,15 +508,17 @@ public class DiskCache {
if (!file.exists()) {
return;
}
- DataInputStream in =
- new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
+ DataInputStream in =
+ new DataInputStream(
+ new BufferedInputStream(
+ new FileInputStream(file)));
try {
String sig = in.readUTF();
int spaceLimit = in.readInt(); /* Ignored -- use current limit */
- int spaceUsed = in.readInt(); /* Ignored -- updated as entries are read */
+ int spaceUsed = in.readInt(); /* Ignored -- updated as entries are read */
int numEntries = in.readInt();
if (!sig.equals(CONTENTS_VERSION)) {
- throw new IOException("Invalid format");
+ throw new IOException(Util.bind("file.badFormat")/*nonNLS*/);
}
/* Read to a temp. array of entries. The entries are in most- to
@@ -558,7 +534,7 @@ public class DiskCache {
for (int i = numEntries - 1; i >= 0; --i) {
fEntryCache.add(entries[i]);
}
-
+
/* Read in names of files to be deleted. */
/* But first, check that we are not at the end of the file (which occurs
* in pre-existing file formats). Try reading an int to find this out. */
@@ -570,19 +546,19 @@ public class DiskCache {
} catch (IOException ignoreMe) {
/* We're at the end of file, so it's a pre-existing format. */
}
- if (moreToRead) {
+ if(moreToRead) {
fFilesToBeDeleted = new Vector();
for (int i = 0; i < numFilesToBeDeleted; i++) {
String fileName = in.readUTF();
fFilesToBeDeleted.addElement(fileName);
}
}
-
- } finally {
+
+ }
+ finally {
in.close();
}
}
-
/**
* Internal - Read an entry from a stream. Returns an internal cache Entry.
*/
@@ -600,7 +576,6 @@ public class DiskCache {
}
return new Entry(key, size, fileName, lastAccess, extraInfo, flags);
}
-
/**
* Internal - Remember to delete a file later.
*/
@@ -608,58 +583,49 @@ public class DiskCache {
if (!fFilesToBeDeleted.contains(fileName))
fFilesToBeDeleted.addElement(fileName);
}
-
/**
* Remove an entry from the cache and delete its contents.
* Answer the entry if found, or null if not found.
*/
public DiskCacheEntry remove(String key) {
Entry entry;
- synchronized (fEntryCache) {
+ synchronized(fEntryCache) {
entry = fEntryCache.removeKey(key);
}
if (entry == null) {
return null;
- } else {
+ }
+ else {
modified();
return entry.asDiskCacheEntry();
}
}
-
- public synchronized void removeAll(Vector keys) {
- Enumeration enum = keys.elements();
- while (enum.hasMoreElements()) {
- String key = (String) enum.nextElement();
- remove(key);
- }
+public synchronized void removeAll(Vector keys) {
+ Enumeration enum = keys.elements();
+ while (enum.hasMoreElements()) {
+ String key = (String) enum.nextElement();
+ remove(key);
}
-
+}
/**
* Renames an entry in the cache.
* Returns true if the rename succeeded, false otherwise.
*/
public boolean rename(String oldKey, String newKey) {
long lastAccess = System.currentTimeMillis();
- synchronized (fEntryCache) {
+ synchronized(fEntryCache) {
Entry oldEntry = (Entry) fEntryCache.get(oldKey);
if (oldEntry == null) {
return false;
- } else {
- Entry newEntry =
- new Entry(
- newKey,
- oldEntry._fSpace,
- (String) oldEntry._fValue,
- lastAccess,
- oldEntry.fExtraInfo,
- oldEntry.fFlags);
+ }
+ else {
+ Entry newEntry = new Entry(newKey, oldEntry._fSpace, (String) oldEntry._fValue, lastAccess, oldEntry.fExtraInfo, oldEntry.fFlags);
fEntryCache.add(newEntry);
}
}
modified();
return true;
}
-
/**
* Save all in-memory cache state to persistent storage.
* Tries to deleted undeleted entry files.
@@ -675,24 +641,26 @@ public class DiskCache {
* the face of errors such as disk full.
*/
File tempFile = new File(fDirectory, TEMP_CONTENTS_FILE_NAME);
- DataOutputStream out =
- new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tempFile)));
+ DataOutputStream out =
+ new DataOutputStream(
+ new BufferedOutputStream(
+ new FileOutputStream(tempFile)));
boolean ok = false;
try {
- synchronized (fEntryCache) {
+ synchronized(fEntryCache) {
out.writeUTF(CONTENTS_VERSION);
out.writeInt(getSpaceLimit());
out.writeInt(getSpaceUsed());
int numEntries = fEntryCache.getNumEntries();
out.writeInt(numEntries);
for (Enumeration e = fEntryCache.getEntries(); e.hasMoreElements();) {
- Entry entry = (Entry) e.nextElement();
+ Entry entry = (Entry)e.nextElement();
writeEntry(entry, out);
}
int numFilesToBeDeleted = fFilesToBeDeleted.size();
out.writeInt(numFilesToBeDeleted);
Enumeration e = fFilesToBeDeleted.elements();
- while (e.hasMoreElements()) {
+ while(e.hasMoreElements()) {
String fileName = (String) e.nextElement();
out.writeUTF(fileName);
}
@@ -706,31 +674,29 @@ public class DiskCache {
ok = true;
fIsDirty = false;
}
- } finally {
+ }
+ finally {
if (!ok) {
out.close();
tempFile.delete();
}
}
}
-
/**
* Sets the delay in milliseconds between periodic saves.
*/
public void setPeriodicSaveInterval(int interval) {
fPeriodicSaveInterval = interval;
}
-
/**
* Sets the space limit of the cache, in Kilobytes.
*/
public void setSpaceLimit(int limit) {
fSpaceLimit = limit;
- synchronized (fEntryCache) {
+ synchronized(fEntryCache) {
fEntryCache.setSpaceLimit(limit * 1024);
}
}
-
/**
* Internal -
* Create and start a thread which checks every so often whether
@@ -743,51 +709,53 @@ public class DiskCache {
public void run() {
try {
Thread.sleep(fPeriodicSaveInterval);
- } catch (InterruptedException e) {
+ }
+ catch (InterruptedException e) {
}
for (;;) {
- synchronized (DiskCache.this) {
+ synchronized(DiskCache.this) {
if (fIsDirty) {
try {
- save(); // clears dirty flag
- } catch (IOException e) {
+ save(); // clears dirty flag
+ }
+ catch (IOException e) {
// Ignore
}
- } else {
+ }
+ else {
// drop ref to thread and terminate
- fPeriodicSaveThread = null;
+ fPeriodicSaveThread = null;
return;
}
}
try {
Thread.sleep(fPeriodicSaveInterval);
- } catch (InterruptedException e) {
+ }
+ catch (InterruptedException e) {
}
}
- }
+ }
};
fPeriodicSaveThread.setName("DiskCache periodic save");
fPeriodicSaveThread.start();
-
+
}
-
/**
* Internal - Write an internal cache Entry to a stream.
*/
- protected void writeEntry(Entry entry, DataOutputStream out)
- throws IOException {
- out.writeUTF((String) entry._fKey);
+ protected void writeEntry(Entry entry, DataOutputStream out) throws IOException {
+ out.writeUTF((String)entry._fKey);
out.writeInt(entry._fSpace);
- out.writeUTF((String) entry._fValue); // fileName
+ out.writeUTF((String)entry._fValue); // fileName
out.writeLong(entry.fLastAccess);
out.writeInt(entry.fFlags);
byte[] extraInfo = entry.fExtraInfo;
if (extraInfo == null) {
out.writeInt(0);
- } else {
+ }
+ else {
out.writeInt(extraInfo.length);
out.write(extraInfo);
}
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/DiskCacheEntry.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/DiskCacheEntry.java
index 16891ac971..d5d374fbcd 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/DiskCacheEntry.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/DiskCacheEntry.java
@@ -9,19 +9,13 @@ public class DiskCacheEntry {
/**
* Create an entry.
*/
- DiskCacheEntry(
- String key,
- int size,
- String fileName,
- long lastAccess,
- byte[] extraInfo) {
+ DiskCacheEntry(String key, int size, String fileName, long lastAccess, byte[] extraInfo) {
fKey = key;
fSize = size;
fFileName = fileName;
fLastAccess = lastAccess;
fExtraInfo = extraInfo;
}
-
/**
* Returns the extra info associated with this entry,
* or null if there is no extra info.
@@ -29,7 +23,6 @@ public class DiskCacheEntry {
public byte[] getExtraInfo() {
return fExtraInfo;
}
-
/**
* Returns the file name of the entry.
* This name is assigned by the cache and is, strictly speaking,
@@ -39,7 +32,6 @@ public class DiskCacheEntry {
public String getFileName() {
return fFileName;
}
-
/**
* Returns the key for this entry.
* The key was used to look up this entry.
@@ -47,7 +39,6 @@ public class DiskCacheEntry {
public String getKey() {
return fKey;
}
-
/**
* Returns the time that this entry was last accessed,
* in milliseconds since Jan 1, 1970.
@@ -55,12 +46,10 @@ public class DiskCacheEntry {
public long getLastAccess() {
return fLastAccess;
}
-
/**
* Returns the size of the entry in bytes.
*/
public int getSize() {
return fSize;
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/Dumper.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/Dumper.java
index bbbed933ad..7f7693fc15 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/Dumper.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/Dumper.java
@@ -23,297 +23,273 @@ import java.io.*;
public class Dumper {
int fTabLevel = 0;
PrintWriter fWriter;
- /**
- * Creates a dumper which sends output to System.out.
- */
- public Dumper() {
- this(System.out);
- }
-
- /**
- * Creates a dumper which sends output to the given OutputStream.
- */
- public Dumper(OutputStream out) {
- this(new PrintWriter(out));
- }
-
- /**
- * Creates a dumper which sends output to the given PrintWriter.
- */
- public Dumper(PrintWriter writer) {
- fWriter = writer;
- }
-
- /**
- * Returns the class name to use for the given object.
- */
- String classNameFor(Object val) {
- String name = val.getClass().getName();
- int i = name.lastIndexOf('.');
- if (i != -1) {
- name = name.substring(i + 1);
- }
- return name;
- }
-
- /**
- * Dumps the given array.
- * Prints a maximum of maxPerLine items per line.
- */
- public void dump(int[] val, int maxPerLine) {
- int len = val.length;
- boolean oneLine = (len <= maxPerLine);
- if (!oneLine) {
- ++fTabLevel;
- }
- fWriter.print("[");
- for (int i = 0; i < len; ++i) {
- if (!oneLine) {
- if ((i % maxPerLine) == 0) {
- fWriter.println();
- tabIfNeeded();
- fWriter.print(i);
- fWriter.print(": ");
- }
- }
- fWriter.print(val[i]);
- if (i + 1 < len) {
- fWriter.print(", ");
- }
- }
- if (oneLine) {
- fWriter.print("]");
- fWriter.println();
- } else {
- fWriter.println();
- --fTabLevel;
- tabIfNeeded();
- fWriter.print("]");
- fWriter.println();
- }
+/**
+ * Creates a dumper which sends output to System.out.
+ */
+public Dumper() {
+ this(System.out);
+}
+/**
+ * Creates a dumper which sends output to the given OutputStream.
+ */
+public Dumper(OutputStream out) {
+ this(new PrintWriter(out));
+}
+/**
+ * Creates a dumper which sends output to the given PrintWriter.
+ */
+public Dumper(PrintWriter writer) {
+ fWriter = writer;
+}
+/**
+ * Returns the class name to use for the given object.
+ */
+String classNameFor(Object val) {
+ String name = val.getClass().getName();
+ int i = name.lastIndexOf('.');
+ if (i != -1) {
+ name = name.substring(i+1);
}
-
- /**
- * Dumps the given array.
- */
- public void dump(Object[] val) {
- int len = val.length;
- fWriter.print("[");
- if (len > 0) {
- fWriter.println();
- ++fTabLevel;
- for (int i = 0; i < len; ++i) {
- dump(val[i]);
- }
- --fTabLevel;
- tabIfNeeded();
- }
- fWriter.println("]");
+ return name;
+}
+/**
+ * Dumps the given array.
+ * Prints a maximum of maxPerLine items per line.
+ */
+public void dump(int[] val, int maxPerLine) {
+ int len = val.length;
+ boolean oneLine = (len <= maxPerLine);
+ if (!oneLine) {
+ ++fTabLevel;
}
-
- /**
- * Dumps the given array.
- * Prints a maximum of maxPerLine items per line.
- */
- public void dump(String[] val, int maxPerLine) {
- int len = val.length;
- boolean oneLine = (len <= maxPerLine);
+ fWriter.print("["/*nonNLS*/);
+ for (int i = 0; i < len; ++i) {
if (!oneLine) {
- ++fTabLevel;
- }
- fWriter.print("[");
- boolean newLine = !oneLine;
- for (int i = 0; i < len; ++i) {
- if (newLine) {
+ if ((i % maxPerLine) == 0) {
fWriter.println();
tabIfNeeded();
+ fWriter.print(i);
+ fWriter.print(": ");
}
- fWriter.print("\"" + val[i] + "\"");
- if (i + 1 < len) {
- fWriter.print(", ");
- }
- newLine = (i != 0 && (i % maxPerLine) == 0);
- }
- fWriter.print("]");
- if (oneLine || newLine) {
- fWriter.println();
}
- if (!oneLine) {
- --fTabLevel;
+ fWriter.print(val[i]);
+ if (i + 1 < len) {
+ fWriter.print(", "/*nonNLS*/);
}
}
-
- /**
- * Dumps the given value.
- */
- public void dump(Object val) {
- tabIfNeeded();
- if (val instanceof IDumpable) {
- IDumpable dumpable = (IDumpable) val;
- fWriter.println(classNameFor(val) + " {");
- int originalLevel = fTabLevel;
- ++fTabLevel;
- try {
- dumpable.dump(this);
- } catch (Throwable t) {
- fWriter.println("*ERR*");
- }
- fTabLevel = originalLevel;
- tabIfNeeded();
- fWriter.println("}");
- } else {
- fWriter.println(val);
- }
- }
-
- /**
- * Dumps the given value, with the given name as a prefix.
- */
- public void dump(String name, int[] val) {
- dump(name, val, 10);
- }
-
- /**
- * Dumps the given array, with the given name as a prefix.
- * Prints a maximum of maxPerLine items per line.
- */
- public void dump(String name, int[] val, int maxPerLine) {
- prefix(name);
- dump(val, maxPerLine);
- }
-
- /**
- * Dumps the given value, with the given name as a prefix.
- */
- public void dump(String name, Object[] val) {
- prefix(name);
- dump(val);
- }
-
- /**
- * Dumps the given value, with the given name as a prefix.
- */
- public void dump(String name, String[] val) {
- prefix(name);
- dump(val, 5);
+ if (oneLine) {
+ fWriter.print("]"/*nonNLS*/);
+ fWriter.println();
}
-
- /**
- * Dumps the given value, with the given name as a prefix.
- */
- public void dump(String name, int val) {
- prefix(name);
- fWriter.println(val);
+ else {
+ fWriter.println();
+ --fTabLevel;
+ tabIfNeeded();
+ fWriter.print("]"/*nonNLS*/);
+ fWriter.println();
}
-
- /**
- * Dumps the given value, with the given name as a prefix.
- */
- public void dump(String name, Object val) {
- prefix(name);
+}
+/**
+ * Dumps the given array.
+ */
+public void dump(Object[] val) {
+ int len = val.length;
+ fWriter.print("["/*nonNLS*/);
+ if (len > 0) {
fWriter.println();
++fTabLevel;
- dump(val);
+ for (int i = 0; i < len; ++i) {
+ dump(val[i]);
+ }
--fTabLevel;
+ tabIfNeeded();
}
-
- /**
- * Dumps the given value, with the given name as a prefix.
- */
- public void dump(String name, String val) {
- prefix(name);
- fWriter.println(val == null ? "null" : "\"" + val + "\"");
- }
-
- /**
- * Dumps the given value, with the given name as a prefix.
- */
- public void dump(String name, boolean val) {
- prefix(name);
- fWriter.println(val);
- }
-
- /**
- * Dumps the given message, with the given name as a prefix.
- */
- public void dumpMessage(String name, String msg) {
- prefix(name);
- fWriter.println(msg);
+ fWriter.println("]"/*nonNLS*/);
+}
+/**
+ * Dumps the given array.
+ * Prints a maximum of maxPerLine items per line.
+ */
+public void dump(String[] val, int maxPerLine) {
+ int len = val.length;
+ boolean oneLine = (len <= maxPerLine);
+ if (!oneLine) {
+ ++fTabLevel;
}
-
- /**
- * Flushes the output writer.
- */
- public void flush() {
- fWriter.flush();
+ fWriter.print("["/*nonNLS*/);
+ boolean newLine = !oneLine;
+ for (int i = 0; i < len; ++i) {
+ if (newLine) {
+ fWriter.println();
+ tabIfNeeded();
+ }
+ fWriter.print("\""/*nonNLS*/ + val[i] + "\""/*nonNLS*/);
+ if (i + 1 < len) {
+ fWriter.print(", "/*nonNLS*/);
+ }
+ newLine = (i != 0 && (i % maxPerLine) == 0);
}
-
- /**
- * Returns the current tab level.
- */
- public int getTabLevel() {
- return fTabLevel;
+ fWriter.print("]"/*nonNLS*/);
+ if (oneLine || newLine) {
+ fWriter.println();
}
-
- /**
- * Returns the underlying PrintWriter.
- */
- public PrintWriter getWriter() {
- return fWriter;
+ if (!oneLine) {
+ --fTabLevel;
}
-
- /**
- * Increase the current tab level.
- */
- public void indent() {
+}
+/**
+ * Dumps the given value.
+ */
+public void dump(Object val) {
+ tabIfNeeded();
+ if (val instanceof IDumpable) {
+ IDumpable dumpable = (IDumpable) val;
+ fWriter.println(classNameFor(val) + " {"/*nonNLS*/);
+ int originalLevel = fTabLevel;
++fTabLevel;
- }
-
- /**
- * Decrease the current tab level.
- */
- public void outdent() {
- if (--fTabLevel < 0)
- fTabLevel = 0;
- }
-
- /**
- * Outputs the given prefix, tabbing first if needed.
- */
- void prefix(String name) {
+ try {
+ dumpable.dump(this);
+ }
+ catch (Throwable t) {
+ fWriter.println("*ERR*"/*nonNLS*/);
+ }
+ fTabLevel = originalLevel;
tabIfNeeded();
- fWriter.print(name);
- fWriter.print(": ");
- }
-
- /**
- * Print an object directly, without a newline.
- */
- public void print(Object obj) {
- fWriter.print(obj);
- }
-
- /**
- * Print a newline directly.
- */
- public void println() {
- fWriter.println();
+ fWriter.println("}"/*nonNLS*/);
}
-
- /**
- * Print an object directly, with a newline.
- */
- public void println(Object obj) {
- fWriter.println(obj);
+ else {
+ fWriter.println(val);
}
-
- /**
- * Outputs tabs if needed.
- */
- void tabIfNeeded() {
- for (int i = 0; i < fTabLevel; ++i) {
- fWriter.print(" ");
- }
+}
+/**
+ * Dumps the given value, with the given name as a prefix.
+ */
+public void dump(String name, int[] val) {
+ dump(name, val, 10);
+}
+/**
+ * Dumps the given array, with the given name as a prefix.
+ * Prints a maximum of maxPerLine items per line.
+ */
+public void dump(String name, int[] val, int maxPerLine) {
+ prefix(name);
+ dump(val, maxPerLine);
+}
+/**
+ * Dumps the given value, with the given name as a prefix.
+ */
+public void dump(String name, Object[] val) {
+ prefix(name);
+ dump(val);
+}
+/**
+ * Dumps the given value, with the given name as a prefix.
+ */
+public void dump(String name, String[] val) {
+ prefix(name);
+ dump(val, 5);
+}
+/**
+ * Dumps the given value, with the given name as a prefix.
+ */
+public void dump(String name, int val) {
+ prefix(name);
+ fWriter.println(val);
+}
+/**
+ * Dumps the given value, with the given name as a prefix.
+ */
+public void dump(String name, Object val) {
+ prefix(name);
+ fWriter.println();
+ ++fTabLevel;
+ dump(val);
+ --fTabLevel;
+}
+/**
+ * Dumps the given value, with the given name as a prefix.
+ */
+public void dump(String name, String val) {
+ prefix(name);
+ fWriter.println(val == null ? "null" : "\""/*nonNLS*/ + val + "\""/*nonNLS*/);
+}
+/**
+ * Dumps the given value, with the given name as a prefix.
+ */
+public void dump(String name, boolean val) {
+ prefix(name);
+ fWriter.println(val);
+}
+/**
+ * Dumps the given message, with the given name as a prefix.
+ */
+public void dumpMessage(String name, String msg) {
+ prefix(name);
+ fWriter.println(msg);
+}
+/**
+ * Flushes the output writer.
+ */
+public void flush() {
+ fWriter.flush();
+}
+/**
+ * Returns the current tab level.
+ */
+public int getTabLevel() {
+ return fTabLevel;
+}
+/**
+ * Returns the underlying PrintWriter.
+ */
+public PrintWriter getWriter() {
+ return fWriter;
+}
+/**
+ * Increase the current tab level.
+ */
+public void indent() {
+ ++fTabLevel;
+}
+/**
+ * Decrease the current tab level.
+ */
+public void outdent() {
+ if (--fTabLevel < 0)
+ fTabLevel = 0;
+}
+/**
+ * Outputs the given prefix, tabbing first if needed.
+ */
+void prefix(String name) {
+ tabIfNeeded();
+ fWriter.print(name);
+ fWriter.print(": ");
+}
+/**
+ * Print an object directly, without a newline.
+ */
+public void print(Object obj) {
+ fWriter.print(obj);
+}
+/**
+ * Print a newline directly.
+ */
+public void println() {
+ fWriter.println();
+}
+/**
+ * Print an object directly, with a newline.
+ */
+public void println(Object obj) {
+ fWriter.println(obj);
+}
+/**
+ * Outputs tabs if needed.
+ */
+void tabIfNeeded() {
+ for (int i = 0; i < fTabLevel; ++i) {
+ fWriter.print(" "/*nonNLS*/);
}
-
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/HackFinder.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/HackFinder.java
index 13b616559c..a060884a13 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/HackFinder.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/HackFinder.java
@@ -1,16 +1,14 @@
package org.eclipse.jdt.internal.core.util;
public class HackFinder {
- /**
- * Find stuff to revisit.
- */
- public static void fixMeLater(String arg) {
- }
-
- /**
- * Find stuff to revisit.
- */
- public static void fixMeSoon(String arg) {
- }
-
+/**
+ * Find stuff to revisit.
+ */
+public static void fixMeLater(String arg) {
+}
+/**
+ * Find stuff to revisit.
+ */
+public static void fixMeSoon(String arg) {
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/IProgressListener.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/IProgressListener.java
index d0c40368c7..ffce4a37a1 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/IProgressListener.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/IProgressListener.java
@@ -2,25 +2,25 @@ package org.eclipse.jdt.internal.core.util;
public interface IProgressListener {
- /** Notifies that the main task is beginning.
- @param name the name (or description) of the main task
- @param totalWork the total number of work units into which
- the main task is been subdivided
- */
- public void begin(String name, int totalWork);
- /** Notifies that the work is done, the main task is completed.
- */
- public void done();
- /** Notifies that a subtask of the main task is beginning.
- Subtasks are optional; the main task might not have subtasks.
- @param name the name (or description) of the subtask
- */
- public void nowDoing(String name);
- /** Notifies that a given number of work unit of the main task
- has been completed. Note that this amount represents an
- installment, as opposed to a cumulative amount of work done
- to date.
- @param work the work units just completed
- */
- public void worked(int work);
+/** Notifies that the main task is beginning.
+@param name the name (or description) of the main task
+@param totalWork the total number of work units into which
+the main task is been subdivided
+ */
+public void begin(String name, int totalWork);
+/** Notifies that the work is done, the main task is completed.
+ */
+public void done();
+/** Notifies that a subtask of the main task is beginning.
+Subtasks are optional; the main task might not have subtasks.
+@param name the name (or description) of the subtask
+ */
+public void nowDoing(String name);
+/** Notifies that a given number of work unit of the main task
+has been completed. Note that this amount represents an
+installment, as opposed to a cumulative amount of work done
+to date.
+@param work the work units just completed
+ */
+public void worked(int work);
} // IProgressListener
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/LRUCache.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/LRUCache.java
index 4738c559f3..fbac18a93b 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/LRUCache.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/LRUCache.java
@@ -34,42 +34,42 @@ public class LRUCache implements Cloneable {
* @see LRUCache
*/
protected static class LRUCacheEntry {
-
+
/**
* Hash table key
*/
public Object _fKey;
-
+
/**
* Hash table value (an LRUCacheEntry object)
*/
- public Object _fValue;
+ public Object _fValue;
/**
* Time value for queue sorting
*/
public int _fTimestamp;
-
+
/**
* Cache footprint of this entry
*/
public int _fSpace;
-
+
/**
* Previous entry in queue
*/
public LRUCacheEntry _fPrevious;
-
+
/**
* Next entry in queue
*/
public LRUCacheEntry _fNext;
-
+
/**
* Creates a new instance of the receiver with the provided values
* for key, value, and space.
*/
- public LRUCacheEntry(Object key, Object value, int space) {
+ public LRUCacheEntry (Object key, Object value, int space) {
_fKey = key;
_fValue = value;
_fSpace = space;
@@ -80,25 +80,25 @@ public class LRUCache implements Cloneable {
*/
public String toString() {
- return "LRUCacheEntry [" + _fKey + "-->" + _fValue + "]";
+ return "LRUCacheEntry ["/*nonNLS*/ + _fKey + "-->"/*nonNLS*/ + _fValue + "]"/*nonNLS*/;
}
- }
+ }
/**
* Amount of cache space used so far
*/
protected int fCurrentSpace;
-
+
/**
* Maximum space allowed in cache
*/
protected int fSpaceLimit;
-
+
/**
* Counter for handing out sequential timestamps
*/
- protected int fTimestampCounter;
-
+ protected int fTimestampCounter;
+
/**
* Hash table for fast random access to cache entries
*/
@@ -106,14 +106,14 @@ public class LRUCache implements Cloneable {
/**
* Start of queue (most recently used entry)
- */
+ */
protected LRUCacheEntry fEntryQueue;
/**
* End of queue (least recently used entry)
- */
+ */
protected LRUCacheEntry fEntryQueueTail;
-
+
/**
* Default amount of space in the cache
*/
@@ -123,41 +123,38 @@ public class LRUCache implements Cloneable {
* <code>DEFAULT_SPACELIMIT</code>.
*/
public LRUCache() {
-
+
this(DEFAULT_SPACELIMIT);
}
-
/**
* Creates a new cache.
* @param size Size of Cache
*/
public LRUCache(int size) {
-
+
fTimestampCounter = fCurrentSpace = 0;
fEntryQueue = fEntryQueueTail = null;
fEntryTable = new Hashtable(size);
fSpaceLimit = size;
}
-
/**
* Returns a new cache containing the same contents.
*
* @return New copy of object.
*/
public Object clone() {
-
+
LRUCache newCache = newInstance(fSpaceLimit);
LRUCacheEntry qEntry;
-
+
/* Preserve order of entries by copying from oldest to newest */
qEntry = this.fEntryQueueTail;
while (qEntry != null) {
- newCache.privateAdd(qEntry._fKey, qEntry._fValue, qEntry._fSpace);
+ newCache.privateAdd (qEntry._fKey, qEntry._fValue, qEntry._fSpace);
qEntry = qEntry._fPrevious;
}
return newCache;
}
-
/**
* Flushes all entries from the cache.
*/
@@ -165,33 +162,30 @@ public class LRUCache implements Cloneable {
fCurrentSpace = 0;
LRUCacheEntry entry = fEntryQueueTail; // Remember last entry
- fEntryTable = new Hashtable(); // Clear it out
- fEntryQueue = fEntryQueueTail = null;
- while (entry != null) { // send deletion notifications in LRU order
+ fEntryTable = new Hashtable(); // Clear it out
+ fEntryQueue = fEntryQueueTail = null;
+ while (entry != null) { // send deletion notifications in LRU order
privateNotifyDeletionFromCache(entry);
entry = entry._fPrevious;
}
}
-
/**
* Flushes the given entry from the cache. Does nothing if entry does not
* exist in cache.
*
* @param key Key of object to flush
*/
- public void flush(Object key) {
-
+ public void flush (Object key) {
+
LRUCacheEntry entry;
-
+
entry = (LRUCacheEntry) fEntryTable.get(key);
/* If entry does not exist, return */
- if (entry == null)
- return;
+ if (entry == null) return;
- this.privateRemoveEntry(entry, false);
+ this.privateRemoveEntry (entry, false);
}
-
/**
* Answers the value in the cache at the given key.
* If the value is not in the cache, returns null
@@ -200,57 +194,53 @@ public class LRUCache implements Cloneable {
* @return Retreived object, or null if object does not exist
*/
public Object get(Object key) {
-
+
LRUCacheEntry entry = (LRUCacheEntry) fEntryTable.get(key);
if (entry == null) {
return null;
}
-
- this.updateTimestamp(entry);
+
+ this.updateTimestamp (entry);
return entry._fValue;
}
-
/**
* Returns the amount of space that is current used in the cache.
*/
public int getCurrentSpace() {
return fCurrentSpace;
}
-
/**
* Returns the maximum amount of space available in the cache.
*/
public int getSpaceLimit() {
return fSpaceLimit;
}
-
/**
* Returns an Enumeration of the keys currently in the cache.
*/
public Enumeration keys() {
-
+
return fEntryTable.keys();
}
-
/**
* Returns an enumeration that iterates over all the keys and values
* currently in the cache.
*/
public ICacheEnumeration keysAndValues() {
return new ICacheEnumeration() {
-
+
Enumeration fValues = fEntryTable.elements();
LRUCacheEntry fEntry;
-
+
public boolean hasMoreElements() {
return fValues.hasMoreElements();
}
-
+
public Object nextElement() {
fEntry = (LRUCacheEntry) fValues.nextElement();
return fEntry._fKey;
}
-
+
public Object getValue() {
if (fEntry == null) {
throw new java.util.NoSuchElementException();
@@ -259,7 +249,6 @@ public class LRUCache implements Cloneable {
}
};
}
-
/**
* Ensures there is the specified amount of free space in the receiver,
* by removing old entries if necessary. Returns true if the requested space was
@@ -267,73 +256,69 @@ public class LRUCache implements Cloneable {
*
* @param space Amount of space to free up
*/
- protected boolean makeSpace(int space) {
-
+ protected boolean makeSpace (int space) {
+
int limit;
-
+
limit = this.getSpaceLimit();
-
+
/* if space is already available */
if (fCurrentSpace + space <= limit) {
return true;
}
-
+
/* if entry is too big for cache */
if (space > limit) {
return false;
}
-
+
/* Free up space by removing oldest entries */
while (fCurrentSpace + space > limit && fEntryQueueTail != null) {
- this.privateRemoveEntry(fEntryQueueTail, false);
+ this.privateRemoveEntry (fEntryQueueTail, false);
}
return true;
}
-
/**
* Returns a new LRUCache instance
*/
protected LRUCache newInstance(int size) {
return new LRUCache(size);
}
-
/**
* Adds an entry for the given key/value/space.
*/
- protected void privateAdd(Object key, Object value, int space) {
-
+ protected void privateAdd (Object key, Object value, int space) {
+
LRUCacheEntry entry;
-
+
entry = new LRUCacheEntry(key, value, space);
- this.privateAddEntry(entry, false);
+ this.privateAddEntry (entry, false);
}
-
/**
* Adds the given entry from the receiver.
* @param shuffle Indicates whether we are just shuffling the queue
* (i.e., the entry table is left alone).
*/
- protected void privateAddEntry(LRUCacheEntry entry, boolean shuffle) {
-
+ protected void privateAddEntry (LRUCacheEntry entry, boolean shuffle) {
+
if (!shuffle) {
- fEntryTable.put(entry._fKey, entry);
+ fEntryTable.put (entry._fKey, entry);
fCurrentSpace += entry._fSpace;
}
-
+
entry._fTimestamp = fTimestampCounter++;
entry._fNext = this.fEntryQueue;
entry._fPrevious = null;
-
+
if (fEntryQueue == null) {
/* this is the first and last entry */
fEntryQueueTail = entry;
} else {
fEntryQueue._fPrevious = entry;
}
-
+
fEntryQueue = entry;
}
-
/**
* An entry has been removed from the cache, for example because it has
* fallen off the bottom of the LRU queue.
@@ -342,19 +327,18 @@ public class LRUCache implements Cloneable {
protected void privateNotifyDeletionFromCache(LRUCacheEntry entry) {
// Default is NOP.
}
-
/**
* Removes the entry from the entry queue.
* @param shuffle indicates whether we are just shuffling the queue
* (i.e., the entry table is left alone).
*/
- protected void privateRemoveEntry(LRUCacheEntry entry, boolean shuffle) {
-
+ protected void privateRemoveEntry (LRUCacheEntry entry, boolean shuffle) {
+
LRUCacheEntry previous, next;
-
+
previous = entry._fPrevious;
next = entry._fNext;
-
+
if (!shuffle) {
fEntryTable.remove(entry._fKey);
fCurrentSpace -= entry._fSpace;
@@ -375,7 +359,6 @@ public class LRUCache implements Cloneable {
next._fPrevious = previous;
}
}
-
/**
* Sets the value in the cache at the given key. Returns the value.
*
@@ -384,16 +367,16 @@ public class LRUCache implements Cloneable {
* @return added value.
*/
public Object put(Object key, Object value) {
-
+
int newSpace, oldSpace, newTotal;
LRUCacheEntry entry;
-
+
/* Check whether there's an entry in the cache */
- newSpace = spaceFor(key, value);
- entry = (LRUCacheEntry) fEntryTable.get(key);
-
+ newSpace = spaceFor (key, value);
+ entry = (LRUCacheEntry) fEntryTable.get (key);
+
if (entry != null) {
-
+
/**
* Replace the entry in the cache if it would not overflow
* the cache. Otherwise flush the entry and re-add it so as
@@ -402,21 +385,20 @@ public class LRUCache implements Cloneable {
oldSpace = entry._fSpace;
newTotal = getCurrentSpace() - oldSpace + newSpace;
if (newTotal <= getSpaceLimit()) {
- updateTimestamp(entry);
+ updateTimestamp (entry);
entry._fValue = value;
entry._fSpace = newSpace;
this.fCurrentSpace = newTotal;
return value;
} else {
- privateRemoveEntry(entry, false);
+ privateRemoveEntry (entry, false);
}
}
if (makeSpace(newSpace)) {
- privateAdd(key, value, newSpace);
+ privateAdd (key, value, newSpace);
}
return value;
}
-
/**
* Removes and returns the value in the cache for the given key.
* If the key is not in the cache, returns null.
@@ -424,17 +406,16 @@ public class LRUCache implements Cloneable {
* @param key Key of object to remove from cache.
* @return Value removed from cache.
*/
- public Object removeKey(Object key) {
-
+ public Object removeKey (Object key) {
+
LRUCacheEntry entry = (LRUCacheEntry) fEntryTable.get(key);
if (entry == null) {
return null;
}
Object value = entry._fValue;
- this.privateRemoveEntry(entry, false);
+ this.privateRemoveEntry (entry, false);
return value;
}
-
/**
* Sets the maximum amount of space that the cache can store
*
@@ -446,73 +427,67 @@ public class LRUCache implements Cloneable {
}
fSpaceLimit = limit;
}
-
/**
* Returns the space taken by the given key and value.
*/
- protected int spaceFor(Object key, Object value) {
-
+ protected int spaceFor (Object key, Object value) {
+
if (value instanceof ILRUCacheable) {
return ((ILRUCacheable) value).getCacheFootprint();
} else {
return 1;
}
}
-
- /**
- * Returns a String that represents the value of this object. This method
- * is for debugging purposes only.
- */
- public String toString() {
- return "LRUCache "
- + (fCurrentSpace * 100.0 / fSpaceLimit)
- + "% full\n"
- + this.toStringContents();
+/**
+ * Returns a String that represents the value of this object. This method
+ * is for debugging purposes only.
+ */
+public String toString() {
+ return
+ "LRUCache "/*nonNLS*/ + (fCurrentSpace * 100.0 / fSpaceLimit) + "% full\n"/*nonNLS*/ +
+ this.toStringContents();
+}
+/**
+ * Returns a String that represents the contents of this object. This method
+ * is for debugging purposes only.
+ */
+protected String toStringContents() {
+ StringBuffer result = new StringBuffer();
+ int length = fEntryTable.size();
+ Object[] unsortedKeys = new Object[length];
+ String[] unsortedToStrings = new String[length];
+ Enumeration e = this.keys();
+ for (int i = 0; i < length; i++) {
+ Object key = e.nextElement();
+ unsortedKeys[i] = key;
+ unsortedToStrings[i] =
+ (key instanceof org.eclipse.jdt.internal.core.JavaElement) ?
+ ((org.eclipse.jdt.internal.core.JavaElement)key).getElementName() :
+ key.toString();
}
-
- /**
- * Returns a String that represents the contents of this object. This method
- * is for debugging purposes only.
- */
- protected String toStringContents() {
- StringBuffer result = new StringBuffer();
- int length = fEntryTable.size();
- Object[] unsortedKeys = new Object[length];
- String[] unsortedToStrings = new String[length];
- Enumeration e = this.keys();
- for (int i = 0; i < length; i++) {
- Object key = e.nextElement();
- unsortedKeys[i] = key;
- unsortedToStrings[i] =
- (key instanceof org.eclipse.jdt.internal.core.JavaElement)
- ? ((org.eclipse.jdt.internal.core.JavaElement) key).getElementName()
- : key.toString();
- }
- ToStringSorter sorter = new ToStringSorter();
- sorter.sort(unsortedKeys, unsortedToStrings);
- for (int i = 0; i < length; i++) {
- String toString = sorter.sortedStrings[i];
- Object value = this.get(sorter.sortedObjects[i]);
- result.append(toString);
- result.append(" -> ");
- result.append(value);
- result.append("\n");
- }
- return result.toString();
+ ToStringSorter sorter = new ToStringSorter();
+ sorter.sort(unsortedKeys, unsortedToStrings);
+ for (int i = 0; i < length; i++) {
+ String toString = sorter.sortedStrings[i];
+ Object value = this.get(sorter.sortedObjects[i]);
+ result.append(toString);
+ result.append(" -> "/*nonNLS*/);
+ result.append(value);
+ result.append("\n"/*nonNLS*/);
}
-
+ return result.toString();
+}
/**
* Updates the timestamp for the given entry, ensuring that the queue is
* kept in correct order. The entry must exist
*/
- protected void updateTimestamp(LRUCacheEntry entry) {
-
+ protected void updateTimestamp (LRUCacheEntry entry) {
+
entry._fTimestamp = fTimestampCounter++;
if (fEntryQueue != entry) {
- this.privateRemoveEntry(entry, true);
- this.privateAddEntry(entry, true);
+ this.privateRemoveEntry (entry, true);
+ this.privateAddEntry (entry, true);
}
return;
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/LookupTable.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/LookupTable.java
index becc26dd04..7af03f86e3 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/LookupTable.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/LookupTable.java
@@ -18,7 +18,7 @@ public class LookupTable extends Dictionary implements Cloneable {
protected Object[] keys;
protected Object[] values;
protected int modCount;
-
+
// Types of Enumeration
protected static final int KEYS = 0;
protected static final int VALUES = 1;
@@ -32,48 +32,46 @@ public class LookupTable extends Dictionary implements Cloneable {
protected Object[] table;
protected int index;
protected Object entry;
-
+
/**
* The modCount value that the enumeration believes that the backing
* lookup table should have. If this expectation is violated, the enumeration
* has detected concurrent modification.
*/
protected int expectedModCount = modCount;
+
+ Enumerator(int type) {
+ this.type = type;
+ table = (type == KEYS ? keys : values);
+ index = table.length;
+ }
+
+ public boolean hasMoreElements() {
+ while (entry == null && index > 0)
+ entry = table[--index];
+ return entry != null;
+ }
- Enumerator(int type) {
- this.type = type;
- table = (type == KEYS ? keys : values);
- index = table.length;
- }
-
- public boolean hasMoreElements() {
- while (entry == null && index > 0)
- entry = table[--index];
- return entry != null;
- }
-
- public Object nextElement() {
- if (modCount != expectedModCount)
- throw new IllegalStateException();
- while (entry == null && index > 0)
- entry = table[--index];
- if (entry != null) {
- Object next = entry;
- entry = null;
- return next;
- }
- throw new NoSuchElementException("LookupTable Enumerator");
+ public Object nextElement() {
+ if (modCount != expectedModCount)
+ throw new IllegalStateException();
+ while (entry == null && index > 0)
+ entry = table[--index];
+ if (entry != null) {
+ Object next = entry;
+ entry = null;
+ return next;
}
+ throw new NoSuchElementException("LookupTable Enumerator");
}
-
+ }
/**
* Constructs a new, empty LookupTable with a default capacity (11) and load
* factor (0.5).
*/
public LookupTable() {
- this(11, 0.5f);
+ this(11, 0.5f);
}
-
/**
* Constructs a new, empty LookupTable with the specified initial capacity
* and default load factor (0.5).
@@ -83,9 +81,8 @@ public class LookupTable extends Dictionary implements Cloneable {
* than zero.
*/
public LookupTable(int initialCapacity) {
- this(initialCapacity, 0.5f);
+ this(initialCapacity, 0.5f);
}
-
/**
* Constructs a new, empty LookupTable with the specified initial
* capacity and the specified load factor.
@@ -96,19 +93,19 @@ public class LookupTable extends Dictionary implements Cloneable {
* than zero, or if the load factor is nonpositive.
*/
public LookupTable(int initialCapacity, float loadFactor) {
- if (initialCapacity < 0)
- throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
+ if (initialCapacity < 0)
+ throw new IllegalArgumentException("Illegal Capacity: "+
+ initialCapacity);
if (loadFactor <= 0)
- throw new IllegalArgumentException("Illegal Load: " + loadFactor);
+ throw new IllegalArgumentException("Illegal Load: "+loadFactor);
- if (initialCapacity == 0)
+ if (initialCapacity==0)
initialCapacity = 1;
- this.loadFactor = loadFactor;
- keys = new Object[initialCapacity];
- values = new Object[initialCapacity];
- threshold = (int) (initialCapacity * loadFactor);
+ this.loadFactor = loadFactor;
+ keys = new Object[initialCapacity];
+ values = new Object[initialCapacity];
+ threshold = (int)(initialCapacity * loadFactor);
}
-
/**
* Clears this lookup table so that it contains no keys.
*/
@@ -116,13 +113,12 @@ public class LookupTable extends Dictionary implements Cloneable {
Object tab1[] = keys;
Object tab2[] = values;
modCount++;
- for (int index = keys.length; --index >= 0;) {
- tab1[index] = null;
- tab2[index] = null;
- }
+ for (int index = keys.length; --index >= 0; ) {
+ tab1[index] = null;
+ tab2[index] = null;
+ }
count = 0;
}
-
/**
* Creates a shallow copy of this lookup table. All the structure of the
* lookup table itself is copied, but the keys and values are not cloned.
@@ -131,7 +127,7 @@ public class LookupTable extends Dictionary implements Cloneable {
* @return a clone of the lookup table.
*/
public synchronized Object clone() {
- try {
+ try {
LookupTable t = (LookupTable) super.clone();
int size = keys.length;
t.keys = new Object[size];
@@ -140,12 +136,11 @@ public class LookupTable extends Dictionary implements Cloneable {
System.arraycopy(values, 0, t.values, 0, size);
t.modCount = 0;
return t;
- } catch (CloneNotSupportedException e) {
+ } catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
-
/**
* Tests if some key maps into the specified value in this lookup table.
* This operation is more expensive than the <code>containsKey</code>
@@ -165,19 +160,18 @@ public class LookupTable extends Dictionary implements Cloneable {
* @see Map
*/
public synchronized boolean contains(Object value) {
- if (value == null) {
- throw new NullPointerException();
- }
+ if (value == null) {
+ throw new NullPointerException();
+ }
- Object tab[] = values;
- for (int i = tab.length; i-- > 0;) {
- if (tab[i].equals(value)) {
- return true;
- }
+ Object tab[] = values;
+ for (int i = tab.length ; i-- > 0 ;) {
+ if (tab[i].equals(value)) {
+ return true;
}
- return false;
}
-
+ return false;
+ }
/**
* Tests if the specified object is a key in this lookup table.
*
@@ -193,21 +187,16 @@ public class LookupTable extends Dictionary implements Cloneable {
int index = (key.hashCode() & 0x7FFFFFFF) % size;
for (int i = index; i < size; ++i) {
Object testKey = tab[i];
- if (testKey == null)
- return false;
- if (testKey.equals(key))
- return true;
+ if (testKey == null) return false;
+ if (testKey.equals(key)) return true;
}
for (int i = 0; i < index; ++i) {
Object testKey = tab[i];
- if (testKey == null)
- return false;
- if (testKey.equals(key))
- return true;
+ if (testKey == null) return false;
+ if (testKey.equals(key)) return true;
}
return false;
}
-
/**
* Returns an enumeration of the values in this lookup table.
* Use the Enumeration methods on the returned object to fetch the elements
@@ -222,7 +211,6 @@ public class LookupTable extends Dictionary implements Cloneable {
public synchronized Enumeration elements() {
return new Enumerator(VALUES);
}
-
/**
* Increases the capacity of and internally reorganizes this
* lookup table, in order to accommodate and access its entries more
@@ -233,7 +221,6 @@ public class LookupTable extends Dictionary implements Cloneable {
protected void expand() {
rehash(keys.length * 2 + 1);
}
-
/**
* Returns the value to which the specified key is mapped in this lookup table.
*
@@ -244,26 +231,21 @@ public class LookupTable extends Dictionary implements Cloneable {
* @see #put(Object, Object)
*/
public synchronized Object get(Object key) {
- Object[] tab = keys;
- int size = tab.length;
- int index = (key.hashCode() & 0x7FFFFFFF) % size;
- for (int i = index; i < size; ++i) {
- Object testKey = tab[i];
- if (testKey == null)
- return null;
- if (testKey.equals(key))
- return values[i];
- }
- for (int i = 0; i < index; ++i) {
- Object testKey = tab[i];
- if (testKey == null)
- return null;
- if (testKey.equals(key))
- return values[i];
- }
- return null;
+ Object[] tab = keys;
+ int size = tab.length;
+ int index = (key.hashCode() & 0x7FFFFFFF) % size;
+ for (int i = index; i < size; ++i) {
+ Object testKey = tab[i];
+ if (testKey == null) return null;
+ if (testKey.equals(key)) return values[i];
+ }
+ for (int i = 0; i < index; ++i) {
+ Object testKey = tab[i];
+ if (testKey == null) return null;
+ if (testKey.equals(key)) return values[i];
+ }
+ return null;
}
-
/**
* Tests if this lookup table maps no keys to values.
*
@@ -271,9 +253,8 @@ public class LookupTable extends Dictionary implements Cloneable {
* <code>false</code> otherwise.
*/
public boolean isEmpty() {
- return count == 0;
+ return count == 0;
}
-
/**
* Returns an enumeration of the keys in this lookup table.
*
@@ -286,7 +267,6 @@ public class LookupTable extends Dictionary implements Cloneable {
public synchronized Enumeration keys() {
return new Enumerator(KEYS);
}
-
/**
* Maps the specified <code>key</code> to the specified
* <code>value</code> in this lookup table. Neither the key nor the
@@ -307,7 +287,7 @@ public class LookupTable extends Dictionary implements Cloneable {
public synchronized Object put(Object key, Object value) {
// Make sure the value is not null
if (value == null) {
- throw new NullPointerException();
+ throw new NullPointerException();
}
Object[] tab = keys;
int size = tab.length;
@@ -349,21 +329,20 @@ public class LookupTable extends Dictionary implements Cloneable {
expand();
return put(key, value);
}
-
protected void rehash(int newSize) {
- /*
- System.out.println("LookupTable.rehash()");
- System.out.println(" oldSize= " + keys.length);
- System.out.println(" count= " + count);
- System.out.println(" threshold= " + threshold);
- System.out.println(" newSize= " + newSize);
- */
+/*
+ System.out.println("LookupTable.rehash()");
+ System.out.println(" oldSize= " + keys.length);
+ System.out.println(" count= " + count);
+ System.out.println(" threshold= " + threshold);
+ System.out.println(" newSize= " + newSize);
+*/
Object[] newKeys = new Object[newSize];
Object[] newValues = new Object[newSize];
if (count > 0) {
Object[] oldKeys = keys;
Object[] oldValues = values;
- for (int i = keys.length; i-- > 0;) {
+ for (int i = keys.length; i-- > 0; ) {
Object key = oldKeys[i];
if (key != null) {
int hashIndex = (key.hashCode() & 0x7FFFFFFF) % newSize;
@@ -379,10 +358,9 @@ public class LookupTable extends Dictionary implements Cloneable {
keys = newKeys;
values = newValues;
threshold = (int) (newSize * loadFactor);
-
- // sanityCheck("rehash");
+
+// sanityCheck("rehash");
}
-
/**
* The element at target has been removed. Move the elements
* to keep the receiver properly hashed.
@@ -392,15 +370,13 @@ public class LookupTable extends Dictionary implements Cloneable {
Object[] tab = keys;
int size = tab.length;
for (;;) {
- if (++index >= size)
- index = 0;
+ if (++index >= size) index = 0;
Object element = tab[index];
- if (element == null)
- break;
+ if (element == null) break;
int hashIndex = (element.hashCode() & 0x7FFFFFFF) % size;
- if (index < target ? hashIndex <= target
- && hashIndex > index : hashIndex <= target
- || hashIndex > index) {
+ if (index < target
+ ? hashIndex <= target && hashIndex > index
+ : hashIndex <= target || hashIndex > index) {
keys[target] = element;
values[target] = values[index];
target = index;
@@ -409,7 +385,6 @@ public class LookupTable extends Dictionary implements Cloneable {
keys[target] = null;
values[target] = null;
}
-
/**
* Removes the key (and its corresponding value) from this
* lookup table. This method does nothing if the key is not in the lookup table.
@@ -424,89 +399,67 @@ public class LookupTable extends Dictionary implements Cloneable {
int hashIndex = (key.hashCode() & 0x7FFFFFFF) % size;
for (int i = hashIndex; i < size; ++i) {
Object element = tab[i];
- if (element == null)
- return null;
+ if (element == null) return null;
if (element.equals(key)) {
Object oldValue = values[i];
rehashTo(i);
--count;
- // sanityCheck("remove");
+// sanityCheck("remove");
++modCount;
return oldValue;
}
}
for (int i = 0; i < hashIndex; ++i) {
Object element = tab[i];
- if (element == null)
- return null;
+ if (element == null) return null;
if (element.equals(key)) {
Object oldValue = values[i];
rehashTo(i);
--count;
- // sanityCheck("remove");
+// sanityCheck("remove");
++modCount;
return oldValue;
}
}
return null;
}
-
protected void sanityCheck(String where) {
int n = 0;
for (int i = 0; i < keys.length; ++i) {
if (keys[i] == null) {
if (values[i] != null) {
- System.err.println(
- "LookupTable sanity check in "
- + where
- + ": key is null, but value isn't at index "
- + i);
+ System.err.println("LookupTable sanity check in " + where + ": key is null, but value isn't at index " + i);
throw new Error();
}
- } else {
+ }
+ else {
if (values[i] == null) {
- System.err.println(
- "LookupTable sanity check in "
- + where
- + ": value is null, but key isn't at index "
- + i);
+ System.err.println("LookupTable sanity check in " + where + ": value is null, but key isn't at index " + i);
throw new Error();
- } else {
+ }
+ else {
++n;
Object value = get(keys[i]);
if (value == null || value != values[i]) {
- System.err.println(
- "LookupTable sanity check in "
- + where
- + ": key doesn't hash to proper value: "
- + keys[i]);
+ System.err.println("LookupTable sanity check in " + where + ": key doesn't hash to proper value: " + keys[i]);
throw new Error();
}
}
}
}
if (n != count) {
- System.err.println(
- "LookupTable sanity check in "
- + where
- + ": count is "
- + count
- + " but there are "
- + n
- + " entries");
+ System.err.println("LookupTable sanity check in " + where + ": count is " + count + " but there are " + n + " entries");
throw new Error();
}
}
-
/**
* Returns the number of keys in this LookupTable.
*
* @return the number of keys in this lookup table.
*/
public int size() {
- return count;
+ return count;
}
-
/**
* Returns a string representation of this <tt>LookupTable</tt> object
* in the form of a set of entries, enclosed in braces and separated
@@ -519,26 +472,27 @@ public class LookupTable extends Dictionary implements Cloneable {
* @return a string representation of this lookup table.
*/
public synchronized String toString() {
- StringBuffer buf = new StringBuffer();
- buf.append("{");
- boolean first = true;
- for (int i = 0, max = keys.length; i < max; i++) {
- if (keys[i] != null) {
- if (first) {
- first = false;
- } else {
- buf.append(", ");
- }
- if (buf.length() > 1000) {
- buf.append("...");
- break;
- } else {
- buf.append(keys[i]).append("=").append(values[i]);
- }
+ StringBuffer buf = new StringBuffer();
+ buf.append("{"/*nonNLS*/);
+ boolean first = true;
+ for (int i = 0, max = keys.length; i < max; i++) {
+ if (keys[i] != null) {
+ if (first) {
+ first = false;
}
- }
- buf.append("}");
- return buf.toString();
+ else {
+ buf.append(", "/*nonNLS*/);
+ }
+ if (buf.length() > 1000) {
+ buf.append("..."/*nonNLS*/);
+ break;
+ }
+ else {
+ buf.append(keys[i]).append("="/*nonNLS*/).append(values[i]);
+ }
+ }
+ }
+ buf.append("}"/*nonNLS*/);
+ return buf.toString();
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/ReferenceInfoAdapter.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/ReferenceInfoAdapter.java
index b302950922..6c6e7c5dec 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/ReferenceInfoAdapter.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/ReferenceInfoAdapter.java
@@ -1,58 +1,32 @@
package org.eclipse.jdt.internal.core.util;
public abstract class ReferenceInfoAdapter {
- /**
- * Does nothing.
- */
- public void acceptConstructorReference(
- char[] typeName,
- int argCount,
- int sourcePosition) {
- }
-
- /**
- * Does nothing.
- */
- public void acceptFieldReference(char[] fieldName, int sourcePosition) {
- }
-
- /**
- * Does nothing.
- */
- public void acceptMethodReference(
- char[] methodName,
- int argCount,
- int sourcePosition) {
- }
-
- /**
- * Does nothing.
- */
- public void acceptTypeReference(
- char[][] typeName,
- int sourceStart,
- int sourceEnd) {
- }
-
- /**
- * Does nothing.
- */
- public void acceptTypeReference(char[] typeName, int sourcePosition) {
- }
-
- /**
- * Does nothing.
- */
- public void acceptUnknownReference(
- char[][] name,
- int sourceStart,
- int sourceEnd) {
- }
-
- /**
- * Does nothing.
- */
- public void acceptUnknownReference(char[] name, int sourcePosition) {
- }
-
+/**
+ * Does nothing.
+ */
+public void acceptConstructorReference(char[] typeName, int argCount, int sourcePosition) {}
+/**
+ * Does nothing.
+ */
+public void acceptFieldReference(char[] fieldName, int sourcePosition) {}
+/**
+ * Does nothing.
+ */
+public void acceptMethodReference(char[] methodName, int argCount, int sourcePosition) {}
+/**
+ * Does nothing.
+ */
+public void acceptTypeReference(char[][] typeName, int sourceStart, int sourceEnd) {}
+/**
+ * Does nothing.
+ */
+public void acceptTypeReference(char[] typeName, int sourcePosition) {}
+/**
+ * Does nothing.
+ */
+public void acceptUnknownReference(char[][] name, int sourceStart, int sourceEnd) {}
+/**
+ * Does nothing.
+ */
+public void acceptUnknownReference(char[] name, int sourcePosition) {}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/StringHashtableOfInt.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/StringHashtableOfInt.java
index 6eeb2a1b3f..f9bd5387a3 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/StringHashtableOfInt.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/StringHashtableOfInt.java
@@ -7,123 +7,113 @@ public class StringHashtableOfInt {
int elementSize; // number of elements in the table
int threshold;
- public StringHashtableOfInt() {
- this(13);
- }
-
- public StringHashtableOfInt(int size) {
- this.elementSize = 0;
- this.threshold = size; // size represents the expected number of elements
- int extraRoom = (int) (size * 1.75f);
- if (this.threshold == extraRoom)
- extraRoom++;
- this.keyTable = new String[extraRoom];
- this.valueTable = new int[extraRoom];
- }
-
- public boolean containsKey(String key) {
- int index = (key.hashCode() & 0x7FFFFFFF) % valueTable.length;
- String currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.equals(key))
- return true;
- index = (index + 1) % keyTable.length;
- }
- return false;
- }
-
- /**
- * Returns the value at the given key.
- * Returns -1 if not found.
- */
- public int get(String key) {
- int index = (key.hashCode() & 0x7FFFFFFF) % valueTable.length;
- String currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.equals(key))
- return valueTable[index];
- index = (index + 1) % keyTable.length;
- }
- return -1;
- }
-
- public int put(String key, int value) {
- int index = (key.hashCode() & 0x7FFFFFFF) % valueTable.length;
- String currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.equals(key))
- return valueTable[index] = value;
- index = (index + 1) % keyTable.length;
- }
- keyTable[index] = key;
- valueTable[index] = value;
-
- // assumes the threshold is never equal to the size of the table
- if (++elementSize > threshold)
- rehash();
- return value;
+public StringHashtableOfInt() {
+ this(13);
+}
+public StringHashtableOfInt(int size) {
+ this.elementSize = 0;
+ this.threshold = size; // size represents the expected number of elements
+ int extraRoom = (int) (size * 1.75f);
+ if (this.threshold == extraRoom)
+ extraRoom++;
+ this.keyTable = new String[extraRoom];
+ this.valueTable = new int[extraRoom];
+}
+public boolean containsKey(String key) {
+ int index = (key.hashCode() & 0x7FFFFFFF) % valueTable.length;
+ String currentKey;
+ while ((currentKey = keyTable[index]) != null) {
+ if (currentKey.equals(key))
+ return true;
+ index = (index + 1) % keyTable.length;
}
-
- private void rehash() {
- StringHashtableOfInt newHashtable = new StringHashtableOfInt(elementSize * 2);
- // double the number of expected elements
- String currentKey;
- for (int i = keyTable.length; --i >= 0;)
- if ((currentKey = keyTable[i]) != null)
- newHashtable.put(currentKey, valueTable[i]);
-
- this.keyTable = newHashtable.keyTable;
- this.valueTable = newHashtable.valueTable;
- this.threshold = newHashtable.threshold;
+ return false;
+}
+/**
+ * Returns the value at the given key.
+ * Returns -1 if not found.
+ */
+public int get(String key) {
+ int index = (key.hashCode() & 0x7FFFFFFF) % valueTable.length;
+ String currentKey;
+ while ((currentKey = keyTable[index]) != null) {
+ if (currentKey.equals(key))
+ return valueTable[index];
+ index = (index + 1) % keyTable.length;
}
-
- public int size() {
- return elementSize;
+ return -1;
+}
+public int put(String key, int value) {
+ int index = (key.hashCode() & 0x7FFFFFFF) % valueTable.length;
+ String currentKey;
+ while ((currentKey = keyTable[index]) != null) {
+ if (currentKey.equals(key))
+ return valueTable[index] = value;
+ index = (index + 1) % keyTable.length;
}
+ keyTable[index] = key;
+ valueTable[index] = value;
- /**
- * Return the keys sorted by their values.
- */
- public String[] sortedKeys(int maxValue) {
- String[] result = new String[this.elementSize];
-
- // compute a list of the end positions of each layer in result
- int[] endPos = new int[maxValue + 1];
- int length = this.keyTable.length;
- for (int i = 0; i < length; i++) {
- String key = this.keyTable[i];
- if (key != null) {
- for (int j = this.valueTable[i]; j <= maxValue; j++) {
- endPos[j]++;
- }
+ // assumes the threshold is never equal to the size of the table
+ if (++elementSize > threshold)
+ rehash();
+ return value;
+}
+private void rehash() {
+ StringHashtableOfInt newHashtable = new StringHashtableOfInt(elementSize * 2); // double the number of expected elements
+ String currentKey;
+ for (int i = keyTable.length; --i >= 0;)
+ if ((currentKey = keyTable[i]) != null)
+ newHashtable.put(currentKey, valueTable[i]);
+
+ this.keyTable = newHashtable.keyTable;
+ this.valueTable = newHashtable.valueTable;
+ this.threshold = newHashtable.threshold;
+}
+public int size() {
+ return elementSize;
+}
+/**
+ * Return the keys sorted by their values.
+ */
+public String[] sortedKeys(int maxValue) {
+ String[] result = new String[this.elementSize];
+
+ // compute a list of the end positions of each layer in result
+ int[] endPos = new int[maxValue+1];
+ int length = this.keyTable.length;
+ for (int i = 0; i < length; i++) {
+ String key = this.keyTable[i];
+ if (key != null) {
+ for (int j = this.valueTable[i]; j <= maxValue; j++) {
+ endPos[j]++;
}
}
+ }
- // store the keys in order of their values
- for (int i = 0; i < length; i++) {
- String key = this.keyTable[i];
- if (key != null) {
- int value = this.valueTable[i];
- int index = --endPos[value];
- result[index] = key;
- }
+ // store the keys in order of their values
+ for (int i = 0; i < length; i++) {
+ String key = this.keyTable[i];
+ if (key != null) {
+ int value = this.valueTable[i];
+ int index = --endPos[value];
+ result[index] = key;
}
-
- return result;
}
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- for (int i = 0, length = this.valueTable.length; i < length; i++) {
- String key = this.keyTable[i];
- if (key != null) {
- buffer.append(key);
- buffer.append(" -> ");
- buffer.append(this.valueTable[i]);
- buffer.append("\n");
- }
+ return result;
+}
+public String toString() {
+ StringBuffer buffer = new StringBuffer();
+ for (int i = 0, length = this.valueTable.length; i < length; i++) {
+ String key = this.keyTable[i];
+ if (key != null) {
+ buffer.append(key);
+ buffer.append(" -> "/*nonNLS*/);
+ buffer.append(this.valueTable[i]);
+ buffer.append("\n"/*nonNLS*/);
}
- return buffer.toString();
}
-
+ return buffer.toString();
+}
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/StringMatcher.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/StringMatcher.java
index cf3c394fb2..3d161d9018 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/StringMatcher.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/StringMatcher.java
@@ -13,14 +13,14 @@ public class StringMatcher {
protected boolean fIgnoreCase;
protected boolean fHasLeadingStar;
protected boolean fHasTrailingStar;
- protected String fSegments[];
- //the given pattern is split into * separated segments
+ protected String fSegments[]; //the given pattern is split into * separated segments
/* boundary value beyond which we don't need to search in the text */
protected int fBound = 0;
+
protected static final char fSingleWildCard = '\u0000';
-
+
public static class Position {
int start; //inclusive
int end; //exclusive
@@ -35,7 +35,6 @@ public class StringMatcher {
return end;
}
}
-
/**
* StringMatcher constructor takes in a String object that is a simple
* pattern which may contain ‘*’ for 0 and many characters and
@@ -46,7 +45,6 @@ public class StringMatcher {
public StringMatcher(String aPattern, boolean ignoreCase) {
this(aPattern, ignoreCase, false);
}
-
/**
* StringMatcher constructor takes in a String object that is a simple
* pattern which may contain ‘*’ for 0 and many characters and
@@ -67,10 +65,7 @@ public class StringMatcher {
* @param ignoreWildCards if true, wild cards and their escape sequences are ignored
* (everything is taken literally).
*/
- public StringMatcher(
- String aPattern,
- boolean ignoreCase,
- boolean ignoreWildCards) {
+ public StringMatcher(String aPattern, boolean ignoreCase, boolean ignoreWildCards) {
fIgnoreCase = ignoreCase;
fIgnoreWildCards = ignoreWildCards;
fLength = aPattern.length();
@@ -81,14 +76,13 @@ public class StringMatcher {
} else {
fPattern = aPattern;
}
-
+
if (fIgnoreWildCards) {
parseNoWildCards();
} else {
parseWildCards();
}
}
-
/**
* Find the first occurrence of the pattern between <code>start</code)(inclusive)
* and <code>end</code>(exclusive).
@@ -104,15 +98,15 @@ public class StringMatcher {
*/
public StringMatcher.Position find(String text, int start, int end) {
- if (fPattern == null || text == null)
+ if (fPattern == null|| text == null)
throw new IllegalArgumentException();
-
+
int tlen = text.length();
if (start < 0)
start = 0;
if (end > tlen)
end = tlen;
- if (end < 0 || start >= end)
+ if (end < 0 ||start >= end )
return null;
if (fLength == 0)
return new Position(start, start);
@@ -120,36 +114,34 @@ public class StringMatcher {
int x = posIn(text, start, end);
if (x < 0)
return null;
- return new Position(x, x + fLength);
+ return new Position(x, x+fLength);
}
int segCount = fSegments.length;
- if (segCount == 0) //pattern contains only '*'(s)
- return new Position(start, end);
-
+ if (segCount == 0)//pattern contains only '*'(s)
+ return new Position (start, end);
+
int curPos = start;
- int matchStart = -1;
+ int matchStart = -1;
for (int i = 0; i < segCount && curPos < end; ++i) {
String current = fSegments[i];
int nextMatch = regExpPosIn(text, curPos, end, current);
- if (nextMatch < 0)
+ if (nextMatch < 0 )
return null;
- if (i == 0)
+ if(i == 0)
matchStart = nextMatch;
curPos = nextMatch + current.length();
}
return new Position(matchStart, curPos);
}
-
/**
* match the given <code>text</code> with the pattern
* @return true if matched eitherwise false
* @param <code>text</code>, a String object
*/
- public boolean match(String text) {
+ public boolean match(String text) {
return match(text, 0, text.length());
}
-
/**
* Given the starting (inclusive) and the ending (exclusive) poisitions in the
* <code>text</code>, determine if the given substring matches with aPattern
@@ -161,37 +153,37 @@ public class StringMatcher {
public boolean match(String text, int start, int end) {
if (null == fPattern || null == text)
throw new IllegalArgumentException();
-
+
if (start > end)
return false;
-
+
if (fIgnoreWildCards)
return fPattern.regionMatches(fIgnoreCase, 0, text, start, fLength);
int segCount = fSegments.length;
- if (segCount == 0) //pattern contains only '*'(s) or empty pattern
+ if (segCount == 0)//pattern contains only '*'(s) or empty pattern
return true;
if (start == end)
return fLength == 0;
if (fLength == 0)
- return start == end;
-
+ return start == end;
+
int tlen = text.length();
if (start < 0)
start = 0;
if (end > tlen)
- end = tlen;
-
+ end = tlen;
+
int tCurPos = start;
int bound = end - fBound;
- if (bound < 0)
+ if ( bound < 0)
return false;
- int i = 0;
+ int i=0;
String current = fSegments[i];
int segLength = current.length();
/* process first segment */
- if (!fHasLeadingStar) {
- if (!regExpRegionMatches(text, start, current, 0, segLength)) {
+ if (!fHasLeadingStar){
+ if(!regExpRegionMatches(text, start, current, 0, segLength)) {
return false;
} else {
++i;
@@ -199,8 +191,8 @@ public class StringMatcher {
}
}
- /* process middle segments */
- for (; i < segCount && tCurPos <= bound; ++i) {
+ /* process middle segments */
+ for ( ; i < segCount && tCurPos <= bound; ++i) {
current = fSegments[i];
int currentMatch;
int k = current.indexOf(fSingleWildCard);
@@ -208,7 +200,7 @@ public class StringMatcher {
currentMatch = textPosIn(text, tCurPos, end, current);
if (currentMatch < 0)
return false;
- } else {
+ } else {
currentMatch = regExpPosIn(text, tCurPos, end, current);
if (currentMatch < 0)
return false;
@@ -221,9 +213,8 @@ public class StringMatcher {
int clen = current.length();
return regExpRegionMatches(text, end - clen, current, 0, clen);
}
- return i == segCount;
+ return i == segCount ;
}
-
/**
* This method parses the given pattern into segments seperated by wildcard '*' characters.
* Since wildcards are not being used in this case, the pattern consists of a single segment.
@@ -233,15 +224,14 @@ public class StringMatcher {
fSegments[0] = fPattern;
fBound = fLength;
}
-
/**
* This method parses the given pattern into segments seperated by wildcard '*' characters.
* @param p, a String object that is a simple regular expression with ‘*’ and/or ‘?’
*/
private void parseWildCards() {
- if (fPattern.startsWith("*"))
+ if(fPattern.startsWith("*"/*nonNLS*/))
fHasLeadingStar = true;
- if (fPattern.endsWith("*")) {
+ if(fPattern.endsWith("*"/*nonNLS*/)) {
/* make sure it's not an escaped wildcard */
if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') {
fHasTrailingStar = true;
@@ -255,7 +245,7 @@ public class StringMatcher {
while (pos < fLength) {
char c = fPattern.charAt(pos++);
switch (c) {
- case '\\' :
+ case '\\':
if (pos >= fLength) {
buf.append(c);
} else {
@@ -269,20 +259,20 @@ public class StringMatcher {
buf.append(next);
}
}
- break;
- case '*' :
+ break;
+ case '*':
if (buf.length() > 0) {
/* new segment */
temp.addElement(buf.toString());
fBound += buf.length();
buf.setLength(0);
}
- break;
- case '?' :
+ break;
+ case '?':
/* append special character representing single match wildcard */
buf.append(fSingleWildCard);
- break;
- default :
+ break;
+ default:
buf.append(c);
}
}
@@ -292,38 +282,33 @@ public class StringMatcher {
temp.addElement(buf.toString());
fBound += buf.length();
}
-
+
fSegments = new String[temp.size()];
temp.copyInto(fSegments);
}
-
/**
* @param <code>text</code>, a string which contains no wildcard
* @param <code>start</code>, the starting index in the text for search, inclusive
* @param <code>end</code>, the stopping point of search, exclusive
* @return the starting index in the text of the pattern , or -1 if not found
*/
- protected int posIn(
- String text,
- int start,
- int end) { //no wild card in pattern
+ protected int posIn(String text, int start, int end) {//no wild card in pattern
int max = end - fLength;
-
+
if (!fIgnoreCase) {
int i = text.indexOf(fPattern, start);
if (i == -1 || i > max)
return -1;
return i;
}
-
+
for (int i = start; i <= max; ++i) {
if (text.regionMatches(true, i, fPattern, 0, fLength))
return i;
}
-
+
return -1;
}
-
/**
* @param <code>text</code>, a simple regular expression that may only contain '?'(s)
* @param <code>start</code>, the starting index in the text for search, inclusive
@@ -334,7 +319,7 @@ public class StringMatcher {
*/
protected int regExpPosIn(String text, int start, int end, String p) {
int plen = p.length();
-
+
int max = end - plen;
for (int i = start; i <= max; ++i) {
if (regExpRegionMatches(text, i, p, 0, plen))
@@ -342,7 +327,6 @@ public class StringMatcher {
}
return -1;
}
-
/**
*
* @return boolean
@@ -352,12 +336,7 @@ public class StringMatcher {
* @param <code>p</code>, String, String, a simple regular expression that may contain '?'
* @param <code>ignoreCase</code>, boolean indicating wether code>p</code> is case sensitive
*/
- protected boolean regExpRegionMatches(
- String text,
- int tStart,
- String p,
- int pStart,
- int plen) {
+ protected boolean regExpRegionMatches(String text, int tStart, String p, int pStart, int plen) {
while (plen-- > 0) {
char tchar = text.charAt(tStart++);
char pchar = p.charAt(pStart++);
@@ -380,7 +359,6 @@ public class StringMatcher {
}
return true;
}
-
/**
* @param <code>text</code>, the string to match
* @param <code>start</code>, the starting index in the text for search, inclusive
@@ -389,24 +367,23 @@ public class StringMatcher {
* @param <code>ignoreCase</code>, boolean indicating wether code>p</code> is case sensitive
* @return the starting index in the text of the pattern , or -1 if not found
*/
- protected int textPosIn(String text, int start, int end, String p) {
-
+ protected int textPosIn(String text, int start, int end, String p) {
+
int plen = p.length();
int max = end - plen;
-
+
if (!fIgnoreCase) {
int i = text.indexOf(p, start);
if (i == -1 || i > max)
return -1;
return i;
}
-
+
for (int i = 0; i <= max; ++i) {
if (text.regionMatches(true, i, p, 0, plen))
return i;
}
-
+
return -1;
}
-
}
diff --git a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/ToStringSorter.java b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/ToStringSorter.java
index 4c242923a3..ede2146800 100644
--- a/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/ToStringSorter.java
+++ b/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/util/ToStringSorter.java
@@ -3,62 +3,58 @@ package org.eclipse.jdt.internal.core.util;
public class ToStringSorter {
Object[] sortedObjects;
String[] sortedStrings;
- /**
- * Returns true if stringTwo is 'greater than' stringOne
- * This is the 'ordering' method of the sort operation.
- */
- public boolean compare(String stringOne, String stringTwo) {
- return stringOne.compareTo(stringTwo) < 0;
- }
-
- /**
- * Sort the objects in sorted collection and return that collection.
- */
- private void quickSort(int left, int right) {
- int originalLeft = left;
- int originalRight = right;
- int midIndex = (left + right) / 2;
- Object mid = this.sortedObjects[midIndex];
- String midToString = this.sortedStrings[midIndex];
-
- do {
- while (compare(this.sortedStrings[left], midToString))
- left++;
- while (compare(midToString, this.sortedStrings[right]))
- right--;
- if (left <= right) {
- Object tmp = this.sortedObjects[left];
- this.sortedObjects[left] = this.sortedObjects[right];
- this.sortedObjects[right] = tmp;
- String tmpToString = this.sortedStrings[left];
- this.sortedStrings[left] = this.sortedStrings[right];
- this.sortedStrings[right] = tmpToString;
- left++;
- right--;
- }
+/**
+ * Returns true if stringTwo is 'greater than' stringOne
+ * This is the 'ordering' method of the sort operation.
+ */
+public boolean compare(String stringOne, String stringTwo) {
+ return stringOne.compareTo(stringTwo) < 0;
+}
+/**
+ * Sort the objects in sorted collection and return that collection.
+ */
+private void quickSort(int left, int right) {
+ int originalLeft = left;
+ int originalRight = right;
+ int midIndex = (left + right) / 2;
+ Object mid = this.sortedObjects[midIndex];
+ String midToString = this.sortedStrings[midIndex];
+
+ do {
+ while (compare(this.sortedStrings[left], midToString))
+ left++;
+ while (compare(midToString, this.sortedStrings[right]))
+ right--;
+ if (left <= right) {
+ Object tmp = this.sortedObjects[left];
+ this.sortedObjects[left] = this.sortedObjects[right];
+ this.sortedObjects[right] = tmp;
+ String tmpToString = this.sortedStrings[left];
+ this.sortedStrings[left] = this.sortedStrings[right];
+ this.sortedStrings[right] = tmpToString;
+ left++;
+ right--;
}
- while (left <= right);
-
- if (originalLeft < right)
- quickSort(originalLeft, right);
- if (left < originalRight)
- quickSort(left, originalRight);
- }
-
- /**
- * Return a new sorted collection from this unsorted collection.
- * Sort using quick sort.
- */
- public void sort(Object[] unSortedObjects, String[] unsortedStrings) {
- int size = unSortedObjects.length;
- this.sortedObjects = new Object[size];
- this.sortedStrings = new String[size];
-
- //copy the array so can return a new sorted collection
- System.arraycopy(unSortedObjects, 0, this.sortedObjects, 0, size);
- System.arraycopy(unsortedStrings, 0, this.sortedStrings, 0, size);
- if (size > 1)
- quickSort(0, size - 1);
- }
-
+ } while (left <= right);
+
+ if (originalLeft < right)
+ quickSort(originalLeft, right);
+ if (left < originalRight)
+ quickSort(left, originalRight);
+}
+/**
+ * Return a new sorted collection from this unsorted collection.
+ * Sort using quick sort.
+ */
+public void sort(Object[] unSortedObjects, String[] unsortedStrings) {
+ int size = unSortedObjects.length;
+ this.sortedObjects = new Object[size];
+ this.sortedStrings = new String[size];
+
+ //copy the array so can return a new sorted collection
+ System.arraycopy(unSortedObjects, 0, this.sortedObjects, 0, size);
+ System.arraycopy(unsortedStrings, 0, this.sortedStrings, 0, size);
+ if (size > 1)
+ quickSort(0, size - 1);
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/IJavaSearchConstants.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/IJavaSearchConstants.java
index 10adfef9b0..ac79bb980d 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/IJavaSearchConstants.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/IJavaSearchConstants.java
@@ -22,60 +22,60 @@ public interface IJavaSearchConstants {
* of match in unknown.
*/
int UNKNOWN = -1;
-
+
/* Nature of searched element */
-
+
/**
* The searched element is a type.
*/
- int TYPE = 0;
+ int TYPE= 0;
/**
* The searched element is a method.
*/
- int METHOD = 1;
+ int METHOD= 1;
/**
* The searched element is a package.
*/
- int PACKAGE = 2;
+ int PACKAGE= 2;
/**
* The searched element is a constructor.
*/
- int CONSTRUCTOR = 3;
+ int CONSTRUCTOR= 3;
/**
* The searched element is a field.
*/
- int FIELD = 4;
+ int FIELD= 4;
/**
* The searched element is a class.
*/
- int CLASS = 5;
+ int CLASS= 5;
/**
* The searched element is an interface.
*/
- int INTERFACE = 6;
+ int INTERFACE= 6;
/* Nature of match */
-
+
/**
* The search result is a declaration.
*/
- int DECLARATIONS = 0;
+ int DECLARATIONS= 0;
/**
* The search result is a type that implements an interface.
*/
- int IMPLEMENTORS = 1;
+ int IMPLEMENTORS= 1;
/**
* The search result is a reference.
*/
- int REFERENCES = 2;
+ int REFERENCES= 2;
/**
* The search result is a declaration, a reference, or an implementor
* of an interface.
*/
- int ALL_OCCURRENCES = 3;
+ int ALL_OCCURRENCES= 3;
/* Syntactic match modes */
-
+
/**
* The search pattern matches exactly the search result,
* i.e. the source of the search result equals the search pattern.
@@ -91,8 +91,9 @@ public interface IJavaSearchConstants {
*/
int PATTERN_MATCH = 2;
- /* Case sensitivity */
+ /* Case sensitivity */
+
/**
* The search pattern matches the search result only
* if case are the same.
@@ -102,9 +103,10 @@ public interface IJavaSearchConstants {
* The search pattern ignores cases in the search result.
*/
boolean CASE_INSENSITIVE = false;
+
/* Waiting policies */
-
+
/**
* The search operation starts immediately, even if the underlying indexer
* has not finished indexing the workspace. Results will more likely
@@ -121,5 +123,6 @@ public interface IJavaSearchConstants {
* the workspace before starting the search.
*/
int WAIT_UNTIL_READY_TO_SEARCH = IJobConstants.WaitUntilReady;
-
+
+
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/IJavaSearchResultCollector.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/IJavaSearchResultCollector.java
index 8c06406f97..1d253aa33e 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/IJavaSearchResultCollector.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/IJavaSearchResultCollector.java
@@ -43,42 +43,42 @@ public interface IJavaSearchResultCollector {
* but a problem prevented the search engine from being more accurate
* (typically because of the classpath was not correctly set).
*/
- int POTENTIAL_MATCH = 1;
+ int POTENTIAL_MATCH = 1;
- /**
- * Called before the actual search starts.
- */
- public void aboutToStart();
- /**
- * Accepts the given search result.
- *
- * @param resource the resource in which the match has been found
- * @param start the start position of the match, -1 if it is unknown
- * @param end the end position of the match, -1 if it is unknown;
- * the ending offset is exclusive, meaning that the actual range of characters
- * covered is <code>[start, end]</code>
- * @param enclosingElement the Java element that contains the character range
- * <code>[start, end]</code>; the value can be <code>null</code> indicating that
- * no enclosing Java element has been found
- * @param accuracy the level of accuracy the search result has; either
- * <code>EXACT_MATCH</code> or <code>POTENTIAL_MATCH</code>
- * @exception CoreException if this collector had a problem accepting the search result
- */
- public void accept(
- IResource resource,
- int start,
- int end,
- IJavaElement enclosingElement,
- int accuracy)
- throws CoreException;
- /**
- * Called when the search has ended.
- */
- public void done();
- /**
- * Returns the progress monitor used to setup and report progress.
- *
- * @return a progress monitor or null if no progress monitor is provided
- */
- public IProgressMonitor getProgressMonitor();
+/**
+ * Called before the actual search starts.
+ */
+public void aboutToStart();
+/**
+ * Accepts the given search result.
+ *
+ * @param resource the resource in which the match has been found
+ * @param start the start position of the match, -1 if it is unknown
+ * @param end the end position of the match, -1 if it is unknown;
+ * the ending offset is exclusive, meaning that the actual range of characters
+ * covered is <code>[start, end]</code>
+ * @param enclosingElement the Java element that contains the character range
+ * <code>[start, end]</code>; the value can be <code>null</code> indicating that
+ * no enclosing Java element has been found
+ * @param accuracy the level of accuracy the search result has; either
+ * <code>EXACT_MATCH</code> or <code>POTENTIAL_MATCH</code>
+ * @exception CoreException if this collector had a problem accepting the search result
+ */
+public void accept(
+ IResource resource,
+ int start,
+ int end,
+ IJavaElement enclosingElement,
+ int accuracy)
+ throws CoreException;
+/**
+ * Called when the search has ended.
+ */
+public void done();
+/**
+ * Returns the progress monitor used to setup and report progress.
+ *
+ * @return a progress monitor or null if no progress monitor is provided
+ */
+public IProgressMonitor getProgressMonitor();
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/IJavaSearchScope.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/IJavaSearchScope.java
index 4ff51a164a..e1aa7431f1 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/IJavaSearchScope.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/IJavaSearchScope.java
@@ -23,56 +23,56 @@ public interface IJavaSearchScope {
* to the .class file in the jar.
*/
String JAR_FILE_ENTRY_SEPARATOR = JarFileEntryDocument.JAR_FILE_ENTRY_SEPARATOR;
- /**
- * Checks whether the resource at the given path is enclosed by this scope.
- *
- * @param resourcePath if the resource is contained in
- * a JAR file, the path is composed of 2 paths separated
- * by <code>JAR_FILE_ENTRY_SEPARATOR</code>: the first path is the full OS path
- * to the JAR, the second path is the path to the resource inside the JAR.
- * @return whether the resourse is enclosed by this scope
- */
- public boolean encloses(String resourcePath);
- /**
- * Checks whether this scope encloses the given element.
- *
- * @param the element
- * @return <code>true</code> if the element is in this scope
- */
- public boolean encloses(IJavaElement element);
- /**
- * Returns the paths to the enclosing projects and JARs for this search scope.
- *
- * @return an array of paths to the enclosing projects and JARS. A project path is
- * the full path to the project. A JAR path is the full OS path to the JAR file.
- */
- IPath[] enclosingProjectsAndJars();
- /**
- * Returns whether this scope contains any <code>.class</code> files (either
- * in folders or within JARs).
- *
- * @return whether this scope contains any <code>.class</code> files
- */
- boolean includesBinaries();
- /**
- * Returns whether this scope includes classpaths defined by
- * the projects of the resources of this search scope.
- *
- * @return whether this scope includes classpaths
- */
- boolean includesClasspaths();
- /**
- * Sets whether this scope contains any <code>.class</code> files (either
- * in folders or within JARs).
- *
- * @param includesBinaries whether this scope contains any <code>.class</code> files
- */
- public void setIncludesBinaries(boolean includesBinaries);
- /**
- * Sets whether this scope includes the classpaths defined by
- * the projects of the resources of this search scope.
- *
- * @return includesClasspaths whether this scope includes classpaths
- */
- public void setIncludesClasspaths(boolean includesClasspaths);
+/**
+ * Checks whether the resource at the given path is enclosed by this scope.
+ *
+ * @param resourcePath if the resource is contained in
+ * a JAR file, the path is composed of 2 paths separated
+ * by <code>JAR_FILE_ENTRY_SEPARATOR</code>: the first path is the full OS path
+ * to the JAR, the second path is the path to the resource inside the JAR.
+ * @return whether the resourse is enclosed by this scope
+ */
+public boolean encloses(String resourcePath);
+/**
+ * Checks whether this scope encloses the given element.
+ *
+ * @param the element
+ * @return <code>true</code> if the element is in this scope
+ */
+public boolean encloses(IJavaElement element);
+/**
+ * Returns the paths to the enclosing projects and JARs for this search scope.
+ *
+ * @return an array of paths to the enclosing projects and JARS. A project path is
+ * the full path to the project. A JAR path is the full OS path to the JAR file.
+ */
+IPath[] enclosingProjectsAndJars();
+/**
+ * Returns whether this scope contains any <code>.class</code> files (either
+ * in folders or within JARs).
+ *
+ * @return whether this scope contains any <code>.class</code> files
+ */
+boolean includesBinaries();
+/**
+ * Returns whether this scope includes classpaths defined by
+ * the projects of the resources of this search scope.
+ *
+ * @return whether this scope includes classpaths
+ */
+boolean includesClasspaths();
+/**
+ * Sets whether this scope contains any <code>.class</code> files (either
+ * in folders or within JARs).
+ *
+ * @param includesBinaries whether this scope contains any <code>.class</code> files
+ */
+public void setIncludesBinaries(boolean includesBinaries);
+/**
+ * Sets whether this scope includes the classpaths defined by
+ * the projects of the resources of this search scope.
+ *
+ * @return includesClasspaths whether this scope includes classpaths
+ */
+public void setIncludesClasspaths(boolean includesClasspaths);
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/ISearchPattern.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/ISearchPattern.java
index ff7c7ddea1..e982ac6a98 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/ISearchPattern.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/ISearchPattern.java
@@ -5,7 +5,7 @@ package org.eclipse.jdt.core.search;
* All Rights Reserved.
*/
import org.eclipse.jdt.core.*;
-
+
/**
* A search pattern defines how search results are found. Use <code>SearchEngine.createSearchPattern</code>
* to create a search pattern.
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/ITypeNameRequestor.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/ITypeNameRequestor.java
index 9d8a9688a7..4c17166049 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/ITypeNameRequestor.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/ITypeNameRequestor.java
@@ -1,42 +1,34 @@
package org.eclipse.jdt.core.search;
public interface ITypeNameRequestor {
- /**
- * Accepts a top-level or a member class.
- *
- * @param packageName the dot-separated name of the package of the class
- * @param simpleTypeName the simple name of the class
- * @param enclosingTypeNames if the class is a member type,
- * the simple names of the enclosing types from the outer-most to the
- * direct parent of the class (e.g. if the class is x.y.A$B$C then
- * the enclosing types are [A, B]. This is an empty array if the class
- * is a top-level type.
- * @param path the full path to the resource containing the class. If the resource is a .class file
- * or a .java file, this is the full path in the workspace to this resource. If the
- * resource is a .zip or .jar file, this is the full OS path to this file.
- */
- void acceptClass(
- char[] packageName,
- char[] simpleTypeName,
- char[][] enclosingTypeNames,
- String path);
- /**
- * Accepts a top-level or a member interface.
- *
- * @param packageName the dot-separated name of the package of the interface
- * @param simpleTypeName the simple name of the interface
- * @param enclosingTypeNames if the interface is a member type,
- * the simple names of the enclosing types from the outer-most to the
- * direct parent of the interface (e.g. if the interface is x.y.A$B$I then
- * the enclosing types are [A, B]. This is an empty array if the interface
- * is a top-level type.
- * @param path the full path to the resource containing the interface. If the resource is a .class file
- * or a .java file, this is the full path in the workspace to this resource. If the
- * resource is a .zip or .jar file, this is the full OS path to this file.
- */
- void acceptInterface(
- char[] packageName,
- char[] simpleTypeName,
- char[][] enclosingTypeNames,
- String path);
+/**
+ * Accepts a top-level or a member class.
+ *
+ * @param packageName the dot-separated name of the package of the class
+ * @param simpleTypeName the simple name of the class
+ * @param enclosingTypeNames if the class is a member type,
+ * the simple names of the enclosing types from the outer-most to the
+ * direct parent of the class (e.g. if the class is x.y.A$B$C then
+ * the enclosing types are [A, B]. This is an empty array if the class
+ * is a top-level type.
+ * @param path the full path to the resource containing the class. If the resource is a .class file
+ * or a .java file, this is the full path in the workspace to this resource. If the
+ * resource is a .zip or .jar file, this is the full OS path to this file.
+ */
+void acceptClass(char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path);
+/**
+ * Accepts a top-level or a member interface.
+ *
+ * @param packageName the dot-separated name of the package of the interface
+ * @param simpleTypeName the simple name of the interface
+ * @param enclosingTypeNames if the interface is a member type,
+ * the simple names of the enclosing types from the outer-most to the
+ * direct parent of the interface (e.g. if the interface is x.y.A$B$I then
+ * the enclosing types are [A, B]. This is an empty array if the interface
+ * is a top-level type.
+ * @param path the full path to the resource containing the interface. If the resource is a .class file
+ * or a .java file, this is the full path in the workspace to this resource. If the
+ * resource is a .zip or .jar file, this is the full OS path to this file.
+ */
+void acceptInterface(char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path);
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/SearchEngine.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/SearchEngine.java
index b2e9c50fcc..f6df0d67b0 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/SearchEngine.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/SearchEngine.java
@@ -40,595 +40,486 @@ import java.util.*;
* </p>
*/
public class SearchEngine {
- /**
- * Returns a java search scope limited to the hierarchy of the given type.
- * The java elements resulting from a search with this scope will
- * be types in this hierarchy, or members of the types in this hierarchy.
- *
- * @param type the focus of the hierarchy scope
- * @return a new hierarchy scope
- * @exception JavaModelException if the hierarchy could not be computed on the given type
- */
- public static IJavaSearchScope createHierarchyScope(IType type)
- throws JavaModelException {
- return new HierarchyScope(type);
- }
-
- /**
- * Returns a java search scope limited to the given resources.
- * The java elements resulting from a search with this scope will
- * have their underlying resource included in or equals to one of the given
- * resources.
- * <p>
- * Resources must not overlap, e.g. one cannot include a folder and its children.
- * </p>
- *
- * @param resources the resources the scope is limited to
- * @return a new java search scope
- */
- public static IJavaSearchScope createJavaSearchScope(IResource[] resources) {
- JavaSearchScope scope = new JavaSearchScope();
- for (int i = 0, length = resources.length; i < length; i++) {
- scope.add(resources[i]);
- }
- return scope;
- }
-
- /**
- * Returns a search pattern that combines the given two patterns into a "or" pattern.
- * The search result will match either the left pattern or the right pattern.
- *
- * @param leftPattern the left pattern
- * @param rightPattern the right pattern
- * @return a "or" pattern
- */
- public static ISearchPattern createOrSearchPattern(
- ISearchPattern leftPattern,
- ISearchPattern rightPattern) {
- return new OrPattern((SearchPattern) leftPattern, (SearchPattern) rightPattern);
- }
-
- /**
- * Returns a search pattern based on a given string pattern. The string patterns support '*' wild-cards.
- * The remaining parameters are used to narrow down the type of expected results.
- *
- * <p>
- * Examples:
- * <ul>
- * <li>search for case insensitive references to <code>Object</code>:
- * <code>createSearchPattern("Object", TYPE, REFERENCES, false);</code>
- * <li>search for case sensitive references to exact <code>Object()</code> constructor:
- * <code>createSearchPattern("java.lang.Object()", CONSTRUCTOR, REFERENCES, true);</code>
- * <li>search for implementors of <code>java.lang.Runnable</code>:
- * <code>createSearchPattern("java.lang.Runnable", TYPE, IMPLEMENTORS, true);</code>
- * @param searchFor determines the nature of the searched elements
- * <ul>
- * <li><code>IJavaSearchConstants.CLASS</code>: only look for classes
- * <li><code>IJavaSearchConstants.INTERFACE</code>: only look for interfaces
- * <li><code>IJavaSearchConstants.TYPE</code>: look for both classes and interfaces
- * <li><code>IJavaSearchConstants.FIELD</code>: look for fields
- * <li><code>IJavaSearchConstants.METHOD</code>: look for methods
- * <li><code>IJavaSearchConstants.CONSTRUCTOR</code>: look for constructors
- * <li><code>IJavaSearchConstants.PACKAGE</code>: look for packages
- * </ul>
- * @param limitTo determines the nature of the expected matches
- * <ul>
- * <li><code>IJavaSearchConstants.DECLARATIONS</code>: will search declarations matching with the corresponding
- * element. In case the element is a method, declarations of matching methods in subtypes will also
- * be found, allowing to find declarations of abstract methods, etc.
- *
- * <li><code>IJavaSearchConstants.REFERENCES</code>: will search references to the given element.
- *
- * <li><code>IJavaSearchConstants.ALL_OCCURRENCES</code>: will search for either declarations or references as specified
- * above.
- *
- * <li><code>IJavaSearchConstants.IMPLEMENTORS</code>: for interface, will find all types which implements a given interface.
- * </ul>
- *
- * @param isCaseSensitive indicates whether the search is case sensitive or not.
- * @return a search pattern on the given string pattern, or <code>null</code> if the string pattern is ill-formed.
- */
- public static ISearchPattern createSearchPattern(
- String stringPattern,
- int searchFor,
- int limitTo,
- boolean isCaseSensitive) {
-
- return SearchPattern.createPattern(
- stringPattern,
- searchFor,
- limitTo,
- IJavaSearchConstants.PATTERN_MATCH,
- isCaseSensitive);
- }
-
- /**
- * Returns a search pattern based on a given Java element.
- * The pattern is used to trigger the appropriate search, and can be parameterized as follows:
- *
- * @param element the java element the search pattern is based on
- * @param limitTo determines the nature of the expected matches
- * <ul>
- * <li><code>IJavaSearchConstants.DECLARATIONS</code>: will search declarations matching with the corresponding
- * element. In case the element is a method, declarations of matching methods in subtypes will also
- * be found, allowing to find declarations of abstract methods, etc.
- *
- * <li><code>IJavaSearchConstants.REFERENCES</code>: will search references to the given element.
- *
- * <li><code>IJavaSearchConstants.ALL_OCCURRENCES</code>: will search for either declarations or references as specified
- * above.
- *
- * <li><code>IJavaSearchConstants.IMPLEMENTORS</code>: for interface, will find all types which implements a given interface.
- * </ul>
- * @return a search pattern for a java element or <code>null</code> if the given element is ill-formed
- */
- public static ISearchPattern createSearchPattern(
- IJavaElement element,
- int limitTo) {
-
- return SearchPattern.createPattern(element, limitTo);
- }
-
- /**
- * Returns a java search scope with the workspace as the only limit.
- *
- * @return a new workspace scope
- */
- public static IJavaSearchScope createWorkspaceScope() {
- return new JavaWorkspaceScope();
- }
-
- /**
- * Searches for the Java element determined by the given signature. The signature
- * can be incomplete. For example, a call like
- * <code>search(ws,"run()",METHOD,REFERENCES,col)</code>
- * searchs for all references to the method <code>run</code>.
- *
- * @param workspace the workspace
- * @param pattern the pattern to be searched for
- * @param searchFor a hint what kind of Java element the string pattern represents.
- * Look into <code>IJavaSearchConstants</code> for valid values
- * @param limitTo one of the following values:
- * <ul>
- * <li><code>IJavaSearchConstants.DECLARATIONS</code>: search
- * for declarations only </li>
- * <li><code>IJavaSearchConstants.REFERENCES</code>: search
- * for all references </li>
- * <li><code>IJavaSearchConstants.ALL_OCCURENCES</code>: search
- * for both declarations and all references </li>
- * <li><code>IJavaSearchConstants.IMPLEMENTORS</code>: search for
- * all implementors of an interface; the value is only valid if
- * the Java element represents an interface
- * </ul>
- * @param scope the search result has to be limited to the given scope
- * @param resultCollector a callback object to which each match is reported
- * @exception JavaModelException if the search failed. Reasons include:
- * <ul>
- * <li>the classpath is incorrectly set
- * </ul>
- */
- public void search(
- IWorkspace workspace,
- String patternString,
- int searchFor,
- int limitTo,
- IJavaSearchScope scope,
- IJavaSearchResultCollector resultCollector)
- throws JavaModelException {
-
- search(
- workspace,
- createSearchPattern(patternString, searchFor, limitTo, true),
- scope,
- resultCollector);
- }
-
- /**
- * Searches for the given Java element.
- *
- * @param workspace the workspace
- * @param element the Java element to be searched for
- * @param limitTo one of the following values:
- * <ul>
- * <li><code>IJavaSearchConstants.DECLARATIONS</code>: search
- * for declarations only </li>
- * <li><code>IJavaSearchConstants.REFERENCES</code>: search
- * for all references </li>
- * <li><code>IJavaSearchConstants.ALL_OCCURENCES</code>: search
- * for both declarations and all references </li>
- * <li><code>IJavaSearchConstants.IMPLEMENTORS</code>: search for
- * all implementors of an interface; the value is only valid if
- * the Java element represents an interface
- * </ul>
- * @param scope the search result has to be limited to the given scope
- * @param resultCollector a callback object to which each match is reported
- * @exception JavaModelException if the search failed. Reasons include:
- * <ul>
- * <li>the element doesn't exist
- * <li>the classpath is incorrectly set
- * </ul>
- */
- public void search(
- IWorkspace workspace,
- IJavaElement element,
- int limitTo,
- IJavaSearchScope scope,
- IJavaSearchResultCollector resultCollector)
- throws JavaModelException {
-
- search(
- workspace,
- createSearchPattern(element, limitTo),
- scope,
- resultCollector);
+/**
+ * Returns a java search scope limited to the hierarchy of the given type.
+ * The java elements resulting from a search with this scope will
+ * be types in this hierarchy, or members of the types in this hierarchy.
+ *
+ * @param type the focus of the hierarchy scope
+ * @return a new hierarchy scope
+ * @exception JavaModelException if the hierarchy could not be computed on the given type
+ */
+public static IJavaSearchScope createHierarchyScope(IType type) throws JavaModelException {
+ return new HierarchyScope(type);
+}
+/**
+ * Returns a java search scope limited to the given resources.
+ * The java elements resulting from a search with this scope will
+ * have their underlying resource included in or equals to one of the given
+ * resources.
+ * <p>
+ * Resources must not overlap, e.g. one cannot include a folder and its children.
+ * </p>
+ *
+ * @param resources the resources the scope is limited to
+ * @return a new java search scope
+ */
+public static IJavaSearchScope createJavaSearchScope(IResource[] resources) {
+ JavaSearchScope scope = new JavaSearchScope();
+ for (int i = 0, length = resources.length; i < length; i++) {
+ scope.add(resources[i]);
}
+ return scope;
+}
+/**
+ * Returns a search pattern that combines the given two patterns into a "or" pattern.
+ * The search result will match either the left pattern or the right pattern.
+ *
+ * @param leftPattern the left pattern
+ * @param rightPattern the right pattern
+ * @return a "or" pattern
+ */
+public static ISearchPattern createOrSearchPattern(ISearchPattern leftPattern, ISearchPattern rightPattern) {
+ return new OrPattern((SearchPattern)leftPattern, (SearchPattern)rightPattern);
+}
+/**
+ * Returns a search pattern based on a given string pattern. The string patterns support '*' wild-cards.
+ * The remaining parameters are used to narrow down the type of expected results.
+ *
+ * <p>
+ * Examples:
+ * <ul>
+ * <li>search for case insensitive references to <code>Object</code>:
+ * <code>createSearchPattern("Object", TYPE, REFERENCES, false);</code>
+ * <li>search for case sensitive references to exact <code>Object()</code> constructor:
+ * <code>createSearchPattern("java.lang.Object()", CONSTRUCTOR, REFERENCES, true);</code>
+ * <li>search for implementors of <code>java.lang.Runnable</code>:
+ * <code>createSearchPattern("java.lang.Runnable", TYPE, IMPLEMENTORS, true);</code>
+ * @param searchFor determines the nature of the searched elements
+ * <ul>
+ * <li><code>IJavaSearchConstants.CLASS</code>: only look for classes
+ * <li><code>IJavaSearchConstants.INTERFACE</code>: only look for interfaces
+ * <li><code>IJavaSearchConstants.TYPE</code>: look for both classes and interfaces
+ * <li><code>IJavaSearchConstants.FIELD</code>: look for fields
+ * <li><code>IJavaSearchConstants.METHOD</code>: look for methods
+ * <li><code>IJavaSearchConstants.CONSTRUCTOR</code>: look for constructors
+ * <li><code>IJavaSearchConstants.PACKAGE</code>: look for packages
+ * </ul>
+ * @param limitTo determines the nature of the expected matches
+ * <ul>
+ * <li><code>IJavaSearchConstants.DECLARATIONS</code>: will search declarations matching with the corresponding
+ * element. In case the element is a method, declarations of matching methods in subtypes will also
+ * be found, allowing to find declarations of abstract methods, etc.
+ *
+ * <li><code>IJavaSearchConstants.REFERENCES</code>: will search references to the given element.
+ *
+ * <li><code>IJavaSearchConstants.ALL_OCCURRENCES</code>: will search for either declarations or references as specified
+ * above.
+ *
+ * <li><code>IJavaSearchConstants.IMPLEMENTORS</code>: for interface, will find all types which implements a given interface.
+ * </ul>
+ *
+ * @param isCaseSensitive indicates whether the search is case sensitive or not.
+ * @return a search pattern on the given string pattern, or <code>null</code> if the string pattern is ill-formed.
+ */
+public static ISearchPattern createSearchPattern(String stringPattern, int searchFor, int limitTo, boolean isCaseSensitive) {
- /**
- * Searches for matches of a given search pattern. Search patterns can be created using helper
- * methods (from a String pattern or a Java element) and encapsulate the description of what is
- * being searched (e.g. search method declarations in a case sensitive way).
- *
- * @param workspace the workspace
- * @param searchPattern the pattern to be searched for
- * @param scope the search result has to be limited to the given scope
- * @param resultCollector a callback object to which each match is reported
- * @exception JavaModelException if the search failed. Reasons include:
- * <ul>
- * <li>the classpath is incorrectly set
- * </ul>
- */
- public void search(
- IWorkspace workspace,
- ISearchPattern searchPattern,
- IJavaSearchScope scope,
- IJavaSearchResultCollector resultCollector)
- throws JavaModelException {
+ return SearchPattern.createPattern(stringPattern, searchFor, limitTo, IJavaSearchConstants.PATTERN_MATCH, isCaseSensitive);
+}
+/**
+ * Returns a search pattern based on a given Java element.
+ * The pattern is used to trigger the appropriate search, and can be parameterized as follows:
+ *
+ * @param element the java element the search pattern is based on
+ * @param limitTo determines the nature of the expected matches
+ * <ul>
+ * <li><code>IJavaSearchConstants.DECLARATIONS</code>: will search declarations matching with the corresponding
+ * element. In case the element is a method, declarations of matching methods in subtypes will also
+ * be found, allowing to find declarations of abstract methods, etc.
+ *
+ * <li><code>IJavaSearchConstants.REFERENCES</code>: will search references to the given element.
+ *
+ * <li><code>IJavaSearchConstants.ALL_OCCURRENCES</code>: will search for either declarations or references as specified
+ * above.
+ *
+ * <li><code>IJavaSearchConstants.IMPLEMENTORS</code>: for interface, will find all types which implements a given interface.
+ * </ul>
+ * @return a search pattern for a java element or <code>null</code> if the given element is ill-formed
+ */
+public static ISearchPattern createSearchPattern(IJavaElement element, int limitTo) {
- /* search is starting */
- resultCollector.aboutToStart();
+ return SearchPattern.createPattern(element, limitTo);
+}
+/**
+ * Returns a java search scope with the workspace as the only limit.
+ *
+ * @return a new workspace scope
+ */
+public static IJavaSearchScope createWorkspaceScope() {
+ return new JavaWorkspaceScope();
+}
+/**
+ * Searches for the Java element determined by the given signature. The signature
+ * can be incomplete. For example, a call like
+ * <code>search(ws,"run()",METHOD,REFERENCES,col)</code>
+ * searchs for all references to the method <code>run</code>.
+ *
+ * @param workspace the workspace
+ * @param pattern the pattern to be searched for
+ * @param searchFor a hint what kind of Java element the string pattern represents.
+ * Look into <code>IJavaSearchConstants</code> for valid values
+ * @param limitTo one of the following values:
+ * <ul>
+ * <li><code>IJavaSearchConstants.DECLARATIONS</code>: search
+ * for declarations only </li>
+ * <li><code>IJavaSearchConstants.REFERENCES</code>: search
+ * for all references </li>
+ * <li><code>IJavaSearchConstants.ALL_OCCURENCES</code>: search
+ * for both declarations and all references </li>
+ * <li><code>IJavaSearchConstants.IMPLEMENTORS</code>: search for
+ * all implementors of an interface; the value is only valid if
+ * the Java element represents an interface
+ * </ul>
+ * @param scope the search result has to be limited to the given scope
+ * @param resultCollector a callback object to which each match is reported
+ * @exception JavaModelException if the search failed. Reasons include:
+ * <ul>
+ * <li>the classpath is incorrectly set
+ * </ul>
+ */
+public void search(IWorkspace workspace, String patternString, int searchFor, int limitTo, IJavaSearchScope scope, IJavaSearchResultCollector resultCollector) throws JavaModelException {
- try {
- if (searchPattern == null)
- return;
+ search(workspace, createSearchPattern(patternString, searchFor, limitTo, true), scope, resultCollector);
+}
+/**
+ * Searches for the given Java element.
+ *
+ * @param workspace the workspace
+ * @param element the Java element to be searched for
+ * @param limitTo one of the following values:
+ * <ul>
+ * <li><code>IJavaSearchConstants.DECLARATIONS</code>: search
+ * for declarations only </li>
+ * <li><code>IJavaSearchConstants.REFERENCES</code>: search
+ * for all references </li>
+ * <li><code>IJavaSearchConstants.ALL_OCCURENCES</code>: search
+ * for both declarations and all references </li>
+ * <li><code>IJavaSearchConstants.IMPLEMENTORS</code>: search for
+ * all implementors of an interface; the value is only valid if
+ * the Java element represents an interface
+ * </ul>
+ * @param scope the search result has to be limited to the given scope
+ * @param resultCollector a callback object to which each match is reported
+ * @exception JavaModelException if the search failed. Reasons include:
+ * <ul>
+ * <li>the element doesn't exist
+ * <li>the classpath is incorrectly set
+ * </ul>
+ */
+public void search(IWorkspace workspace, IJavaElement element, int limitTo, IJavaSearchScope scope, IJavaSearchResultCollector resultCollector) throws JavaModelException {
- /* initialize progress monitor */
- IProgressMonitor progressMonitor = resultCollector.getProgressMonitor();
- if (progressMonitor != null) {
- progressMonitor.beginTask("Searching...", 105);
- // 5 for getting paths, 100 for locating matches
- }
+ search(workspace, createSearchPattern(element, limitTo), scope, resultCollector);
+}
+/**
+ * Searches for matches of a given search pattern. Search patterns can be created using helper
+ * methods (from a String pattern or a Java element) and encapsulate the description of what is
+ * being searched (e.g. search method declarations in a case sensitive way).
+ *
+ * @param workspace the workspace
+ * @param searchPattern the pattern to be searched for
+ * @param scope the search result has to be limited to the given scope
+ * @param resultCollector a callback object to which each match is reported
+ * @exception JavaModelException if the search failed. Reasons include:
+ * <ul>
+ * <li>the classpath is incorrectly set
+ * </ul>
+ */
+public void search(IWorkspace workspace, ISearchPattern searchPattern, IJavaSearchScope scope, IJavaSearchResultCollector resultCollector) throws JavaModelException {
- /* index search */
- PathCollector pathCollector = new PathCollector();
+ /* search is starting */
+ resultCollector.aboutToStart();
- IndexManager indexManager =
- ((JavaModelManager) JavaModelManager.getJavaModelManager()).getIndexManager();
- int detailLevel = IInfoConstants.PathInfo | IInfoConstants.PositionInfo;
- MatchLocator matchLocator =
- new MatchLocator(
- (SearchPattern) searchPattern,
- detailLevel,
- resultCollector,
- scope);
- if (indexManager != null) {
- indexManager.performConcurrentJob(
- new PatternSearchJob(
- (SearchPattern) searchPattern,
- scope,
- detailLevel,
- pathCollector,
- indexManager,
- progressMonitor),
- IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
- progressMonitor);
+ try {
+ if (searchPattern == null) return;
- if (progressMonitor != null) {
- progressMonitor.worked(5);
- }
+ /* initialize progress monitor */
+ IProgressMonitor progressMonitor = resultCollector.getProgressMonitor();
+ if (progressMonitor != null) {
+ progressMonitor.beginTask("Searching...", 105); // 5 for getting paths, 100 for locating matches
+ }
- /* eliminating false matches and locating them */
- if (progressMonitor != null && progressMonitor.isCanceled())
- throw new OperationCanceledException();
- matchLocator.locateMatches(pathCollector.getPaths(), workspace);
- }
+ /* index search */
+ PathCollector pathCollector = new PathCollector();
+
+ IndexManager indexManager = ((JavaModelManager)JavaModelManager.getJavaModelManager())
+ .getIndexManager();
+ int detailLevel = IInfoConstants.PathInfo | IInfoConstants.PositionInfo;
+ MatchLocator matchLocator = new MatchLocator((SearchPattern)searchPattern, detailLevel, resultCollector, scope);
+ if (indexManager != null) {
+ indexManager.performConcurrentJob(
+ new PatternSearchJob(
+ (SearchPattern)searchPattern,
+ scope,
+ detailLevel,
+ pathCollector,
+ indexManager,
+ progressMonitor),
+ IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
+ progressMonitor);
if (progressMonitor != null) {
- progressMonitor.done();
+ progressMonitor.worked(5);
}
-
- matchLocator.locatePackageDeclarations(workspace);
- } finally {
- /* search has ended */
- resultCollector.done();
+
+ /* eliminating false matches and locating them */
+ if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException();
+ matchLocator.locateMatches(pathCollector.getPaths(), workspace);
}
- }
-
- /**
- * Searches for all top-level types and member types in the given scope.
- * The search can be selecting specific types (given a package or a type name
- * prefix and match modes).
- *
- * @param workspace the workspace to search in
- * @param packageName the full name of the package of the searched types, or a prefix for this
- * package, or a wild-carded string for this package.
- * @param typeName the dot-separated qualied name of the searched type (the qualification include
- * the enclosing types if the searched type is a member type), or a prefix
- * for this type, or a wild-carded string for this type.
- * @param matchMode one of
- * <ul>
- * <li><code>IJavaSearchConstants.EXACT_MATCH</code> if the package name and type name are the full names
- * of the searched types.
- * <li><code>IJavaSearchConstants.PREFIX_MATCH</code> if the package name and type name are prefixes of the names
- * of the searched types.
- * <li><code>IJavaSearchConstants.PATTERN_MATCH</code> if the package name and type name contain wild-cards.
- * </ul>
- * @param isCaseSensitive whether the search should be case senistive
- * @param searchFor one of
- * <ul>
- * <li><code>IJavaSearchConstants.CLASS</code> if searching for classes only
- * <li><code>IJavaSearchConstants.INTERFACE</code> if searching for interfaces only
- * <li><code>IJavaSearchConstants.TYPE</code> if searching for both classes and interfaces
- * </ul>
- * @param scope the scope to search in
- * @param nameRequestor the requestor that collects the results of the search
- * @param waitingPolicy one of
- * <ul>
- * <li><code>IJavaSearchConstants.FORCE_IMMEDIATE_SEARCH</code> if the search should start immediately
- * <li><code>IJavaSearchConstants.CANCEL_IF_NOT_READY_TO_SEARCH</code> if the search should be canceled if the
- * underlying indexer has not finished indexing the workspace
- * <li><code>IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH</code> if the search should wait for the
- * underlying indexer to finish indexing the workspace
- * </ul>
- * @param progressMonitor the progress monitor to report progress to, or <code>null</code> if no progress
- * monitor is provided
- * @exception JavaModelException if the search failed. Reasons include:
- * <ul>
- * <li>the classpath is incorrectly set
- * </ul>
- */
- public void searchAllTypeNames(
- IWorkspace workspace,
- char[] packageName,
- char[] typeName,
- int matchMode,
- boolean isCaseSensitive,
- int searchFor,
- IJavaSearchScope scope,
- final ITypeNameRequestor nameRequestor,
- int waitingPolicy,
- IProgressMonitor progressMonitor)
- throws JavaModelException {
-
- IndexManager indexManager =
- ((JavaModelManager) JavaModelManager.getJavaModelManager()).getIndexManager();
- if (indexManager == null)
- return;
- char classOrInterface;
- switch (searchFor) {
- case IJavaSearchConstants.CLASS :
- classOrInterface = IIndexConstants.CLASS_SUFFIX;
- break;
- case IJavaSearchConstants.INTERFACE :
- classOrInterface = IIndexConstants.INTERFACE_SUFFIX;
- break;
- default :
- classOrInterface = IIndexConstants.TYPE_SUFFIX;
- break;
+ if (progressMonitor != null) {
+ progressMonitor.done();
}
- SearchPattern pattern =
- new TypeDeclarationPattern(packageName, null, // do find member types
- typeName, classOrInterface, matchMode, isCaseSensitive);
-
- IIndexSearchRequestor searchRequestor = new IndexSearchAdapter() {
- public void acceptClassDeclaration(
- String resourcePath,
- char[] simpleTypeName,
- char[][] enclosingTypeNames,
- char[] packageName) {
- nameRequestor.acceptClass(
- packageName,
- simpleTypeName,
- enclosingTypeNames,
- resourcePath);
- }
- public void acceptInterfaceDeclaration(
- String resourcePath,
- char[] simpleTypeName,
- char[][] enclosingTypeNames,
- char[] packageName) {
- nameRequestor.acceptInterface(
- packageName,
- simpleTypeName,
- enclosingTypeNames,
- resourcePath);
- }
- };
-
- indexManager.performConcurrentJob(
- new PatternSearchJob(
- pattern,
- scope,
- IInfoConstants.NameInfo | IInfoConstants.PathInfo,
- searchRequestor,
- indexManager,
- progressMonitor),
- waitingPolicy,
- progressMonitor);
- }
- /**
- * Searches for all declarations of the fields accessed in the given element.
- * The element can be a compilation unit, a type, or a method.
- * Reports the field declarations using the given collector.
- * <p>
- * Consider the following code:
- * <code>
- * <pre>
- * class A {
- * int field1;
- * }
- * class B extends A {
- * String value;
- * }
- * class X {
- * void test() {
- * B b = new B();
- * System.out.println(b.value + b.field1);
- * };
- * }
- * </pre>
- * </code>
- * then searching for declarations of accessed fields in method
- * <code>X.test()</code> would collect the fields
- * <code>B.value</code> and <code>A.field1</code>.
- * </p>
- *
- * @param workspace the workspace
- * @param enclosingElement the method, type, or compilation unit to be searched in
- * @param resultCollector a callback object to which each match is reported
- * @exception JavaModelException if the search failed. Reasons include:
- * <ul>
- * <li>the element doesn't exist
- * <li>the classpath is incorrectly set
- * </ul>
- */
- public void searchDeclarationsOfAccessedFields(
- IWorkspace workspace,
- IJavaElement enclosingElement,
- IJavaSearchResultCollector resultCollector)
- throws JavaModelException {
- MatchLocator locator =
- new MatchLocator(
- (SearchPattern) createSearchPattern("*",
- IJavaSearchConstants.FIELD,
- IJavaSearchConstants.REFERENCES,
- true),
- IInfoConstants.DeclarationInfo,
- resultCollector,
- new JavaWorkspaceScope());
- // TBD: limit search to type or method by passing start and end of enclosing element
- locator.locateMatches(
- new String[] {
- enclosingElement.getUnderlyingResource().getFullPath().toString()},
- workspace);
+ matchLocator.locatePackageDeclarations(workspace);
+ } finally {
+ /* search has ended */
+ resultCollector.done();
}
-
- /**
- * Searches for all declarations of the types referenced in the given element.
- * The element can be a compilation unit, a type, or a method.
- * Reports the type declarations using the given collector.
- * <p>
- * Consider the following code:
- * <code>
- * <pre>
- * class A {
- * }
- * class B extends A {
- * }
- * interface I {
- * int VALUE = 0;
- * }
- * class X {
- * void test() {
- * B b = new B();
- * this.foo(b, I.VALUE);
- * };
- * }
- * </pre>
- * <code>
- * then searching for declarations of referenced types in method <code>X.test()</code>
- * would collect the class <code>B</code> and the interface <code>I</code>.
- * </p>
- *
- * @param workspace the workspace
- * @param enclosingElement the method, type, or compilation unit to be searched in
- * @param resultCollector a callback object to which each match is reported
- * @exception JavaModelException if the search failed. Reasons include:
- * <ul>
- * <li>the element doesn't exist
- * <li>the classpath is incorrectly set
- * </ul>
- */
- public void searchDeclarationsOfReferencedTypes(
- IWorkspace workspace,
- IJavaElement enclosingElement,
- IJavaSearchResultCollector resultCollector)
- throws JavaModelException {
- MatchLocator locator =
- new MatchLocator(
- (SearchPattern) createSearchPattern("*",
- IJavaSearchConstants.TYPE,
- IJavaSearchConstants.REFERENCES,
- true),
- IInfoConstants.DeclarationInfo,
- resultCollector,
- new JavaWorkspaceScope());
- // TBD: limit search to type or method by passing start and end of enclosing element
- locator.locateMatches(
- new String[] {
- enclosingElement.getUnderlyingResource().getFullPath().toString()},
- workspace);
- }
-
- /**
- * Searches for all declarations of the methods invoked in the given element.
- * The element can be a compilation unit, a type, or a method.
- * Reports the method declarations using the given collector.
- * <p>
- * Consider the following code:
- * <code>
- * <pre>
- * class A {
- * void foo() {};
- * void bar() {};
- * }
- * class B extends A {
- * void foo() {};
- * }
- * class X {
- * void test() {
- * A a = new B();
- * a.foo();
- * B b = (B)a;
- * b.bar();
- * };
- * }
- * </pre>
- * </code>
- * then searching for declarations of sent messages in method
- * <code>X.test()</code> would collect the methods
- * <code>A.foo()</code>, <code>B.foo()</code>, and <code>A.bar()</code>.
- * </p>
- *
- * @param workspace the workspace
- * @param enclosingElement the method, type, or compilation unit to be searched in
- * @param resultCollector a callback object to which each match is reported
- * @exception JavaModelException if the search failed. Reasons include:
- * <ul>
- * <li>the element doesn't exist
- * <li>the classpath is incorrectly set
- * </ul>
- */
- public void searchDeclarationsOfSentMessages(
- IWorkspace workspace,
- IJavaElement enclosingElement,
- IJavaSearchResultCollector resultCollector)
- throws JavaModelException {
- MatchLocator locator =
- new MatchLocator(
- (SearchPattern) createSearchPattern("*",
- IJavaSearchConstants.METHOD,
- IJavaSearchConstants.REFERENCES,
- true),
- IInfoConstants.DeclarationInfo,
- resultCollector,
- new JavaWorkspaceScope());
- // TBD: limit search to type or method by passing start and end of enclosing element
- locator.locateMatches(
- new String[] {
- enclosingElement.getUnderlyingResource().getFullPath().toString()},
- workspace);
+}
+/**
+ * Searches for all top-level types and member types in the given scope.
+ * The search can be selecting specific types (given a package or a type name
+ * prefix and match modes).
+ *
+ * @param workspace the workspace to search in
+ * @param packageName the full name of the package of the searched types, or a prefix for this
+ * package, or a wild-carded string for this package.
+ * @param typeName the dot-separated qualied name of the searched type (the qualification include
+ * the enclosing types if the searched type is a member type), or a prefix
+ * for this type, or a wild-carded string for this type.
+ * @param matchMode one of
+ * <ul>
+ * <li><code>IJavaSearchConstants.EXACT_MATCH</code> if the package name and type name are the full names
+ * of the searched types.
+ * <li><code>IJavaSearchConstants.PREFIX_MATCH</code> if the package name and type name are prefixes of the names
+ * of the searched types.
+ * <li><code>IJavaSearchConstants.PATTERN_MATCH</code> if the package name and type name contain wild-cards.
+ * </ul>
+ * @param isCaseSensitive whether the search should be case senistive
+ * @param searchFor one of
+ * <ul>
+ * <li><code>IJavaSearchConstants.CLASS</code> if searching for classes only
+ * <li><code>IJavaSearchConstants.INTERFACE</code> if searching for interfaces only
+ * <li><code>IJavaSearchConstants.TYPE</code> if searching for both classes and interfaces
+ * </ul>
+ * @param scope the scope to search in
+ * @param nameRequestor the requestor that collects the results of the search
+ * @param waitingPolicy one of
+ * <ul>
+ * <li><code>IJavaSearchConstants.FORCE_IMMEDIATE_SEARCH</code> if the search should start immediately
+ * <li><code>IJavaSearchConstants.CANCEL_IF_NOT_READY_TO_SEARCH</code> if the search should be canceled if the
+ * underlying indexer has not finished indexing the workspace
+ * <li><code>IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH</code> if the search should wait for the
+ * underlying indexer to finish indexing the workspace
+ * </ul>
+ * @param progressMonitor the progress monitor to report progress to, or <code>null</code> if no progress
+ * monitor is provided
+ * @exception JavaModelException if the search failed. Reasons include:
+ * <ul>
+ * <li>the classpath is incorrectly set
+ * </ul>
+ */
+public void searchAllTypeNames(
+ IWorkspace workspace,
+ char[] packageName,
+ char[] typeName,
+ int matchMode,
+ boolean isCaseSensitive,
+ int searchFor,
+ IJavaSearchScope scope,
+ final ITypeNameRequestor nameRequestor,
+ int waitingPolicy,
+ IProgressMonitor progressMonitor) throws JavaModelException {
+
+ IndexManager indexManager = ((JavaModelManager)JavaModelManager.getJavaModelManager()).getIndexManager();
+ if (indexManager == null) return;
+
+ char classOrInterface;
+ switch(searchFor){
+ case IJavaSearchConstants.CLASS :
+ classOrInterface = IIndexConstants.CLASS_SUFFIX;
+ break;
+ case IJavaSearchConstants.INTERFACE :
+ classOrInterface = IIndexConstants.INTERFACE_SUFFIX;
+ break;
+ default :
+ classOrInterface = IIndexConstants.TYPE_SUFFIX;
+ break;
}
-
+ SearchPattern pattern = new TypeDeclarationPattern(
+ packageName,
+ null, // do find member types
+ typeName,
+ classOrInterface,
+ matchMode,
+ isCaseSensitive);
+
+ IIndexSearchRequestor searchRequestor = new IndexSearchAdapter(){
+ public void acceptClassDeclaration(String resourcePath, char[] simpleTypeName, char[][] enclosingTypeNames, char[] packageName) {
+ nameRequestor.acceptClass(packageName, simpleTypeName, enclosingTypeNames, resourcePath);
+ }
+ public void acceptInterfaceDeclaration(String resourcePath, char[] simpleTypeName, char[][] enclosingTypeNames, char[] packageName) {
+ nameRequestor.acceptInterface(packageName, simpleTypeName, enclosingTypeNames, resourcePath);
+ }
+ };
+
+ indexManager.performConcurrentJob(
+ new PatternSearchJob(pattern, scope, IInfoConstants.NameInfo | IInfoConstants.PathInfo, searchRequestor, indexManager, progressMonitor),
+ waitingPolicy,
+ progressMonitor);
+}
+/**
+ * Searches for all declarations of the fields accessed in the given element.
+ * The element can be a compilation unit, a type, or a method.
+ * Reports the field declarations using the given collector.
+ * <p>
+ * Consider the following code:
+ * <code>
+ * <pre>
+ * class A {
+ * int field1;
+ * }
+ * class B extends A {
+ * String value;
+ * }
+ * class X {
+ * void test() {
+ * B b = new B();
+ * System.out.println(b.value + b.field1);
+ * };
+ * }
+ * </pre>
+ * </code>
+ * then searching for declarations of accessed fields in method
+ * <code>X.test()</code> would collect the fields
+ * <code>B.value</code> and <code>A.field1</code>.
+ * </p>
+ *
+ * @param workspace the workspace
+ * @param enclosingElement the method, type, or compilation unit to be searched in
+ * @param resultCollector a callback object to which each match is reported
+ * @exception JavaModelException if the search failed. Reasons include:
+ * <ul>
+ * <li>the element doesn't exist
+ * <li>the classpath is incorrectly set
+ * </ul>
+ */
+public void searchDeclarationsOfAccessedFields(IWorkspace workspace, IJavaElement enclosingElement, IJavaSearchResultCollector resultCollector) throws JavaModelException {
+ MatchLocator locator = new MatchLocator(
+ (SearchPattern)createSearchPattern("*", IJavaSearchConstants.FIELD, IJavaSearchConstants.REFERENCES, true),
+ IInfoConstants.DeclarationInfo,
+ resultCollector,
+ new JavaWorkspaceScope());
+ // TBD: limit search to type or method by passing start and end of enclosing element
+ locator.locateMatches(
+ new String[] {enclosingElement.getUnderlyingResource().getFullPath().toString()},
+ workspace);
+}
+/**
+ * Searches for all declarations of the types referenced in the given element.
+ * The element can be a compilation unit, a type, or a method.
+ * Reports the type declarations using the given collector.
+ * <p>
+ * Consider the following code:
+ * <code>
+ * <pre>
+ * class A {
+ * }
+ * class B extends A {
+ * }
+ * interface I {
+ * int VALUE = 0;
+ * }
+ * class X {
+ * void test() {
+ * B b = new B();
+ * this.foo(b, I.VALUE);
+ * };
+ * }
+ * </pre>
+ * <code>
+ * then searching for declarations of referenced types in method <code>X.test()</code>
+ * would collect the class <code>B</code> and the interface <code>I</code>.
+ * </p>
+ *
+ * @param workspace the workspace
+ * @param enclosingElement the method, type, or compilation unit to be searched in
+ * @param resultCollector a callback object to which each match is reported
+ * @exception JavaModelException if the search failed. Reasons include:
+ * <ul>
+ * <li>the element doesn't exist
+ * <li>the classpath is incorrectly set
+ * </ul>
+ */
+public void searchDeclarationsOfReferencedTypes(IWorkspace workspace, IJavaElement enclosingElement, IJavaSearchResultCollector resultCollector) throws JavaModelException {
+ MatchLocator locator = new MatchLocator(
+ (SearchPattern)createSearchPattern("*", IJavaSearchConstants.TYPE, IJavaSearchConstants.REFERENCES, true),
+ IInfoConstants.DeclarationInfo,
+ resultCollector,
+ new JavaWorkspaceScope());
+ // TBD: limit search to type or method by passing start and end of enclosing element
+ locator.locateMatches(
+ new String[] {enclosingElement.getUnderlyingResource().getFullPath().toString()},
+ workspace);
+}
+/**
+ * Searches for all declarations of the methods invoked in the given element.
+ * The element can be a compilation unit, a type, or a method.
+ * Reports the method declarations using the given collector.
+ * <p>
+ * Consider the following code:
+ * <code>
+ * <pre>
+ * class A {
+ * void foo() {};
+ * void bar() {};
+ * }
+ * class B extends A {
+ * void foo() {};
+ * }
+ * class X {
+ * void test() {
+ * A a = new B();
+ * a.foo();
+ * B b = (B)a;
+ * b.bar();
+ * };
+ * }
+ * </pre>
+ * </code>
+ * then searching for declarations of sent messages in method
+ * <code>X.test()</code> would collect the methods
+ * <code>A.foo()</code>, <code>B.foo()</code>, and <code>A.bar()</code>.
+ * </p>
+ *
+ * @param workspace the workspace
+ * @param enclosingElement the method, type, or compilation unit to be searched in
+ * @param resultCollector a callback object to which each match is reported
+ * @exception JavaModelException if the search failed. Reasons include:
+ * <ul>
+ * <li>the element doesn't exist
+ * <li>the classpath is incorrectly set
+ * </ul>
+ */
+public void searchDeclarationsOfSentMessages(IWorkspace workspace, IJavaElement enclosingElement, IJavaSearchResultCollector resultCollector) throws JavaModelException {
+ MatchLocator locator = new MatchLocator(
+ (SearchPattern)createSearchPattern("*", IJavaSearchConstants.METHOD, IJavaSearchConstants.REFERENCES, true),
+ IInfoConstants.DeclarationInfo,
+ resultCollector,
+ new JavaWorkspaceScope());
+ // TBD: limit search to type or method by passing start and end of enclosing element
+ locator.locateMatches(
+ new String[] {enclosingElement.getUnderlyingResource().getFullPath().toString()},
+ workspace);
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/package.html b/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/package.html
new file mode 100644
index 0000000000..2eb35a57af
--- /dev/null
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/core/search/package.html
@@ -0,0 +1,18 @@
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+ <meta name="Author" content="IBM">
+ <meta name="GENERATOR" content="Mozilla/4.73 [en] (Windows NT 5.0; U) [Netscape]">
+ <title>Package-level Javadoc</title>
+</head>
+<body>
+Provides support for searching the workspace Java
+elements that match a particular description.
+<h2>
+Package Specification</h2>
+This package provides support for searching the workspace Java elements
+that match a particular description. In particular, it provides a search
+engine with a set of search patterns and search result requestors.
+</body>
+</html>
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/DocumentFactory.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/DocumentFactory.java
index 622cf10c5d..4a108303bf 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/DocumentFactory.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/DocumentFactory.java
@@ -15,9 +15,7 @@ public class DocumentFactory {
public static IDocument newDocument(File file) {
return new FileDocument(file);
}
-
public static IDocument newDocument(IFile file) {
return new IFileDocument(file);
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/IEntryResult.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/IEntryResult.java
index d5c54fda63..1e481f9e34 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/IEntryResult.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/IEntryResult.java
@@ -1,6 +1,6 @@
package org.eclipse.jdt.internal.core.index;
public interface IEntryResult {
- public int[] getFileReferences();
- public char[] getWord();
+public int[] getFileReferences();
+public char[] getWord();
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/IIndexer.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/IIndexer.java
index dcd5ac90ce..15f3dad7ee 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/IIndexer.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/IIndexer.java
@@ -13,8 +13,7 @@ public interface IIndexer {
* the given type of file, and only call this method if so.
*/
- void index(IDocument document, IIndexerOutput output)
- throws java.io.IOException;
+ void index(IDocument document, IIndexerOutput output) throws java.io.IOException;
/**
* Sets the document types the <code>IIndexer</code> handles.
*/
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/IndexFactory.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/IndexFactory.java
index d8c83e3301..6e4e177db4 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/IndexFactory.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/IndexFactory.java
@@ -12,19 +12,13 @@ public class IndexFactory {
public static IIndex newIndex(File indexDirectory) throws IOException {
return new Index(indexDirectory);
}
-
- public static IIndex newIndex(File indexDirectory, String indexName)
- throws IOException {
+ public static IIndex newIndex(File indexDirectory, String indexName) throws IOException {
return new Index(indexDirectory, indexName);
}
-
public static IIndex newIndex(String indexName) throws IOException {
return new Index(indexName);
}
-
- public static IIndex newIndex(String indexName, String toString)
- throws IOException {
+ public static IIndex newIndex(String indexName, String toString) throws IOException {
return new Index(indexName, toString);
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Block.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Block.java
index 5a18cda102..7396bce5c8 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Block.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Block.java
@@ -23,23 +23,20 @@ public abstract class Block {
protected Field field;
public Block(int blockSize) {
- this.blockSize = blockSize;
- field = new Field(blockSize);
+ this.blockSize= blockSize;
+ field= new Field(blockSize);
}
-
/**
* Empties the block.
*/
public void clear() {
field.clear();
}
-
/**
* Flushes the block
*/
public void flush() {
}
-
/**
* Loads the block with the given number in memory, reading it from a RandomAccessFile.
*/
@@ -47,7 +44,6 @@ public abstract class Block {
raf.seek(blockNum * (long) blockSize);
raf.readFully(field.buffer());
}
-
/**
* Writes the block in a RandomAccessFile, giving it a block number.
*/
@@ -55,5 +51,4 @@ public abstract class Block {
raf.seek(blockNum * (long) blockSize);
raf.write(field.buffer());
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/BlocksIndexInput.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/BlocksIndexInput.java
index e715a14c26..7411051c4a 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/BlocksIndexInput.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/BlocksIndexInput.java
@@ -14,8 +14,7 @@ import java.util.*;
* This input is used for reading indexes saved using a BlocksIndexOutput.
*/
public class BlocksIndexInput extends IndexInput {
- public static final int CACHE_SIZE = 16;
- // Cache 16 blocks of 8K each, for a cache size of 128K
+ public static final int CACHE_SIZE= 16; // Cache 16 blocks of 8K each, for a cache size of 128K
protected FileListBlock currentFileListBlock;
protected int currentFileListBlockNum;
protected int currentIndexBlockNum;
@@ -23,21 +22,19 @@ public class BlocksIndexInput extends IndexInput {
private RandomAccessFile raf;
protected File indexFile;
protected LRUCache blockCache;
- protected boolean opened = false;
+ protected boolean opened= false;
protected IndexSummary summary;
public BlocksIndexInput(File inputFile) {
- this.indexFile = inputFile;
- blockCache = new LRUCache(CACHE_SIZE);
+ this.indexFile= inputFile;
+ blockCache= new LRUCache(CACHE_SIZE);
}
-
/**
* @see IndexInput#clearCache
*/
public void clearCache() {
- blockCache = new LRUCache(CACHE_SIZE);
+ blockCache= new LRUCache(CACHE_SIZE);
}
-
/**
* @see IndexInput#close
*/
@@ -45,11 +42,10 @@ public class BlocksIndexInput extends IndexInput {
public void close() throws IOException {
if (opened) {
raf.close();
- summary = null;
- opened = false;
+ summary= null;
+ opened= false;
}
}
-
/**
* @see IndexInput#getCurrentFile
*/
@@ -57,120 +53,107 @@ public class BlocksIndexInput extends IndexInput {
public IndexedFile getCurrentFile() throws IOException {
if (!hasMoreFiles())
return null;
- IndexedFile file = null;
- if ((file = currentFileListBlock.getFile(filePosition)) == null) {
- currentFileListBlockNum = summary.getBlockNumForFileNum(filePosition);
- currentFileListBlock = getFileListBlock(currentFileListBlockNum);
- file = currentFileListBlock.getFile(filePosition);
+ IndexedFile file= null;
+ if ((file= currentFileListBlock.getFile(filePosition)) == null) {
+ currentFileListBlockNum= summary.getBlockNumForFileNum(filePosition);
+ currentFileListBlock= getFileListBlock(currentFileListBlockNum);
+ file= currentFileListBlock.getFile(filePosition);
}
return file;
}
-
/**
* Returns the entry corresponding to the given word.
*/
protected WordEntry getEntry(char[] word) throws IOException {
- int blockNum = summary.getBlockNumForWord(word);
- if (blockNum == -1)
- return null;
- IndexBlock block = getIndexBlock(blockNum);
+ int blockNum= summary.getBlockNumForWord(word);
+ if (blockNum == -1) return null;
+ IndexBlock block= getIndexBlock(blockNum);
return block.findExactEntry(word);
}
-
/**
* Returns the FileListBlock with the given number.
*/
protected FileListBlock getFileListBlock(int blockNum) throws IOException {
- Integer key = new Integer(blockNum);
- Block block = (Block) blockCache.get(key);
+ Integer key= new Integer(blockNum);
+ Block block= (Block) blockCache.get(key);
if (block != null && block instanceof FileListBlock)
return (FileListBlock) block;
- FileListBlock fileListBlock = new FileListBlock(IIndexConstants.BLOCK_SIZE);
+ FileListBlock fileListBlock= new FileListBlock(IIndexConstants.BLOCK_SIZE);
fileListBlock.read(raf, blockNum);
blockCache.put(key, fileListBlock);
return fileListBlock;
}
-
/**
* Returns the IndexBlock (containing words) with the given number.
*/
protected IndexBlock getIndexBlock(int blockNum) throws IOException {
- Integer key = new Integer(blockNum);
- Block block = (Block) blockCache.get(key);
+ Integer key= new Integer(blockNum);
+ Block block= (Block) blockCache.get(key);
if (block != null && block instanceof IndexBlock)
return (IndexBlock) block;
- IndexBlock indexBlock =
- new GammaCompressedIndexBlock(IIndexConstants.BLOCK_SIZE);
+ IndexBlock indexBlock= new GammaCompressedIndexBlock(IIndexConstants.BLOCK_SIZE);
indexBlock.read(raf, blockNum);
blockCache.put(key, indexBlock);
return indexBlock;
}
-
/**
* @see IndexInput#getIndexedFile
*/
public IndexedFile getIndexedFile(int fileNum) throws IOException {
- int blockNum = summary.getBlockNumForFileNum(fileNum);
+ int blockNum= summary.getBlockNumForFileNum(fileNum);
if (blockNum == -1)
return null;
- FileListBlock block = getFileListBlock(blockNum);
+ FileListBlock block= getFileListBlock(blockNum);
return block.getFile(fileNum);
}
-
/**
* @see IndexInput#getIndexedFile
*/
- public IndexedFile getIndexedFile(IDocument document)
- throws java.io.IOException {
+ public IndexedFile getIndexedFile(IDocument document) throws java.io.IOException {
setFirstFile();
- String name = document.getName();
+ String name= document.getName();
while (hasMoreFiles()) {
- IndexedFile file = getCurrentFile();
- String path = file.getPath();
+ IndexedFile file= getCurrentFile();
+ String path= file.getPath();
if (path.equals(name))
return file;
moveToNextFile();
}
return null;
}
-
/**
* Returns the list of numbers of files containing the given word.
*/
protected int[] getMatchingFileNumbers(char[] word) throws IOException {
- int blockNum = summary.getBlockNumForWord(word);
+ int blockNum= summary.getBlockNumForWord(word);
if (blockNum == -1)
return new int[0];
- IndexBlock block = getIndexBlock(blockNum);
- WordEntry entry = block.findExactEntry(word);
+ IndexBlock block= getIndexBlock(blockNum);
+ WordEntry entry= block.findExactEntry(word);
return entry == null ? new int[0] : entry.getRefs();
}
-
/**
* @see IndexInput#getNumFiles
*/
public int getNumFiles() {
return summary.getNumFiles();
}
-
/**
* @see IndexInput#getNumWords
*/
public int getNumWords() {
return summary.getNumWords();
}
-
/**
* @see IndexInput#getSource
*/
public Object getSource() {
return indexFile;
}
-
/**
* Initialises the blocksIndexInput
*/
@@ -179,14 +162,12 @@ public class BlocksIndexInput extends IndexInput {
setFirstFile();
setFirstWord();
}
-
/**
* @see IndexInput#moveToNextFile
*/
public void moveToNextFile() throws IOException {
filePosition++;
}
-
/**
* @see IndexInput#moveToNextEntry
*/
@@ -196,233 +177,209 @@ public class BlocksIndexInput extends IndexInput {
return;
}
//if end of the current block, we load the next one.
- boolean endOfBlock = !currentIndexBlock.nextEntry(currentWordEntry);
+ boolean endOfBlock= !currentIndexBlock.nextEntry(currentWordEntry);
if (endOfBlock) {
- currentIndexBlock = getIndexBlock(++currentIndexBlockNum);
+ currentIndexBlock= getIndexBlock(++currentIndexBlockNum);
currentIndexBlock.nextEntry(currentWordEntry);
}
}
-
/**
* @see IndexInput#open
*/
public void open() throws IOException {
if (!opened) {
- raf = new SafeRandomAccessFile(indexFile, "r");
- String sig = raf.readUTF();
+ raf= new SafeRandomAccessFile(indexFile, "r");
+ String sig= raf.readUTF();
if (!sig.equals(IIndexConstants.SIGNATURE))
throw new IOException("Wrong format");
- int summaryBlockNum = raf.readInt();
+ int summaryBlockNum= raf.readInt();
raf.seek(summaryBlockNum * (long) IIndexConstants.BLOCK_SIZE);
- summary = new IndexSummary();
+ summary= new IndexSummary();
summary.read(raf);
init();
- opened = true;
+ opened= true;
}
}
-
/**
* @see IndexInput#query
*/
public IQueryResult[] query(String word) throws IOException {
open();
- int[] fileNums = getMatchingFileNumbers(word.toCharArray());
- int size = fileNums.length;
- IQueryResult[] files = new IQueryResult[size];
- for (int i = 0; i < size; ++i) {
- files[i] = getIndexedFile(fileNums[i]);
+ int[] fileNums= getMatchingFileNumbers(word.toCharArray());
+ int size= fileNums.length;
+ IQueryResult[] files= new IQueryResult[size];
+ for (int i= 0; i < size; ++i) {
+ files[i]= getIndexedFile(fileNums[i]);
}
return files;
}
-
- /**
- * If no prefix is provided in the pattern, then this operation will have to walk
- * all the entries of the whole index.
- */
- public IEntryResult[] queryEntriesMatching(char[] pattern /*, boolean isCaseSensitive*/)
- throws IOException {
- open();
-
- if (pattern == null || pattern.length == 0)
- return null;
- int[] blockNums = null;
- int firstStar = CharOperation.indexOf('*', pattern);
- switch (firstStar) {
- case -1 :
- WordEntry entry = getEntry(pattern);
- if (entry == null)
- return null;
- return new IEntryResult[] { new EntryResult(entry.getWord(), entry.getRefs())};
- case 0 :
- blockNums = summary.getAllBlockNums();
- break;
- default :
- char[] prefix = CharOperation.subarray(pattern, 0, firstStar);
- blockNums = summary.getBlockNumsForPrefix(prefix);
- }
- if (blockNums == null || blockNums.length == 0)
- return null;
-
- IEntryResult[] entries = new IEntryResult[5];
- int count = 0;
- for (int i = 0, max = blockNums.length; i < max; i++) {
- IndexBlock block = getIndexBlock(blockNums[i]);
- block.reset();
- boolean found = false;
- WordEntry entry = new WordEntry();
- while (block.nextEntry(entry)) {
- if (CharOperation.match(entry.getWord(), pattern, true)) {
- if (count == entries.length) {
- System.arraycopy(entries, 0, entries = new IEntryResult[count * 2], 0, count);
- }
- entries[count++] = new EntryResult(entry.getWord(), entry.getRefs());
- found = true;
- } else {
- if (found)
- break;
+/**
+ * If no prefix is provided in the pattern, then this operation will have to walk
+ * all the entries of the whole index.
+ */
+public IEntryResult[] queryEntriesMatching(char[] pattern/*, boolean isCaseSensitive*/) throws IOException {
+ open();
+
+ if (pattern == null || pattern.length == 0) return null;
+ int[] blockNums = null;
+ int firstStar = CharOperation.indexOf('*', pattern);
+ switch (firstStar){
+ case -1 :
+ WordEntry entry = getEntry(pattern);
+ if (entry == null) return null;
+ return new IEntryResult[]{ new EntryResult(entry.getWord(), entry.getRefs()) };
+ case 0 :
+ blockNums = summary.getAllBlockNums();
+ break;
+ default :
+ char[] prefix = CharOperation.subarray(pattern, 0, firstStar);
+ blockNums = summary.getBlockNumsForPrefix(prefix);
+ }
+ if (blockNums == null || blockNums.length == 0) return null;
+
+ IEntryResult[] entries = new IEntryResult[5];
+ int count = 0;
+ for (int i = 0, max = blockNums.length; i < max; i++) {
+ IndexBlock block = getIndexBlock(blockNums[i]);
+ block.reset();
+ boolean found = false;
+ WordEntry entry = new WordEntry();
+ while (block.nextEntry(entry)) {
+ if (CharOperation.match(entry.getWord(), pattern, true)) {
+ if (count == entries.length){
+ System.arraycopy(entries, 0, entries = new IEntryResult[count*2], 0, count);
}
+ entries[count++] = new EntryResult(entry.getWord(), entry.getRefs());
+ found = true;
+ } else {
+ if (found) break;
}
}
- if (count != entries.length) {
- System.arraycopy(entries, 0, entries = new IEntryResult[count], 0, count);
- }
- return entries;
}
-
- public IEntryResult[] queryEntriesPrefixedBy(char[] prefix /*, boolean isCaseSensitive*/)
- throws IOException {
- open();
-
- int blockLoc = summary.getFirstBlockLocationForPrefix(prefix);
- if (blockLoc < 0)
- return null;
-
- IEntryResult[] entries = new IEntryResult[5];
- int count = 0;
- while (blockLoc >= 0) {
- IndexBlock block = getIndexBlock(summary.getBlockNum(blockLoc));
- block.reset();
- boolean found = false;
- WordEntry entry = new WordEntry();
- while (block.nextEntry(entry)) {
- if (CharOperation.prefixEquals(prefix, entry.getWord() /*, isCaseSensitive*/
- )) {
- if (count == entries.length) {
- System.arraycopy(entries, 0, entries = new IEntryResult[count * 2], 0, count);
- }
- entries[count++] = new EntryResult(entry.getWord(), entry.getRefs());
- found = true;
- } else {
- if (found)
- break;
+ if (count != entries.length){
+ System.arraycopy(entries, 0, entries = new IEntryResult[count], 0, count);
+ }
+ return entries;
+}
+public IEntryResult[] queryEntriesPrefixedBy(char[] prefix/*, boolean isCaseSensitive*/) throws IOException {
+ open();
+
+ int blockLoc = summary.getFirstBlockLocationForPrefix(prefix);
+ if (blockLoc < 0) return null;
+
+ IEntryResult[] entries = new IEntryResult[5];
+ int count = 0;
+ while(blockLoc >= 0){
+ IndexBlock block = getIndexBlock(summary.getBlockNum(blockLoc));
+ block.reset();
+ boolean found = false;
+ WordEntry entry = new WordEntry();
+ while (block.nextEntry(entry)) {
+ if (CharOperation.prefixEquals(prefix, entry.getWord()/*, isCaseSensitive*/)) {
+ if (count == entries.length){
+ System.arraycopy(entries, 0, entries = new IEntryResult[count*2], 0, count);
}
+ entries[count++] = new EntryResult(entry.getWord(), entry.getRefs());
+ found = true;
+ } else {
+ if (found) break;
}
- /* consider next block ? */
- blockLoc = summary.getNextBlockLocationForPrefix(prefix, blockLoc);
}
- if (count == 0)
- return null;
- if (count != entries.length) {
- System.arraycopy(entries, 0, entries = new IEntryResult[count], 0, count);
- }
- return entries;
+ /* consider next block ? */
+ blockLoc = summary.getNextBlockLocationForPrefix(prefix, blockLoc);
}
-
- public IQueryResult[] queryFilesReferringToPrefix(char[] prefix)
- throws IOException {
- open();
-
- int blockLoc = summary.getFirstBlockLocationForPrefix(prefix);
- if (blockLoc < 0)
- return null;
-
- IEntryResult[] entries = new IEntryResult[5];
-
- // each filename must be returned already once
- org.eclipse.jdt.internal.compiler.util.HashtableOfInt fileMatches =
- new org.eclipse.jdt.internal.compiler.util.HashtableOfInt(20);
- int count = 0;
- while (blockLoc >= 0) {
- IndexBlock block = getIndexBlock(summary.getBlockNum(blockLoc));
- block.reset();
- boolean found = false;
- WordEntry entry = new WordEntry();
- while (block.nextEntry(entry)) {
- if (CharOperation.prefixEquals(prefix, entry.getWord() /*, isCaseSensitive*/
- )) {
- int[] refs = entry.getRefs();
- for (int i = 0, max = refs.length; i < max; i++) {
- int ref = refs[i];
- if (!fileMatches.containsKey(ref)) {
- count++;
- fileMatches.put(ref, getIndexedFile(ref));
- }
+ if (count == 0) return null;
+ if (count != entries.length){
+ System.arraycopy(entries, 0, entries = new IEntryResult[count], 0, count);
+ }
+ return entries;
+}
+public IQueryResult[] queryFilesReferringToPrefix(char[] prefix) throws IOException {
+ open();
+
+ int blockLoc = summary.getFirstBlockLocationForPrefix(prefix);
+ if (blockLoc < 0) return null;
+
+ IEntryResult[] entries = new IEntryResult[5];
+
+ // each filename must be returned already once
+ org.eclipse.jdt.internal.compiler.util.HashtableOfInt fileMatches = new org.eclipse.jdt.internal.compiler.util.HashtableOfInt(20);
+ int count = 0;
+ while(blockLoc >= 0){
+ IndexBlock block = getIndexBlock(summary.getBlockNum(blockLoc));
+ block.reset();
+ boolean found = false;
+ WordEntry entry = new WordEntry();
+ while (block.nextEntry(entry)) {
+ if (CharOperation.prefixEquals(prefix, entry.getWord()/*, isCaseSensitive*/)) {
+ int [] refs = entry.getRefs();
+ for (int i = 0, max = refs.length; i < max; i++){
+ int ref = refs[i];
+ if (!fileMatches.containsKey(ref)){
+ count++;
+ fileMatches.put(ref, getIndexedFile(ref));
}
- found = true;
- } else {
- if (found)
- break;
}
- }
- /* consider next block ? */
- blockLoc = summary.getNextBlockLocationForPrefix(prefix, blockLoc);
- }
- /* extract indexed files */
- IQueryResult[] files = new IQueryResult[count];
- Object[] indexedFiles = fileMatches.valueTable;
- for (int i = 0, index = 0, max = indexedFiles.length; i < max; i++) {
- IndexedFile indexedFile = (IndexedFile) indexedFiles[i];
- if (indexedFile != null) {
- files[index++] = indexedFile;
+ found = true;
+ } else {
+ if (found) break;
}
}
- return files;
+ /* consider next block ? */
+ blockLoc = summary.getNextBlockLocationForPrefix(prefix, blockLoc);
}
-
+ /* extract indexed files */
+ IQueryResult[] files = new IQueryResult[count];
+ Object[] indexedFiles = fileMatches.valueTable;
+ for (int i = 0, index = 0, max = indexedFiles.length; i < max; i++){
+ IndexedFile indexedFile = (IndexedFile) indexedFiles[i];
+ if (indexedFile != null){
+ files[index++] = indexedFile;
+ }
+ }
+ return files;
+}
/**
* @see IndexInput#query
*/
public IQueryResult[] queryInDocumentNames(String word) throws IOException {
open();
- Vector matches = new Vector();
+ Vector matches= new Vector();
setFirstFile();
while (hasMoreFiles()) {
- IndexedFile file = getCurrentFile();
+ IndexedFile file= getCurrentFile();
if (file.getPath().indexOf(word) != -1)
matches.addElement(file);
moveToNextFile();
}
- IQueryResult[] match = new IQueryResult[matches.size()];
+ IQueryResult[] match= new IQueryResult[matches.size()];
matches.copyInto(match);
return match;
}
-
/**
* @see IndexInput#setFirstFile
*/
protected void setFirstFile() throws IOException {
- filePosition = 1;
+ filePosition= 1;
if (getNumFiles() > 0) {
- currentFileListBlockNum = summary.getBlockNumForFileNum(1);
- currentFileListBlock = getFileListBlock(currentFileListBlockNum);
+ currentFileListBlockNum= summary.getBlockNumForFileNum(1);
+ currentFileListBlock= getFileListBlock(currentFileListBlockNum);
}
}
-
/**
* @see IndexInput#setFirstWord
*/
protected void setFirstWord() throws IOException {
- wordPosition = 1;
+ wordPosition= 1;
if (getNumWords() > 0) {
- currentIndexBlockNum = summary.getFirstWordBlockNum();
- currentIndexBlock = getIndexBlock(currentIndexBlockNum);
- currentWordEntry = new WordEntry();
+ currentIndexBlockNum= summary.getFirstWordBlockNum();
+ currentIndexBlock= getIndexBlock(currentIndexBlockNum);
+ currentWordEntry= new WordEntry();
currentIndexBlock.reset();
currentIndexBlock.nextEntry(currentWordEntry);
}
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/BlocksIndexOutput.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/BlocksIndexOutput.java
index e18e594a15..a0577e714c 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/BlocksIndexOutput.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/BlocksIndexOutput.java
@@ -17,39 +17,38 @@ import java.io.*;
public class BlocksIndexOutput extends IndexOutput {
protected RandomAccessFile indexOut;
protected int blockNum;
- protected boolean opened = false;
+ protected boolean opened= false;
protected File indexFile;
protected FileListBlock fileListBlock;
protected IndexBlock indexBlock;
- protected int numWords = 0;
+ protected int numWords= 0;
protected IndexSummary summary;
- protected int numFiles = 0;
+ protected int numFiles= 0;
protected boolean firstInBlock;
protected boolean firstIndexBlock;
protected boolean firstFileListBlock;
public BlocksIndexOutput(File indexFile) {
- this.indexFile = indexFile;
- summary = new IndexSummary();
- blockNum = 1;
- firstInBlock = true;
- firstIndexBlock = true;
- firstFileListBlock = true;
+ this.indexFile= indexFile;
+ summary= new IndexSummary();
+ blockNum= 1;
+ firstInBlock= true;
+ firstIndexBlock= true;
+ firstFileListBlock= true;
}
-
/**
* @see IndexOutput#addFile
*/
public void addFile(IndexedFile indexedFile) throws IOException {
if (firstFileListBlock) {
- firstInBlock = true;
- fileListBlock = new FileListBlock(IIndexConstants.BLOCK_SIZE);
- firstFileListBlock = false;
+ firstInBlock= true;
+ fileListBlock= new FileListBlock(IIndexConstants.BLOCK_SIZE);
+ firstFileListBlock= false;
}
if (fileListBlock.addFile(indexedFile)) {
if (firstInBlock) {
summary.addFirstFileInBlock(indexedFile, blockNum);
- firstInBlock = false;
+ firstInBlock= false;
}
numFiles++;
} else {
@@ -60,22 +59,21 @@ public class BlocksIndexOutput extends IndexOutput {
addFile(indexedFile);
}
}
-
/**
* @see IndexOutput#addWord
*/
public void addWord(WordEntry entry) throws IOException {
if (firstIndexBlock) {
- indexBlock = new GammaCompressedIndexBlock(IIndexConstants.BLOCK_SIZE);
- firstInBlock = true;
- firstIndexBlock = false;
+ indexBlock= new GammaCompressedIndexBlock(IIndexConstants.BLOCK_SIZE);
+ firstInBlock= true;
+ firstIndexBlock= false;
}
if (entry.getNumRefs() == 0)
return;
if (indexBlock.addEntry(entry)) {
if (firstInBlock) {
summary.addFirstWordInBlock(entry.getWord(), blockNum);
- firstInBlock = false;
+ firstInBlock= false;
}
numWords++;
} else {
@@ -86,24 +84,22 @@ public class BlocksIndexOutput extends IndexOutput {
addWord(entry);
}
}
-
/**
* @see IndexOutput#close
*/
public void close() throws IOException {
if (opened) {
indexOut.close();
- summary = null;
- numFiles = 0;
- opened = false;
+ summary= null;
+ numFiles= 0;
+ opened= false;
}
}
-
/**
* @see IndexOutput#flush
*/
public void flush() throws IOException {
-
+
summary.setNumFiles(numFiles);
summary.setNumWords(numWords);
indexOut.seek(blockNum * (long) IIndexConstants.BLOCK_SIZE);
@@ -112,57 +108,52 @@ public class BlocksIndexOutput extends IndexOutput {
indexOut.writeUTF(IIndexConstants.SIGNATURE);
indexOut.writeInt(blockNum);
}
-
/**
* Writes the current fileListBlock on the disk and initialises it
* (when it's full or it's the end of the index).
*/
protected void flushFiles() throws IOException {
- if (!firstFileListBlock && fileListBlock != null) {
+ if (!firstFileListBlock
+ && fileListBlock != null) {
fileListBlock.flush();
fileListBlock.write(indexOut, blockNum++);
fileListBlock.clear();
- firstInBlock = true;
+ firstInBlock= true;
}
}
-
/**
* Writes the current indexBlock on the disk and initialises it
* (when it's full or it's the end of the index).
*/
protected void flushWords() throws IOException {
- if (!firstInBlock
- && indexBlock != null) {
- // could have added a document without any indexed word, no block created yet
+ if (!firstInBlock
+ && indexBlock != null) { // could have added a document without any indexed word, no block created yet
indexBlock.flush();
indexBlock.write(indexOut, blockNum++);
indexBlock.clear();
- firstInBlock = true;
+ firstInBlock= true;
}
}
-
/**
* @see IndexOutput#getDestination
*/
public Object getDestination() {
return indexFile;
}
-
/**
* @see IndexOutput#open
*/
public void open() throws IOException {
if (!opened) {
- summary = new IndexSummary();
- numFiles = 0;
- numWords = 0;
- blockNum = 1;
- firstInBlock = true;
- firstIndexBlock = true;
- firstFileListBlock = true;
- indexOut = new SafeRandomAccessFile(this.indexFile, "rw");
- opened = true;
+ summary= new IndexSummary();
+ numFiles= 0;
+ numWords= 0;
+ blockNum= 1;
+ firstInBlock= true;
+ firstIndexBlock= true;
+ firstFileListBlock= true;
+ indexOut= new SafeRandomAccessFile(this.indexFile, "rw");
+ opened= true;
}
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/CodeByteStream.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/CodeByteStream.java
index 9eb46bca13..acd449ac02 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/CodeByteStream.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/CodeByteStream.java
@@ -8,78 +8,67 @@ import java.io.*;
public class CodeByteStream {
protected byte[] bytes;
- protected int byteOffset = 0;
- protected int bitOffset = 0;
- protected int markByteOffset = -1;
- protected int markBitOffset = -1;
+ protected int byteOffset= 0;
+ protected int bitOffset= 0;
+ protected int markByteOffset= -1;
+ protected int markBitOffset= -1;
public CodeByteStream() {
this(16);
}
-
public CodeByteStream(byte[] bytes) {
- this.bytes = bytes;
+ this.bytes= bytes;
}
-
public CodeByteStream(int initialByteLength) {
- bytes = new byte[initialByteLength];
+ bytes= new byte[initialByteLength];
}
-
public int byteLength() {
return (bitOffset + 7) / 8 + byteOffset;
}
-
public byte[] getBytes(int startOffset, int endOffset) {
- int byteLength = byteLength();
- if (startOffset > byteLength
- || endOffset > byteLength
- || startOffset > endOffset)
+ int byteLength= byteLength();
+ if (startOffset > byteLength || endOffset > byteLength || startOffset > endOffset)
throw new IndexOutOfBoundsException();
- int length = endOffset - startOffset;
- byte[] result = new byte[length];
+ int length= endOffset - startOffset;
+ byte[] result= new byte[length];
System.arraycopy(bytes, startOffset, result, 0, length);
if (endOffset == byteLength && bitOffset != 0) {
- int mask = (1 << bitOffset) - 1;
+ int mask= (1 << bitOffset) - 1;
result[length - 1] &= (mask << 8 - bitOffset);
}
return result;
}
-
protected void grow() {
- byte[] newBytes = new byte[bytes.length * 2 + 1];
+ byte[] newBytes= new byte[bytes.length * 2 + 1];
System.arraycopy(bytes, 0, newBytes, 0, bytes.length);
- bytes = newBytes;
+ bytes= newBytes;
}
-
public void mark() {
- markByteOffset = byteOffset;
- markBitOffset = bitOffset;
+ markByteOffset= byteOffset;
+ markBitOffset= bitOffset;
}
-
/**
* Reads a single bit (value == 0 or == 1).
*/
public int readBit() {
- int value = (bytes[byteOffset] >> (7 - bitOffset)) & 1;
+ int value= (bytes[byteOffset] >> (7 - bitOffset)) & 1;
if (++bitOffset >= 8) {
- bitOffset = 0;
+ bitOffset= 0;
++byteOffset;
}
return value;
}
-
/**
* Read up to 32 bits from the stream.
*/
public int readBits(int numBits) {
- int value = 0;
+ int value= 0;
while (numBits > 0) {
- int bitsToRead = 8 - bitOffset;
+ int bitsToRead= 8 - bitOffset;
if (bitsToRead > numBits)
- bitsToRead = numBits;
- int mask = (1 << bitsToRead) - 1;
- value |= ((bytes[byteOffset] >> (8 - bitOffset - bitsToRead)) & mask)
- << (numBits - bitsToRead);
+ bitsToRead= numBits;
+ int mask= (1 << bitsToRead) - 1;
+ value |= ((bytes[byteOffset] >> (8 - bitOffset - bitsToRead)) & mask) << (numBits - bitsToRead);
numBits -= bitsToRead;
bitOffset += bitsToRead;
if (bitOffset >= 8) {
@@ -89,22 +78,19 @@ public class CodeByteStream {
}
return value;
}
-
public final int readByte() {
// no need to rebuild byte value from bit sequences
- if (bitOffset == 0)
- return bytes[byteOffset++] & 255;
-
- int value = 0;
+ if (bitOffset == 0) return bytes[byteOffset++] & 255;
+
+ int value= 0;
int numBits = 8;
while (numBits > 0) {
- int bitsToRead = 8 - bitOffset;
+ int bitsToRead= 8 - bitOffset;
if (bitsToRead > numBits)
- bitsToRead = numBits;
- int mask = (1 << bitsToRead) - 1;
- value |= ((bytes[byteOffset] >> (8 - bitOffset - bitsToRead)) & mask)
- << (numBits - bitsToRead);
+ bitsToRead= numBits;
+ int mask= (1 << bitsToRead) - 1;
+ value |= ((bytes[byteOffset] >> (8 - bitOffset - bitsToRead)) & mask) << (numBits - bitsToRead);
numBits -= bitsToRead;
bitOffset += bitsToRead;
if (bitOffset >= 8) {
@@ -114,22 +100,20 @@ public class CodeByteStream {
}
return value;
}
-
/**
* Reads a value using Gamma coding.
*/
public int readGamma() {
- int numBits = readUnary();
+ int numBits= readUnary();
return readBits(numBits - 1) | (1 << (numBits - 1));
}
-
public char[] readSmallUTF() throws UTFDataFormatException {
- int utflen = readByte();
- char str[] = new char[utflen];
- int count = 0;
- int strlen = 0;
+ int utflen= readByte();
+ char str[]= new char[utflen];
+ int count= 0;
+ int strlen= 0;
while (count < utflen) {
- int c = readByte();
+ int c= readByte();
int char2, char3;
switch (c >> 4) {
case 0 :
@@ -142,7 +126,7 @@ public class CodeByteStream {
case 7 :
// 0xxxxxxx
count++;
- str[strlen++] = (char) c;
+ str[strlen++]= (char) c;
break;
case 12 :
case 13 :
@@ -150,22 +134,21 @@ public class CodeByteStream {
count += 2;
if (count > utflen)
throw new UTFDataFormatException();
- char2 = readByte();
+ char2= readByte();
if ((char2 & 0xC0) != 0x80)
throw new UTFDataFormatException();
- str[strlen++] = (char) (((c & 0x1F) << 6) | (char2 & 0x3F));
+ str[strlen++]= (char) (((c & 0x1F) << 6) | (char2 & 0x3F));
break;
case 14 :
// 1110 xxxx 10xx xxxx 10xx xxxx
count += 3;
if (count > utflen)
throw new UTFDataFormatException();
- char2 = readByte();
- char3 = readByte();
+ char2= readByte();
+ char3= readByte();
if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80))
throw new UTFDataFormatException();
- str[strlen++] =
- (char) (((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0));
+ str[strlen++]= (char) (((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0));
break;
default :
// 10xx xxxx, 1111 xxxx
@@ -173,96 +156,85 @@ public class CodeByteStream {
}
}
if (strlen < utflen)
- System.arraycopy(str, 0, str = new char[strlen], 0, strlen);
+ System.arraycopy(str, 0, str= new char[strlen], 0, strlen);
return str;
}
-
/**
* Reads a value in unary.
*/
public int readUnary() {
- int value = 1;
- int mask = 1 << (7 - bitOffset);
+ int value= 1;
+ int mask= 1 << (7 - bitOffset);
while ((bytes[byteOffset] & mask) != 0) {
++value;
if (++bitOffset >= 8) {
- bitOffset = 0;
+ bitOffset= 0;
++byteOffset;
- mask = 0x80;
+ mask= 0x80;
} else {
mask >>>= 1;
}
}
// skip the 0 bit
if (++bitOffset >= 8) {
- bitOffset = 0;
+ bitOffset= 0;
++byteOffset;
}
return value;
}
-
public void reset() {
- byteOffset = bitOffset = 0;
- markByteOffset = markBitOffset = -1;
+ byteOffset= bitOffset= 0;
+ markByteOffset= markBitOffset= -1;
}
-
public void reset(byte[] bytes) {
- this.bytes = bytes;
+ this.bytes= bytes;
reset();
}
-
public void reset(byte[] bytes, int byteOffset) {
reset(bytes);
- this.byteOffset = byteOffset;
+ this.byteOffset= byteOffset;
}
-
public boolean resetToMark() {
if (markByteOffset == -1)
return false;
- byteOffset = markByteOffset;
- bitOffset = markBitOffset;
- markByteOffset = markBitOffset = -1;
+ byteOffset= markByteOffset;
+ bitOffset= markBitOffset;
+ markByteOffset= markBitOffset= -1;
return true;
}
-
public void skipBits(int numBits) {
- int newOffset = byteOffset * 8 + bitOffset + numBits;
+ int newOffset= byteOffset * 8 + bitOffset + numBits;
if (newOffset < 0 || (newOffset + 7) / 8 >= bytes.length)
throw new IllegalArgumentException();
- byteOffset = newOffset / 8;
- bitOffset = newOffset % 8;
+ byteOffset= newOffset / 8;
+ bitOffset= newOffset % 8;
}
-
public byte[] toByteArray() {
return getBytes(0, byteLength());
}
-
/**
* Writes a single bit (value == 0 or == 1).
*/
public void writeBit(int value) {
bytes[byteOffset] |= (value & 1) << (7 - bitOffset);
if (++bitOffset >= 8) {
- bitOffset = 0;
+ bitOffset= 0;
if (++byteOffset >= bytes.length)
grow();
}
}
-
/**
* Write up to 32 bits to the stream.
* The least significant numBits bits of value are written.
*/
public void writeBits(int value, int numBits) {
while (numBits > 0) {
- int bitsToWrite = 8 - bitOffset;
+ int bitsToWrite= 8 - bitOffset;
if (bitsToWrite > numBits)
- bitsToWrite = numBits;
- int shift = 8 - bitOffset - bitsToWrite;
- int mask = ((1 << bitsToWrite) - 1) << shift;
- bytes[byteOffset] =
- (byte) ((bytes[byteOffset] & ~mask)
- | (((value >>> (numBits - bitsToWrite)) << shift) & mask));
+ bitsToWrite= numBits;
+ int shift= 8 - bitOffset - bitsToWrite;
+ int mask= ((1 << bitsToWrite) - 1) << shift;
+ bytes[byteOffset]= (byte) ((bytes[byteOffset] & ~mask) | (((value >>> (numBits - bitsToWrite)) << shift) & mask));
numBits -= bitsToWrite;
bitOffset += bitsToWrite;
if (bitOffset >= 8) {
@@ -272,11 +244,9 @@ public class CodeByteStream {
}
}
}
-
public void writeByte(int value) {
writeBits(value, 8);
}
-
/**
* Writes the given value using Gamma coding, in which positive integer x
* is represented by coding floor(log2(x) in unary followed by the value
@@ -286,8 +256,8 @@ public class CodeByteStream {
public void writeGamma(int value) {
if (value < 1)
throw new IllegalArgumentException();
- int temp = value;
- int numBits = 0;
+ int temp= value;
+ int numBits= 0;
while (temp != 0) {
temp >>>= 1;
++numBits;
@@ -295,58 +265,53 @@ public class CodeByteStream {
writeUnary(numBits);
writeBits(value, numBits - 1);
}
-
public void writeSmallUTF(char[] str) {
writeSmallUTF(str, 0, str.length);
}
-
public void writeSmallUTF(char[] str, int start, int end) {
- int utflen = 0;
- for (int i = start; i < end; i++) {
- int c = str[i];
+ int utflen= 0;
+ for (int i= start; i < end; i++) {
+ int c= str[i];
if ((c >= 0x0001) && (c <= 0x007F)) {
utflen++;
- } else
- if (c > 0x07FF) {
- utflen += 3;
- } else {
- utflen += 2;
- }
+ } else if (c > 0x07FF) {
+ utflen += 3;
+ } else {
+ utflen += 2;
+ }
}
if (utflen > 255)
throw new IllegalArgumentException();
writeByte(utflen & 0xFF);
- for (int i = start; i < end; i++) {
- int c = str[i];
+ for (int i= start; i < end; i++) {
+ int c= str[i];
if ((c >= 0x0001) && (c <= 0x007F)) {
writeByte(c);
- } else
- if (c > 0x07FF) {
- writeByte(0xE0 | ((c >> 12) & 0x0F));
- writeByte(0x80 | ((c >> 6) & 0x3F));
- writeByte(0x80 | ((c >> 0) & 0x3F));
- } else {
- writeByte(0xC0 | ((c >> 6) & 0x1F));
- writeByte(0x80 | ((c >> 0) & 0x3F));
- }
+ } else if (c > 0x07FF) {
+ writeByte(0xE0 | ((c >> 12) & 0x0F));
+ writeByte(0x80 | ((c >> 6) & 0x3F));
+ writeByte(0x80 | ((c >> 0) & 0x3F));
+ } else {
+ writeByte(0xC0 | ((c >> 6) & 0x1F));
+ writeByte(0x80 | ((c >> 0) & 0x3F));
+ }
}
}
-
/**
* Write the given value in unary. The value must be >= 1.
*/
public void writeUnary(int value) {
if (value < 1)
throw new IllegalArgumentException();
- int mask = 1 << (7 - bitOffset);
+ int mask= 1 << (7 - bitOffset);
// write N-1 1-bits
while (--value > 0) {
bytes[byteOffset] |= mask;
if (++bitOffset >= 8) {
- bitOffset = 0;
+ bitOffset= 0;
if (++byteOffset >= bytes.length)
grow();
- mask = 0x80;
+ mask= 0x80;
} else {
mask >>>= 1;
}
@@ -354,44 +319,40 @@ public class CodeByteStream {
// write a 0-bit
bytes[byteOffset] &= ~mask;
if (++bitOffset >= 8) {
- bitOffset = 0;
+ bitOffset= 0;
if (++byteOffset >= bytes.length)
grow();
}
}
-
public void writeUTF(char[] str) {
- int strlen = str.length;
- int utflen = 0;
- for (int i = 0; i < strlen; i++) {
- int c = str[i];
+ int strlen= str.length;
+ int utflen= 0;
+ for (int i= 0; i < strlen; i++) {
+ int c= str[i];
if ((c >= 0x0001) && (c <= 0x007F)) {
utflen++;
- } else
- if (c > 0x07FF) {
- utflen += 3;
- } else {
- utflen += 2;
- }
+ } else if (c > 0x07FF) {
+ utflen += 3;
+ } else {
+ utflen += 2;
+ }
}
if (utflen > 65535)
throw new IllegalArgumentException();
writeByte((utflen >>> 8) & 0xFF);
writeByte((utflen >>> 0) & 0xFF);
- for (int i = 0; i < strlen; i++) {
- int c = str[i];
+ for (int i= 0; i < strlen; i++) {
+ int c= str[i];
if ((c >= 0x0001) && (c <= 0x007F)) {
writeByte(c);
- } else
- if (c > 0x07FF) {
- writeByte(0xE0 | ((c >> 12) & 0x0F));
- writeByte(0x80 | ((c >> 6) & 0x3F));
- writeByte(0x80 | ((c >> 0) & 0x3F));
- } else {
- writeByte(0xC0 | ((c >> 6) & 0x1F));
- writeByte(0x80 | ((c >> 0) & 0x3F));
- }
+ } else if (c > 0x07FF) {
+ writeByte(0xE0 | ((c >> 12) & 0x0F));
+ writeByte(0x80 | ((c >> 6) & 0x3F));
+ writeByte(0x80 | ((c >> 0) & 0x3F));
+ } else {
+ writeByte(0xC0 | ((c >> 6) & 0x1F));
+ writeByte(0x80 | ((c >> 0) & 0x3F));
+ }
}
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/EntryResult.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/EntryResult.java
index 7112194bcb..2dff5061c7 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/EntryResult.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/EntryResult.java
@@ -9,63 +9,52 @@ import org.eclipse.jdt.internal.compiler.util.*;
public class EntryResult implements IEntryResult {
private char[] word;
- private int[] fileRefs;
-
- public EntryResult(char[] word, int[] refs) {
- this.word = word;
- this.fileRefs = refs;
+ private int[] fileRefs;
+
+public EntryResult(char[] word, int[] refs) {
+ this.word = word;
+ this.fileRefs = refs;
+}
+public boolean equals(Object anObject){
+
+ if (this == anObject) {
+ return true;
}
-
- public boolean equals(Object anObject) {
-
- if (this == anObject) {
- return true;
- }
- if ((anObject != null) && (anObject instanceof EntryResult)) {
- EntryResult anEntryResult = (EntryResult) anObject;
- if (!CharOperation.equals(this.word, anEntryResult.word))
- return false;
-
- int length;
- int[] refs, otherRefs;
- if ((length = (refs = this.fileRefs).length)
- != (otherRefs = anEntryResult.fileRefs).length)
- return false;
- for (int i = 0; i < length; i++) {
- if (refs[i] != otherRefs[i])
- return false;
- }
- return true;
+ if ((anObject != null) && (anObject instanceof EntryResult)) {
+ EntryResult anEntryResult = (EntryResult) anObject;
+ if (!CharOperation.equals(this.word, anEntryResult.word)) return false;
+
+ int length;
+ int[] refs, otherRefs;
+ if ((length = (refs = this.fileRefs).length) != (otherRefs = anEntryResult.fileRefs).length) return false;
+ for (int i = 0; i < length; i++){
+ if (refs[i] != otherRefs[i]) return false;
}
- return false;
-
- }
-
- public int[] getFileReferences() {
- return fileRefs;
- }
-
- public char[] getWord() {
- return word;
+ return true;
}
-
- public int hashCode() {
- return CharOperation.hashCode(word);
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer(word.length * 2);
- buffer.append("EntryResult: word=");
- buffer.append(word);
- buffer.append(", refs={");
- for (int i = 0; i < fileRefs.length; i++) {
- if (i > 0)
- buffer.append(',');
- buffer.append(' ');
- buffer.append(fileRefs[i]);
- }
- buffer.append(" }");
- return buffer.toString();
+ return false;
+
+}
+public int[] getFileReferences() {
+ return fileRefs;
+}
+public char[] getWord() {
+ return word;
+}
+public int hashCode(){
+ return CharOperation.hashCode(word);
+}
+public String toString(){
+ StringBuffer buffer = new StringBuffer(word.length * 2);
+ buffer.append("EntryResult: word=");
+ buffer.append(word);
+ buffer.append(", refs={");
+ for (int i = 0; i < fileRefs.length; i++){
+ if (i > 0) buffer.append(',');
+ buffer.append(' ');
+ buffer.append(fileRefs[i]);
}
-
+ buffer.append(" }");
+ return buffer.toString();
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Field.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Field.java
index db4c1606d1..85a83d0ba0 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Field.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Field.java
@@ -15,243 +15,195 @@ public class Field {
* ByteSegment constructor comment.
*/
public Field(byte[] bytes) {
- this.buffer = bytes;
- this.offset = 0;
- this.length = bytes.length;
+ this.buffer= bytes;
+ this.offset= 0;
+ this.length= bytes.length;
}
-
/**
* ByteSegment constructor comment.
*/
public Field(byte[] bytes, int length) {
- this.buffer = bytes;
- this.offset = 0;
- this.length = length;
+ this.buffer= bytes;
+ this.offset= 0;
+ this.length= length;
}
-
/**
* ByteSegment constructor comment.
*/
public Field(byte[] bytes, int offset, int length) {
- this.buffer = bytes;
- this.offset = offset;
- this.length = length;
+ this.buffer= bytes;
+ this.offset= offset;
+ this.length= length;
}
-
/**
* Creates a new field containing an empty buffer of the given length.
*/
public Field(int length) {
- this.buffer = new byte[length];
- this.offset = 0;
- this.length = length;
+ this.buffer= new byte[length];
+ this.offset= 0;
+ this.length= length;
}
-
public byte[] buffer() {
return buffer;
}
-
public Field buffer(byte[] buffer) {
- this.buffer = buffer;
+ this.buffer= buffer;
return this;
}
-
public Field clear() {
clear(buffer, offset, length);
return this;
}
-
protected static void clear(byte[] buffer, int offset, int length) {
- int n = offset;
- for (int i = 0; i < length; i++) {
- buffer[n] = 0;
+ int n= offset;
+ for (int i= 0; i < length; i++) {
+ buffer[n]= 0;
n++;
}
}
-
public Field clear(int length) {
clear(buffer, offset, length);
return this;
}
-
public Field clear(int offset, int length) {
clear(buffer, this.offset + offset, length);
return this;
}
-
- protected static int compare(
- byte[] buffer1,
- int offset1,
- int length1,
- byte[] buffer2,
- int offset2,
- int length2) {
- int n = Math.min(length1, length2);
- for (int i = 0; i < n; i++) {
- int j1 = buffer1[offset1 + i] & 255;
- int j2 = buffer2[offset2 + i] & 255;
+ protected static int compare(byte[] buffer1, int offset1, int length1, byte[] buffer2, int offset2, int length2) {
+ int n= Math.min(length1, length2);
+ for (int i= 0; i < n; i++) {
+ int j1= buffer1[offset1 + i] & 255;
+ int j2= buffer2[offset2 + i] & 255;
if (j1 > j2)
return 1;
if (j1 < j2)
return -1;
}
if (length1 > n) {
- for (int i = n; i < length1; i++)
+ for (int i= n; i < length1; i++)
if (buffer1[offset1 + i] != 0)
return 1;
return 0;
}
- for (int i = n; i < length2; i++)
+ for (int i= n; i < length2; i++)
if (buffer2[offset2 + i] != 0)
return -1;
return 0;
}
-
public static int compare(Field f1, Field f2) {
- return compare(
- f1.buffer,
- f1.offset,
- f1.length,
- f2.buffer,
- f2.offset,
- f2.length);
+ return compare(f1.buffer, f1.offset, f1.length, f2.buffer, f2.offset, f2.length);
}
-
// copy bytes from one offset to another within the field
public Field copy(int fromOffset, int toOffset, int length) {
- System.arraycopy(
- buffer,
- offset + fromOffset,
- buffer,
- offset + toOffset,
- length);
+ System.arraycopy(buffer, offset + fromOffset, buffer, offset + toOffset, length);
return this;
}
-
public Field dec(int n) {
offset -= n;
return this;
}
-
public byte[] get() {
- byte[] result = new byte[length];
+ byte[] result= new byte[length];
System.arraycopy(buffer, offset, result, 0, length);
return result;
}
-
public byte[] get(int offset, int length) {
- byte[] result = new byte[length];
+ byte[] result= new byte[length];
System.arraycopy(buffer, this.offset + offset, result, 0, length);
return result;
}
-
public Field getField(int offset, int length) {
return new Field(buffer, this.offset + offset, length);
}
-
public int getInt1() {
return buffer[this.offset];
}
-
public int getInt1(int offset) {
return buffer[this.offset + offset];
}
-
public int getInt2() {
- int i = this.offset;
- int v = buffer[i++];
- v = (v << 8) | (buffer[i++] & 255);
+ int i= this.offset;
+ int v= buffer[i++];
+ v= (v << 8) | (buffer[i++] & 255);
return v;
}
-
public int getInt2(int offset) {
- int i = this.offset + offset;
- int v = buffer[i++];
- v = (v << 8) | (buffer[i++] & 255);
+ int i= this.offset + offset;
+ int v= buffer[i++];
+ v= (v << 8) | (buffer[i++] & 255);
return v;
}
-
public int getInt3() {
- int i = this.offset;
- int v = buffer[i++];
- v = (v << 8) | (buffer[i++] & 255);
- v = (v << 8) | (buffer[i++] & 255);
+ int i= this.offset;
+ int v= buffer[i++];
+ v= (v << 8) | (buffer[i++] & 255);
+ v= (v << 8) | (buffer[i++] & 255);
return v;
}
-
public int getInt3(int offset) {
- int i = this.offset + offset;
- int v = buffer[i++];
- v = (v << 8) | (buffer[i++] & 255);
- v = (v << 8) | (buffer[i++] & 255);
+ int i= this.offset + offset;
+ int v= buffer[i++];
+ v= (v << 8) | (buffer[i++] & 255);
+ v= (v << 8) | (buffer[i++] & 255);
return v;
}
-
public int getInt4() {
- int i = this.offset;
- int v = buffer[i++];
- v = (v << 8) | (buffer[i++] & 255);
- v = (v << 8) | (buffer[i++] & 255);
- v = (v << 8) | (buffer[i++] & 255);
+ int i= this.offset;
+ int v= buffer[i++];
+ v= (v << 8) | (buffer[i++] & 255);
+ v= (v << 8) | (buffer[i++] & 255);
+ v= (v << 8) | (buffer[i++] & 255);
return v;
}
-
public int getInt4(int offset) {
- int i = this.offset + offset;
- int v = buffer[i++];
- v = (v << 8) | (buffer[i++] & 255);
- v = (v << 8) | (buffer[i++] & 255);
- v = (v << 8) | (buffer[i++] & 255);
+ int i= this.offset + offset;
+ int v= buffer[i++];
+ v= (v << 8) | (buffer[i++] & 255);
+ v= (v << 8) | (buffer[i++] & 255);
+ v= (v << 8) | (buffer[i++] & 255);
return v;
}
-
public int getUInt1() {
return buffer[this.offset] & 255;
}
-
public int getUInt1(int offset) {
return buffer[this.offset + offset] & 255;
}
-
public int getUInt2() {
- int i = this.offset;
- int v = (buffer[i++] & 255);
- v = (v << 8) | (buffer[i++] & 255);
+ int i= this.offset;
+ int v= (buffer[i++] & 255);
+ v= (v << 8) | (buffer[i++] & 255);
return v;
}
-
public int getUInt2(int offset) {
- int i = this.offset + offset;
- int v = (buffer[i++] & 255);
- v = (v << 8) | (buffer[i++] & 255);
+ int i= this.offset + offset;
+ int v= (buffer[i++] & 255);
+ v= (v << 8) | (buffer[i++] & 255);
return v;
}
-
public int getUInt3() {
- int i = this.offset;
- int v = (buffer[i++] & 255);
- v = (v << 8) | (buffer[i++] & 255);
- v = (v << 8) | (buffer[i++] & 255);
+ int i= this.offset;
+ int v= (buffer[i++] & 255);
+ v= (v << 8) | (buffer[i++] & 255);
+ v= (v << 8) | (buffer[i++] & 255);
return v;
}
-
public int getUInt3(int offset) {
- int i = this.offset + offset;
- int v = (buffer[i++] & 255);
- v = (v << 8) | (buffer[i++] & 255);
- v = (v << 8) | (buffer[i++] & 255);
+ int i= this.offset + offset;
+ int v= (buffer[i++] & 255);
+ v= (v << 8) | (buffer[i++] & 255);
+ v= (v << 8) | (buffer[i++] & 255);
return v;
}
-
public char[] getUTF(int offset) throws UTFDataFormatException {
- int pos = this.offset + offset;
- int utflen = getUInt2(pos);
+ int pos= this.offset + offset;
+ int utflen= getUInt2(pos);
pos += 2;
- char str[] = new char[utflen];
- int count = 0;
- int strlen = 0;
+ char str[]= new char[utflen];
+ int count= 0;
+ int strlen= 0;
while (count < utflen) {
- int c = buffer[pos++] & 0xFF;
+ int c= buffer[pos++] & 0xFF;
int char2, char3;
switch (c >> 4) {
case 0 :
@@ -264,7 +216,7 @@ public class Field {
case 7 :
// 0xxxxxxx
count++;
- str[strlen++] = (char) c;
+ str[strlen++]= (char) c;
break;
case 12 :
case 13 :
@@ -272,22 +224,21 @@ public class Field {
count += 2;
if (count > utflen)
throw new UTFDataFormatException();
- char2 = buffer[pos++] & 0xFF;
+ char2= buffer[pos++] & 0xFF;
if ((char2 & 0xC0) != 0x80)
throw new UTFDataFormatException();
- str[strlen++] = (char) (((c & 0x1F) << 6) | (char2 & 0x3F));
+ str[strlen++]= (char) (((c & 0x1F) << 6) | (char2 & 0x3F));
break;
case 14 :
// 1110 xxxx 10xx xxxx 10xx xxxx
count += 3;
if (count > utflen)
throw new UTFDataFormatException();
- char2 = buffer[pos++] & 0xFF;
- char3 = buffer[pos++] & 0xFF;
+ char2= buffer[pos++] & 0xFF;
+ char3= buffer[pos++] & 0xFF;
if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80))
throw new UTFDataFormatException();
- str[strlen++] =
- (char) (((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0));
+ str[strlen++]= (char) (((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0));
break;
default :
// 10xx xxxx, 1111 xxxx
@@ -295,151 +246,129 @@ public class Field {
}
}
if (strlen < utflen)
- System.arraycopy(str, 0, str = new char[strlen], 0, strlen);
+ System.arraycopy(str, 0, str= new char[strlen], 0, strlen);
return str;
}
-
public Field inc(int n) {
offset += n;
return this;
}
-
public int length() {
return length;
}
-
public Field length(int length) {
- this.length = length;
+ this.length= length;
return this;
}
-
/**
Returns the offset into the underlying byte array that this field is defined over.
*/
public int offset() {
return offset;
}
-
public Field offset(int offset) {
- this.offset = offset;
+ this.offset= offset;
return this;
}
-
public Field pointTo(int offset) {
return new Field(buffer, this.offset + offset, 0);
}
-
public Field put(byte[] b) {
return put(0, b);
}
-
public Field put(int offset, byte[] b) {
System.arraycopy(b, 0, buffer, this.offset + offset, b.length);
return this;
}
-
public Field put(int offset, Field f) {
System.arraycopy(f.buffer, f.offset, buffer, this.offset + offset, f.length);
return this;
}
-
public Field put(Field f) {
System.arraycopy(f.buffer, f.offset, buffer, offset, f.length);
return this;
}
-
public Field putInt1(int n) {
- buffer[offset] = (byte) (n);
+ buffer[offset]= (byte) (n);
return this;
}
-
public Field putInt1(int offset, int n) {
- buffer[this.offset + offset] = (byte) (n);
+ buffer[this.offset + offset]= (byte) (n);
return this;
}
-
public Field putInt2(int n) {
- int i = offset;
- buffer[i++] = (byte) (n >> 8);
- buffer[i++] = (byte) (n >> 0);
+ int i= offset;
+ buffer[i++]= (byte) (n >> 8);
+ buffer[i++]= (byte) (n >> 0);
return this;
}
-
public Field putInt2(int offset, int n) {
- int i = this.offset + offset;
- buffer[i++] = (byte) (n >> 8);
- buffer[i++] = (byte) (n >> 0);
+ int i= this.offset + offset;
+ buffer[i++]= (byte) (n >> 8);
+ buffer[i++]= (byte) (n >> 0);
return this;
}
-
public Field putInt3(int n) {
- int i = offset;
- buffer[i++] = (byte) (n >> 16);
- buffer[i++] = (byte) (n >> 8);
- buffer[i++] = (byte) (n >> 0);
+ int i= offset;
+ buffer[i++]= (byte) (n >> 16);
+ buffer[i++]= (byte) (n >> 8);
+ buffer[i++]= (byte) (n >> 0);
return this;
}
-
public Field putInt3(int offset, int n) {
- int i = this.offset + offset;
- buffer[i++] = (byte) (n >> 16);
- buffer[i++] = (byte) (n >> 8);
- buffer[i++] = (byte) (n >> 0);
+ int i= this.offset + offset;
+ buffer[i++]= (byte) (n >> 16);
+ buffer[i++]= (byte) (n >> 8);
+ buffer[i++]= (byte) (n >> 0);
return this;
}
-
public Field putInt4(int n) {
- int i = offset;
- buffer[i++] = (byte) (n >> 24);
- buffer[i++] = (byte) (n >> 16);
- buffer[i++] = (byte) (n >> 8);
- buffer[i++] = (byte) (n >> 0);
+ int i= offset;
+ buffer[i++]= (byte) (n >> 24);
+ buffer[i++]= (byte) (n >> 16);
+ buffer[i++]= (byte) (n >> 8);
+ buffer[i++]= (byte) (n >> 0);
return this;
}
-
public Field putInt4(int offset, int n) {
- int i = this.offset + offset;
- buffer[i++] = (byte) (n >> 24);
- buffer[i++] = (byte) (n >> 16);
- buffer[i++] = (byte) (n >> 8);
- buffer[i++] = (byte) (n >> 0);
+ int i= this.offset + offset;
+ buffer[i++]= (byte) (n >> 24);
+ buffer[i++]= (byte) (n >> 16);
+ buffer[i++]= (byte) (n >> 8);
+ buffer[i++]= (byte) (n >> 0);
return this;
}
-
public int putUTF(int offset, char[] str) {
- int strlen = str.length;
- int utflen = 0;
- for (int i = 0; i < strlen; i++) {
- int c = str[i];
+ int strlen= str.length;
+ int utflen= 0;
+ for (int i= 0; i < strlen; i++) {
+ int c= str[i];
if ((c >= 0x0001) && (c <= 0x007F)) {
utflen++;
- } else
- if (c > 0x07FF) {
- utflen += 3;
- } else {
- utflen += 2;
- }
+ } else if (c > 0x07FF) {
+ utflen += 3;
+ } else {
+ utflen += 2;
+ }
}
if (utflen > 65535)
throw new IllegalArgumentException();
- int pos = this.offset + offset;
- buffer[pos++] = (byte) ((utflen >>> 8) & 0xFF);
- buffer[pos++] = (byte) ((utflen >>> 0) & 0xFF);
- for (int i = 0; i < strlen; i++) {
- int c = str[i];
+ int pos= this.offset + offset;
+ buffer[pos++]= (byte) ((utflen >>> 8) & 0xFF);
+ buffer[pos++]= (byte) ((utflen >>> 0) & 0xFF);
+ for (int i= 0; i < strlen; i++) {
+ int c= str[i];
if ((c >= 0x0001) && (c <= 0x007F)) {
- buffer[pos++] = ((byte) c);
- } else
- if (c > 0x07FF) {
- buffer[pos++] = ((byte) (0xE0 | ((c >> 12) & 0x0F)));
- buffer[pos++] = ((byte) (0x80 | ((c >> 6) & 0x3F)));
- buffer[pos++] = ((byte) (0x80 | ((c >> 0) & 0x3F)));
- } else {
- buffer[pos++] = ((byte) (0xC0 | ((c >> 6) & 0x1F)));
- buffer[pos++] = ((byte) (0x80 | ((c >> 0) & 0x3F)));
- }
+ buffer[pos++]= ((byte) c);
+ } else if (c > 0x07FF) {
+ buffer[pos++]= ((byte) (0xE0 | ((c >> 12) & 0x0F)));
+ buffer[pos++]= ((byte) (0x80 | ((c >> 6) & 0x3F)));
+ buffer[pos++]= ((byte) (0x80 | ((c >> 0) & 0x3F)));
+ } else {
+ buffer[pos++]= ((byte) (0xC0 | ((c >> 6) & 0x1F)));
+ buffer[pos++]= ((byte) (0x80 | ((c >> 0) & 0x3F)));
+ }
}
return 2 + utflen;
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/FileDocument.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/FileDocument.java
index 14ba1a9e96..975a818990 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/FileDocument.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/FileDocument.java
@@ -16,47 +16,39 @@ public class FileDocument extends PropertyDocument {
public FileDocument(File file) {
super();
- this.file = file;
+ this.file= file;
}
-
/**
* @see IDocument#getByteContent
*/
public byte[] getByteContent() throws IOException {
return Util.getFileByteContent(file);
}
-
/**
* @see IDocument#getCharContent
*/
public char[] getCharContent() throws IOException {
return Util.getFileCharContent(file);
}
-
/**
* @see IDocument#getName
*/
public String getName() {
- return file.getAbsolutePath().replace(
- File.separatorChar,
- IIndexConstants.FILE_SEPARATOR);
+ return file.getAbsolutePath().replace(File.separatorChar, IIndexConstants.FILE_SEPARATOR);
}
-
/**
* @see IDocument#getStringContent
*/
public String getStringContent() throws IOException {
return new String(getCharContent());
}
-
/**
* @see IDocument#getType
*/
public String getType() {
- int lastDot = file.getPath().lastIndexOf('.');
+ int lastDot= file.getPath().lastIndexOf('.');
if (lastDot == -1)
return "";
return file.getPath().substring(lastDot + 1);
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/FileListBlock.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/FileListBlock.java
index 8a113082db..b1f8a8e231 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/FileListBlock.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/FileListBlock.java
@@ -9,103 +9,95 @@ import java.util.*;
public class FileListBlock extends Block {
- protected int offset = 0;
- protected String prevPath = null;
- protected String[] paths = null;
+ protected int offset= 0;
+ protected String prevPath= null;
+ protected String[] paths= null;
public FileListBlock(int blockSize) {
super(blockSize);
}
-
/**
* add the name of the indexedfile to the buffr of the field.
* The name is not the entire name of the indexedfile, but the
* difference between its name and the name of the previous indexedfile ...
*/
public boolean addFile(IndexedFile indexedFile) {
- int offset = this.offset;
+ int offset= this.offset;
if (isEmpty()) {
field.putInt4(offset, indexedFile.getFileNumber());
offset += 4;
}
- String path = indexedFile.getPath() + indexedFile.propertiesToString();
- int prefixLen = prevPath == null ? 0 : Util.prefixLength(prevPath, path);
- int sizeEstimate = 2 + 2 + (path.length() - prefixLen) * 3;
+ String path= indexedFile.getPath() + indexedFile.propertiesToString();
+ int prefixLen= prevPath == null ? 0 : Util.prefixLength(prevPath, path);
+ int sizeEstimate= 2 + 2 + (path.length() - prefixLen) * 3;
if (offset + sizeEstimate > blockSize - 2)
return false;
field.putInt2(offset, prefixLen);
offset += 2;
- char[] chars = new char[path.length() - prefixLen];
+ char[] chars= new char[path.length() - prefixLen];
path.getChars(prefixLen, path.length(), chars, 0);
offset += field.putUTF(offset, chars);
- this.offset = offset;
- prevPath = path;
+ this.offset= offset;
+ prevPath= path;
return true;
}
-
public void clear() {
reset();
super.clear();
}
-
public void flush() {
if (offset > 0) {
field.putInt2(offset, 0);
field.putInt2(offset + 2, 0);
- offset = 0;
+ offset= 0;
}
}
-
public IndexedFile getFile(int fileNum) throws IOException {
- IndexedFile resp = null;
+ IndexedFile resp= null;
try {
- String[] paths = getPaths();
- int i = fileNum - field.getInt4(0);
- resp = new IndexedFile(paths[i], fileNum);
+ String[] paths= getPaths();
+ int i= fileNum - field.getInt4(0);
+ resp= new IndexedFile(paths[i], fileNum);
} catch (Exception e) {
//fileNum too big
}
return resp;
}
-
/**
* Creates a vector of paths reading the buffer of the field.
*/
protected String[] getPaths() throws IOException {
if (paths == null) {
- Vector v = new Vector();
- int offset = 4;
- char[] prevPath = null;
+ Vector v= new Vector();
+ int offset= 4;
+ char[] prevPath= null;
for (;;) {
- int prefixLen = field.getUInt2(offset);
+ int prefixLen= field.getUInt2(offset);
offset += 2;
- int utfLen = field.getUInt2(offset);
- char[] path = field.getUTF(offset);
+ int utfLen= field.getUInt2(offset);
+ char[] path= field.getUTF(offset);
offset += 2 + utfLen;
if (prefixLen != 0) {
- char[] temp = new char[prefixLen + path.length];
+ char[] temp= new char[prefixLen + path.length];
System.arraycopy(prevPath, 0, temp, 0, prefixLen);
System.arraycopy(path, 0, temp, prefixLen, path.length);
- path = temp;
+ path= temp;
}
if (path.length == 0)
break;
v.addElement(new String(path));
- prevPath = path;
+ prevPath= path;
}
- paths = new String[v.size()];
+ paths= new String[v.size()];
v.copyInto(paths);
}
return paths;
}
-
public boolean isEmpty() {
return offset == 0;
}
-
public void reset() {
- offset = 0;
- prevPath = null;
+ offset= 0;
+ prevPath= null;
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/GammaCompressedIndexBlock.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/GammaCompressedIndexBlock.java
index a9aeaf0c3c..b0600ac8ae 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/GammaCompressedIndexBlock.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/GammaCompressedIndexBlock.java
@@ -10,16 +10,15 @@ import java.io.*;
* Uses prefix coding on words, and gamma coding of document numbers differences.
*/
public class GammaCompressedIndexBlock extends IndexBlock {
- CodeByteStream writeCodeStream = new CodeByteStream();
+ CodeByteStream writeCodeStream= new CodeByteStream();
CodeByteStream readCodeStream;
- char[] prevWord = null;
- int offset = 0;
+ char[] prevWord= null;
+ int offset= 0;
public GammaCompressedIndexBlock(int blockSize) {
super(blockSize);
- readCodeStream = new CodeByteStream(field.buffer());
+ readCodeStream= new CodeByteStream(field.buffer());
}
-
/**
* @see IndexBlock#addEntry
*/
@@ -29,93 +28,84 @@ public class GammaCompressedIndexBlock extends IndexBlock {
if (offset + writeCodeStream.byteLength() > this.blockSize - 2) {
return false;
}
- byte[] bytes = writeCodeStream.toByteArray();
+ byte[] bytes= writeCodeStream.toByteArray();
field.put(offset, bytes);
offset += bytes.length;
- prevWord = entry.getWord();
+ prevWord= entry.getWord();
return true;
}
-
- protected void encodeEntry(
- WordEntry entry,
- char[] prevWord,
- CodeByteStream codeStream) {
- char[] word = entry.getWord();
- int prefixLen = prevWord == null ? 0 : Util.prefixLength(prevWord, word);
+ protected void encodeEntry(WordEntry entry, char[] prevWord, CodeByteStream codeStream) {
+ char[] word= entry.getWord();
+ int prefixLen= prevWord == null ? 0 : Util.prefixLength(prevWord, word);
codeStream.writeByte(prefixLen);
codeStream.writeSmallUTF(word, prefixLen, word.length);
- int n = entry.getNumRefs();
+ int n= entry.getNumRefs();
codeStream.writeGamma(n);
- int prevRef = 0;
- for (int i = 0; i < n; ++i) {
- int ref = entry.getRef(i);
+ int prevRef= 0;
+ for (int i= 0; i < n; ++i) {
+ int ref= entry.getRef(i);
if (ref <= prevRef)
throw new IllegalArgumentException();
codeStream.writeGamma(ref - prevRef);
- prevRef = ref;
+ prevRef= ref;
}
}
-
/**
* @see IndexBlock#flush
*/
public void flush() {
if (offset > 0) {
field.putInt2(offset, 0);
- offset = 0;
- prevWord = null;
+ offset= 0;
+ prevWord= null;
}
}
-
/**
* @see IndexBlock#isEmpty
*/
public boolean isEmpty() {
return offset == 0;
}
-
/**
* @see IndexBlock#nextEntry
*/
public boolean nextEntry(WordEntry entry) {
try {
readCodeStream.reset(field.buffer(), offset);
- int prefixLength = readCodeStream.readByte();
- char[] word = readCodeStream.readSmallUTF();
+ int prefixLength= readCodeStream.readByte();
+ char[] word= readCodeStream.readSmallUTF();
if (prevWord != null && prefixLength > 0) {
- char[] temp = new char[prefixLength + word.length];
+ char[] temp= new char[prefixLength + word.length];
System.arraycopy(prevWord, 0, temp, 0, prefixLength);
System.arraycopy(word, 0, temp, prefixLength, word.length);
- word = temp;
+ word= temp;
}
if (word.length == 0) {
return false;
}
entry.reset(word);
- int n = readCodeStream.readGamma();
- int prevRef = 0;
- for (int i = 0; i < n; ++i) {
- int ref = prevRef + readCodeStream.readGamma();
+ int n= readCodeStream.readGamma();
+ int prevRef= 0;
+ for (int i= 0; i < n; ++i) {
+ int ref= prevRef + readCodeStream.readGamma();
if (ref < prevRef)
throw new InternalError();
entry.addRef(ref);
- prevRef = ref;
+ prevRef= ref;
}
- offset = readCodeStream.byteLength();
- prevWord = word;
+ offset= readCodeStream.byteLength();
+ prevWord= word;
return true;
} catch (UTFDataFormatException e) {
return false;
}
}
-
/**
* @see IndexBlock#reset
*/
public void reset() {
super.reset();
- offset = 0;
- prevWord = null;
+ offset= 0;
+ prevWord= null;
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/HashtableOfObject.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/HashtableOfObject.java
index 7b4614d918..41a966d6a9 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/HashtableOfObject.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/HashtableOfObject.java
@@ -16,86 +16,74 @@ public final class HashtableOfObject {
public HashtableOfObject() {
this(13);
}
-
public HashtableOfObject(int size) {
- this.elementSize = 0;
- this.threshold = size; // size represents the expected number of elements
- int extraRoom = (int) (size * 1.75f);
+ this.elementSize= 0;
+ this.threshold= size; // size represents the expected number of elements
+ int extraRoom= (int) (size * 1.75f);
if (this.threshold == extraRoom)
extraRoom++;
- this.keyTable = new char[extraRoom][];
- this.valueTable = new Object[extraRoom];
+ this.keyTable= new char[extraRoom][];
+ this.valueTable= new Object[extraRoom];
}
-
public boolean containsKey(char[] key) {
- int index = CharOperation.hashCode(key) % valueTable.length;
- int keyLength = key.length;
+ int index= CharOperation.hashCode(key) % valueTable.length;
+ int keyLength= key.length;
char[] currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.length == keyLength
- && CharOperation.prefixEquals(currentKey, key))
+ while ((currentKey= keyTable[index]) != null) {
+ if (currentKey.length == keyLength && CharOperation.prefixEquals(currentKey, key))
return true;
- index = (index + 1) % keyTable.length;
+ index= (index + 1) % keyTable.length;
}
return false;
}
-
public Object get(char[] key) {
- int index = CharOperation.hashCode(key) % valueTable.length;
- int keyLength = key.length;
+ int index= CharOperation.hashCode(key) % valueTable.length;
+ int keyLength= key.length;
char[] currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.length == keyLength
- && CharOperation.prefixEquals(currentKey, key))
+ while ((currentKey= keyTable[index]) != null) {
+ if (currentKey.length == keyLength && CharOperation.prefixEquals(currentKey, key))
return valueTable[index];
- index = (index + 1) % keyTable.length;
+ index= (index + 1) % keyTable.length;
}
return null;
}
-
public Object put(char[] key, Object value) {
- int index = CharOperation.hashCode(key) % valueTable.length;
- int keyLength = key.length;
+ int index= CharOperation.hashCode(key) % valueTable.length;
+ int keyLength= key.length;
char[] currentKey;
- while ((currentKey = keyTable[index]) != null) {
- if (currentKey.length == keyLength
- && CharOperation.prefixEquals(currentKey, key))
- return valueTable[index] = value;
- index = (index + 1) % keyTable.length;
+ while ((currentKey= keyTable[index]) != null) {
+ if (currentKey.length == keyLength && CharOperation.prefixEquals(currentKey, key))
+ return valueTable[index]= value;
+ index= (index + 1) % keyTable.length;
}
- keyTable[index] = key;
- valueTable[index] = value;
+ keyTable[index]= key;
+ valueTable[index]= value;
// assumes the threshold is never equal to the size of the table
if (++elementSize > threshold)
rehash();
return value;
}
-
private void rehash() {
- HashtableOfObject newHashtable = new HashtableOfObject(elementSize * 2);
- // double the number of expected elements
+ HashtableOfObject newHashtable= new HashtableOfObject(elementSize * 2); // double the number of expected elements
char[] currentKey;
- for (int i = keyTable.length; --i >= 0;)
- if ((currentKey = keyTable[i]) != null)
+ for (int i= keyTable.length; --i >= 0;)
+ if ((currentKey= keyTable[i]) != null)
newHashtable.put(currentKey, valueTable[i]);
- this.keyTable = newHashtable.keyTable;
- this.valueTable = newHashtable.valueTable;
- this.threshold = newHashtable.threshold;
+ this.keyTable= newHashtable.keyTable;
+ this.valueTable= newHashtable.valueTable;
+ this.threshold= newHashtable.threshold;
}
-
public int size() {
return elementSize;
}
-
public String toString() {
- String s = "";
+ String s= "";
Object object;
- for (int i = 0, length = valueTable.length; i < length; i++)
- if ((object = valueTable[i]) != null)
+ for (int i= 0, length= valueTable.length; i < length; i++)
+ if ((object= valueTable[i]) != null)
s += new String(keyTable[i]) + " -> " + object.toString() + "\n";
return s;
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IFileDocument.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IFileDocument.java
index 468561f91a..940dab27a6 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IFileDocument.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IFileDocument.java
@@ -7,6 +7,8 @@ package org.eclipse.jdt.internal.core.index.impl;
import java.io.*;
import org.eclipse.core.resources.*;
+import org.eclipse.core.runtime.IPath;
+
/**
* An <code>IFileDocument</code> represents an IFile.
*/
@@ -21,65 +23,59 @@ public class IFileDocument extends PropertyDocument {
* IFileDocument constructor comment.
*/
public IFileDocument(IFile file) {
- this(file, (char[]) null);
+ this(file, (char[])null);
}
-
/**
* IFileDocument constructor comment.
*/
public IFileDocument(IFile file, byte[] byteContents) {
- this.file = file;
- this.byteContents = byteContents;
+ this.file= file;
+ this.byteContents= byteContents;
}
-
/**
* IFileDocument constructor comment.
*/
public IFileDocument(IFile file, char[] charContents) {
- this.file = file;
- this.charContents = charContents;
+ this.file= file;
+ this.charContents= charContents;
}
-
/**
* @see IDocument#getByteContent
*/
public byte[] getByteContent() throws IOException {
- if (byteContents != null)
- return byteContents;
- return byteContents = Util.getFileByteContent(file.getLocation().toFile());
+ if (byteContents != null) return byteContents;
+ IPath location = file.getLocation();
+ if (location == null) return new byte[0];
+ return byteContents = Util.getFileByteContent(location.toFile());
}
-
/**
* @see IDocument#getCharContent
*/
public char[] getCharContent() throws IOException {
- if (charContents != null)
- return charContents;
- return charContents = Util.getFileCharContent(file.getLocation().toFile());
+ if (charContents != null) return charContents;
+ IPath location = file.getLocation();
+ if (location == null) return new char[0];
+ return charContents = Util.getFileCharContent(location.toFile());
}
-
/**
* @see IDocument#getName
*/
public String getName() {
return file.getFullPath().toString();
}
-
/**
* @see IDocument#getStringContent
*/
public String getStringContent() throws java.io.IOException {
return new String(getCharContent());
}
-
/**
* @see IDocument#getType
*/
public String getType() {
- String extension = file.getFileExtension();
+ String extension= file.getFileExtension();
if (extension == null)
return "";
return extension;
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IIndexConstants.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IIndexConstants.java
index 2eaf770f04..55fd6d3f57 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IIndexConstants.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IIndexConstants.java
@@ -4,13 +4,13 @@ public interface IIndexConstants {
/**
* The signature of the index file.
*/
- public static final String SIGNATURE = "INDEX FILE 0.001";
+ public static final String SIGNATURE= "INDEX FILE 0.001";
/**
* The signature of the index file.
*/
- public static final char FILE_SEPARATOR = '/';
+ public static final char FILE_SEPARATOR= '/';
/**
* The size of a block for a <code>Block</code>.
*/
- public static final int BLOCK_SIZE = 8192;
+ public static final int BLOCK_SIZE= 8192;
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/InMemoryIndex.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/InMemoryIndex.java
index 805a265249..1881845b3c 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/InMemoryIndex.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/InMemoryIndex.java
@@ -18,22 +18,22 @@ public class InMemoryIndex {
/**
* hashtable of WordEntrys = words+numbers of the files they appear in.
*/
- protected HashtableOfObject words = new HashtableOfObject(1023);
+ protected HashtableOfObject words= new HashtableOfObject(1023);
/**
* Vector of IndexedFiles = file name + a unique number.
*/
- protected ObjectVector files = new ObjectVector();
+ protected ObjectVector files= new ObjectVector();
/**
* Number of references in the index (not the number of actual words).
*/
- protected int wordCount = 0;
+ protected int wordCount= 0;
/**
* Size of the index.
*/
- protected long footprint = 0;
+ protected long footprint= 0;
protected long indexFileSize;
private char[][] sortedWords;
@@ -41,64 +41,58 @@ public class InMemoryIndex {
public InMemoryIndex() {
super();
}
-
/**
* @see IIndex#addFile
*/
public IndexedFile addDocument(IDocument document) {
- IndexedFile indexedFile = new IndexedFile(document, this.files.size + 1);
+ IndexedFile indexedFile= new IndexedFile(document, this.files.size + 1);
this.files.add(indexedFile);
this.footprint += indexedFile.footprint() + 4;
this.sortedFiles = null;
return indexedFile;
}
-
/**
* Adds the references of the word to the index (reference = number of the file the word belongs to).
*/
protected void addRef(char[] word, int[] references) {
- int size = references.length;
- int i = 0;
+ int size= references.length;
+ int i= 0;
while (i < size) {
if (references[i] != 0)
addRef(word, references[i]);
i++;
}
}
-
/**
* Looks if the word already exists in the index and add the fileNum to this word.
* If the word does not exist, it adds it in the index.
*/
protected void addRef(char[] word, int fileNum) {
- word = preprocessWord(word);
- WordEntry entry = (WordEntry) this.words.get(word);
+ word= preprocessWord(word);
+ WordEntry entry= (WordEntry) this.words.get(word);
if (entry == null) {
- entry = new WordEntry(word);
+ entry= new WordEntry(word);
entry.addRef(fileNum);
this.words.put(word, entry);
- this.sortedWords = null;
+ this.sortedWords= null;
this.footprint += entry.footprint();
} else {
this.footprint += entry.addRef(fileNum);
}
++this.wordCount;
}
-
/**
* @see IIndex#addRef
*/
public void addRef(IndexedFile indexedFile, char[] word) {
addRef(word, indexedFile.getFileNumber());
}
-
/**
* @see IIndex#addRef
*/
public void addRef(IndexedFile indexedFile, String word) {
addRef(word.toCharArray(), indexedFile.getFileNumber());
}
-
/**
* Returns the footprint of the index.
*/
@@ -106,92 +100,83 @@ public class InMemoryIndex {
public long getFootprint() {
return this.footprint;
}
-
/**
* Returns the indexed file with the given path, or null if such file does not exist.
*/
public IndexedFile getIndexedFile(String path) {
- for (int i = files.size; i > 0; i--) {
- IndexedFile file = (IndexedFile) files.elementAt(i - 1);
+ for (int i= files.size; i > 0; i--) {
+ IndexedFile file= (IndexedFile) files.elementAt(i - 1);
if (file.getPath().equals(path))
return file;
}
return null;
}
-
/**
* @see IIndex#getNumFiles
*/
public int getNumFiles() {
return files.size;
}
-
/**
* @see IIndex#getNumWords
*/
public int getNumWords() {
return words.elementSize;
}
-
/**
* Returns the words contained in the hashtable of words, sorted by alphabetical order.
*/
protected IndexedFile[] getSortedFiles() {
if (this.sortedFiles == null) {
- IndexedFile[] indexedfiles = new IndexedFile[files.size];
- for (int i = 0; i < indexedfiles.length; i++)
- indexedfiles[i] = (IndexedFile) files.elementAt(i);
+ IndexedFile[] indexedfiles= new IndexedFile[files.size];
+ for (int i= 0; i < indexedfiles.length; i++)
+ indexedfiles[i]= (IndexedFile) files.elementAt(i);
Util.sort(indexedfiles);
- this.sortedFiles = indexedfiles;
+ this.sortedFiles= indexedfiles;
}
return this.sortedFiles;
}
-
/**
* Returns the words contained in the hashtable of words, sorted by alphabetical order.
*/
protected char[][] getSortedWords() {
if (this.sortedWords == null) {
- char[][] words = new char[this.words.size()][];
- int numWords = 0;
- char[][] keys = this.words.keyTable;
- for (int i = keys.length; i-- > 0;) {
+ char[][] words= new char[this.words.size()][];
+ int numWords= 0;
+ char[][] keys= this.words.keyTable;
+ for (int i= keys.length; i-- > 0;) {
if (keys[i] != null) {
- words[numWords++] = keys[i];
+ words[numWords++]= keys[i];
}
}
Util.sort(words);
- this.sortedWords = words;
+ this.sortedWords= words;
}
return this.sortedWords;
}
-
/**
* Returns the word entry corresponding to the given word.
*/
protected WordEntry getWordEntry(char[] word) {
return (WordEntry) words.get(word);
}
-
/**
* Initialises the fields of the index
*/
public void init() {
- words = new HashtableOfObject(1023);
- files = new ObjectVector();
- wordCount = 0;
- footprint = 0;
- sortedWords = null;
- sortedFiles = null;
+ words= new HashtableOfObject(1023);
+ files= new ObjectVector();
+ wordCount= 0;
+ footprint= 0;
+ sortedWords= null;
+ sortedFiles= null;
}
-
protected char[] preprocessWord(char[] word) {
if (word.length > 255) {
- System.arraycopy(word, 0, word = new char[255], 0, 255);
+ System.arraycopy(word, 0, word= new char[255], 0, 255);
}
return word;
}
-
/**
* Saves the index in the given file.
* Structure of the saved Index :
@@ -207,10 +192,9 @@ public class InMemoryIndex {
*/
public void save(File file) throws IOException {
- BlocksIndexOutput output = new BlocksIndexOutput(file);
+ BlocksIndexOutput output= new BlocksIndexOutput(file);
save(output);
}
-
/**
* Saves the index in the given IndexOutput.
* Structure of the saved Index :
@@ -226,29 +210,28 @@ public class InMemoryIndex {
*/
protected void save(IndexOutput output) throws IOException {
- boolean ok = false;
- char[][] sortedWords = getSortedWords();
+ boolean ok= false;
+ char[][] sortedWords= getSortedWords();
try {
output.open();
- int numFiles = this.files.size;
- for (int i = 0; i < numFiles; ++i) {
- IndexedFile indexedFile = (IndexedFile) this.files.elementAt(i);
+ int numFiles= this.files.size;
+ for (int i= 0; i < numFiles; ++i) {
+ IndexedFile indexedFile= (IndexedFile) this.files.elementAt(i);
output.addFile(indexedFile);
}
- int numWords = sortedWords.length;
- for (int i = 0; i < numWords; ++i) {
- char[] word = sortedWords[i];
- WordEntry entry = (WordEntry) this.words.get(word);
+ int numWords= sortedWords.length;
+ for (int i= 0; i < numWords; ++i) {
+ char[] word= sortedWords[i];
+ WordEntry entry= (WordEntry) this.words.get(word);
output.addWord(entry);
}
output.flush();
output.close();
- ok = true;
+ ok= true;
} finally {
if (!ok)
if (output != null)
output.close();
}
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Index.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Index.java
index 45925eed4f..4148024005 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Index.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Index.java
@@ -20,7 +20,7 @@ public class Index implements IIndex {
/**
* Maximum size of the index
*/
- public static final int MAX_FOOTPRINT = 2500000;
+ public static final int MAX_FOOTPRINT= 2500000;
/**
* Index in memory, who is merged with mainIndex each times it
@@ -44,8 +44,8 @@ public class Index implements IIndex {
* Files removed form the oldIndex.
*/
protected Hashtable removedInOld;
- protected static final int CAN_MERGE = 0;
- protected static final int MERGED = 1;
+ protected static final int CAN_MERGE= 0;
+ protected static final int MERGED= 1;
private File indexFile;
/**
@@ -53,28 +53,24 @@ public class Index implements IIndex {
*/
private String toString;
public Index(File indexDirectory) throws IOException {
- this(indexDirectory, ".index");
+ this(indexDirectory,".index");
}
-
public Index(File indexDirectory, String indexName) throws IOException {
super();
- state = MERGED;
- indexFile = new File(indexDirectory, indexName);
+ state= MERGED;
+ indexFile= new File(indexDirectory, indexName);
initialize();
}
-
public Index(String indexName) throws IOException {
this(indexName, null);
}
-
public Index(String indexName, String toString) throws IOException {
super();
- state = MERGED;
- indexFile = new File(indexName);
+ state= MERGED;
+ indexFile= new File(indexName);
this.toString = toString;
initialize();
}
-
/**
* Indexes the given document, using the appropriate indexer registered in the indexerRegistry.
* If the document already exists in the index, it overrides the previous one. The changes will be
@@ -84,15 +80,14 @@ public class Index implements IIndex {
if (timeToMerge()) {
merge();
}
- IndexedFile indexedFile = addsIndex.getIndexedFile(document.getName());
+ IndexedFile indexedFile= addsIndex.getIndexedFile(document.getName());
if (indexedFile != null /*&& removedInAdds.get(document.getName()) == null*/
)
remove(indexedFile, MergeFactory.ADDS_INDEX);
- IndexerOutput output = new IndexerOutput(addsIndex);
+ IndexerOutput output= new IndexerOutput(addsIndex);
indexer.index(document, output);
- state = CAN_MERGE;
+ state= CAN_MERGE;
}
-
/**
* Returns true if the index in memory is not empty, so
* merge() can be called to fill the mainIndex with the files and words
@@ -101,109 +96,101 @@ public class Index implements IIndex {
protected boolean canMerge() {
return state == CAN_MERGE;
}
-
/**
* Initialises the indexGenerator.
*/
public void empty() throws IOException {
- if (indexFile.exists()) {
+ if (indexFile.exists()){
indexFile.delete();
//initialisation of mainIndex
- InMemoryIndex mainIndex = new InMemoryIndex();
- IndexOutput mainIndexOutput = new BlocksIndexOutput(indexFile);
+ InMemoryIndex mainIndex= new InMemoryIndex();
+ IndexOutput mainIndexOutput= new BlocksIndexOutput(indexFile);
if (!indexFile.exists())
mainIndex.save(mainIndexOutput);
}
//initialisation of addsIndex
- addsIndex = new InMemoryIndex();
- addsIndexInput = new SimpleIndexInput(addsIndex);
+ addsIndex= new InMemoryIndex();
+ addsIndexInput= new SimpleIndexInput(addsIndex);
//vectors who keep track of the removed Files
- removedInAdds = new Hashtable(11);
- removedInOld = new Hashtable(11);
+ removedInAdds= new Hashtable(11);
+ removedInOld= new Hashtable(11);
}
-
/**
* @see IIndex#getIndexFile
*/
public File getIndexFile() {
return indexFile;
}
-
/**
* @see IIndex#getNumDocuments
*/
public int getNumDocuments() throws IOException {
save();
- IndexInput input = new BlocksIndexInput(indexFile);
+ IndexInput input= new BlocksIndexInput(indexFile);
try {
input.open();
return input.getNumFiles();
} finally {
input.close();
- }
+ }
}
-
/**
* @see IIndex#getNumWords
*/
public int getNumWords() throws IOException {
save();
- IndexInput input = new BlocksIndexInput(indexFile);
+ IndexInput input= new BlocksIndexInput(indexFile);
try {
input.open();
return input.getNumWords();
} finally {
input.close();
- }
+ }
}
-
/**
* Returns the path corresponding to a given document number
*/
public String getPath(int documentNumber) throws IOException {
save();
- IndexInput input = new BlocksIndexInput(indexFile);
+ IndexInput input= new BlocksIndexInput(indexFile);
try {
input.open();
IndexedFile file = input.getIndexedFile(documentNumber);
- if (file == null)
- return null;
+ if (file == null) return null;
return file.getPath();
} finally {
input.close();
- }
+ }
}
-
/**
* see IIndex.hasChanged
*/
public boolean hasChanged() {
return canMerge();
}
-
/**
* Initialises the indexGenerator.
*/
public void initialize() throws IOException {
-
+
//initialisation of addsIndex
- addsIndex = new InMemoryIndex();
- addsIndexInput = new SimpleIndexInput(addsIndex);
+ addsIndex= new InMemoryIndex();
+ addsIndexInput= new SimpleIndexInput(addsIndex);
//vectors who keep track of the removed Files
- removedInAdds = new Hashtable(11);
- removedInOld = new Hashtable(11);
+ removedInAdds= new Hashtable(11);
+ removedInOld= new Hashtable(11);
// check whether existing index file can be read
if (indexFile.exists()) {
- IndexInput mainIndexInput = new BlocksIndexInput(indexFile);
+ IndexInput mainIndexInput= new BlocksIndexInput(indexFile);
try {
mainIndexInput.open();
- } catch (IOException e) {
- BlocksIndexInput input = (BlocksIndexInput) mainIndexInput;
+ } catch(IOException e) {
+ BlocksIndexInput input = (BlocksIndexInput)mainIndexInput;
try {
input.opened = true;
input.close();
@@ -216,12 +203,11 @@ public class Index implements IIndex {
}
mainIndexInput.close();
} else {
- InMemoryIndex mainIndex = new InMemoryIndex();
- IndexOutput mainIndexOutput = new BlocksIndexOutput(indexFile);
+ InMemoryIndex mainIndex= new InMemoryIndex();
+ IndexOutput mainIndexOutput= new BlocksIndexOutput(indexFile);
mainIndex.save(mainIndexOutput);
}
}
-
/**
* Merges the in memory index and the index on the disk, and saves the results on the disk.
*/
@@ -229,126 +215,117 @@ public class Index implements IIndex {
//System.out.println("merge");
//initialisation of tempIndex
- File tempFile = new File(indexFile.getAbsolutePath() + "TempVA");
+ File tempFile= new File(indexFile.getAbsolutePath() + "TempVA");
- boolean exists = indexFile.exists();
- IndexInput mainIndexInput = new BlocksIndexInput(indexFile);
- BlocksIndexOutput tempIndexOutput = new BlocksIndexOutput(tempFile);
+ boolean exists= indexFile.exists();
+ IndexInput mainIndexInput= new BlocksIndexInput(indexFile);
+ BlocksIndexOutput tempIndexOutput= new BlocksIndexOutput(tempFile);
//invoke a mergeFactory
new MergeFactory(
- mainIndexInput,
- addsIndexInput,
- tempIndexOutput,
- removedInOld,
- removedInAdds)
- .merge();
-
+ mainIndexInput,
+ addsIndexInput,
+ tempIndexOutput,
+ removedInOld,
+ removedInAdds).merge();
+
//rename the file created to become the main index
- File mainIndexFile = (File) mainIndexInput.getSource();
- File tempIndexFile = (File) tempIndexOutput.getDestination();
+ File mainIndexFile= (File) mainIndexInput.getSource();
+ File tempIndexFile= (File) tempIndexOutput.getDestination();
mainIndexFile.delete();
tempIndexFile.renameTo(mainIndexFile);
-
+
//initialise remove vectors and addsindex, and change the state
removedInAdds.clear();
removedInOld.clear();
addsIndex.init();
- addsIndexInput = new SimpleIndexInput(addsIndex);
- state = MERGED;
+ addsIndexInput= new SimpleIndexInput(addsIndex);
+ state= MERGED;
}
-
/**
* @see IIndex#query
*/
public IQueryResult[] query(String word) throws IOException {
save();
- IndexInput input = new BlocksIndexInput(indexFile);
+ IndexInput input= new BlocksIndexInput(indexFile);
try {
return input.query(word);
} finally {
input.close();
}
}
-
public IEntryResult[] queryEntries(char[] prefix) throws IOException {
save();
- IndexInput input = new BlocksIndexInput(indexFile);
+ IndexInput input= new BlocksIndexInput(indexFile);
try {
return input.queryEntriesPrefixedBy(prefix);
} finally {
input.close();
}
}
-
/**
* @see IIndex#queryInDocumentNames
*/
public IQueryResult[] queryInDocumentNames(String word) throws IOException {
save();
- IndexInput input = new BlocksIndexInput(indexFile);
+ IndexInput input= new BlocksIndexInput(indexFile);
try {
return input.queryInDocumentNames(word);
} finally {
input.close();
}
}
-
/**
* @see IIndex#queryPrefix
*/
public IQueryResult[] queryPrefix(char[] prefix) throws IOException {
save();
- IndexInput input = new BlocksIndexInput(indexFile);
+ IndexInput input= new BlocksIndexInput(indexFile);
try {
return input.queryFilesReferringToPrefix(prefix);
} finally {
input.close();
}
}
-
/**
* @see IIndex#remove
*/
public void remove(String documentName) throws IOException {
- IndexedFile file = addsIndex.getIndexedFile(documentName);
+ IndexedFile file= addsIndex.getIndexedFile(documentName);
if (file != null) {
//the file is in the adds Index, we remove it from this one
- Int lastRemoved = (Int) removedInAdds.get(documentName);
+ Int lastRemoved= (Int) removedInAdds.get(documentName);
if (lastRemoved != null) {
- int fileNum = file.getFileNumber();
+ int fileNum= file.getFileNumber();
if (lastRemoved.value < fileNum)
- lastRemoved.value = fileNum;
+ lastRemoved.value= fileNum;
} else
removedInAdds.put(documentName, new Int(file.getFileNumber()));
} else {
//we remove the file from the old index
removedInOld.put(documentName, new Int(1));
}
- state = CAN_MERGE;
+ state= CAN_MERGE;
}
-
/**
* Removes the given document from the given index (MergeFactory.ADDS_INDEX for the
* in memory index, MergeFactory.OLD_INDEX for the index on the disk).
*/
protected void remove(IndexedFile file, int index) throws IOException {
- String name = file.getPath();
+ String name= file.getPath();
if (index == MergeFactory.ADDS_INDEX) {
- Int lastRemoved = (Int) removedInAdds.get(name);
+ Int lastRemoved= (Int) removedInAdds.get(name);
if (lastRemoved != null) {
if (lastRemoved.value < file.getFileNumber())
- lastRemoved.value = file.getFileNumber();
+ lastRemoved.value= file.getFileNumber();
} else
removedInAdds.put(name, new Int(file.getFileNumber()));
- } else
- if (index == MergeFactory.OLD_INDEX)
- removedInOld.put(name, new Int(1));
- else
- throw new Error();
- state = CAN_MERGE;
+ } else if (index == MergeFactory.OLD_INDEX)
+ removedInOld.put(name, new Int(1));
+ else
+ throw new Error();
+ state= CAN_MERGE;
}
-
/**
* @see IIndex#save
*/
@@ -356,7 +333,6 @@ public class Index implements IIndex {
if (canMerge())
merge();
}
-
/**
* Returns true if the in memory index reaches a critical size,
* to merge it with the index on the disk.
@@ -364,11 +340,8 @@ public class Index implements IIndex {
protected boolean timeToMerge() {
return (addsIndex.getFootprint() >= MAX_FOOTPRINT);
}
-
- public String toString() {
- if (this.toString == null)
- return super.toString();
- return this.toString;
- }
-
+public String toString() {
+ if (this.toString == null) return super.toString();
+ return this.toString;
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexBlock.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexBlock.java
index 9fd1a67a55..ab2dfbe4f9 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexBlock.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexBlock.java
@@ -17,7 +17,6 @@ public abstract class IndexBlock extends Block {
public IndexBlock(int blockSize) {
super(blockSize);
}
-
/**
* Adds the given wordEntry to the indexBlock.
*/
@@ -30,13 +29,12 @@ public abstract class IndexBlock extends Block {
reset();
super.clear();
}
-
/**
* @see Block#findEntry
*/
public WordEntry findEntryMatching(char[] pattern, boolean isCaseSensitive) {
reset();
- WordEntry entry = new WordEntry();
+ WordEntry entry= new WordEntry();
while (nextEntry(entry)) {
if (CharOperation.match(pattern, entry.getWord(), isCaseSensitive)) {
return entry;
@@ -44,13 +42,12 @@ public abstract class IndexBlock extends Block {
}
return null;
}
-
/**
* @see Block#findEntry
*/
public WordEntry findEntryPrefixedBy(char[] word, boolean isCaseSensitive) {
reset();
- WordEntry entry = new WordEntry();
+ WordEntry entry= new WordEntry();
while (nextEntry(entry)) {
if (CharOperation.prefixEquals(entry.getWord(), word, isCaseSensitive)) {
return entry;
@@ -58,13 +55,12 @@ public abstract class IndexBlock extends Block {
}
return null;
}
-
/**
* @see Block#findEntry
*/
public WordEntry findExactEntry(char[] word) {
reset();
- WordEntry entry = new WordEntry();
+ WordEntry entry= new WordEntry();
while (nextEntry(entry)) {
if (CharOperation.equals(entry.getWord(), word)) {
return entry;
@@ -72,7 +68,6 @@ public abstract class IndexBlock extends Block {
}
return null;
}
-
/**
* Returns whether the block is empty or not (if it doesn't contain any wordEntry).
*/
@@ -87,5 +82,4 @@ public abstract class IndexBlock extends Block {
*/
public void reset() {
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexInput.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexInput.java
index ae4380c38f..5bb973b060 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexInput.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexInput.java
@@ -23,10 +23,9 @@ public abstract class IndexInput {
public IndexInput() {
super();
- wordPosition = 1;
- filePosition = 1;
+ wordPosition= 1;
+ filePosition= 1;
}
-
/**
* clears the cache of this indexInput, if it keeps track of the information already read.
*/
@@ -48,14 +47,12 @@ public abstract class IndexInput {
return null;
return currentWordEntry;
}
-
/**
* Returns the position of the current file the input is pointing to in the index.
*/
public int getFilePosition() {
return filePosition;
}
-
/**
* Returns the indexedFile corresponding to the given document number in the index the input
* reads in, or null if such indexedFile does not exist.
@@ -66,8 +63,7 @@ public abstract class IndexInput {
* reads in (e.g. the indexedFile with the same path in this index), or null if such
* indexedFile does not exist.
*/
- public abstract IndexedFile getIndexedFile(IDocument document)
- throws IOException;
+ public abstract IndexedFile getIndexedFile(IDocument document) throws IOException;
/**
* Returns the number of files in the index.
*/
@@ -87,14 +83,12 @@ public abstract class IndexInput {
public boolean hasMoreFiles() {
return getFilePosition() <= getNumFiles();
}
-
/**
* Returns true if the input has not reached the end of the index for the files.
*/
public boolean hasMoreWords() {
return wordPosition <= getNumWords();
}
-
/**
* Moves the pointer on the current file to the next file in the index.
*/
@@ -109,24 +103,20 @@ public abstract class IndexInput {
public abstract void open() throws IOException;
public void printStats(PrintStream out) {
out.println("Index stats :");
- int numFiles = getNumFiles();
+ int numFiles= getNumFiles();
out.println(" files: " + numFiles);
out.println(" total words indexed (unique): " + this.getNumWords());
}
-
/**
* Returns the list of the files containing the given word in the index.
*/
public abstract IQueryResult[] query(String word) throws IOException;
- public abstract IEntryResult[] queryEntriesPrefixedBy(char[] prefix /*, boolean isCaseSensitive*/)
- throws IOException;
- public abstract IQueryResult[] queryFilesReferringToPrefix(char[] prefix)
- throws IOException;
+ public abstract IEntryResult[] queryEntriesPrefixedBy(char[] prefix /*, boolean isCaseSensitive*/) throws IOException;
+public abstract IQueryResult[] queryFilesReferringToPrefix(char[] prefix) throws IOException;
/**
* Returns the list of the files whose name contain the given word in the index.
*/
- public abstract IQueryResult[] queryInDocumentNames(String word)
- throws IOException;
+ public abstract IQueryResult[] queryInDocumentNames(String word) throws IOException;
/**
* Set the pointer on the current file to the first file of the index.
*/
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexSummary.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexSummary.java
index 4a94dfb90c..fda0669e01 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexSummary.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexSummary.java
@@ -19,12 +19,12 @@ public class IndexSummary {
/**
* First file for each block.
*/
- protected Vector firstFilesInBlocks = new Vector();
+ protected Vector firstFilesInBlocks= new Vector();
/**
* First word for each block.
*/
- protected Vector firstWordsInBlocks = new Vector();
+ protected Vector firstWordsInBlocks= new Vector();
/**
* Number of files in the index.
@@ -44,37 +44,35 @@ public class IndexSummary {
static class FirstWordInBlock {
char[] word;
int blockNum;
- public String toString() {
- return "FirstWordInBlock: " + new String(word) + ", blockNum: " + blockNum;
+ public String toString(){
+ return "FirstWordInBlock: " + new String(word) + ", blockNum: " +blockNum;
}
}
protected int firstWordBlockNum;
- protected boolean firstWordAdded = true;
+ protected boolean firstWordAdded= true;
/**
* Adds the given file as the first file for the given Block number.
*/
public void addFirstFileInBlock(IndexedFile indexedFile, int blockNum) {
- FirstFileInBlock entry = new FirstFileInBlock();
- entry.indexedFile = indexedFile;
- entry.blockNum = blockNum;
+ FirstFileInBlock entry= new FirstFileInBlock();
+ entry.indexedFile= indexedFile;
+ entry.blockNum= blockNum;
firstFilesInBlocks.addElement(entry);
}
-
/**
* Adds the given word as the first word for the given Block number.
*/
public void addFirstWordInBlock(char[] word, int blockNum) {
if (firstWordAdded) {
- firstWordBlockNum = blockNum;
- firstWordAdded = false;
+ firstWordBlockNum= blockNum;
+ firstWordAdded= false;
}
- FirstWordInBlock entry = new FirstWordInBlock();
- entry.word = word;
- entry.blockNum = blockNum;
+ FirstWordInBlock entry= new FirstWordInBlock();
+ entry.word= word;
+ entry.blockNum= blockNum;
firstWordsInBlocks.addElement(entry);
}
-
/**
* Returns the numbers of all the blocks
*/
@@ -82,253 +80,233 @@ public class IndexSummary {
int max = firstWordsInBlocks.size();
int[] blockNums = new int[max];
- for (int i = 0; i < max; i++) {
- blockNums[i] = ((FirstWordInBlock) firstWordsInBlocks.elementAt(i)).blockNum;
+ for (int i = 0; i < max; i++){
+ blockNums[i] = ((FirstWordInBlock)firstWordsInBlocks.elementAt(i)).blockNum;
}
return blockNums;
}
-
- public int getBlockNum(int blockLocation) {
- return (
- (FirstWordInBlock) firstWordsInBlocks.elementAt(blockLocation)).blockNum;
- }
-
+public int getBlockNum(int blockLocation) {
+ return ((FirstWordInBlock) firstWordsInBlocks.elementAt(blockLocation)).blockNum;
+}
/**
* Returns the number of the Block containing the file with the given number.
*/
public int getBlockNumForFileNum(int fileNum) {
- int min = 0;
- int max = firstFilesInBlocks.size() - 1;
+ int min= 0;
+ int max= firstFilesInBlocks.size() - 1;
while (min <= max) {
- int mid = (min + max) / 2;
- FirstFileInBlock entry = (FirstFileInBlock) firstFilesInBlocks.elementAt(mid);
- int compare = fileNum - entry.indexedFile.getFileNumber();
+ int mid= (min + max) / 2;
+ FirstFileInBlock entry= (FirstFileInBlock) firstFilesInBlocks.elementAt(mid);
+ int compare= fileNum - entry.indexedFile.getFileNumber();
if (compare == 0)
return entry.blockNum;
if (compare < 0)
- max = mid - 1;
+ max= mid - 1;
else
- min = mid + 1;
+ min= mid + 1;
}
if (max < 0)
return -1;
- FirstFileInBlock entry = (FirstFileInBlock) firstFilesInBlocks.elementAt(max);
+ FirstFileInBlock entry= (FirstFileInBlock) firstFilesInBlocks.elementAt(max);
return entry.blockNum;
}
-
/**
* Returns the number of the Block containing the given word.
*/
public int getBlockNumForWord(char[] word) {
- int min = 0;
- int max = firstWordsInBlocks.size() - 1;
+ int min= 0;
+ int max= firstWordsInBlocks.size() - 1;
while (min <= max) {
- int mid = (min + max) / 2;
- FirstWordInBlock entry = (FirstWordInBlock) firstWordsInBlocks.elementAt(mid);
- int compare = Util.compare(word, entry.word);
+ int mid= (min + max) / 2;
+ FirstWordInBlock entry= (FirstWordInBlock) firstWordsInBlocks.elementAt(mid);
+ int compare= Util.compare(word, entry.word);
if (compare == 0)
return entry.blockNum;
if (compare < 0)
- max = mid - 1;
+ max= mid - 1;
else
- min = mid + 1;
+ min= mid + 1;
}
if (max < 0)
return -1;
- FirstWordInBlock entry = (FirstWordInBlock) firstWordsInBlocks.elementAt(max);
+ FirstWordInBlock entry= (FirstWordInBlock) firstWordsInBlocks.elementAt(max);
return entry.blockNum;
}
-
public int[] getBlockNumsForPrefix(char[] prefix) {
- int min = 0;
- int size = firstWordsInBlocks.size();
- int max = size - 1;
- int match = -1;
+ int min= 0;
+ int size= firstWordsInBlocks.size();
+ int max= size - 1;
+ int match= -1;
while (min <= max && match < 0) {
- int mid = (min + max) / 2;
- FirstWordInBlock entry = (FirstWordInBlock) firstWordsInBlocks.elementAt(mid);
- int compare = Util.startsWith(entry.word, prefix);
+ int mid= (min + max) / 2;
+ FirstWordInBlock entry= (FirstWordInBlock) firstWordsInBlocks.elementAt(mid);
+ int compare= Util.startsWith(entry.word, prefix);
if (compare == 0) {
- match = mid;
+ match= mid;
break;
- }
+ }
if (compare >= 0)
- max = mid - 1;
+ max= mid - 1;
else
- min = mid + 1;
+ min= mid + 1;
}
if (max < 0)
return new int[0];
-
+
if (match < 0)
- match = max;
-
- int firstBlock = match - 1;
+ match= max;
+
+ int firstBlock= match - 1;
// Look if previous blocks are affected
for (; firstBlock >= 0; firstBlock--) {
- FirstWordInBlock entry =
- (FirstWordInBlock) firstWordsInBlocks.elementAt(firstBlock);
+ FirstWordInBlock entry= (FirstWordInBlock) firstWordsInBlocks.elementAt(firstBlock);
if (!CharOperation.startsWith(entry.word, prefix))
break;
}
if (firstBlock < 0)
- firstBlock = 0;
-
+ firstBlock= 0;
+
// Look if next blocks are affected
- int firstNotIncludedBlock = match + 1;
+ int firstNotIncludedBlock= match + 1;
for (; firstNotIncludedBlock < size; firstNotIncludedBlock++) {
- FirstWordInBlock entry =
- (FirstWordInBlock) firstWordsInBlocks.elementAt(firstNotIncludedBlock);
+ FirstWordInBlock entry= (FirstWordInBlock) firstWordsInBlocks.elementAt(firstNotIncludedBlock);
if (!CharOperation.startsWith(entry.word, prefix))
break;
}
-
- int numberOfBlocks = firstNotIncludedBlock - firstBlock;
- int[] result = new int[numberOfBlocks];
- int pos = firstBlock;
- for (int i = 0; i < numberOfBlocks; i++, pos++) {
- FirstWordInBlock entry = (FirstWordInBlock) firstWordsInBlocks.elementAt(pos);
- result[i] = entry.blockNum;
+
+ int numberOfBlocks= firstNotIncludedBlock - firstBlock;
+ int[] result= new int[numberOfBlocks];
+ int pos= firstBlock;
+ for (int i= 0; i < numberOfBlocks; i++, pos++) {
+ FirstWordInBlock entry= (FirstWordInBlock) firstWordsInBlocks.elementAt(pos);
+ result[i]= entry.blockNum;
}
return result;
}
-
- public int getFirstBlockLocationForPrefix(char[] prefix) {
- int min = 0;
- int size = firstWordsInBlocks.size();
- int max = size - 1;
- int match = -1;
- while (min <= max) {
- int mid = (min + max) / 2;
- FirstWordInBlock entry = (FirstWordInBlock) firstWordsInBlocks.elementAt(mid);
- int compare = Util.startsWith(entry.word, prefix);
- if (compare == 0) {
- match = mid;
- break;
- }
- if (compare >= 0) {
- max = mid - 1;
- } else {
- match = mid; // not perfect match, but could be inside
- min = mid + 1;
- }
+public int getFirstBlockLocationForPrefix(char[] prefix) {
+ int min = 0;
+ int size = firstWordsInBlocks.size();
+ int max = size - 1;
+ int match = -1;
+ while (min <= max) {
+ int mid = (min + max) / 2;
+ FirstWordInBlock entry = (FirstWordInBlock) firstWordsInBlocks.elementAt(mid);
+ int compare = Util.startsWith(entry.word, prefix);
+ if (compare == 0) {
+ match = mid;
+ break;
}
- if (max < 0)
- return -1;
-
- // no match at all, might be some matching entries inside max block
- if (match < 0) {
- match = max;
+ if (compare >= 0) {
+ max = mid - 1;
} else {
- // look for possible matches inside previous blocks
- while (match > 0) {
- FirstWordInBlock entry = (FirstWordInBlock) firstWordsInBlocks.elementAt(match);
- if (!CharOperation.startsWith(entry.word, prefix)) {
- break;
- }
- match--;
+ match = mid; // not perfect match, but could be inside
+ min = mid + 1;
+ }
+ }
+ if (max < 0) return -1;
+
+ // no match at all, might be some matching entries inside max block
+ if (match < 0){
+ match = max;
+ } else {
+ // look for possible matches inside previous blocks
+ while (match > 0){
+ FirstWordInBlock entry = (FirstWordInBlock) firstWordsInBlocks.elementAt(match);
+ if (!CharOperation.startsWith(entry.word, prefix)){
+ break;
}
+ match--;
}
- return match;
}
-
+ return match;
+}
/**
* Returns the number of the first IndexBlock (containing words).
*/
public int getFirstWordBlockNum() {
return firstWordBlockNum;
}
-
- /**
- * Blocks are contiguous, so the next one is a potential candidate if its first word starts with
- * the given prefix
- */
- public int getNextBlockLocationForPrefix(char[] prefix, int blockLoc) {
- if (++blockLoc < firstWordsInBlocks.size()) {
- FirstWordInBlock entry =
- (FirstWordInBlock) firstWordsInBlocks.elementAt(blockLoc);
- if (CharOperation.startsWith(entry.word, prefix))
- return blockLoc;
- }
- return -1;
+/**
+ * Blocks are contiguous, so the next one is a potential candidate if its first word starts with
+ * the given prefix
+ */
+public int getNextBlockLocationForPrefix(char[] prefix, int blockLoc) {
+ if (++blockLoc < firstWordsInBlocks.size()){
+ FirstWordInBlock entry= (FirstWordInBlock) firstWordsInBlocks.elementAt(blockLoc);
+ if (CharOperation.startsWith(entry.word, prefix)) return blockLoc;
}
-
+ return -1;
+}
/**
* Returns the number of files contained in the index.
*/
public int getNumFiles() {
return numFiles;
}
-
/**
* Returns the number of words contained in the index.
*/
public int getNumWords() {
return numWords;
}
-
/**
* Loads the summary in memory.
*/
public void read(RandomAccessFile raf) throws IOException {
- numFiles = raf.readInt();
- numWords = raf.readInt();
- firstWordBlockNum = raf.readInt();
- int numFirstFiles = raf.readInt();
- for (int i = 0; i < numFirstFiles; ++i) {
- FirstFileInBlock entry = new FirstFileInBlock();
- String path = raf.readUTF();
- int fileNum = raf.readInt();
- entry.indexedFile = new IndexedFile(path, fileNum);
- entry.blockNum = raf.readInt();
+ numFiles= raf.readInt();
+ numWords= raf.readInt();
+ firstWordBlockNum= raf.readInt();
+ int numFirstFiles= raf.readInt();
+ for (int i= 0; i < numFirstFiles; ++i) {
+ FirstFileInBlock entry= new FirstFileInBlock();
+ String path= raf.readUTF();
+ int fileNum= raf.readInt();
+ entry.indexedFile= new IndexedFile(path, fileNum);
+ entry.blockNum= raf.readInt();
firstFilesInBlocks.addElement(entry);
}
- int numFirstWords = raf.readInt();
- for (int i = 0; i < numFirstWords; ++i) {
- FirstWordInBlock entry = new FirstWordInBlock();
- entry.word = raf.readUTF().toCharArray();
- entry.blockNum = raf.readInt();
+ int numFirstWords= raf.readInt();
+ for (int i= 0; i < numFirstWords; ++i) {
+ FirstWordInBlock entry= new FirstWordInBlock();
+ entry.word= raf.readUTF().toCharArray();
+ entry.blockNum= raf.readInt();
firstWordsInBlocks.addElement(entry);
}
}
-
/**
* Sets the number of files of the index.
*/
public void setNumFiles(int numFiles) {
- this.numFiles = numFiles;
+ this.numFiles= numFiles;
}
-
/**
* Sets the number of words of the index.
*/
public void setNumWords(int numWords) {
- this.numWords = numWords;
+ this.numWords= numWords;
}
-
/**
* Saves the summary on the disk.
*/
public void write(RandomAccessFile raf) throws IOException {
- long fp = raf.getFilePointer();
+ long fp= raf.getFilePointer();
raf.writeInt(numFiles);
raf.writeInt(numWords);
raf.writeInt(firstWordBlockNum);
raf.writeInt(firstFilesInBlocks.size());
- for (int i = 0, size = firstFilesInBlocks.size(); i < size; ++i) {
- FirstFileInBlock entry = (FirstFileInBlock) firstFilesInBlocks.elementAt(i);
+ for (int i= 0, size= firstFilesInBlocks.size(); i < size; ++i) {
+ FirstFileInBlock entry= (FirstFileInBlock) firstFilesInBlocks.elementAt(i);
raf.writeUTF(entry.indexedFile.getPath());
raf.writeInt(entry.indexedFile.getFileNumber());
raf.writeInt(entry.blockNum);
}
raf.writeInt(firstWordsInBlocks.size());
- for (int i = 0, size = firstWordsInBlocks.size(); i < size; ++i) {
- FirstWordInBlock entry = (FirstWordInBlock) firstWordsInBlocks.elementAt(i);
+ for (int i= 0, size= firstWordsInBlocks.size(); i < size; ++i) {
+ FirstWordInBlock entry= (FirstWordInBlock) firstWordsInBlocks.elementAt(i);
raf.writeUTF(new String(entry.word));
raf.writeInt(entry.blockNum);
}
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexedFile.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexedFile.java
index 27f6ab3f17..0f5256c5fd 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexedFile.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexedFile.java
@@ -20,55 +20,51 @@ import org.eclipse.jdt.internal.core.index.*;
public class IndexedFile implements IQueryResult {
protected String path;
protected int fileNumber;
- protected static final String INFO_BEGIN = "(";
- protected static final String INFO_END = ")";
- protected static final String INFO_SEPARATOR = ",";
- protected static final String INFO_VALUE_SEPARATOR = ":";
- protected static final int MAX_PROPERTIES_SIZE = 2 * 1024;
+ protected static final String INFO_BEGIN= "(";
+ protected static final String INFO_END= ")";
+ protected static final String INFO_SEPARATOR= ",";
+ protected static final String INFO_VALUE_SEPARATOR= ":";
+ protected static final int MAX_PROPERTIES_SIZE= 2 * 1024;
protected Hashtable properties;
- protected int propertiesSize = 2 * (INFO_BEGIN.length() + INFO_END.length());
+ protected int propertiesSize= 2 * (INFO_BEGIN.length() + INFO_END.length());
public IndexedFile(String pathOrInfo, int fileNum) {
if (fileNum < 1)
throw new IllegalArgumentException();
- this.fileNumber = fileNum;
- properties = new Hashtable();
- int dp = pathOrInfo.indexOf(INFO_BEGIN);
+ this.fileNumber= fileNum;
+ properties= new Hashtable();
+ int dp= pathOrInfo.indexOf(INFO_BEGIN);
if (dp == -1)
- path = pathOrInfo;
+ path= pathOrInfo;
else {
- String fileInfo = pathOrInfo;
- path = fileInfo.substring(0, dp);
- String props = fileInfo.substring(dp, fileInfo.length());
- StringTokenizer t =
- new StringTokenizer(props.substring(1, props.length() - 1), INFO_SEPARATOR);
+ String fileInfo= pathOrInfo;
+ path= fileInfo.substring(0, dp);
+ String props= fileInfo.substring(dp, fileInfo.length());
+ StringTokenizer t= new StringTokenizer(props.substring(1, props.length() - 1), INFO_SEPARATOR);
while (t.hasMoreTokens()) {
- String g = t.nextToken();
+ String g= t.nextToken();
try {
- int dpt = g.indexOf(INFO_VALUE_SEPARATOR);
+ int dpt= g.indexOf(INFO_VALUE_SEPARATOR);
setProperty(g.substring(0, dpt), g.substring(dpt + 1, g.length()));
} catch (Exception e) {
}
}
}
}
-
public IndexedFile(IDocument document, int fileNum) {
if (fileNum < 1)
throw new IllegalArgumentException();
- this.path = document.getName();
- this.fileNumber = fileNum;
- properties = new Hashtable();
+ this.path= document.getName();
+ this.fileNumber= fileNum;
+ properties= new Hashtable();
computeProperties(document);
}
-
protected void computeProperties(IDocument document) {
- for (Enumeration e = document.getPropertyNames(); e.hasMoreElements();) {
- String property = (String) e.nextElement();
+ for (Enumeration e= document.getPropertyNames(); e.hasMoreElements();) {
+ String property= (String) e.nextElement();
setProperty(property, document.getProperty(property));
}
}
-
/**
* Returns the path represented by pathString converted back to a path relative to the local file system.
*
@@ -95,17 +91,15 @@ public class IndexedFile implements IQueryResult {
int index = pathString.indexOf(JarFileEntryDocument.JAR_FILE_ENTRY_SEPARATOR);
if (index == -1)
return pathString;
-
+
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
Path jarPath = new Path(pathString.substring(0, index));
if (!jarPath.isAbsolute()) {
- return jarPath.makeAbsolute().toString()
- + pathString.substring(index, pathString.length());
+ return jarPath.makeAbsolute().toString() + pathString.substring(index, pathString.length());
} else {
return jarPath.toOSString() + pathString.substring(index, pathString.length());
}
}
-
/**
* Returns the size of the indexedFile.
*/
@@ -113,40 +107,35 @@ public class IndexedFile implements IQueryResult {
//object+ 2 slots + size of the string
return 8 + (2 * 4) + (28 + path.length() * 2);
}
-
/**
* Returns the file number.
*/
public int getFileNumber() {
return fileNumber;
}
-
/**
* Returns the path.
*/
public String getPath() {
return path;
}
-
public String getProperty(String propertyName) {
return (String) properties.get(propertyName);
;
}
-
/**
* getPropertyNames method comment.
*/
public Enumeration getPropertyNames() {
return properties.keys();
}
-
public String propertiesToString() {
if (properties.isEmpty())
return "";
- StringBuffer prop = new StringBuffer(INFO_BEGIN);
- for (Enumeration e = getPropertyNames(); e.hasMoreElements();) {
- String property = (String) e.nextElement();
- String value = getProperty(property);
+ StringBuffer prop= new StringBuffer(INFO_BEGIN);
+ for (Enumeration e= getPropertyNames(); e.hasMoreElements();) {
+ String property= (String) e.nextElement();
+ String value= getProperty(property);
prop.append(property);
prop.append(INFO_VALUE_SEPARATOR);
prop.append(value);
@@ -156,30 +145,21 @@ public class IndexedFile implements IQueryResult {
prop.append(INFO_END);
return prop.toString();
}
-
/**
* Sets the file number.
*/
public void setFileNumber(int fileNumber) {
- this.fileNumber = fileNumber;
+ this.fileNumber= fileNumber;
}
-
/**
* getPropertyNames method comment.
*/
public void setProperty(String propertyName, String value) {
- propertiesSize
- += (INFO_SEPARATOR.length()
- + propertyName.length()
- + INFO_VALUE_SEPARATOR.length()
- + value.length())
- * 2;
+ propertiesSize += (INFO_SEPARATOR.length() + propertyName.length() + INFO_VALUE_SEPARATOR.length() + value.length()) * 2;
if (propertiesSize < MAX_PROPERTIES_SIZE)
properties.put(propertyName, value);
}
-
public String toString() {
return "IndexedFile(" + fileNumber + ": " + path + ")";
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexerOutput.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexerOutput.java
index c8d9644a4e..8165b60429 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexerOutput.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/IndexerOutput.java
@@ -21,21 +21,19 @@ public class IndexerOutput implements IIndexerOutput {
* IndexerOutput constructor comment.
*/
public IndexerOutput(InMemoryIndex index) {
- this.index = index;
+ this.index= index;
}
-
/**
* Adds the given document to the inMemoryIndex.
*/
public void addDocument(IDocument document) {
if (indexedFile == null) {
- indexedFile = index.addDocument(document);
+ indexedFile= index.addDocument(document);
} else {
throw new IllegalStateException();
}
}
-
/**
* Adds a reference to the given word to the inMemoryIndex.
*/
@@ -45,12 +43,10 @@ public class IndexerOutput implements IIndexerOutput {
}
index.addRef(indexedFile, word);
}
-
/**
* Adds a reference to the given word to the inMemoryIndex.
*/
public void addRef(String word) {
addRef(word.toCharArray());
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Int.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Int.java
index 3b80e785b5..0a09b953c9 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Int.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Int.java
@@ -6,7 +6,6 @@ public class Int {
* Int constructor comment.
*/
public Int(int i) {
- value = i;
+ value= i;
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/JarFileDocument.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/JarFileDocument.java
index 638d427f5c..f689a1ff5f 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/JarFileDocument.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/JarFileDocument.java
@@ -14,56 +14,49 @@ import java.io.*;
public class JarFileDocument extends PropertyDocument {
protected IFile file;
- /**
- * JarFileDocument constructor comment.
- */
- public JarFileDocument(IFile file) {
- this.file = file;
- }
-
- /**
- * This API always return null for a JarFileDocument
- * @see IDocument#getByteContent
- */
- public byte[] getByteContent() throws IOException {
- return null;
- }
-
- /**
- * This API always return null for a JarFileDocument
- * @see IDocument#getByteContent
- */
- public char[] getCharContent() throws IOException {
- return null;
- }
-
- public File getFile() {
- return file.getLocation().toFile();
- }
-
+/**
+ * JarFileDocument constructor comment.
+ */
+public JarFileDocument(IFile file) {
+ this.file = file;
+}
+/**
+ * This API always return null for a JarFileDocument
+ * @see IDocument#getByteContent
+ */
+public byte[] getByteContent() throws IOException {
+ return null;
+}
+/**
+ * This API always return null for a JarFileDocument
+ * @see IDocument#getByteContent
+ */
+public char[] getCharContent() throws IOException {
+ return null;
+}
+public File getFile() {
+ return file.getLocation().toFile();
+}
/**
* @see IDocument#getName
*/
public String getName() {
return file.getFullPath().toString();
}
-
- /**
- * This API always return null for a JarFileDocument
- * @see IDocument#getByteContent
- */
- public String getStringContent() throws java.io.IOException {
- return null;
- }
-
+/**
+ * This API always return null for a JarFileDocument
+ * @see IDocument#getByteContent
+ */
+public String getStringContent() throws java.io.IOException {
+ return null;
+}
/**
* @see IDocument#getType
*/
public String getType() {
- String extension = file.getFileExtension();
+ String extension= file.getFileExtension();
if (extension == null)
return "";
return extension;
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/JarFileEntryDocument.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/JarFileEntryDocument.java
index 4edbe7fb6c..d8dd5fe37a 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/JarFileEntryDocument.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/JarFileEntryDocument.java
@@ -10,6 +10,7 @@ import org.eclipse.core.runtime.Path;
import java.io.*;
import java.util.zip.*;
+
/**
* An <code>JarFileEntryDocument</code> represents an jar file.
*/
@@ -19,58 +20,48 @@ public class JarFileEntryDocument extends PropertyDocument {
protected byte[] byteContents;
protected Path zipFilePath;
public static final String JAR_FILE_ENTRY_SEPARATOR = "|";
- /**
- * JarFileEntryDocument constructor comment.
- */
- public JarFileEntryDocument(
- ZipEntry entry,
- byte[] contents,
- Path zipFilePath) {
- this.zipEntry = entry;
- this.byteContents = contents;
- this.zipFilePath = zipFilePath;
- }
-
- /**
- * This API always return null for a JarFileDocument
- * @see IDocument#getByteContent
- */
- public byte[] getByteContent() throws IOException {
- return this.byteContents;
- }
-
- /**
- * This API always return null for a JarFileDocument
- * @see IDocument#getByteContent
- */
- public char[] getCharContent() throws IOException {
- return null;
- }
-
+/**
+ * JarFileEntryDocument constructor comment.
+ */
+public JarFileEntryDocument(ZipEntry entry, byte[] contents, Path zipFilePath) {
+ this.zipEntry = entry;
+ this.byteContents = contents;
+ this.zipFilePath = zipFilePath;
+}
+/**
+ * This API always return null for a JarFileDocument
+ * @see IDocument#getByteContent
+ */
+public byte[] getByteContent() throws IOException {
+ return this.byteContents;
+}
+/**
+ * This API always return null for a JarFileDocument
+ * @see IDocument#getByteContent
+ */
+public char[] getCharContent() throws IOException {
+ return null;
+}
/**
* @see IDocument#getName
*/
public String getName() {
return zipFilePath + JAR_FILE_ENTRY_SEPARATOR + zipEntry.getName();
}
-
- /**
- * This API always return null for a JarFileDocument
- * @see IDocument#getByteContent
- */
- public String getStringContent() throws java.io.IOException {
- return null;
- }
-
+/**
+ * This API always return null for a JarFileDocument
+ * @see IDocument#getByteContent
+ */
+public String getStringContent() throws java.io.IOException {
+ return null;
+}
/**
* @see IDocument#getType
*/
public String getType() {
return "class";
}
-
- public void setBytes(byte[] byteContents) {
- this.byteContents = byteContents;
- }
-
+public void setBytes(byte[] byteContents) {
+ this.byteContents = byteContents;
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/LRUCache.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/LRUCache.java
index c080db7018..cdf8025586 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/LRUCache.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/LRUCache.java
@@ -76,9 +76,9 @@ public class LRUCache implements Cloneable {
* for key, value, and space.
*/
public LRUCacheEntry(Object key, Object value, int space) {
- _fKey = key;
- _fValue = value;
- _fSpace = space;
+ _fKey= key;
+ _fValue= value;
+ _fSpace= space;
}
/**
@@ -123,7 +123,7 @@ public class LRUCache implements Cloneable {
/**
* Default amount of space in the cache
*/
- protected static final int DEFAULT_SPACELIMIT = 100;
+ protected static final int DEFAULT_SPACELIMIT= 100;
/**
* Creates a new cache. Size of cache is defined by
* <code>DEFAULT_SPACELIMIT</code>.
@@ -132,19 +132,17 @@ public class LRUCache implements Cloneable {
this(DEFAULT_SPACELIMIT);
}
-
/**
* Creates a new cache.
* @param size Size of Cache
*/
public LRUCache(int size) {
- fTimestampCounter = fCurrentSpace = 0;
- fEntryQueue = fEntryQueueTail = null;
- fEntryTable = new Hashtable(size);
- fSpaceLimit = size;
+ fTimestampCounter= fCurrentSpace= 0;
+ fEntryQueue= fEntryQueueTail= null;
+ fEntryTable= new Hashtable(size);
+ fSpaceLimit= size;
}
-
/**
* Returns a new cache containing the same contents.
*
@@ -152,33 +150,31 @@ public class LRUCache implements Cloneable {
*/
public Object clone() {
- LRUCache newCache = newInstance(fSpaceLimit);
+ LRUCache newCache= newInstance(fSpaceLimit);
LRUCacheEntry qEntry;
/* Preserve order of entries by copying from oldest to newest */
- qEntry = this.fEntryQueueTail;
+ qEntry= this.fEntryQueueTail;
while (qEntry != null) {
newCache.privateAdd(qEntry._fKey, qEntry._fValue, qEntry._fSpace);
- qEntry = qEntry._fPrevious;
+ qEntry= qEntry._fPrevious;
}
return newCache;
}
-
/**
* Flushes all entries from the cache.
*/
public void flush() {
- fCurrentSpace = 0;
- LRUCacheEntry entry = fEntryQueueTail; // Remember last entry
- fEntryTable = new Hashtable(); // Clear it out
- fEntryQueue = fEntryQueueTail = null;
+ fCurrentSpace= 0;
+ LRUCacheEntry entry= fEntryQueueTail; // Remember last entry
+ fEntryTable= new Hashtable(); // Clear it out
+ fEntryQueue= fEntryQueueTail= null;
while (entry != null) { // send deletion notifications in LRU order
privateNotifyDeletionFromCache(entry);
- entry = entry._fPrevious;
+ entry= entry._fPrevious;
}
}
-
/**
* Flushes the given entry from the cache. Does nothing if entry does not
* exist in cache.
@@ -189,7 +185,7 @@ public class LRUCache implements Cloneable {
LRUCacheEntry entry;
- entry = (LRUCacheEntry) fEntryTable.get(key);
+ entry= (LRUCacheEntry) fEntryTable.get(key);
/* If entry does not exist, return */
if (entry == null)
@@ -197,7 +193,6 @@ public class LRUCache implements Cloneable {
this.privateRemoveEntry(entry, false);
}
-
/**
* Answers the value in the cache at the given key.
* If the value is not in the cache, returns null
@@ -207,7 +202,7 @@ public class LRUCache implements Cloneable {
*/
public Object get(Object key) {
- LRUCacheEntry entry = (LRUCacheEntry) fEntryTable.get(key);
+ LRUCacheEntry entry= (LRUCacheEntry) fEntryTable.get(key);
if (entry == null) {
return null;
}
@@ -215,21 +210,18 @@ public class LRUCache implements Cloneable {
this.updateTimestamp(entry);
return entry._fValue;
}
-
/**
* Returns the amount of space that is current used in the cache.
*/
public int getCurrentSpace() {
return fCurrentSpace;
}
-
/**
* Returns the maximum amount of space available in the cache.
*/
public int getSpaceLimit() {
return fSpaceLimit;
}
-
/**
* Returns an Enumeration of the keys currently in the cache.
*/
@@ -237,7 +229,6 @@ public class LRUCache implements Cloneable {
return fEntryTable.keys();
}
-
/**
* Returns an enumeration that iterates over all the keys and values
* currently in the cache.
@@ -245,7 +236,7 @@ public class LRUCache implements Cloneable {
public ICacheEnumeration keysAndValues() {
return new ICacheEnumeration() {
- Enumeration fValues = fEntryTable.elements();
+ Enumeration fValues= fEntryTable.elements();
LRUCacheEntry fEntry;
public boolean hasMoreElements() {
@@ -253,7 +244,7 @@ public class LRUCache implements Cloneable {
}
public Object nextElement() {
- fEntry = (LRUCacheEntry) fValues.nextElement();
+ fEntry= (LRUCacheEntry) fValues.nextElement();
return fEntry._fKey;
}
@@ -265,7 +256,6 @@ public class LRUCache implements Cloneable {
}
};
}
-
/**
* Ensures there is the specified amount of free space in the receiver,
* by removing old entries if necessary. Returns true if the requested space was
@@ -277,7 +267,7 @@ public class LRUCache implements Cloneable {
int limit;
- limit = this.getSpaceLimit();
+ limit= this.getSpaceLimit();
/* if space is already available */
if (fCurrentSpace + space <= limit) {
@@ -295,14 +285,12 @@ public class LRUCache implements Cloneable {
}
return true;
}
-
/**
* Returns a new LRUCache instance
*/
protected LRUCache newInstance(int size) {
return new LRUCache(size);
}
-
/**
* Adds an entry for the given key/value/space.
*/
@@ -310,10 +298,9 @@ public class LRUCache implements Cloneable {
LRUCacheEntry entry;
- entry = new LRUCacheEntry(key, value, space);
+ entry= new LRUCacheEntry(key, value, space);
this.privateAddEntry(entry, false);
}
-
/**
* Adds the given entry from the receiver.
* @param shuffle Indicates whether we are just shuffling the queue
@@ -326,20 +313,19 @@ public class LRUCache implements Cloneable {
fCurrentSpace += entry._fSpace;
}
- entry._fTimestamp = fTimestampCounter++;
- entry._fNext = this.fEntryQueue;
- entry._fPrevious = null;
+ entry._fTimestamp= fTimestampCounter++;
+ entry._fNext= this.fEntryQueue;
+ entry._fPrevious= null;
if (fEntryQueue == null) {
/* this is the first and last entry */
- fEntryQueueTail = entry;
+ fEntryQueueTail= entry;
} else {
- fEntryQueue._fPrevious = entry;
+ fEntryQueue._fPrevious= entry;
}
- fEntryQueue = entry;
+ fEntryQueue= entry;
}
-
/**
* An entry has been removed from the cache, for example because it has
* fallen off the bottom of the LRU queue.
@@ -348,7 +334,6 @@ public class LRUCache implements Cloneable {
protected void privateNotifyDeletionFromCache(LRUCacheEntry entry) {
// Default is NOP.
}
-
/**
* Removes the entry from the entry queue.
* @param shuffle indicates whether we are just shuffling the queue
@@ -358,8 +343,8 @@ public class LRUCache implements Cloneable {
LRUCacheEntry previous, next;
- previous = entry._fPrevious;
- next = entry._fNext;
+ previous= entry._fPrevious;
+ next= entry._fNext;
if (!shuffle) {
fEntryTable.remove(entry._fKey);
@@ -369,19 +354,18 @@ public class LRUCache implements Cloneable {
/* if this was the first entry */
if (previous == null) {
- fEntryQueue = next;
+ fEntryQueue= next;
} else {
- previous._fNext = next;
+ previous._fNext= next;
}
/* if this was the last entry */
if (next == null) {
- fEntryQueueTail = previous;
+ fEntryQueueTail= previous;
} else {
- next._fPrevious = previous;
+ next._fPrevious= previous;
}
}
-
/**
* Sets the value in the cache at the given key. Returns the value.
*
@@ -395,8 +379,8 @@ public class LRUCache implements Cloneable {
LRUCacheEntry entry;
/* Check whether there's an entry in the cache */
- newSpace = spaceFor(key, value);
- entry = (LRUCacheEntry) fEntryTable.get(key);
+ newSpace= spaceFor(key, value);
+ entry= (LRUCacheEntry) fEntryTable.get(key);
if (entry != null) {
@@ -405,13 +389,13 @@ public class LRUCache implements Cloneable {
* the cache. Otherwise flush the entry and re-add it so as
* to keep cache within budget
*/
- oldSpace = entry._fSpace;
- newTotal = getCurrentSpace() - oldSpace + newSpace;
+ oldSpace= entry._fSpace;
+ newTotal= getCurrentSpace() - oldSpace + newSpace;
if (newTotal <= getSpaceLimit()) {
updateTimestamp(entry);
- entry._fValue = value;
- entry._fSpace = newSpace;
- this.fCurrentSpace = newTotal;
+ entry._fValue= value;
+ entry._fSpace= newSpace;
+ this.fCurrentSpace= newTotal;
return value;
} else {
privateRemoveEntry(entry, false);
@@ -422,7 +406,6 @@ public class LRUCache implements Cloneable {
}
return value;
}
-
/**
* Removes and returns the value in the cache for the given key.
* If the key is not in the cache, returns null.
@@ -432,15 +415,14 @@ public class LRUCache implements Cloneable {
*/
public Object removeKey(Object key) {
- LRUCacheEntry entry = (LRUCacheEntry) fEntryTable.get(key);
+ LRUCacheEntry entry= (LRUCacheEntry) fEntryTable.get(key);
if (entry == null) {
return null;
}
- Object value = entry._fValue;
+ Object value= entry._fValue;
this.privateRemoveEntry(entry, false);
return value;
}
-
/**
* Sets the maximum amount of space that the cache can store
*
@@ -450,9 +432,8 @@ public class LRUCache implements Cloneable {
if (limit < fSpaceLimit) {
makeSpace(fSpaceLimit - limit);
}
- fSpaceLimit = limit;
+ fSpaceLimit= limit;
}
-
/**
* Returns the space taken by the given key and value.
*/
@@ -464,7 +445,6 @@ public class LRUCache implements Cloneable {
return 1;
}
}
-
/**
* Returns a String that represents the value of this object. This method
* is for debugging purposes only.
@@ -473,19 +453,17 @@ public class LRUCache implements Cloneable {
return "LRUCache " + (getCurrentSpace() * 100.0 / getSpaceLimit()) + "% full";
}
-
/**
* Updates the timestamp for the given entry, ensuring that the queue is
* kept in correct order. The entry must exist
*/
protected void updateTimestamp(LRUCacheEntry entry) {
- entry._fTimestamp = fTimestampCounter++;
+ entry._fTimestamp= fTimestampCounter++;
if (fEntryQueue != entry) {
this.privateRemoveEntry(entry, true);
this.privateAddEntry(entry, true);
}
return;
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/MemoryCheckThread.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/MemoryCheckThread.java
index b3859153a5..04bcfaf993 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/MemoryCheckThread.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/MemoryCheckThread.java
@@ -1,7 +1,7 @@
package org.eclipse.jdt.internal.core.index.impl;
public class MemoryCheckThread extends Thread {
- Runtime rt = Runtime.getRuntime();
+ Runtime rt= Runtime.getRuntime();
int timeToSleep;
/**
* MemoryCheckThread constructor comment.
@@ -11,21 +11,18 @@ public class MemoryCheckThread extends Thread {
setDaemon(true);
setPriority(Thread.MAX_PRIORITY);
}
-
/**
* MemoryCheckThread constructor comment.
*/
public MemoryCheckThread(int time) {
super();
- timeToSleep = time;
+ timeToSleep= time;
setDaemon(true);
setPriority(Thread.MAX_PRIORITY);
}
-
public long evaluateMemory() {
return rt.totalMemory() - rt.freeMemory();
}
-
/**
* Insert the method's description here.
* Creation date: (6/27/00 9:14:35 AM)
@@ -40,5 +37,4 @@ public class MemoryCheckThread extends Thread {
System.out.println(evaluateMemory());
}
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/MergeFactory.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/MergeFactory.java
index 952b0ef428..6135357898 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/MergeFactory.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/MergeFactory.java
@@ -42,34 +42,27 @@ public class MergeFactory {
protected Hashtable removedInAdds;
protected int[] mappingOld;
protected int[] mappingAdds;
- public static final int ADDS_INDEX = 0;
- public static final int OLD_INDEX = 1;
+ public static final int ADDS_INDEX= 0;
+ public static final int OLD_INDEX= 1;
/**
* MergeFactory constructor comment.
* @param directory java.io.File
*/
- public MergeFactory(
- IndexInput oldIndexInput,
- IndexInput addsIndexInput,
- BlocksIndexOutput mergeIndexOutput,
- Hashtable removedInOld,
- Hashtable removedInAdds) {
- oldInput = oldIndexInput;
- addsInput = addsIndexInput;
- mergeOutput = mergeIndexOutput;
- this.removedInOld = removedInOld;
- this.removedInAdds = removedInAdds;
+ public MergeFactory(IndexInput oldIndexInput, IndexInput addsIndexInput, BlocksIndexOutput mergeIndexOutput, Hashtable removedInOld, Hashtable removedInAdds) {
+ oldInput= oldIndexInput;
+ addsInput= addsIndexInput;
+ mergeOutput= mergeIndexOutput;
+ this.removedInOld= removedInOld;
+ this.removedInAdds= removedInAdds;
}
-
/**
* Initialise the merge.
*/
protected void init() {
- mappingOld = new int[oldInput.getNumFiles() + 1];
- mappingAdds = new int[addsInput.getNumFiles() + 1];
+ mappingOld= new int[oldInput.getNumFiles() + 1];
+ mappingAdds= new int[addsInput.getNumFiles() + 1];
}
-
/**
* Merges the 2 indexes into a new one on the disk.
*/
@@ -89,7 +82,6 @@ public class MergeFactory {
addsInput.close();
mergeOutput.close();
}
-
/**
* Merges the files of the 2 indexes in the new index, removes the files
* to be removed, and records the changes made to propagate them to the
@@ -97,20 +89,20 @@ public class MergeFactory {
*/
protected void mergeFiles() throws IOException {
- int positionInMerge = 1;
+ int positionInMerge= 1;
int compare;
while (oldInput.hasMoreFiles() || addsInput.hasMoreFiles()) {
- IndexedFile file1 = oldInput.getCurrentFile();
- IndexedFile file2 = addsInput.getCurrentFile();
+ IndexedFile file1= oldInput.getCurrentFile();
+ IndexedFile file2= addsInput.getCurrentFile();
//if the file has been removed we don't take it into account
while (file1 != null && wasRemoved(file1, OLD_INDEX)) {
oldInput.moveToNextFile();
- file1 = oldInput.getCurrentFile();
+ file1= oldInput.getCurrentFile();
}
while (file2 != null && wasRemoved(file2, ADDS_INDEX)) {
addsInput.moveToNextFile();
- file2 = addsInput.getCurrentFile();
+ file2= addsInput.getCurrentFile();
}
//the addsIndex was empty, we just removed files from the oldIndex
@@ -119,40 +111,37 @@ public class MergeFactory {
//test if we reached the end of one the 2 index
if (file1 == null)
- compare = 1;
+ compare= 1;
+ else if (file2 == null)
+ compare= -1;
else
- if (file2 == null)
- compare = -1;
- else
- compare = file1.getPath().compareTo(file2.getPath());
+ compare= file1.getPath().compareTo(file2.getPath());
//records the changes to Make
if (compare == 0) {
//the file has been modified:
//we remove it from the oldIndex and add it to the addsIndex
removeFile(file1, OLD_INDEX);
- mappingAdds[file2.getFileNumber()] = positionInMerge;
+ mappingAdds[file2.getFileNumber()]= positionInMerge;
file1.setFileNumber(positionInMerge);
mergeOutput.addFile(file1);
oldInput.moveToNextFile();
addsInput.moveToNextFile();
- } else
- if (compare < 0) {
- mappingOld[file1.getFileNumber()] = positionInMerge;
- file1.setFileNumber(positionInMerge);
- mergeOutput.addFile(file1);
- oldInput.moveToNextFile();
- } else {
- mappingAdds[file2.getFileNumber()] = positionInMerge;
- file2.setFileNumber(positionInMerge);
- mergeOutput.addFile(file2);
- addsInput.moveToNextFile();
- }
+ } else if (compare < 0) {
+ mappingOld[file1.getFileNumber()]= positionInMerge;
+ file1.setFileNumber(positionInMerge);
+ mergeOutput.addFile(file1);
+ oldInput.moveToNextFile();
+ } else {
+ mappingAdds[file2.getFileNumber()]= positionInMerge;
+ file2.setFileNumber(positionInMerge);
+ mergeOutput.addFile(file2);
+ addsInput.moveToNextFile();
+ }
positionInMerge++;
}
- mergeOutput.flushFiles();
+ mergeOutput.flushFiles();
}
-
/**
* Merges the files of the 2 indexes in the new index, according to the changes
* recorded during mergeFiles().
@@ -160,50 +149,46 @@ public class MergeFactory {
protected void mergeReferences() throws IOException {
int compare;
while (oldInput.hasMoreWords() || addsInput.hasMoreWords()) {
- WordEntry word1 = oldInput.getCurrentWordEntry();
- WordEntry word2 = addsInput.getCurrentWordEntry();
+ WordEntry word1= oldInput.getCurrentWordEntry();
+ WordEntry word2= addsInput.getCurrentWordEntry();
if (word1 == null && word2 == null)
break;
-
+
if (word1 == null)
- compare = 1;
+ compare= 1;
+ else if (word2 == null)
+ compare= -1;
else
- if (word2 == null)
- compare = -1;
- else
- compare = Util.compare(word1.getWord(), word2.getWord());
+ compare= Util.compare(word1.getWord(), word2.getWord());
if (compare < 0) {
word1.mapRefs(mappingOld);
mergeOutput.addWord(word1);
oldInput.moveToNextWordEntry();
- } else
- if (compare > 0) {
- word2.mapRefs(mappingAdds);
- mergeOutput.addWord(word2);
- addsInput.moveToNextWordEntry();
- } else {
- word1.mapRefs(mappingOld);
- word2.mapRefs(mappingAdds);
- word1.addRefs(word2.getRefs());
- mergeOutput.addWord(word1);
- addsInput.moveToNextWordEntry();
- oldInput.moveToNextWordEntry();
- }
+ } else if (compare > 0) {
+ word2.mapRefs(mappingAdds);
+ mergeOutput.addWord(word2);
+ addsInput.moveToNextWordEntry();
+ } else {
+ word1.mapRefs(mappingOld);
+ word2.mapRefs(mappingAdds);
+ word1.addRefs(word2.getRefs());
+ mergeOutput.addWord(word1);
+ addsInput.moveToNextWordEntry();
+ oldInput.moveToNextWordEntry();
+ }
}
mergeOutput.flushWords();
}
-
/**
* Records the deletion of one file.
*/
protected void removeFile(IndexedFile file, int index) {
if (index == OLD_INDEX)
- mappingOld[file.getFileNumber()] = -1;
+ mappingOld[file.getFileNumber()]= -1;
else
- mappingAdds[file.getFileNumber()] = -1;
+ mappingAdds[file.getFileNumber()]= -1;
}
-
/**
* Returns whether the given file has to be removed from the given index
* (ADDS_INDEX or OLD_INDEX). If it has to be removed, the mergeFactory
@@ -211,26 +196,24 @@ public class MergeFactory {
*/
protected boolean wasRemoved(IndexedFile indexedFile, int index) {
- String path = indexedFile.getPath();
+ String path= indexedFile.getPath();
if (index == OLD_INDEX) {
if (removedInOld.remove(path) != null) {
- mappingOld[indexedFile.getFileNumber()] = -1;
+ mappingOld[indexedFile.getFileNumber()]= -1;
return true;
}
- } else
- if (index == ADDS_INDEX) {
- Int lastRemoved = (Int) removedInAdds.get(path);
- if (lastRemoved != null) {
- int fileNum = indexedFile.getFileNumber();
- if (lastRemoved.value >= fileNum) {
- mappingAdds[fileNum] = -1;
- //if (lastRemoved.value == fileNum) // ONLY if files in sorted order for names AND fileNums
- //removedInAdds.remove(path);
- return true;
- }
+ } else if (index == ADDS_INDEX) {
+ Int lastRemoved= (Int) removedInAdds.get(path);
+ if (lastRemoved != null) {
+ int fileNum= indexedFile.getFileNumber();
+ if (lastRemoved.value >= fileNum) {
+ mappingAdds[fileNum]= -1;
+ //if (lastRemoved.value == fileNum) // ONLY if files in sorted order for names AND fileNums
+ //removedInAdds.remove(path);
+ return true;
}
}
+ }
return false;
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/ObjectVector.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/ObjectVector.java
index b0dae9422b..bd7ba12ad8 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/ObjectVector.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/ObjectVector.java
@@ -1,73 +1,64 @@
package org.eclipse.jdt.internal.core.index.impl;
public final class ObjectVector {
- static int INITIAL_SIZE = 10;
+ static int INITIAL_SIZE= 10;
public int size;
int maxSize;
Object[] elements;
public ObjectVector() {
- maxSize = INITIAL_SIZE;
- size = 0;
- elements = new Object[maxSize];
+ maxSize= INITIAL_SIZE;
+ size= 0;
+ elements= new Object[maxSize];
}
-
public void add(Object newElement) {
if (size == maxSize) // knows that size starts <= maxSize
- System.arraycopy(elements, 0, (elements = new Object[maxSize *= 2]), 0, size);
- elements[size++] = newElement;
+ System.arraycopy(elements, 0, (elements= new Object[maxSize *= 2]), 0, size);
+ elements[size++]= newElement;
}
-
public void addAll(Object[] newElements) {
if (size + newElements.length >= maxSize) {
- maxSize = size + newElements.length; // assume no more elements will be added
- System.arraycopy(elements, 0, (elements = new Object[maxSize]), 0, size);
+ maxSize= size + newElements.length; // assume no more elements will be added
+ System.arraycopy(elements, 0, (elements= new Object[maxSize]), 0, size);
}
System.arraycopy(newElements, 0, elements, size, newElements.length);
size += newElements.length;
}
-
public boolean contains(Object element) {
- for (int i = size; --i >= 0;)
+ for (int i= size; --i >= 0;)
if (element == elements[i])
return true;
return false;
}
-
public Object elementAt(int index) {
return elements[index];
}
-
public Object find(Object element) {
- for (int i = size; --i >= 0;)
+ for (int i= size; --i >= 0;)
if (element == elements[i])
return elements[i];
return null;
}
-
public Object remove(Object element) {
// assumes only one occurrence of the element exists
- for (int i = size; --i >= 0;)
+ for (int i= size; --i >= 0;)
if (element == elements[i]) {
// shift the remaining elements down one spot
System.arraycopy(elements, i + 1, elements, i, --size - i);
- elements[size] = null;
+ elements[size]= null;
return element;
}
return null;
}
-
public void removeAll() {
- for (int i = size; --i >= 0;)
- elements[i] = null;
- size = 0;
+ for (int i= size; --i >= 0;)
+ elements[i]= null;
+ size= 0;
}
-
public String toString() {
- String s = "";
- for (int i = 0; i < size; i++)
+ String s= "";
+ for (int i= 0; i < size; i++)
s += elements[i].toString() + "\n";
return s;
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/PropertyDocument.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/PropertyDocument.java
index e30612b513..05218894cd 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/PropertyDocument.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/PropertyDocument.java
@@ -15,16 +15,14 @@ import java.util.*;
public abstract class PropertyDocument implements IDocument {
protected Hashtable properties;
public PropertyDocument() {
- properties = new Hashtable(5);
+ properties= new Hashtable(5);
}
-
/**
* @see IDocument#getProperty
*/
public String getProperty(String property) {
return (String) properties.get(property);
}
-
/**
* @see IDocument#getPropertyNames
*/
@@ -32,7 +30,6 @@ public abstract class PropertyDocument implements IDocument {
public Enumeration getPropertyNames() {
return properties.keys();
}
-
/**
* @see IDocument#setProperty
*/
@@ -40,5 +37,4 @@ public abstract class PropertyDocument implements IDocument {
public void setProperty(String property, String value) {
properties.put(property, value);
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/SafeRandomAccessFile.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/SafeRandomAccessFile.java
index 637f5f9ac0..fb06d7f771 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/SafeRandomAccessFile.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/SafeRandomAccessFile.java
@@ -11,18 +11,13 @@ import java.io.*;
* on finalize.
*/
public class SafeRandomAccessFile extends RandomAccessFile {
- public SafeRandomAccessFile(java.io.File file, String mode)
- throws java.io.IOException {
+ public SafeRandomAccessFile(java.io.File file, String mode) throws java.io.IOException {
super(file, mode);
}
-
- public SafeRandomAccessFile(String name, String mode)
- throws java.io.IOException {
+ public SafeRandomAccessFile(String name, String mode) throws java.io.IOException {
super(name, mode);
}
-
protected void finalize() throws IOException {
close();
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/SimpleIndexBlock.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/SimpleIndexBlock.java
index cf36680e89..661fa5b706 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/SimpleIndexBlock.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/SimpleIndexBlock.java
@@ -12,52 +12,50 @@ import java.io.*;
* Does no compression of words, and uses 4-byte ints for file numbers and number of files.
*/
public class SimpleIndexBlock extends IndexBlock {
- protected int offset = 0;
+ protected int offset= 0;
public SimpleIndexBlock(int blockSize) {
super(blockSize);
}
-
/**
* @see IndexBlock#addEntry
*/
public boolean addEntry(WordEntry entry) {
- char[] word = entry.getWord();
- int n = entry.getNumRefs();
- int sizeEstimate = 2 + word.length * 3 + 4 + n * 4;
- int offset = this.offset;
+ char[] word= entry.getWord();
+ int n= entry.getNumRefs();
+ int sizeEstimate= 2 + word.length * 3 + 4 + n * 4;
+ int offset= this.offset;
if (offset + sizeEstimate > this.blockSize - 2)
return false;
offset += field.putUTF(offset, word);
field.putInt4(offset, n);
offset += 4;
- for (int i = 0; i < n; ++i) {
+ for (int i= 0; i < n; ++i) {
field.putInt4(offset, entry.getRef(i));
offset += 4;
}
- this.offset = offset;
+ this.offset= offset;
return true;
}
-
public WordEntry findEntry(char[] word) {
try {
- int offset = 0;
+ int offset= 0;
int byteLen;
- while ((byteLen = field.getUInt2(offset)) != 0) {
- char[] tempWord = field.getUTF(offset);
+ while ((byteLen= field.getUInt2(offset)) != 0) {
+ char[] tempWord= field.getUTF(offset);
offset += byteLen + 2;
if (CharOperation.equals(tempWord, word)) {
- WordEntry entry = new WordEntry(word);
- int n = field.getInt4(offset);
+ WordEntry entry= new WordEntry(word);
+ int n= field.getInt4(offset);
offset += 4;
- for (int i = 0; i < n; ++i) {
- int ref = field.getInt4(offset);
+ for (int i= 0; i < n; ++i) {
+ int ref= field.getInt4(offset);
offset += 4;
entry.addRef(ref);
}
return entry;
} else {
- int n = field.getInt4(offset);
+ int n= field.getInt4(offset);
offset += 4 + 4 * n;
}
}
@@ -66,56 +64,51 @@ public class SimpleIndexBlock extends IndexBlock {
return null;
}
}
-
/**
* @see IndexBlock#flush
*/
public void flush() {
if (offset > 0) {
field.putInt2(offset, 0);
- offset = 0;
+ offset= 0;
}
}
-
/**
* @see IndexBlock#isEmpty
*/
public boolean isEmpty() {
return offset == 0;
}
-
/**
* @see IndexBlock#nextEntry
*/
public boolean nextEntry(WordEntry entry) {
try {
- int offset = this.offset;
- int byteLen = field.getUInt2(offset);
+ int offset= this.offset;
+ int byteLen= field.getUInt2(offset);
if (byteLen == 0)
return false;
- char[] word = field.getUTF(offset);
+ char[] word= field.getUTF(offset);
offset += byteLen + 2;
entry.reset(word);
- int n = field.getInt4(offset);
+ int n= field.getInt4(offset);
offset += 4;
- for (int i = 0; i < n; ++i) {
- int ref = field.getInt4(offset);
+ for (int i= 0; i < n; ++i) {
+ int ref= field.getInt4(offset);
offset += 4;
entry.addRef(ref);
}
- this.offset = offset;
+ this.offset= offset;
return true;
} catch (UTFDataFormatException e) {
return false;
}
}
-
/**
* @see IndexBlock#reset
*/
public void reset() {
super.reset();
- this.offset = 0;
+ this.offset= 0;
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/SimpleIndexInput.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/SimpleIndexInput.java
index ceab155488..e2767fcbce 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/SimpleIndexInput.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/SimpleIndexInput.java
@@ -20,22 +20,19 @@ public class SimpleIndexInput extends IndexInput {
public SimpleIndexInput(InMemoryIndex index) {
super();
- this.index = index;
+ this.index= index;
}
-
/**
* @see IndexInput#clearCache
*/
public void clearCache() {
}
-
/**
* @see IndexInput#close
*/
public void close() throws IOException {
- sortedFiles = null;
+ sortedFiles= null;
}
-
/**
* @see IndexInput#getCurrentFile
*/
@@ -44,52 +41,46 @@ public class SimpleIndexInput extends IndexInput {
return null;
return currentFile;
}
-
/**
* @see IndexInput#getIndexedFile
*/
public IndexedFile getIndexedFile(int fileNum) throws IOException {
- for (int i = 0; i < sortedFiles.length; i++)
+ for (int i= 0; i < sortedFiles.length; i++)
if (sortedFiles[i].getFileNumber() == fileNum)
return sortedFiles[i];
return null;
}
-
/**
* @see IndexInput#getIndexedFile
*/
public IndexedFile getIndexedFile(IDocument document) throws IOException {
- for (int i = index.getNumFiles(); i >= 1; i--) {
- IndexedFile file = getIndexedFile(i);
- String path = file.getPath();
- String name = document.getName();
+ for (int i= index.getNumFiles(); i >= 1; i--) {
+ IndexedFile file= getIndexedFile(i);
+ String path= file.getPath();
+ String name= document.getName();
if (name.equals(path))
return file;
}
return null;
}
-
/**
* @see IndexInput#getNumFiles
*/
public int getNumFiles() {
return index.getNumFiles();
}
-
/**
* @see IndexInput#getNumWords
*/
public int getNumWords() {
return sortedWords.length;
}
-
/**
* @see IndexInput#getSource
*/
public Object getSource() {
return index;
}
-
/**
* @see IndexInput#init
*/
@@ -97,7 +88,6 @@ public class SimpleIndexInput extends IndexInput {
index.init();
}
-
/**
* @see IndexInput#moveToNextFile
*/
@@ -106,9 +96,8 @@ public class SimpleIndexInput extends IndexInput {
if (!hasMoreFiles()) {
return;
}
- currentFile = sortedFiles[filePosition - 1];
+ currentFile= sortedFiles[filePosition - 1];
}
-
/**
* @see IndexInput#moveToNextWordEntry
*/
@@ -117,81 +106,71 @@ public class SimpleIndexInput extends IndexInput {
if (!hasMoreWords()) {
return;
}
- char[] word = sortedWords[wordPosition - 1];
- currentWordEntry = (WordEntry) index.words.get(word);
+ char[] word= sortedWords[wordPosition - 1];
+ currentWordEntry= (WordEntry) index.words.get(word);
}
-
/**
* @see IndexInput#open
*/
public void open() throws IOException {
- sortedWords = index.getSortedWords();
- sortedFiles = index.getSortedFiles();
- filePosition = 1;
- wordPosition = 1;
+ sortedWords= index.getSortedWords();
+ sortedFiles= index.getSortedFiles();
+ filePosition= 1;
+ wordPosition= 1;
setFirstFile();
setFirstWord();
}
-
/**
* @see IndexInput#query
*/
public IQueryResult[] query(String word) throws IOException {
- char[] wordChar = word.toCharArray();
- WordEntry wordEntry = index.getWordEntry(wordChar);
- int[] fileNums = wordEntry.getRefs();
- IQueryResult[] files = new IQueryResult[fileNums.length];
- for (int i = 0; i < files.length; i++)
- files[i] = getIndexedFile(fileNums[i]);
+ char[] wordChar= word.toCharArray();
+ WordEntry wordEntry= index.getWordEntry(wordChar);
+ int[] fileNums= wordEntry.getRefs();
+ IQueryResult[] files= new IQueryResult[fileNums.length];
+ for (int i= 0; i < files.length; i++)
+ files[i]= getIndexedFile(fileNums[i]);
return files;
}
-
- public IEntryResult[] queryEntriesPrefixedBy(char[] prefix)
- throws IOException {
- return null;
- }
-
- public IQueryResult[] queryFilesReferringToPrefix(char[] prefix)
- throws IOException {
+public IEntryResult[] queryEntriesPrefixedBy(char[] prefix) throws IOException {
+ return null;
+}
+public IQueryResult[] queryFilesReferringToPrefix(char[] prefix) throws IOException {
return null;
- }
-
+}
/**
* @see IndexInput#query
*/
public IQueryResult[] queryInDocumentNames(String word) throws IOException {
setFirstFile();
- Vector matches = new Vector();
+ Vector matches= new Vector();
while (hasMoreFiles()) {
- IndexedFile file = getCurrentFile();
+ IndexedFile file= getCurrentFile();
if (file.getPath().indexOf(word) != -1)
matches.addElement(file.getPath());
moveToNextFile();
}
- IQueryResult[] match = new IQueryResult[matches.size()];
+ IQueryResult[] match= new IQueryResult[matches.size()];
matches.copyInto(match);
return match;
}
-
/**
* @see IndexInput#setFirstFile
*/
protected void setFirstFile() throws IOException {
- filePosition = 1;
+ filePosition= 1;
if (sortedFiles.length > 0) {
- currentFile = sortedFiles[0];
+ currentFile= sortedFiles[0];
}
}
-
/**
* @see IndexInput#setFirstWord
*/
protected void setFirstWord() throws IOException {
- wordPosition = 1;
+ wordPosition= 1;
if (sortedWords.length > 0) {
- char[] word = sortedWords[0];
- currentWordEntry = (WordEntry) index.words.get(word);
+ char[] word= sortedWords[0];
+ currentWordEntry= (WordEntry) index.words.get(word);
}
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Util.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Util.java
index 808972981d..cd45a90a23 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Util.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/Util.java
@@ -11,7 +11,6 @@ public class Util {
private Util() {
}
-
/**
* Compares two strings lexicographically.
* The comparison is based on the Unicode value of each character in
@@ -24,78 +23,75 @@ public class Util {
* lexicographically greater than str2.
*/
public static int compare(char[] str1, char[] str2) {
- int len1 = str1.length;
- int len2 = str2.length;
- int n = Math.min(len1, len2);
- int i = 0;
+ int len1= str1.length;
+ int len2= str2.length;
+ int n= Math.min(len1, len2);
+ int i= 0;
while (n-- != 0) {
- char c1 = str1[i];
- char c2 = str2[i++];
+ char c1= str1[i];
+ char c2= str2[i++];
if (c1 != c2) {
return c1 - c2;
}
}
return len1 - len2;
}
-
- public static byte[] getFileByteContent(File file) throws java.io.IOException {
- int fileLength;
- byte classFileBytes[] = new byte[fileLength = (int) file.length()];
- BufferedInputStream stream = null;
- try {
- stream = new BufferedInputStream(new FileInputStream(file));
- int bytesRead = 0;
- int lastReadSize = 0;
- while ((lastReadSize != -1) && (bytesRead != fileLength)) {
- lastReadSize = stream.read(classFileBytes, bytesRead, fileLength - bytesRead);
- bytesRead += lastReadSize;
- }
- } finally {
- if (stream != null)
- stream.close();
+public static byte[] getFileByteContent(File file) throws java.io.IOException {
+ int fileLength;
+ byte classFileBytes[] = new byte[fileLength = (int) file.length()];
+ BufferedInputStream stream = null;
+ try {
+ stream = new BufferedInputStream(new FileInputStream(file));
+ int bytesRead = 0;
+ int lastReadSize = 0;
+ while ((lastReadSize != -1) && (bytesRead != fileLength)) {
+ lastReadSize = stream.read(classFileBytes, bytesRead, fileLength - bytesRead);
+ bytesRead += lastReadSize;
}
- return classFileBytes;
+ } finally {
+ if (stream != null)
+ stream.close();
}
-
+ return classFileBytes;
+}
public static char[] getFileCharContent(File file) throws java.io.IOException {
- byte[] bytes = null;
+ byte[] bytes= null;
BufferedReader reader = null;
- char[] contents = null;
+ char[] contents= null;
try {
- reader = new BufferedReader(new FileReader(file));
- int length = (int) file.length();
- contents = new char[length];
- int len = 0;
- int readSize = 0;
+ reader= new BufferedReader(new FileReader(file));
+ int length= (int) file.length();
+ contents= new char[length];
+ int len= 0;
+ int readSize= 0;
while ((readSize != -1) && (len != length)) {
len += readSize;
- readSize = reader.read(contents, len, length - len);
+ readSize= reader.read(contents, len, length - len);
}
if (len != length)
- System.arraycopy(contents, 0, (contents = new char[len]), 0, len);
+ System.arraycopy(contents, 0, (contents= new char[len]), 0, len);
} finally {
if (reader != null)
reader.close();
}
return contents;
}
-
/**
* Adds all files with the given suffix in the given directory
* and all its subdirectories to the given Vector.
*/
public static void getFiles(File fileOrDir, String[] suffix, Vector v) {
if (fileOrDir.isDirectory()) {
- String[] list = fileOrDir.list();
+ String[] list= fileOrDir.list();
if (list != null) {
sort(list);
- for (int i = 0; i < list.length; ++i) {
- File file = new File(fileOrDir, list[i]);
+ for (int i= 0; i < list.length; ++i) {
+ File file= new File(fileOrDir, list[i]);
getFiles(file, suffix, v);
}
}
} else {
- for (int i = 0; i < suffix.length; i++) {
+ for (int i= 0; i < suffix.length; i++) {
if (fileOrDir.getName().toLowerCase().endsWith(suffix[i])) {
v.addElement(fileOrDir);
break;
@@ -103,18 +99,17 @@ public class Util {
}
}
}
-
/**
* Adds all files with the given suffix in the given directory
* and all its subdirectories to the given Vector.
*/
public static void getFiles(File fileOrDir, String suffix, Vector v) {
if (fileOrDir.isDirectory()) {
- String[] list = fileOrDir.list();
+ String[] list= fileOrDir.list();
if (list != null) {
sort(list);
- for (int i = 0; i < list.length; ++i) {
- File file = new File(fileOrDir, list[i]);
+ for (int i= 0; i < list.length; ++i) {
+ File file= new File(fileOrDir, list[i]);
getFiles(file, suffix, v);
}
}
@@ -124,33 +119,30 @@ public class Util {
}
}
}
-
/**
* Returns the length of the common prefix between s1 and s2.
*/
public static int prefixLength(char[] s1, char[] s2) {
- int len = 0;
- int max = Math.min(s1.length, s2.length);
- for (int i = 0; i < max && s1[i] == s2[i]; ++i)
+ int len= 0;
+ int max= Math.min(s1.length, s2.length);
+ for (int i= 0; i < max && s1[i] == s2[i]; ++i)
++len;
return len;
}
-
/**
* Returns the length of the common prefix between s1 and s2.
*/
public static int prefixLength(String s1, String s2) {
- int len = 0;
- int max = Math.min(s1.length(), s2.length());
- for (int i = 0; i < max && s1.charAt(i) == s2.charAt(i); ++i)
+ int len= 0;
+ int max= Math.min(s1.length(), s2.length());
+ for (int i= 0; i < max && s1.charAt(i) == s2.charAt(i); ++i)
++len;
return len;
}
-
private static void quickSort(char[][] list, int left, int right) {
- int original_left = left;
- int original_right = right;
- char[] mid = list[(left + right) / 2];
+ int original_left= left;
+ int original_right= right;
+ char[] mid= list[(left + right) / 2];
do {
while (compare(list[left], mid) < 0) {
left++;
@@ -159,9 +151,9 @@ public class Util {
right--;
}
if (left <= right) {
- char[] tmp = list[left];
- list[left] = list[right];
- list[right] = tmp;
+ char[] tmp= list[left];
+ list[left]= list[right];
+ list[right]= tmp;
left++;
right--;
}
@@ -174,11 +166,10 @@ public class Util {
quickSort(list, left, original_right);
}
}
-
private static void quickSort(int[] list, int left, int right) {
- int original_left = left;
- int original_right = right;
- int mid = list[(left + right) / 2];
+ int original_left= left;
+ int original_right= right;
+ int mid= list[(left + right) / 2];
do {
while (list[left] < mid) {
left++;
@@ -187,9 +178,9 @@ public class Util {
right--;
}
if (left <= right) {
- int tmp = list[left];
- list[left] = list[right];
- list[right] = tmp;
+ int tmp= list[left];
+ list[left]= list[right];
+ list[right]= tmp;
left++;
right--;
}
@@ -202,13 +193,12 @@ public class Util {
quickSort(list, left, original_right);
}
}
-
private static void quickSort(String[] list, int left, int right) {
- int original_left = left;
- int original_right = right;
+ int original_left= left;
+ int original_right= right;
- String mid = list[(left + right) / 2];
+ String mid= list[(left + right) / 2];
do {
while (list[left].compareTo(mid) < 0) {
left++;
@@ -217,9 +207,9 @@ public class Util {
right--;
}
if (left <= right) {
- String tmp = list[left];
- list[left] = list[right];
- list[right] = tmp;
+ String tmp= list[left];
+ list[left]= list[right];
+ list[right]= tmp;
left++;
right--;
}
@@ -233,13 +223,12 @@ public class Util {
quickSort(list, left, original_right);
}
}
-
private static void quickSort(IndexedFile[] list, int left, int right) {
- int original_left = left;
- int original_right = right;
+ int original_left= left;
+ int original_right= right;
- IndexedFile mid = list[(left + right) / 2];
+ IndexedFile mid= list[(left + right) / 2];
do {
while (list[left].getPath().compareTo(mid.getPath()) < 0) {
left++;
@@ -248,9 +237,9 @@ public class Util {
right--;
}
if (left <= right) {
- IndexedFile tmp = list[left];
- list[left] = list[right];
- list[right] = tmp;
+ IndexedFile tmp= list[left];
+ list[left]= list[right];
+ list[right]= tmp;
left++;
right--;
}
@@ -264,7 +253,6 @@ public class Util {
quickSort(list, left, original_right);
}
}
-
/**
* Reads in a string from the specified data input stream. The
* string has been encoded using a modified UTF-8 format.
@@ -289,12 +277,12 @@ public class Util {
* @see java.io.DataInputStream#readUnsignedShort()
*/
public final static char[] readUTF(DataInput in) throws IOException {
- int utflen = in.readUnsignedShort();
- char str[] = new char[utflen];
- int count = 0;
- int strlen = 0;
+ int utflen= in.readUnsignedShort();
+ char str[]= new char[utflen];
+ int count= 0;
+ int strlen= 0;
while (count < utflen) {
- int c = in.readUnsignedByte();
+ int c= in.readUnsignedByte();
int char2, char3;
switch (c >> 4) {
case 0 :
@@ -307,7 +295,7 @@ public class Util {
case 7 :
// 0xxxxxxx
count++;
- str[strlen++] = (char) c;
+ str[strlen++]= (char) c;
break;
case 12 :
case 13 :
@@ -315,22 +303,21 @@ public class Util {
count += 2;
if (count > utflen)
throw new UTFDataFormatException();
- char2 = in.readUnsignedByte();
+ char2= in.readUnsignedByte();
if ((char2 & 0xC0) != 0x80)
throw new UTFDataFormatException();
- str[strlen++] = (char) (((c & 0x1F) << 6) | (char2 & 0x3F));
+ str[strlen++]= (char) (((c & 0x1F) << 6) | (char2 & 0x3F));
break;
case 14 :
// 1110 xxxx 10xx xxxx 10xx xxxx
count += 3;
if (count > utflen)
throw new UTFDataFormatException();
- char2 = in.readUnsignedByte();
- char3 = in.readUnsignedByte();
+ char2= in.readUnsignedByte();
+ char3= in.readUnsignedByte();
if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80))
throw new UTFDataFormatException();
- str[strlen++] =
- (char) (((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0));
+ str[strlen++]= (char) (((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0));
break;
default :
// 10xx xxxx, 1111 xxxx
@@ -338,49 +325,43 @@ public class Util {
}
}
if (strlen < utflen) {
- System.arraycopy(str, 0, str = new char[strlen], 0, strlen);
+ System.arraycopy(str, 0, str= new char[strlen], 0, strlen);
}
return str;
}
-
public static void sort(char[][] list) {
if (list.length > 1)
quickSort(list, 0, list.length - 1);
}
-
public static void sort(int[] list) {
if (list.length > 1)
quickSort(list, 0, list.length - 1);
}
-
public static void sort(String[] list) {
if (list.length > 1)
quickSort(list, 0, list.length - 1);
}
-
public static void sort(IndexedFile[] list) {
if (list.length > 1)
quickSort(list, 0, list.length - 1);
}
-
public static int startsWith(char[] str, char[] prefix) {
- int len1 = str.length;
- int len2 = prefix.length;
- int n = Math.min(len1, len2);
- int i = 0;
+ int len1= str.length;
+ int len2= prefix.length;
+ int n= Math.min(len1, len2);
+ int i= 0;
while (n-- != 0) {
- char c1 = str[i];
- char c2 = prefix[i++];
+ char c1= str[i];
+ char c2= prefix[i++];
if (c1 != c2) {
return c1 - c2;
}
}
if (len2 == i)
return 0;
-
- return 1;
+
+ return 1;
}
-
/**
* Writes a string to the given output stream using UTF-8
* encoding in a machine-independent manner.
@@ -397,37 +378,34 @@ public class Util {
* @since JDK1.0
*/
public static void writeUTF(OutputStream out, char[] str) throws IOException {
- int strlen = str.length;
- int utflen = 0;
- for (int i = 0; i < strlen; i++) {
- int c = str[i];
+ int strlen= str.length;
+ int utflen= 0;
+ for (int i= 0; i < strlen; i++) {
+ int c= str[i];
if ((c >= 0x0001) && (c <= 0x007F)) {
utflen++;
- } else
- if (c > 0x07FF) {
- utflen += 3;
- } else {
- utflen += 2;
- }
+ } else if (c > 0x07FF) {
+ utflen += 3;
+ } else {
+ utflen += 2;
+ }
}
if (utflen > 65535)
throw new UTFDataFormatException();
out.write((utflen >>> 8) & 0xFF);
out.write((utflen >>> 0) & 0xFF);
- for (int i = 0; i < strlen; i++) {
- int c = str[i];
+ for (int i= 0; i < strlen; i++) {
+ int c= str[i];
if ((c >= 0x0001) && (c <= 0x007F)) {
out.write(c);
- } else
- if (c > 0x07FF) {
- out.write(0xE0 | ((c >> 12) & 0x0F));
- out.write(0x80 | ((c >> 6) & 0x3F));
- out.write(0x80 | ((c >> 0) & 0x3F));
- } else {
- out.write(0xC0 | ((c >> 6) & 0x1F));
- out.write(0x80 | ((c >> 0) & 0x3F));
- }
+ } else if (c > 0x07FF) {
+ out.write(0xE0 | ((c >> 12) & 0x0F));
+ out.write(0x80 | ((c >> 6) & 0x3F));
+ out.write(0x80 | ((c >> 0) & 0x3F));
+ } else {
+ out.write(0xC0 | ((c >> 6) & 0x1F));
+ out.write(0x80 | ((c >> 0) & 0x3F));
+ }
}
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/WordEntry.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/WordEntry.java
index 53f6cbf62b..70b24edae7 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/WordEntry.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/index/impl/WordEntry.java
@@ -7,13 +7,11 @@ public class WordEntry {
public WordEntry() {
this(new char[0]);
}
-
public WordEntry(char[] word) {
- fWord = word;
- fNumRefs = 0;
- fRefs = new int[10];
+ fWord= word;
+ fNumRefs= 0;
+ fRefs= new int[10];
}
-
/**
* Adds a reference and records the change in footprint.
*/
@@ -21,57 +19,55 @@ public class WordEntry {
if (fNumRefs > 0 && fRefs[fNumRefs - 1] == fileNum) {
return 0;
}
- int footprintDelta = 0;
+ int footprintDelta= 0;
if (fRefs.length == 0)
- fRefs = new int[20];
+ fRefs= new int[20];
if (fNumRefs == fRefs.length) {
- footprintDelta = fRefs.length * 4;
- int[] newRefs = new int[fRefs.length * 2];
+ footprintDelta= fRefs.length * 4;
+ int[] newRefs= new int[fRefs.length * 2];
System.arraycopy(fRefs, 0, newRefs, 0, fRefs.length);
- fRefs = newRefs;
+ fRefs= newRefs;
}
- fRefs[fNumRefs++] = fileNum;
+ fRefs[fNumRefs++]= fileNum;
return footprintDelta;
}
-
/**
* Adds a set of references and records the change in footprint.
*/
public void addRefs(int[] refs) {
- int[] newRefs = new int[fNumRefs + refs.length];
- int pos1 = 0;
- int pos2 = 0;
- int posNew = 0;
+ int[] newRefs= new int[fNumRefs + refs.length];
+ int pos1= 0;
+ int pos2= 0;
+ int posNew= 0;
int compare;
- int r1 = 0;
- int r2 = 0;
+ int r1= 0;
+ int r2= 0;
while (pos1 < fNumRefs || pos2 < refs.length) {
if (pos1 >= fNumRefs) {
- r2 = refs[pos2];
- compare = -1;
- } else
- if (pos2 >= refs.length) {
- compare = 1;
- r1 = fRefs[pos1];
- } else {
- r1 = fRefs[pos1];
- r2 = refs[pos2];
- compare = r2 - r1;
- }
+ r2= refs[pos2];
+ compare= -1;
+ } else if (pos2 >= refs.length) {
+ compare= 1;
+ r1= fRefs[pos1];
+ } else {
+ r1= fRefs[pos1];
+ r2= refs[pos2];
+ compare= r2 - r1;
+ }
if (compare > 0) {
- newRefs[posNew] = r1;
+ newRefs[posNew]= r1;
posNew++;
pos1++;
} else {
if (r2 != 0) {
- newRefs[posNew] = r2;
+ newRefs[posNew]= r2;
posNew++;
}
pos2++;
}
}
- fRefs = newRefs;
- fNumRefs = posNew;
+ fRefs= newRefs;
+ fNumRefs= posNew;
/*for (int i = 0; i < refs.length; i++)
addRef(refs[i]);
int[] newRefs = new int[fNumRefs];
@@ -79,7 +75,6 @@ public class WordEntry {
fRefs = newRefs;
Util.sort(fRefs);*/
}
-
/**
* Returns the size of the wordEntry
*/
@@ -87,14 +82,12 @@ public class WordEntry {
public int footprint() {
return 8 + (3 * 4) + (8 + fWord.length * 2) + (8 + fRefs.length * 4);
}
-
/**
* Returns the number of references, e.g. the number of files this word appears in.
*/
public int getNumRefs() {
return fNumRefs;
}
-
/**
* returns the file number in the i position in the list of references.
*/
@@ -103,17 +96,15 @@ public class WordEntry {
throw new IndexOutOfBoundsException();
return fRefs[i];
}
-
/**
* Returns the references of the wordEntry (the number of the files it appears in).
*/
public int[] getRefs() {
- int[] result = new int[fNumRefs];
+ int[] result= new int[fNumRefs];
System.arraycopy(fRefs, 0, result, 0, fNumRefs);
return result;
}
-
/**
* returns the word of the wordEntry.
*/
@@ -121,7 +112,6 @@ public class WordEntry {
public char[] getWord() {
return fWord;
}
-
/**
* Changes the references of the wordEntry to match the mapping. For example,<br>
* if the current references are [1 3 4]<br>
@@ -130,35 +120,32 @@ public class WordEntry {
* => references = [2 4 5].<br>
*/
public void mapRefs(int[] mappings) {
- int position = 0;
- for (int i = 0; i < fNumRefs; i++) {
- int map = mappings[fRefs[i]];
+ int position= 0;
+ for (int i= 0; i < fNumRefs; i++) {
+ int map= mappings[fRefs[i]];
if (map != -1 && map != 0) {
- fRefs[position] = map;
+ fRefs[position]= map;
position++;
}
}
- fNumRefs = position;
+ fNumRefs= position;
//to be changed!
- System.arraycopy(fRefs, 0, (fRefs = new int[fNumRefs]), 0, fNumRefs);
+ System.arraycopy(fRefs, 0, (fRefs= new int[fNumRefs]), 0, fNumRefs);
Util.sort(fRefs);
}
-
/**
* Clears the wordEntry.
*/
public void reset(char[] word) {
- for (int i = fNumRefs; i-- > 0;) {
- fRefs[i] = 0;
+ for (int i= fNumRefs; i-- > 0;) {
+ fRefs[i]= 0;
}
- fNumRefs = 0;
- fWord = word;
+ fNumRefs= 0;
+ fWord= word;
}
-
public String toString() {
return new String(fWord);
}
-
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/AbstractSearchScope.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/AbstractSearchScope.java
index 5973530a2d..cad39cb2aa 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/AbstractSearchScope.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/AbstractSearchScope.java
@@ -14,32 +14,30 @@ public abstract class AbstractSearchScope {
protected IResource[] elements = new IResource[5];
protected int elementCount = 0;
- /**
- * Adds the given resource to this search scope.
- */
- public void add(IResource element) {
- if (this.elementCount == this.elements.length) {
- System.arraycopy(
- this.elements,
- 0,
- this.elements = new IResource[this.elementCount * 2],
- 0,
- this.elementCount);
- }
- elements[elementCount++] = element;
+/**
+ * Adds the given resource to this search scope.
+ */
+public void add(IResource element) {
+ if (this.elementCount == this.elements.length) {
+ System.arraycopy(
+ this.elements,
+ 0,
+ this.elements = new IResource[this.elementCount * 2],
+ 0,
+ this.elementCount);
}
-
- /**
- * Returns whether this search scope encloses the given resource.
- */
- protected boolean encloses(IResource element) {
- IPath elementPath = element.getFullPath();
- for (int i = 0; i < elementCount; i++) {
- if (this.elements[i].getFullPath().isPrefixOf(elementPath)) {
- return true;
- }
+ elements[elementCount++] = element;
+}
+/**
+ * Returns whether this search scope encloses the given resource.
+ */
+protected boolean encloses(IResource element) {
+ IPath elementPath = element.getFullPath();
+ for (int i = 0; i < elementCount; i++) {
+ if (this.elements[i].getFullPath().isPrefixOf(elementPath)) {
+ return true;
}
- return false;
}
-
+ return false;
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/HierarchyScope.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
index e6fd0a670e..8c5b5319d9 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/HierarchyScope.java
@@ -18,135 +18,122 @@ import java.util.zip.ZipFile;
/**
* Scope limited to the subtype and supertype hierarchy of a given type.
*/
-public class HierarchyScope
- extends AbstractSearchScope
- implements IJavaSearchScope {
+public class HierarchyScope extends AbstractSearchScope implements IJavaSearchScope {
private ITypeHierarchy fHierarchy;
private IType[] fTypes;
private Hashtable resourcePaths = new Hashtable();
private IPath[] enclosingProjectsAndJars;
- /**
- * Creates a new hiearchy scope for the given type.
- */
- public HierarchyScope(IType type) throws JavaModelException {
- fHierarchy = type.newTypeHierarchy(null);
- buildResourceVector();
- }
-
- private void buildResourceVector() throws JavaModelException {
- Hashtable resources = new Hashtable();
- Hashtable paths = new Hashtable();
- fTypes = fHierarchy.getAllTypes();
- for (int i = 0; i < fTypes.length; i++) {
- IType type = fTypes[i];
- IResource resource = type.getUnderlyingResource();
- if (resource != null && resources.get(resource) == null) {
- resources.put(resource, resource);
- add(resource);
- }
- IPackageFragmentRoot root =
- (IPackageFragmentRoot) type.getPackageFragment().getParent();
- if (root instanceof JarPackageFragmentRoot) {
- // type in a jar
- JarPackageFragmentRoot jar = (JarPackageFragmentRoot) root;
- String zipFileName;
- ZipFile zipFile = null;
- try {
- zipFile = jar.getJar();
- zipFileName = zipFile.getName();
- } catch (CoreException e) {
- throw new JavaModelException(e);
- } finally {
- if (zipFile != null) {
- try {
- zipFile.close();
- } catch (IOException e) {
- // ignore
- }
+/**
+ * Creates a new hiearchy scope for the given type.
+ */
+public HierarchyScope(IType type) throws JavaModelException {
+ fHierarchy = type.newTypeHierarchy(null);
+ buildResourceVector();
+}
+private void buildResourceVector() throws JavaModelException {
+ Hashtable resources = new Hashtable();
+ Hashtable paths = new Hashtable();
+ fTypes = fHierarchy.getAllTypes();
+ for (int i = 0; i < fTypes.length; i++) {
+ IType type = fTypes[i];
+ IResource resource = type.getUnderlyingResource();
+ if (resource != null && resources.get(resource) == null) {
+ resources.put(resource, resource);
+ add(resource);
+ }
+ IPackageFragmentRoot root = (IPackageFragmentRoot)type.getPackageFragment().getParent();
+ if (root instanceof JarPackageFragmentRoot) {
+ // type in a jar
+ JarPackageFragmentRoot jar = (JarPackageFragmentRoot)root;
+ String zipFileName;
+ ZipFile zipFile = null;
+ try {
+ zipFile = jar.getJar();
+ zipFileName = zipFile.getName();
+ } catch (CoreException e) {
+ throw new JavaModelException(e);
+ } finally {
+ if (zipFile != null) {
+ try {
+ zipFile.close();
+ } catch (IOException e) {
+ // ignore
}
}
- String resourcePath =
- zipFileName
- + JAR_FILE_ENTRY_SEPARATOR
- + type.getFullyQualifiedName().replace('.', '/')
- + ".class";
- this.resourcePaths.put(resourcePath, resourcePath);
- paths.put(jar.getPath(), type);
- } else {
- // type is a project
- paths.put(type.getJavaProject().getProject().getFullPath(), type);
}
- }
- this.enclosingProjectsAndJars = new IPath[paths.size()];
- int i = 0;
- for (Enumeration e = paths.keys(); e.hasMoreElements();) {
- this.enclosingProjectsAndJars[i++] = (IPath) e.nextElement();
- }
- }
-
- /* (non-Javadoc)
- * @see IJavaSearchScope#encloses(String)
- */
- public boolean encloses(String resourcePath) {
- int separatorIndex = resourcePath.indexOf(JAR_FILE_ENTRY_SEPARATOR);
- if (separatorIndex != -1) {
- return this.resourcePaths.get(resourcePath) != null;
+ String resourcePath =
+ zipFileName +
+ JAR_FILE_ENTRY_SEPARATOR +
+ type.getFullyQualifiedName().replace('.', '/') +
+ ".class";
+ this.resourcePaths.put(resourcePath, resourcePath);
+ paths.put(jar.getPath(), type);
} else {
- for (int i = 0; i < this.elementCount; i++) {
- if (resourcePath.startsWith(this.elements[i].getFullPath().toString())) {
- return true;
- }
- }
+ // type is a project
+ paths.put(type.getJavaProject().getProject().getFullPath(), type);
}
- return false;
- }
-
- /* (non-Javadoc)
- * @see IJavaSearchScope#encloses(IJavaElement)
- */
- public boolean encloses(IJavaElement element) {
- if (element instanceof IType) {
- return fHierarchy.contains((IType) element);
- } else
- if (element instanceof IMember) {
- return fHierarchy.contains(((IMember) element).getDeclaringType());
- }
- return false;
}
-
- /* (non-Javadoc)
- * @see IJavaSearchScope#enclosingProjectsAndJars()
- */
- public IPath[] enclosingProjectsAndJars() {
- return this.enclosingProjectsAndJars;
- }
-
- /* (non-Javadoc)
- * @see IJavaSearchScope#includesBinaries()
- */
- public boolean includesBinaries() {
- return true;
- }
-
- /* (non-Javadoc)
- * @see IJavaSearchScope#includesClasspaths()
- */
- public boolean includesClasspaths() {
- return true;
+ this.enclosingProjectsAndJars = new IPath[paths.size()];
+ int i = 0;
+ for (Enumeration e = paths.keys(); e.hasMoreElements();) {
+ this.enclosingProjectsAndJars[i++] = (IPath)e.nextElement();
}
-
- /* (non-Javadoc)
- * @see IJavaSearchScope#setIncludesBinaries(boolean)
- */
- public void setIncludesBinaries(boolean includesBinaries) {
+}
+/* (non-Javadoc)
+ * @see IJavaSearchScope#encloses(String)
+ */
+public boolean encloses(String resourcePath) {
+ int separatorIndex = resourcePath.indexOf(JAR_FILE_ENTRY_SEPARATOR);
+ if (separatorIndex != -1) {
+ return this.resourcePaths.get(resourcePath) != null;
+ } else {
+ for (int i = 0; i < this.elementCount; i++){
+ if (resourcePath.startsWith(this.elements[i].getFullPath().toString())) {
+ return true;
+ }
+ }
}
-
- /* (non-Javadoc)
- * @see IJavaSearchScope#setIncludesClasspaths(boolean)
- */
- public void setIncludesClasspaths(boolean includesClasspaths) {
+ return false;
+}
+/* (non-Javadoc)
+ * @see IJavaSearchScope#encloses(IJavaElement)
+ */
+public boolean encloses(IJavaElement element) {
+ if (element instanceof IType) {
+ return fHierarchy.contains((IType)element);
+ } else if (element instanceof IMember) {
+ return fHierarchy.contains(((IMember) element).getDeclaringType());
}
-
+ return false;
+}
+/* (non-Javadoc)
+ * @see IJavaSearchScope#enclosingProjectsAndJars()
+ */
+public IPath[] enclosingProjectsAndJars() {
+ return this.enclosingProjectsAndJars;
+}
+/* (non-Javadoc)
+ * @see IJavaSearchScope#includesBinaries()
+ */
+public boolean includesBinaries() {
+ return true;
+}
+/* (non-Javadoc)
+ * @see IJavaSearchScope#includesClasspaths()
+ */
+public boolean includesClasspaths() {
+ return true;
+}
+/* (non-Javadoc)
+ * @see IJavaSearchScope#setIncludesBinaries(boolean)
+ */
+public void setIncludesBinaries(boolean includesBinaries) {
+}
+/* (non-Javadoc)
+ * @see IJavaSearchScope#setIncludesClasspaths(boolean)
+ */
+public void setIncludesClasspaths(boolean includesClasspaths) {
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/IIndexSearchRequestor.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/IIndexSearchRequestor.java
index 6ace6e4520..57900174c2 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/IIndexSearchRequestor.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/IIndexSearchRequestor.java
@@ -1,102 +1,73 @@
package org.eclipse.jdt.internal.core.search;
public interface IIndexSearchRequestor {
- /**
- * Accepts the declaration of a class in the compilation unit with the given resource path.
- * The class is declared in the given package and with the given type name.
- * <p>
- * Note that the resource path can be null if the search query doesn't require it (eg. get all class names).
- */
- void acceptClassDeclaration(
- String resourcePath,
- char[] simpleTypeName,
- char[][] enclosingTypeNames,
- char[] packageName);
- /**
- * Accepts the declaration of a constructor in the compilation unit with the given resource path.
- * The constructor is declared with a given name and number of arguments.
- */
- void acceptConstructorDeclaration(
- String resourcePath,
- char[] typeName,
- int parameterCount);
- /**
- * Accepts the reference to a constructor in the compilation unit with the given resource path.
- * The constructor is referenced using the given name and a number of arguments.
- *
- * Note that the resource path can be null if the search query doesn't require it.
- */
- void acceptConstructorReference(
- String resourcePath,
- char[] typeName,
- int parameterCount);
- /**
- * Accepts the declaration of a field in the compilation unit with the given resource path.
- * <p>
- * Note that the resource path can be null if the search query doesn't require it (eg. get all class names).
- * Likewise, the declaring package name and the declaring type names if the query doesn't require them.
- */
- void acceptFieldDeclaration(String resourcePath, char[] fieldName);
- /**
- * Accepts the reference to a field in the compilation unit with the given resource path.
- * The field is referenced using the given name
- */
- void acceptFieldReference(String resourcePath, char[] fieldName);
- /**
- * Accepts the declaration of an interface in the compilation unit with the given resource path.
- * The interface is declared in the given package and with the given type name.
- * <p>
- * Note that the resource path can be null if the search query doesn't require it (eg. get all interface names).
- */
- void acceptInterfaceDeclaration(
- String resourcePath,
- char[] simpleTypeName,
- char[][] enclosingTypeNames,
- char[] packageName);
- /**
- * Accepts the declaration of a method in the compilation unit with the given resource path.
- * The method is declared with a given method name and number of arguments.
- */
- void acceptMethodDeclaration(
- String resourcePath,
- char[] methodName,
- int parameterCount);
- /**
- * Accepts the reference to a method in the compilation unit with the given resource path.
- * The method is referenced using the given selector and a number of arguments.
- *
- * Note that the resource path can be null if the search query doesn't require it.
- */
- void acceptMethodReference(
- String resourcePath,
- char[] methodName,
- int parameterCount);
- /**
- * Accepts the reference to a package in the compilation unit with the given resource path.
- * The package is referenced using the given package name.
- *
- * Note that the resource path can be null if the search query doesn't require it.
- */
- void acceptPackageReference(String resourcePath, char[] packageName);
- /**
- * Accepts the reference to a supertype in the compilation unit with the given resource path.
- * Note that the resource path and/or the package name can be null.
- */
- void acceptSuperTypeReference(
- String resourcePath,
- char[] qualification,
- char[] typeName,
- char[] enclosingTypeName,
- char classOrInterface,
- char[] superQualification,
- char[] superTypeName,
- char superClassOrInterface,
- int modifiers);
- /**
- * Accepts the reference to a class in the compilation unit with the given resource path.
- * The class is referenced using the given type name.
- * <p>
- * Note that the resource path can be null if the search query doesn't require it.
- */
- void acceptTypeReference(String resourcePath, char[] typeName);
+/**
+ * Accepts the declaration of a class in the compilation unit with the given resource path.
+ * The class is declared in the given package and with the given type name.
+ * <p>
+ * Note that the resource path can be null if the search query doesn't require it (eg. get all class names).
+ */
+void acceptClassDeclaration(String resourcePath, char[] simpleTypeName, char[][] enclosingTypeNames, char[] packageName);
+/**
+ * Accepts the declaration of a constructor in the compilation unit with the given resource path.
+ * The constructor is declared with a given name and number of arguments.
+ */
+void acceptConstructorDeclaration(String resourcePath, char[] typeName, int parameterCount);
+/**
+ * Accepts the reference to a constructor in the compilation unit with the given resource path.
+ * The constructor is referenced using the given name and a number of arguments.
+ *
+ * Note that the resource path can be null if the search query doesn't require it.
+ */
+void acceptConstructorReference(String resourcePath, char[] typeName, int parameterCount);
+/**
+ * Accepts the declaration of a field in the compilation unit with the given resource path.
+ * <p>
+ * Note that the resource path can be null if the search query doesn't require it (eg. get all class names).
+ * Likewise, the declaring package name and the declaring type names if the query doesn't require them.
+ */
+void acceptFieldDeclaration(String resourcePath, char[] fieldName);
+/**
+ * Accepts the reference to a field in the compilation unit with the given resource path.
+ * The field is referenced using the given name
+ */
+void acceptFieldReference(String resourcePath, char[] fieldName);
+/**
+ * Accepts the declaration of an interface in the compilation unit with the given resource path.
+ * The interface is declared in the given package and with the given type name.
+ * <p>
+ * Note that the resource path can be null if the search query doesn't require it (eg. get all interface names).
+ */
+void acceptInterfaceDeclaration(String resourcePath, char[] simpleTypeName, char[][] enclosingTypeNames, char[] packageName);
+/**
+ * Accepts the declaration of a method in the compilation unit with the given resource path.
+ * The method is declared with a given method name and number of arguments.
+ */
+void acceptMethodDeclaration(String resourcePath, char[] methodName, int parameterCount);
+/**
+ * Accepts the reference to a method in the compilation unit with the given resource path.
+ * The method is referenced using the given selector and a number of arguments.
+ *
+ * Note that the resource path can be null if the search query doesn't require it.
+ */
+void acceptMethodReference(String resourcePath, char[] methodName, int parameterCount);
+/**
+ * Accepts the reference to a package in the compilation unit with the given resource path.
+ * The package is referenced using the given package name.
+ *
+ * Note that the resource path can be null if the search query doesn't require it.
+ */
+void acceptPackageReference(String resourcePath, char[] packageName);
+/**
+ * Accepts the reference to a supertype in the compilation unit with the given resource path.
+ * Note that the resource path and/or the package name can be null.
+ */
+void acceptSuperTypeReference(String resourcePath, char[] qualification, char[] typeName, char[] enclosingTypeName, char classOrInterface, char[] superQualification, char[] superTypeName, char superClassOrInterface, int modifiers);
+/**
+ * Accepts the reference to a class in the compilation unit with the given resource path.
+ * The class is referenced using the given type name.
+ * <p>
+ * Note that the resource path can be null if the search query doesn't require it.
+ */
+void acceptTypeReference(String resourcePath, char[] typeName);
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/IndexSearchAdapter.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/IndexSearchAdapter.java
index 555cc99276..84601b970c 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/IndexSearchAdapter.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/IndexSearchAdapter.java
@@ -1,99 +1,59 @@
package org.eclipse.jdt.internal.core.search;
public class IndexSearchAdapter implements IIndexSearchRequestor {
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptClassDeclaration(
- String resourcePath,
- char[] simpleTypeName,
- char[][] enclosingTypeNames,
- char[] packageName) {
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptConstructorDeclaration(
- String resourcePath,
- char[] typeName,
- int parameterCount) {
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptConstructorReference(
- String resourcePath,
- char[] typeName,
- int parameterCount) {
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptFieldDeclaration(String resourcePath, char[] fieldName) {
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptFieldReference(String resourcePath, char[] fieldName) {
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptInterfaceDeclaration(
- String resourcePath,
- char[] simpleTypeName,
- char[][] enclosingTypeNames,
- char[] packageName) {
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptMethodDeclaration(
- String resourcePath,
- char[] methodName,
- int parameterCount) {
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptMethodReference(
- String resourcePath,
- char[] methodName,
- int parameterCount) {
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptPackageReference(String resourcePath, char[] packageName) {
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptSuperTypeReference(
- String resourcePath,
- char[] qualification,
- char[] typeName,
- char[] enclosingTypeName,
- char classOrInterface,
- char[] superQualification,
- char[] superTypeName,
- char superClassOrInterface,
- int modifiers) {
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptTypeReference(String resourcePath, char[] typeName) {
- }
-
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptClassDeclaration(String resourcePath, char[] simpleTypeName, char[][] enclosingTypeNames, char[] packageName) {
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptConstructorDeclaration(String resourcePath, char[] typeName, int parameterCount) {
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptConstructorReference(String resourcePath, char[] typeName, int parameterCount) {
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptFieldDeclaration(String resourcePath, char[] fieldName) {
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptFieldReference(String resourcePath, char[] fieldName) {
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptInterfaceDeclaration(String resourcePath, char[] simpleTypeName, char[][] enclosingTypeNames, char[] packageName) {
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptMethodDeclaration(String resourcePath, char[] methodName, int parameterCount) {
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptMethodReference(String resourcePath, char[] methodName, int parameterCount) {
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptPackageReference(String resourcePath, char[] packageName) {
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptSuperTypeReference(String resourcePath, char[] qualification, char[] typeName, char[] enclosingTypeName, char classOrInterface, char[] superQualification, char[] superTypeName, char superClassOrInterface, int modifiers){
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptTypeReference(String resourcePath, char[] typeName) {
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/IndexSelector.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/IndexSelector.java
index 4546d6ef50..25b9d48778 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/IndexSelector.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/IndexSelector.java
@@ -25,216 +25,200 @@ public class IndexSelector {
IndexManager indexManager;
IIndex[] indexes;
- public IndexSelector(
- IJavaSearchScope searchScope,
- IJavaElement focus,
- IndexManager indexManager) {
+public IndexSelector(
+ IJavaSearchScope searchScope,
+ IJavaElement focus,
+ IndexManager indexManager) {
- this.searchScope = searchScope;
- this.focus = focus;
- this.indexManager = indexManager;
- }
-
- /**
- * Returns whether elements of the given project or jar can see the focus element
- * either because the focus is part of the project or the jar, or because it is
- * accessible throught the project's classpath
- */
- private boolean canSeeFocus(IPath projectOrJarPath) {
- try {
- while (!(this.focus instanceof IJavaProject)
- && !(this.focus instanceof JarPackageFragmentRoot)) {
- this.focus = this.focus.getParent();
+ this.searchScope = searchScope;
+ this.focus = focus;
+ this.indexManager = indexManager;
+}
+/**
+ * Returns whether elements of the given project or jar can see the focus element
+ * either because the focus is part of the project or the jar, or because it is
+ * accessible throught the project's classpath
+ */
+private boolean canSeeFocus(IPath projectOrJarPath) {
+ try {
+ while (!(this.focus instanceof IJavaProject) && !(this.focus instanceof JarPackageFragmentRoot)) {
+ this.focus = this.focus.getParent();
+ }
+ IJavaModel model = this.focus.getJavaModel();
+ IJavaProject project = this.getJavaProject(projectOrJarPath, model);
+ if (this.focus instanceof JarPackageFragmentRoot) {
+ // focus is part of a jar
+ JarPackageFragmentRoot jar = (JarPackageFragmentRoot)this.focus;
+ IPath jarPath = jar.getPath();
+ if (project == null) {
+ // consider that a jar can see another jar only they are both referenced by the same project
+ return this.haveSameParent(projectOrJarPath, jarPath, model);
+ } else {
+ IClasspathEntry[] entries = project.getResolvedClasspath(true);
+ for (int i = 0, length = entries.length; i < length; i++) {
+ IClasspathEntry entry = entries[i];
+ if ((entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY)
+ && entry.getPath().equals(jarPath)) {
+ return true;
+ }
+ }
+ return false;
}
- IJavaModel model = this.focus.getJavaModel();
- IJavaProject project = this.getJavaProject(projectOrJarPath, model);
- if (this.focus instanceof JarPackageFragmentRoot) {
- // focus is part of a jar
- JarPackageFragmentRoot jar = (JarPackageFragmentRoot) this.focus;
- IPath jarPath = jar.getPath();
- if (project == null) {
- // consider that a jar can see another jar only they are both referenced by the same project
- return this.haveSameParent(projectOrJarPath, jarPath, model);
- } else {
- IClasspathEntry[] entries = project.getResolvedClasspath(true);
- for (int i = 0, length = entries.length; i < length; i++) {
- IClasspathEntry entry = entries[i];
- if ((entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY)
- && entry.getPath().equals(jarPath)) {
+ } else {
+ // focus is part of a project
+ IJavaProject focusProject = (IJavaProject)this.focus;
+ if (project == null) {
+ // consider that a jar can see a project only if it is referenced by this project
+ IClasspathEntry[] entries = focusProject.getResolvedClasspath(true);
+ for (int i = 0, length = entries.length; i < length; i++) {
+ IClasspathEntry entry = entries[i];
+ if ((entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY)
+ && entry.getPath().equals(projectOrJarPath)) {
return true;
- }
}
- return false;
}
+ return false;
} else {
- // focus is part of a project
- IJavaProject focusProject = (IJavaProject) this.focus;
- if (project == null) {
- // consider that a jar can see a project only if it is referenced by this project
- IClasspathEntry[] entries = focusProject.getResolvedClasspath(true);
+ if (focusProject.equals(project)) {
+ return true;
+ } else {
+ IPath focusPath = focusProject.getProject().getFullPath();
+ IClasspathEntry[] entries = project.getResolvedClasspath(true);
for (int i = 0, length = entries.length; i < length; i++) {
IClasspathEntry entry = entries[i];
- if ((entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY)
- && entry.getPath().equals(projectOrJarPath)) {
- return true;
- }
- }
- return false;
- } else {
- if (focusProject.equals(project)) {
- return true;
- } else {
- IPath focusPath = focusProject.getProject().getFullPath();
- IClasspathEntry[] entries = project.getResolvedClasspath(true);
- for (int i = 0, length = entries.length; i < length; i++) {
- IClasspathEntry entry = entries[i];
- if ((entry.getEntryKind() == IClasspathEntry.CPE_PROJECT)
- && entry.getPath().equals(focusPath)) {
+ if ((entry.getEntryKind() == IClasspathEntry.CPE_PROJECT)
+ && entry.getPath().equals(focusPath)) {
return true;
- }
}
- return false;
}
+ return false;
}
}
- } catch (JavaModelException e) {
- return false;
}
+ } catch (JavaModelException e) {
+ return false;
}
-
- private void computeIndexes() {
- Vector indexesInScope = new Vector();
- IPath[] projectsAndJars = this.searchScope.enclosingProjectsAndJars();
- IWorkspaceRoot root = this.indexManager.workspace.getRoot();
- for (int i = 0; i < projectsAndJars.length; i++) {
- IPath location;
- IPath path = projectsAndJars[i];
- if ((!root.getProject(path.lastSegment()).exists())
- // if project does not exist
- && path.segmentCount() > 1
- && ((location = root.getFile(path).getLocation()) == null
- || !new java.io.File(location.toOSString()).exists())
- // and internal jar file does not exist
- && !new java.io.File(path.toOSString()).exists()) {
- // and external jar file does not exist
+}
+private void computeIndexes() {
+ Vector indexesInScope = new Vector();
+ IPath[] projectsAndJars = this.searchScope.enclosingProjectsAndJars();
+ IWorkspaceRoot root = this.indexManager.workspace.getRoot();
+ for (int i = 0; i < projectsAndJars.length; i++) {
+ IPath location;
+ IPath path = projectsAndJars[i];
+ if ((!root.getProject(path.lastSegment()).exists()) // if project does not exist
+ && path.segmentCount() > 1
+ && ((location = root.getFile(path).getLocation()) == null
+ || !new java.io.File(location.toOSString()).exists()) // and internal jar file does not exist
+ && !new java.io.File(path.toOSString()).exists()) { // and external jar file does not exist
continue;
- }
- if (this.focus == null || this.canSeeFocus(path)) {
- IIndex index = this.indexManager.getIndex(path);
- if (indexesInScope.indexOf(index) == -1) {
- indexesInScope.add(index);
- }
+ }
+ if (this.focus == null || this.canSeeFocus(path)) {
+ IIndex index = this.indexManager.getIndex(path);
+ if (indexesInScope.indexOf(index) == -1) {
+ indexesInScope.add(index);
}
}
- this.indexes = new IIndex[indexesInScope.size()];
- indexesInScope.copyInto(this.indexes);
}
-
- public IIndex[] getIndexes() {
- if (this.indexes == null) {
- this.computeIndexes();
- }
- return this.indexes;
+ this.indexes = new IIndex[indexesInScope.size()];
+ indexesInScope.copyInto(this.indexes);
+}
+public IIndex[] getIndexes() {
+ if (this.indexes == null) {
+ this.computeIndexes();
}
-
- /**
- * Returns the java project that corresponds to the given path.
- * Returns null if the path doesn't correspond to a project.
- */
- private IJavaProject getJavaProject(IPath path, IJavaModel model) {
- IJavaProject project = model.getJavaProject(path.lastSegment());
- if (project.exists()) {
- return project;
- } else {
- return null;
- }
+ return this.indexes;
+}
+/**
+ * Returns the java project that corresponds to the given path.
+ * Returns null if the path doesn't correspond to a project.
+ */
+private IJavaProject getJavaProject(IPath path, IJavaModel model) {
+ IJavaProject project = model.getJavaProject(path.lastSegment());
+ if (project.exists()) {
+ return project;
+ } else {
+ return null;
}
-
- /**
- * Returns whether the given jars are referenced in the classpath of the same project.
- */
- private boolean haveSameParent(
- IPath jarPath1,
- IPath jarPath2,
- IJavaModel model) {
- if (jarPath1.equals(jarPath2)) {
- return true;
- }
- try {
- IJavaProject[] projects = model.getJavaProjects();
- for (int i = 0, length = projects.length; i < length; i++) {
- IJavaProject project = projects[i];
- IClasspathEntry[] entries = project.getResolvedClasspath(true);
- boolean referencesJar1 = false;
- boolean referencesJar2 = false;
- for (int j = 0, length2 = entries.length; j < length2; j++) {
- IClasspathEntry entry = entries[j];
- if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
- IPath entryPath = entry.getPath();
- if (entryPath.equals(jarPath1)) {
- referencesJar1 = true;
- } else
- if (entryPath.equals(jarPath2)) {
- referencesJar2 = true;
- }
+}
+/**
+ * Returns whether the given jars are referenced in the classpath of the same project.
+ */
+private boolean haveSameParent(IPath jarPath1, IPath jarPath2, IJavaModel model) {
+ if (jarPath1.equals(jarPath2)) {
+ return true;
+ }
+ try {
+ IJavaProject[] projects = model.getJavaProjects();
+ for (int i = 0, length = projects.length; i < length; i++) {
+ IJavaProject project = projects[i];
+ IClasspathEntry[] entries = project.getResolvedClasspath(true);
+ boolean referencesJar1 = false;
+ boolean referencesJar2 = false;
+ for (int j = 0, length2 = entries.length; j < length2; j++) {
+ IClasspathEntry entry = entries[j];
+ if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
+ IPath entryPath = entry.getPath();
+ if (entryPath.equals(jarPath1)) {
+ referencesJar1 = true;
+ } else if (entryPath.equals(jarPath2)) {
+ referencesJar2 = true;
}
}
- if (referencesJar1 && referencesJar2) {
- return true;
- }
-
}
- } catch (JavaModelException e) {
- e.printStackTrace();
+ if (referencesJar1 && referencesJar2) {
+ return true;
+ }
+
}
- return false;
- }
-
- /**
- * Returns whether elements of the given project can see the focus element
- * either because the focus is part of the project, or because it is
- * accesible throught the project's classpath
- */
- private boolean projectCanSeeFocusElement(IJavaProject project) {
- try {
- while (!(this.focus instanceof IJavaProject)
- && !(this.focus instanceof JarPackageFragmentRoot)) {
- this.focus = this.focus.getParent();
+ } catch (JavaModelException e) {
+ e.printStackTrace();
+ }
+ return false;
+}
+/**
+ * Returns whether elements of the given project can see the focus element
+ * either because the focus is part of the project, or because it is
+ * accesible throught the project's classpath
+ */
+private boolean projectCanSeeFocusElement(IJavaProject project) {
+ try {
+ while (!(this.focus instanceof IJavaProject) && !(this.focus instanceof JarPackageFragmentRoot)) {
+ this.focus = this.focus.getParent();
+ }
+ if (this.focus instanceof JarPackageFragmentRoot) {
+ // this.focus is part of a jar
+ JarPackageFragmentRoot root = (JarPackageFragmentRoot)this.focus;
+ IPath rootPath = root.getPath();
+ IClasspathEntry[] entries = project.getResolvedClasspath(true);
+ for (int i = 0, length = entries.length; i < length; i++) {
+ IClasspathEntry entry = entries[i];
+ if ((entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY)
+ && entry.getPath().equals(rootPath)) {
+ return true;
+ }
}
- if (this.focus instanceof JarPackageFragmentRoot) {
- // this.focus is part of a jar
- JarPackageFragmentRoot root = (JarPackageFragmentRoot) this.focus;
- IPath rootPath = root.getPath();
+ return false;
+ } else {
+ // this.focus is part of a project
+ IJavaProject focusProject = (IJavaProject)this.focus;
+ if (project.equals(focusProject)) {
+ return true;
+ } else {
+ IPath focusPath = focusProject.getProject().getFullPath();
IClasspathEntry[] entries = project.getResolvedClasspath(true);
for (int i = 0, length = entries.length; i < length; i++) {
IClasspathEntry entry = entries[i];
- if ((entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY)
- && entry.getPath().equals(rootPath)) {
- return true;
- }
- }
- return false;
- } else {
- // this.focus is part of a project
- IJavaProject focusProject = (IJavaProject) this.focus;
- if (project.equals(focusProject)) {
- return true;
- } else {
- IPath focusPath = focusProject.getProject().getFullPath();
- IClasspathEntry[] entries = project.getResolvedClasspath(true);
- for (int i = 0, length = entries.length; i < length; i++) {
- IClasspathEntry entry = entries[i];
- if ((entry.getEntryKind() == IClasspathEntry.CPE_PROJECT)
- && entry.getPath().equals(focusPath)) {
+ if ((entry.getEntryKind() == IClasspathEntry.CPE_PROJECT)
+ && entry.getPath().equals(focusPath)) {
return true;
- }
}
- return false;
}
+ return false;
}
- } catch (JavaModelException e) {
- return false;
}
+ } catch (JavaModelException e) {
+ return false;
}
-
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/JavaSearchScope.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/JavaSearchScope.java
index 477b4dd3cd..e747f55769 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/JavaSearchScope.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/JavaSearchScope.java
@@ -20,13 +20,11 @@ import java.util.*;
* in-scope projects, and to not search binaries. By default, both classpaths
* and binaries are included.
*/
-public class JavaSearchScope
- extends AbstractSearchScope
- implements IJavaSearchScope {
+public class JavaSearchScope extends AbstractSearchScope implements IJavaSearchScope {
private boolean includesBinaries = true;
private boolean includesClasspaths = true;
-
+
private IResource fLastCheckedResource;
private boolean fLastResult;
@@ -35,174 +33,160 @@ public class JavaSearchScope
if the resources are projects) */
private IPath[] paths = new IPath[1];
private int pathsCount = 0;
- /**
- * Adds the given resource to this search scope.
- */
- public void add(IResource element) {
- super.add(element);
+/**
+ * Adds the given resource to this search scope.
+ */
+public void add(IResource element) {
+ super.add(element);
- // clear indexer cache
- fLastCheckedResource = null;
+ // clear indexer cache
+ fLastCheckedResource = null;
- if (element instanceof IProject) {
- // remember the paths of its classpath entries
- IJavaModel javaModel = JavaModelManager.getJavaModelManager().getJavaModel();
- IJavaProject javaProject = javaModel.getJavaProject(element.getName());
- try {
- IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
- for (int i = 0, length = entries.length; i < length; i++) {
- IClasspathEntry entry = entries[i];
- this.add(entry.getPath());
- }
- } catch (JavaModelException e) {
+ if (element instanceof IProject) {
+ // remember the paths of its classpath entries
+ IJavaModel javaModel = JavaModelManager.getJavaModel(element.getWorkspace());
+ IJavaProject javaProject = javaModel.getJavaProject(element.getName());
+ try {
+ IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
+ for (int i = 0, length = entries.length; i < length; i++) {
+ IClasspathEntry entry = entries[i];
+ this.add(entry.getPath());
}
- } else {
- this.add(element.getFullPath());
+ } catch (JavaModelException e) {
}
+ } else {
+ this.add(element.getFullPath());
}
-
- /**
- * Adds the given path to this search scope.
- */
- private void add(IPath path) {
- if (this.paths.length == this.pathsCount) {
- System.arraycopy(
- this.paths,
- 0,
- this.paths = new IPath[this.pathsCount * 2],
- 0,
- this.pathsCount);
- }
- this.paths[this.pathsCount++] = path;
+}
+/**
+ * Adds the given path to this search scope.
+ */
+private void add(IPath path) {
+ if (this.paths.length == this.pathsCount) {
+ System.arraycopy(
+ this.paths,
+ 0,
+ this.paths = new IPath[this.pathsCount * 2],
+ 0,
+ this.pathsCount);
}
-
- /* (non-Javadoc)
- * @see IJavaSearchScope#encloses(String)
- */
- public boolean encloses(String resourcePathString) {
- int separatorIndex = resourcePathString.indexOf(JAR_FILE_ENTRY_SEPARATOR);
- if (separatorIndex != -1) {
- resourcePathString = resourcePathString.substring(0, separatorIndex);
- }
- IPath resourcePath = new Path(resourcePathString);
- for (int i = 0; i < this.pathsCount; i++) {
- if (this.paths[i].isPrefixOf(resourcePath)) {
- return true;
- }
+ this.paths[this.pathsCount++] = path;
+}
+/* (non-Javadoc)
+ * @see IJavaSearchScope#encloses(String)
+ */
+public boolean encloses(String resourcePathString) {
+ int separatorIndex = resourcePathString.indexOf(JAR_FILE_ENTRY_SEPARATOR);
+ if (separatorIndex != -1) {
+ resourcePathString = resourcePathString.substring(0, separatorIndex);
+ }
+ IPath resourcePath = new Path(resourcePathString);
+ for (int i = 0; i < this.pathsCount; i++){
+ if (this.paths[i].isPrefixOf(resourcePath)) {
+ return true;
}
- return false;
}
-
- /**
- * Returns whether this search scope encloses the given resource.
- */
- protected boolean encloses(IResource element) {
- boolean encloses = false;
- IPath elementPath = element.getFullPath();
- for (int i = 0; i < this.pathsCount; i++) {
- if (this.paths[i].isPrefixOf(elementPath)) {
- encloses = true;
- break;
- }
+ return false;
+}
+/**
+ * Returns whether this search scope encloses the given resource.
+ */
+protected boolean encloses(IResource element) {
+ boolean encloses = false;
+ IPath elementPath = element.getFullPath();
+ for (int i = 0; i < this.pathsCount; i++) {
+ if (this.paths[i].isPrefixOf(elementPath)) {
+ encloses = true;
+ break;
}
- fLastCheckedResource = element;
- fLastResult = encloses;
- return encloses;
}
-
- /* (non-Javadoc)
- * @see IJavaSearchScope#encloses(IJavaElement)
- */
- public boolean encloses(IJavaElement element) {
- try {
- IResource resource = element.getUnderlyingResource();
- if (resource == null) {
- // case of a binary in an external jar
- return true;
- } else
- if (resource.equals(fLastCheckedResource)) {
- return fLastResult;
- }
- return encloses(resource);
- } catch (JavaModelException e) {
- return false;
+ fLastCheckedResource = element;
+ fLastResult = encloses;
+ return encloses;
+}
+/* (non-Javadoc)
+ * @see IJavaSearchScope#encloses(IJavaElement)
+ */
+public boolean encloses(IJavaElement element) {
+ try {
+ IResource resource = element.getUnderlyingResource();
+ if (resource == null) {
+ // case of a binary in an external jar
+ return true;
+ } else if (resource.equals(fLastCheckedResource)) {
+ return fLastResult;
}
+ return encloses(resource);
+ } catch (JavaModelException e) {
+ return false;
}
-
- /* (non-Javadoc)
- * @see IJavaSearchScope#enclosingProjectsAndJars()
- */
- public IPath[] enclosingProjectsAndJars() {
- try {
- Vector paths = new Vector();
- IJavaModel javaModel = JavaModelManager.getJavaModelManager().getJavaModel();
- IWorkspaceRoot root = javaModel.getWorkspace().getRoot();
- for (int i = 0; i < this.elementCount; i++) {
- IResource element = this.elements[i];
- IPath path = element.getProject().getFullPath();
- IProject project = element.getProject();
- if (project.exists() && project.isOpen()) {
- if (!paths.contains(path))
- paths.add(path);
- if (this.includesClasspaths) {
- IJavaProject javaProject = javaModel.getJavaProject(project.getName());
- IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
- for (int j = 0; j < entries.length; j++) {
- IClasspathEntry entry = entries[j];
- switch (entry.getEntryKind()) {
- case IClasspathEntry.CPE_PROJECT :
+}
+/* (non-Javadoc)
+ * @see IJavaSearchScope#enclosingProjectsAndJars()
+ */
+public IPath[] enclosingProjectsAndJars() {
+ try {
+ Vector paths = new Vector();
+ IJavaModel javaModel = JavaModelManager.getJavaModel(ResourcesPlugin.getWorkspace());
+ IWorkspaceRoot root = javaModel.getWorkspace().getRoot();
+ for (int i = 0; i < this.elementCount; i++){
+ IResource element = this.elements[i];
+ IPath path = element.getProject().getFullPath();
+ IProject project = element.getProject();
+ if (project.exists() && project.isOpen()) {
+ if (!paths.contains(path)) paths.add(path);
+ if (this.includesClasspaths) {
+ IJavaProject javaProject = javaModel.getJavaProject(project.getName());
+ IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
+ for (int j = 0; j < entries.length; j++) {
+ IClasspathEntry entry = entries[j];
+ switch (entry.getEntryKind()) {
+ case IClasspathEntry.CPE_PROJECT:
+ path = entry.getPath();
+ if (!paths.contains(path) && root.getProject(path.lastSegment()).isAccessible()) {
+ paths.add(path);
+ }
+ break;
+ case IClasspathEntry.CPE_LIBRARY:
+ if (this.includesBinaries) {
path = entry.getPath();
- if (!paths.contains(path)
- && root.getProject(path.lastSegment()).isAccessible()) {
- paths.add(path);
- }
- break;
- case IClasspathEntry.CPE_LIBRARY :
- if (this.includesBinaries) {
- path = entry.getPath();
- if (!paths.contains(path))
- paths.add(path);
- }
- break;
- }
+ if (!paths.contains(path)) paths.add(path);
+ }
+ break;
}
}
}
}
- IPath[] result = new IPath[paths.size()];
- paths.copyInto(result);
- return result;
- } catch (JavaModelException e) {
- return new IPath[0];
}
+ IPath[] result = new IPath[paths.size()];
+ paths.copyInto(result);
+ return result;
+ } catch (JavaModelException e) {
+ return new IPath[0];
}
-
- /* (non-Javadoc)
- * @see IJavaSearchScope#includesBinaries()
- */
- public boolean includesBinaries() {
- return this.includesBinaries;
- }
-
- /* (non-Javadoc)
- * @see IJavaSearchScope#includesClasspaths()
- */
- public boolean includesClasspaths() {
- return this.includesClasspaths;
- }
-
- /* (non-Javadoc)
- * @see IJavaSearchScope#setIncludesBinaries
- */
- public void setIncludesBinaries(boolean includesBinaries) {
- this.includesBinaries = includesBinaries;
- }
-
- /* (non-Javadoc)
- * @see IJavaSearchScope#setIncludeClasspaths
- */
- public void setIncludesClasspaths(boolean includesClasspaths) {
- this.includesClasspaths = includesClasspaths;
- }
-
+}
+/* (non-Javadoc)
+ * @see IJavaSearchScope#includesBinaries()
+ */
+public boolean includesBinaries() {
+ return this.includesBinaries;
+}
+/* (non-Javadoc)
+ * @see IJavaSearchScope#includesClasspaths()
+ */
+public boolean includesClasspaths() {
+ return this.includesClasspaths;
+}
+/* (non-Javadoc)
+ * @see IJavaSearchScope#setIncludesBinaries
+ */
+public void setIncludesBinaries(boolean includesBinaries) {
+ this.includesBinaries = includesBinaries;
+}
+/* (non-Javadoc)
+ * @see IJavaSearchScope#setIncludeClasspaths
+ */
+public void setIncludesClasspaths(boolean includesClasspaths) {
+ this.includesClasspaths = includesClasspaths;
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/JavaWorkspaceScope.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/JavaWorkspaceScope.java
index f7cf4eaa20..bcafe45779 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/JavaWorkspaceScope.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/JavaWorkspaceScope.java
@@ -19,12 +19,11 @@ import java.util.*;
* are included.
*/
public class JavaWorkspaceScope extends JavaSearchScope {
- public JavaWorkspaceScope() {
- this.setIncludesBinaries(true);
- IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
- for (int i = 0, length = projects.length; i < length; i++) {
- this.add(projects[i]);
- }
+public JavaWorkspaceScope() {
+ this.setIncludesBinaries(true);
+ IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
+ for (int i = 0, length = projects.length; i < length; i++) {
+ this.add(projects[i]);
}
-
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/PathCollector.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/PathCollector.java
index 5992a9b207..dc213e9b85 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/PathCollector.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/PathCollector.java
@@ -13,161 +13,110 @@ import java.util.*;
* Collects the resource paths reported by a client to this search requestor.
*/
public class PathCollector implements IIndexSearchRequestor {
-
+
/* a set of resource paths */
public Hashtable paths = new Hashtable(5);
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptClassDeclaration(
- String resourcePath,
- char[] simpleTypeName,
- char[][] enclosingTypeNames,
- char[] packageName) {
- this.paths.put(resourcePath, resourcePath);
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptConstructorDeclaration(
- String resourcePath,
- char[] typeName,
- int parameterCount) {
-
- this.paths.put(resourcePath, resourcePath);
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptConstructorReference(
- String resourcePath,
- char[] typeName,
- int parameterCount) {
-
- this.paths.put(resourcePath, resourcePath);
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptFieldDeclaration(String resourcePath, char[] fieldName) {
- this.paths.put(resourcePath, resourcePath);
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptFieldReference(String resourcePath, char[] fieldName) {
-
- this.paths.put(resourcePath, resourcePath);
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptInterfaceDeclaration(
- String resourcePath,
- char[] simpleTypeName,
- char[][] enclosingTypeNames,
- char[] packageName) {
-
- this.paths.put(resourcePath, resourcePath);
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptMethodDeclaration(
- String resourcePath,
- char[] methodName,
- int parameterCount) {
-
- this.paths.put(resourcePath, resourcePath);
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptMethodReference(
- String resourcePath,
- char[] methodName,
- int parameterCount) {
-
- this.paths.put(resourcePath, resourcePath);
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptPackageReference(String resourcePath, char[] packageName) {
-
- this.paths.put(resourcePath, resourcePath);
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptSuperTypeReference(
- String resourcePath,
- char[] qualification,
- char[] typeName,
- char[] enclosingTypeName,
- char classOrInterface,
- char[] superQualification,
- char[] superTypeName,
- char superClassOrInterface,
- int modifiers) {
- this.paths.put(resourcePath, resourcePath);
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptSuperTypeReference(
- String resourcePath,
- char[] qualification,
- char[] typeName,
- char classOrInterface,
- char[] superQualification,
- char[] superTypeName,
- char superClassOrInterface,
- int modifiers) {
- this.paths.put(resourcePath, resourcePath);
- }
-
- /**
- * @see IIndexSearchRequestor
- */
- public void acceptTypeReference(String resourcePath, char[] typeName) {
- this.paths.put(resourcePath, resourcePath);
- }
-
- /**
- * Returns the files that correspond to the paths that have been collected.
- */
- public IFile[] getFiles(IWorkspace workspace) {
- IFile[] result = new IFile[this.paths.size()];
- int i = 0;
- for (Enumeration enum = this.paths.elements(); enum.hasMoreElements();) {
- String resourcePath = (String) enum.nextElement();
- IPath path = new Path(resourcePath);
- result[i++] = workspace.getRoot().getFile(path);
- }
- return result;
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptClassDeclaration(String resourcePath, char[] simpleTypeName, char[][] enclosingTypeNames, char[] packageName) {
+ this.paths.put(resourcePath, resourcePath);
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptConstructorDeclaration(String resourcePath, char[] typeName, int parameterCount) {
+
+ this.paths.put(resourcePath, resourcePath);
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptConstructorReference(String resourcePath, char[] typeName, int parameterCount) {
+
+ this.paths.put(resourcePath, resourcePath);
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptFieldDeclaration(String resourcePath, char[] fieldName) {
+ this.paths.put(resourcePath, resourcePath);
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptFieldReference(String resourcePath, char[] fieldName) {
+
+ this.paths.put(resourcePath, resourcePath);
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptInterfaceDeclaration(String resourcePath, char[] simpleTypeName, char[][] enclosingTypeNames, char[] packageName) {
+
+ this.paths.put(resourcePath, resourcePath);
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptMethodDeclaration(String resourcePath, char[] methodName, int parameterCount) {
+
+ this.paths.put(resourcePath, resourcePath);
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptMethodReference(String resourcePath, char[] methodName, int parameterCount) {
+
+ this.paths.put(resourcePath, resourcePath);
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptPackageReference(String resourcePath, char[] packageName) {
+
+ this.paths.put(resourcePath, resourcePath);
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptSuperTypeReference(String resourcePath, char[] qualification, char[] typeName, char[] enclosingTypeName, char classOrInterface, char[] superQualification, char[] superTypeName, char superClassOrInterface, int modifiers) {
+ this.paths.put(resourcePath, resourcePath);
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptSuperTypeReference(String resourcePath, char[] qualification, char[] typeName, char classOrInterface, char[] superQualification, char[] superTypeName, char superClassOrInterface, int modifiers) {
+ this.paths.put(resourcePath, resourcePath);
+}
+/**
+ * @see IIndexSearchRequestor
+ */
+public void acceptTypeReference(String resourcePath, char[] typeName) {
+ this.paths.put(resourcePath, resourcePath);
+}
+/**
+ * Returns the files that correspond to the paths that have been collected.
+ */
+public IFile[] getFiles(IWorkspace workspace) {
+ IFile[] result = new IFile[this.paths.size()];
+ int i = 0;
+ for (Enumeration enum = this.paths.elements(); enum.hasMoreElements();) {
+ String resourcePath = (String)enum.nextElement();
+ IPath path = new Path(resourcePath);
+ result[i++] = workspace.getRoot().getFile(path);
}
-
- /**
- * Returns the paths that have been collected.
- */
- public String[] getPaths() {
- String[] result = new String[this.paths.size()];
- int i = 0;
- for (Enumeration enum = this.paths.elements(); enum.hasMoreElements();) {
- result[i++] = (String) enum.nextElement();
- }
- return result;
+ return result;
+}
+/**
+ * Returns the paths that have been collected.
+ */
+public String[] getPaths() {
+ String[] result = new String[this.paths.size()];
+ int i = 0;
+ for (Enumeration enum = this.paths.elements(); enum.hasMoreElements();) {
+ result[i++] = (String)enum.nextElement();
}
-
+ return result;
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/PatternSearchJob.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/PatternSearchJob.java
index e8f77c488c..3c9d79f192 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/PatternSearchJob.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/PatternSearchJob.java
@@ -28,119 +28,94 @@ public class PatternSearchJob implements IJob, IJobConstants {
protected IndexSelector indexSelector;
protected long executionTime = 0;
- public PatternSearchJob(
- SearchPattern pattern,
- IJavaSearchScope scope,
- int detailLevel,
- IIndexSearchRequestor requestor,
- IndexManager indexManager,
- IProgressMonitor progressMonitor) {
-
- this(
- pattern,
- scope,
- null,
- detailLevel,
- requestor,
- indexManager,
- progressMonitor);
- }
-
- public PatternSearchJob(
- SearchPattern pattern,
- IJavaSearchScope scope,
- IJavaElement focus,
- int detailLevel,
- IIndexSearchRequestor requestor,
- IndexManager indexManager,
- IProgressMonitor progressMonitor) {
+public PatternSearchJob(
+ SearchPattern pattern,
+ IJavaSearchScope scope,
+ int detailLevel,
+ IIndexSearchRequestor requestor,
+ IndexManager indexManager,
+ IProgressMonitor progressMonitor) {
+
+ this(pattern, scope, null, detailLevel, requestor, indexManager, progressMonitor);
+}
+public PatternSearchJob(
+ SearchPattern pattern,
+ IJavaSearchScope scope,
+ IJavaElement focus,
+ int detailLevel,
+ IIndexSearchRequestor requestor,
+ IndexManager indexManager,
+ IProgressMonitor progressMonitor) {
+
+ this.pattern = pattern;
+ this.scope = scope;
+ this.focus = focus;
+ this.detailLevel = detailLevel;
+ this.requestor = requestor;
+ this.indexManager = indexManager;
+ this.progressMonitor = progressMonitor;
+}
+public boolean belongsTo(String jobFamily){
+ return true;
+}
+/**
+ * execute method comment.
+ */
+public boolean execute() {
- this.pattern = pattern;
- this.scope = scope;
- this.focus = focus;
- this.detailLevel = detailLevel;
- this.requestor = requestor;
- this.indexManager = indexManager;
- this.progressMonitor = progressMonitor;
+ if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException();
+ boolean isComplete = COMPLETE;
+ executionTime = 0;
+ if (this.indexSelector == null) {
+ this.indexSelector = new IndexSelector(this.scope, this.focus, this.indexManager);
}
-
- public boolean belongsTo(String jobFamily) {
- return true;
+ IIndex[] searchIndexes = this.indexSelector.getIndexes();
+ for (int i = 0, max = searchIndexes.length; i < max; i++){
+ isComplete &= search(searchIndexes[i]);
}
-
- /**
- * execute method comment.
- */
- public boolean execute() {
-
- if (progressMonitor != null && progressMonitor.isCanceled())
- throw new OperationCanceledException();
- boolean isComplete = COMPLETE;
- executionTime = 0;
- if (this.indexSelector == null) {
- this.indexSelector =
- new IndexSelector(this.scope, this.focus, this.indexManager);
- }
- IIndex[] searchIndexes = this.indexSelector.getIndexes();
- for (int i = 0, max = searchIndexes.length; i < max; i++) {
- isComplete &= search(searchIndexes[i]);
- }
- if (JobManager.VERBOSE) {
- System.out.println(
- "-> execution time: " + executionTime + " ms. for : " + this);
- }
- return isComplete;
+ if (JobManager.VERBOSE){
+ System.out.println("-> execution time: " + executionTime + " ms. for : "+this);
}
-
- /**
- * execute method comment.
- */
- public boolean search(IIndex index) {
-
- if (progressMonitor != null && progressMonitor.isCanceled())
- throw new OperationCanceledException();
-
- if (index == null)
- return COMPLETE;
- ReadWriteMonitor monitor = indexManager.getMonitorFor(index);
- if (monitor == null)
- return COMPLETE; // index got deleted since acquired
- try {
- monitor.enterRead(); // ask permission to read
-
- /* if index has changed, commit these before querying */
- if (index.hasChanged()) {
- try {
- monitor.exitRead(); // free read lock
- monitor.enterWrite(); // ask permission to write
- if (IndexManager.VERBOSE)
- System.out.println("-> merging index : " + index.getIndexFile());
- index.save();
- } catch (IOException e) {
- return FAILED;
- } finally {
- monitor.exitWrite(); // finished writing
- monitor.enterRead(); // reaquire read permission
- }
+ return isComplete;
+}
+/**
+ * execute method comment.
+ */
+public boolean search(IIndex index) {
+
+ if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException();
+
+ if (index == null) return COMPLETE;
+ ReadWriteMonitor monitor = indexManager.getMonitorFor(index);
+ if (monitor == null) return COMPLETE; // index got deleted since acquired
+ try {
+ monitor.enterRead(); // ask permission to read
+
+ /* if index has changed, commit these before querying */
+ if (index.hasChanged()){
+ try {
+ monitor.exitRead(); // free read lock
+ monitor.enterWrite(); // ask permission to write
+ if (IndexManager.VERBOSE) System.out.println("-> merging index : "+index.getIndexFile());
+ index.save();
+ } catch(IOException e){
+ return FAILED;
+ } finally {
+ monitor.exitWrite(); // finished writing
+ monitor.enterRead(); // reaquire read permission
}
- long start = System.currentTimeMillis();
- pattern.findIndexMatches(
- index,
- requestor,
- detailLevel,
- progressMonitor,
- this.scope);
- executionTime += System.currentTimeMillis() - start;
- return COMPLETE;
- } catch (IOException e) {
- return FAILED;
- } finally {
- monitor.exitRead(); // finished reading
}
+ long start = System.currentTimeMillis();
+ pattern.findIndexMatches(index, requestor, detailLevel, progressMonitor, this.scope);
+ executionTime += System.currentTimeMillis() - start;
+ return COMPLETE;
+ } catch(IOException e){
+ return FAILED;
+ } finally {
+ monitor.exitRead(); // finished reading
}
-
- public String toString() {
- return "searching " + pattern.toString();
- }
-
+}
+public String toString(){
+ return "searching " + pattern.toString();
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/SubTypeSearchJob.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/SubTypeSearchJob.java
index 0add16cda9..28ded259d9 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/SubTypeSearchJob.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/SubTypeSearchJob.java
@@ -21,99 +21,66 @@ import java.util.*;
public class SubTypeSearchJob extends PatternSearchJob {
Hashtable inputs = new Hashtable(5);
- public SubTypeSearchJob(
- SearchPattern pattern,
- IJavaSearchScope scope,
- int detailLevel,
- IIndexSearchRequestor requestor,
- IndexManager indexManager,
- IProgressMonitor progressMonitor) {
- super(pattern, scope, detailLevel, requestor, indexManager, progressMonitor);
- }
-
- public SubTypeSearchJob(
- SearchPattern pattern,
- IJavaSearchScope scope,
- IJavaElement focus,
- int detailLevel,
- IIndexSearchRequestor requestor,
- org.eclipse.jdt.internal.core.search.indexing.IndexManager indexManager,
- IProgressMonitor progressMonitor) {
- super(
- pattern,
- scope,
- focus,
- detailLevel,
- requestor,
- indexManager,
- progressMonitor);
- }
-
- public void closeAll() {
+public SubTypeSearchJob(SearchPattern pattern, IJavaSearchScope scope, int detailLevel, IIndexSearchRequestor requestor, IndexManager indexManager, IProgressMonitor progressMonitor) {
+ super(pattern, scope, detailLevel, requestor, indexManager, progressMonitor);
+}
+public SubTypeSearchJob(SearchPattern pattern, IJavaSearchScope scope, IJavaElement focus, int detailLevel, IIndexSearchRequestor requestor, org.eclipse.jdt.internal.core.search.indexing.IndexManager indexManager, IProgressMonitor progressMonitor) {
+ super(pattern, scope, focus, detailLevel, requestor, indexManager, progressMonitor);
+}
+public void closeAll(){
- Enumeration openedInputs = inputs.elements();
- while (openedInputs.hasMoreElements()) {
- IndexInput input = (IndexInput) openedInputs.nextElement();
- try {
- input.close();
- } catch (IOException e) {
- }
+ Enumeration openedInputs = inputs.elements();
+ while (openedInputs.hasMoreElements()){
+ IndexInput input = (IndexInput) openedInputs.nextElement();
+ try {
+ input.close();
+ } catch(IOException e){
}
}
+}
+/**
+ * execute method comment.
+ */
+public boolean search(IIndex index) {
- /**
- * execute method comment.
- */
- public boolean search(IIndex index) {
+ if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException();
- if (progressMonitor != null && progressMonitor.isCanceled())
- throw new OperationCanceledException();
+ if (index == null) return COMPLETE;
+ ReadWriteMonitor monitor = indexManager.getMonitorFor(index);
+ if (monitor == null) return COMPLETE; // index got deleted since acquired
+ try {
+ monitor.enterRead(); // ask permission to read
- if (index == null)
- return COMPLETE;
- ReadWriteMonitor monitor = indexManager.getMonitorFor(index);
- if (monitor == null)
- return COMPLETE; // index got deleted since acquired
- try {
- monitor.enterRead(); // ask permission to read
-
- /* if index has changed, commit these before querying */
- if (index.hasChanged()) {
- try {
- monitor.exitRead(); // free read lock
- monitor.enterWrite(); // ask permission to write
- if (IndexManager.VERBOSE)
- System.out.println("-> merging index : " + index.getIndexFile());
- index.save();
- } catch (IOException e) {
- return FAILED;
- } finally {
- monitor.exitWrite(); // finished writing
- monitor.enterRead(); // reaquire read permission
- }
+ /* if index has changed, commit these before querying */
+ if (index.hasChanged()){
+ try {
+ monitor.exitRead(); // free read lock
+ monitor.enterWrite(); // ask permission to write
+ if (IndexManager.VERBOSE) System.out.println("-> merging index : "+index.getIndexFile());
+ index.save();
+ } catch(IOException e){
+ return FAILED;
+ } finally {
+ monitor.exitWrite(); // finished writing
+ monitor.enterRead(); // reaquire read permission
}
- long start = System.currentTimeMillis();
+ }
+ long start = System.currentTimeMillis();
- IndexInput input;
- if ((input = (IndexInput) inputs.get(index)) == null) {
- input = new BlocksIndexInput(index.getIndexFile());
- input.open();
- inputs.put(index, input);
- //System.out.println("Acquiring INPUT for "+index);
- }
- pattern.findIndexMatches(
- input,
- requestor,
- detailLevel,
- progressMonitor,
- this.scope);
- executionTime += System.currentTimeMillis() - start;
- return COMPLETE;
- } catch (IOException e) {
- return FAILED;
- } finally {
- monitor.exitRead(); // finished reading
+ IndexInput input;
+ if ((input = (IndexInput) inputs.get(index)) == null){
+ input = new BlocksIndexInput(index.getIndexFile());
+ input.open();
+ inputs.put(index, input);
+ //System.out.println("Acquiring INPUT for "+index);
}
+ pattern.findIndexMatches(input, requestor, detailLevel, progressMonitor, this.scope);
+ executionTime += System.currentTimeMillis() - start;
+ return COMPLETE;
+ } catch(IOException e){
+ return FAILED;
+ } finally {
+ monitor.exitRead(); // finished reading
}
-
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AbstractIndexer.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AbstractIndexer.java
index 1bd8cb7f7c..78e87e7546 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AbstractIndexer.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AbstractIndexer.java
@@ -8,759 +8,566 @@ import org.eclipse.jdt.internal.core.index.*;
import org.eclipse.jdt.core.search.*;
import org.eclipse.jdt.internal.compiler.util.*;
-
+
import java.io.*;
-public abstract class AbstractIndexer
- implements IIndexer, IIndexConstants, IJavaSearchConstants {
+public abstract class AbstractIndexer implements IIndexer, IIndexConstants, IJavaSearchConstants {
IIndexerOutput output;
- /**
- * AbstractIndexer constructor comment.
- */
- public AbstractIndexer() {
- super();
- }
-
- public void addClassDeclaration(
- int modifiers,
- char[] packageName,
- char[] name,
- char[][] enclosingTypeNames,
- char[] superclass,
- char[][] superinterfaces) {
-
- this.output.addRef(
- encodeTypeEntry(packageName, enclosingTypeNames, name, true));
-
- addSuperTypeReference(
- modifiers,
- packageName,
- name,
- enclosingTypeNames,
- CLASS_SUFFIX,
- superclass,
- CLASS_SUFFIX);
- if (superinterfaces != null) {
- for (int i = 0, max = superinterfaces.length; i < max; i++) {
- addSuperTypeReference(
- modifiers,
- packageName,
- name,
- enclosingTypeNames,
- CLASS_SUFFIX,
- superinterfaces[i],
- INTERFACE_SUFFIX);
- }
+/**
+ * AbstractIndexer constructor comment.
+ */
+public AbstractIndexer() {
+ super();
+}
+public void addClassDeclaration(int modifiers, char[] packageName,char[] name, char[][] enclosingTypeNames, char[] superclass, char[][] superinterfaces){
+
+ this.output.addRef(encodeTypeEntry(packageName, enclosingTypeNames, name, true));
+
+ addSuperTypeReference(modifiers, packageName, name, enclosingTypeNames, CLASS_SUFFIX, superclass, CLASS_SUFFIX);
+ if (superinterfaces != null){
+ for (int i = 0, max = superinterfaces.length; i < max; i++){
+ addSuperTypeReference(modifiers, packageName, name, enclosingTypeNames, CLASS_SUFFIX, superinterfaces[i], INTERFACE_SUFFIX);
}
-
}
-
- public void addConstructorDeclaration(
- char[] typeName,
- char[][] parameterTypes,
- char[][] exceptionTypes) {
- // Calculate the number of arguments of the constructor
- int numberOfArguments = 0;
- if (parameterTypes != null) {
- numberOfArguments = parameterTypes.length;
- for (int i = 0; i < numberOfArguments; i++) {
- this.addTypeReference(parameterTypes[i]);
- }
- }
- //convert the number of arguments into a char array
- char[] countChars;
- if (numberOfArguments < 10) {
- countChars = COUNTS[numberOfArguments];
- } else {
- countChars = String.valueOf(numberOfArguments).toCharArray();
- }
- //add the reference
- this.output.addRef(
- concat(
- CONSTRUCTOR_DECL,
- CharOperation.lastSegment(typeName, '.'),
- countChars,
- SEPARATOR));
-
- if (exceptionTypes != null) {
- for (int i = 0, max = exceptionTypes.length; i < max; i++) {
- this.addTypeReference(exceptionTypes[i]);
- }
+
+}
+public void addConstructorDeclaration(char[] typeName, char[][] parameterTypes, char[][] exceptionTypes){
+ // Calculate the number of arguments of the constructor
+ int numberOfArguments = 0;
+ if (parameterTypes != null){
+ numberOfArguments = parameterTypes.length;
+ for (int i = 0; i < numberOfArguments; i++){
+ this.addTypeReference(parameterTypes[i]);
}
}
-
- public void addConstructorReference(char[] typeName, int argCount) {
-
- char[] countChars;
- if (argCount < 10) {
- countChars = COUNTS[argCount];
- } else {
- countChars = String.valueOf(argCount).toCharArray();
- }
- this.output.addRef(
- concat(
- CONSTRUCTOR_REF,
- CharOperation.lastSegment(typeName, '.'),
- countChars,
- SEPARATOR));
-
+ //convert the number of arguments into a char array
+ char[] countChars;
+ if (numberOfArguments < 10) {
+ countChars = COUNTS[numberOfArguments];
+ } else {
+ countChars = String.valueOf(numberOfArguments).toCharArray();
}
+ //add the reference
+ this.output.addRef(concat(CONSTRUCTOR_DECL, CharOperation.lastSegment(typeName,'.'), countChars, SEPARATOR));
- public void addFieldDeclaration(char[] typeName, char[] fieldName) {
- this.output.addRef(CharOperation.concat(FIELD_DECL, fieldName));
- this.addTypeReference(typeName);
+ if (exceptionTypes != null){
+ for (int i = 0, max = exceptionTypes.length; i < max; i++){
+ this.addTypeReference(exceptionTypes[i]);
+ }
}
+}
+public void addConstructorReference(char[] typeName, int argCount){
- public void addFieldReference(char[] fieldName) {
- this.output.addRef(CharOperation.concat(FIELD_REF, fieldName));
+ char[] countChars;
+ if (argCount < 10) {
+ countChars = COUNTS[argCount];
+ } else {
+ countChars = String.valueOf(argCount).toCharArray();
}
+ this.output.addRef(concat(CONSTRUCTOR_REF, CharOperation.lastSegment(typeName, '.'), countChars, SEPARATOR));
+
+}
+public void addFieldDeclaration(char[] typeName, char[] fieldName){
+ this.output.addRef(CharOperation.concat(FIELD_DECL, fieldName));
+ this.addTypeReference(typeName);
+}
+public void addFieldReference(char[] fieldName){
+ this.output.addRef(CharOperation.concat(FIELD_REF, fieldName));
+}
+public void addInterfaceDeclaration(int modifiers, char[] packageName, char[] name, char[][] enclosingTypeNames, char[][] superinterfaces){
- public void addInterfaceDeclaration(
- int modifiers,
- char[] packageName,
- char[] name,
- char[][] enclosingTypeNames,
- char[][] superinterfaces) {
-
- this.output.addRef(
- encodeTypeEntry(packageName, enclosingTypeNames, name, false));
-
- if (superinterfaces != null) {
- for (int i = 0, max = superinterfaces.length; i < max; i++) {
- addSuperTypeReference(
- modifiers,
- packageName,
- name,
- enclosingTypeNames,
- INTERFACE_SUFFIX,
- superinterfaces[i],
- INTERFACE_SUFFIX);
- }
+ this.output.addRef(encodeTypeEntry(packageName, enclosingTypeNames, name, false));
+
+ if (superinterfaces != null){
+ for (int i = 0, max = superinterfaces.length; i < max; i++){
+ addSuperTypeReference(modifiers, packageName, name, enclosingTypeNames, INTERFACE_SUFFIX, superinterfaces[i], INTERFACE_SUFFIX);
}
- /* if willing to connect interfaces to Object as a supertype, then uncomment the following
- else {
- addSuperTypeReference(modifiers, packageName, name, INTERFACE_SUFFIX, null, CLASS_SUFFIX); // extends Object by default
- }
- */
}
-
- public void addMethodDeclaration(
- char[] methodName,
- char[][] parameterTypes,
- char[] returnType,
- char[][] exceptionTypes) {
- // Calculate the number of arguments of the method
- int numberOfArguments = 0;
- if (parameterTypes != null) {
- numberOfArguments = parameterTypes.length;
- for (int i = 0; i < numberOfArguments; i++) {
- this.addTypeReference(parameterTypes[i]);
- }
- }
- //convert the number of arguments into a char array
- char[] countChars;
- if (numberOfArguments < 10) {
- countChars = COUNTS[numberOfArguments];
- } else {
- countChars = String.valueOf(numberOfArguments).toCharArray();
- }
- //add the reference
- this.output.addRef(concat(METHOD_DECL, methodName, countChars, SEPARATOR));
-
- if (exceptionTypes != null) {
- for (int i = 0, max = exceptionTypes.length; i < max; i++) {
- this.addTypeReference(exceptionTypes[i]);
- }
- }
- if (returnType != null)
- this.addTypeReference(returnType);
+ /* if willing to connect interfaces to Object as a supertype, then uncomment the following
+ else {
+ addSuperTypeReference(modifiers, packageName, name, INTERFACE_SUFFIX, null, CLASS_SUFFIX); // extends Object by default
}
-
- public void addMethodReference(char[] methodName, int argCount) {
- char[] countChars;
- if (argCount < 10) {
- countChars = COUNTS[argCount];
- } else {
- countChars = String.valueOf(argCount).toCharArray();
+ */
+}
+public void addMethodDeclaration(char[] methodName, char[][] parameterTypes, char[] returnType, char[][] exceptionTypes){
+ // Calculate the number of arguments of the method
+ int numberOfArguments = 0;
+ if (parameterTypes != null){
+ numberOfArguments = parameterTypes.length;
+ for (int i = 0; i < numberOfArguments; i++){
+ this.addTypeReference(parameterTypes[i]);
}
- this.output.addRef(concat(METHOD_REF, methodName, countChars, SEPARATOR));
-
}
-
- public void addNameReference(char[] name) {
- this.output.addRef(CharOperation.concat(REF, name));
+ //convert the number of arguments into a char array
+ char[] countChars;
+ if (numberOfArguments < 10) {
+ countChars = COUNTS[numberOfArguments];
+ } else {
+ countChars = String.valueOf(numberOfArguments).toCharArray();
}
+ //add the reference
+ this.output.addRef(concat(METHOD_DECL, methodName, countChars, SEPARATOR));
- private void addSuperTypeReference(
- int modifiers,
- char[] packageName,
- char[] typeName,
- char[][] enclosingTypeNames,
- char classOrInterface,
- char[] superTypeName,
- char superClassOrInterface) {
-
- if (superTypeName == null)
- superTypeName = OBJECT;
-
- char[] enclosingTypeName = CharOperation.concatWith(enclosingTypeNames, '$');
- char[] typeSimpleName = CharOperation.lastSegment(typeName, '.');
- char[] superTypeSimpleName = CharOperation.lastSegment(superTypeName, '.');
- char[] superQualification;
- if (superTypeSimpleName == superTypeName) {
- superQualification = null;
- } else {
- int length = superTypeName.length - superTypeSimpleName.length - 1;
- System.arraycopy(
- superTypeName,
- 0,
- superQualification = new char[length],
- 0,
- length);
+ if (exceptionTypes != null){
+ for (int i = 0, max = exceptionTypes.length; i < max; i++){
+ this.addTypeReference(exceptionTypes[i]);
}
- // if the supertype name contains a $, then split it into: source name and append the $ prefix to the qualification
- // e.g. p.A$B ---> p.A$ + B
- char[] superTypeSourceName =
- CharOperation.lastSegment(superTypeSimpleName, '$');
- if (superTypeSourceName != superTypeSimpleName) {
- int start = superQualification == null ? 0 : superQualification.length + 1;
- int prefixLength = superTypeSimpleName.length - superTypeSourceName.length;
- char[] mangledQualification = new char[start + prefixLength];
- if (superQualification != null) {
- System.arraycopy(superQualification, 0, mangledQualification, 0, start - 1);
- mangledQualification[start - 1] = '.';
- }
- System.arraycopy(
- superTypeSimpleName,
- 0,
- mangledQualification,
- start,
- prefixLength);
- superQualification = mangledQualification;
- superTypeSimpleName = superTypeSourceName;
- }
- this.output.addRef(
- concat(
- SUPER_REF,
- superTypeSimpleName,
- superQualification,
- superClassOrInterface,
- typeSimpleName,
- enclosingTypeName,
- packageName,
- classOrInterface,
- (char) modifiers,
- SEPARATOR));
}
-
- public void addTypeReference(char[] typeName) {
-
- this.output.addRef(
- CharOperation.concat(TYPE_REF, CharOperation.lastSegment(typeName, '.')));
+ if (returnType != null) this.addTypeReference(returnType);
+}
+public void addMethodReference(char[] methodName, int argCount){
+ char[] countChars;
+ if (argCount < 10) {
+ countChars = COUNTS[argCount];
+ } else {
+ countChars = String.valueOf(argCount).toCharArray();
}
-
- /**
- * Constructor declaration entries are encoded as follow: 'constructorDecl/' TypeName '/' Arity
- * e.g. constructorDecl/X/0
- * constructorDecl/Y/1
- *
- */
- public static final char[] bestConstructorDeclarationPrefix(
- char[] typeName,
- int arity,
- int matchMode,
- boolean isCaseSensitive) {
-
- if (!isCaseSensitive || typeName == null)
- return CONSTRUCTOR_DECL;
- switch (matchMode) {
- case EXACT_MATCH :
- if (arity >= 0) {
- char[] countChars;
- if (arity < 10) {
- countChars = COUNTS[arity];
- } else {
- countChars = String.valueOf(arity).toCharArray();
- }
- return concat(CONSTRUCTOR_DECL, typeName, countChars, SEPARATOR);
- }
- case PREFIX_MATCH :
- return CharOperation.concat(CONSTRUCTOR_DECL, typeName);
- case PATTERN_MATCH :
- int starPos = CharOperation.indexOf('*', typeName);
- switch (starPos) {
- case -1 :
- return CharOperation.concat(CONSTRUCTOR_DECL, typeName);
- default :
- int refLength = CONSTRUCTOR_DECL.length;
- char[] result = new char[refLength + starPos];
- System.arraycopy(CONSTRUCTOR_DECL, 0, result, 0, refLength);
- System.arraycopy(typeName, 0, result, refLength, starPos);
- return result;
- case 0 : // fall through
- }
- default :
- return CONSTRUCTOR_DECL;
- }
+ this.output.addRef(concat(METHOD_REF, methodName, countChars, SEPARATOR));
+
+}
+public void addNameReference(char[] name){
+ this.output.addRef(CharOperation.concat(REF, name));
+}
+private void addSuperTypeReference(int modifiers, char[] packageName, char[] typeName, char[][] enclosingTypeNames, char classOrInterface, char[] superTypeName, char superClassOrInterface){
+
+ if (superTypeName == null) superTypeName = OBJECT;
+
+ char[] enclosingTypeName = CharOperation.concatWith(enclosingTypeNames, '$');
+ char[] typeSimpleName = CharOperation.lastSegment(typeName, '.');
+ char[] superTypeSimpleName = CharOperation.lastSegment(superTypeName, '.');
+ char[] superQualification;
+ if (superTypeSimpleName == superTypeName){
+ superQualification = null;
+ } else {
+ int length = superTypeName.length - superTypeSimpleName.length - 1;
+ System.arraycopy(superTypeName, 0, superQualification = new char[length], 0, length);
}
-
- /**
- * Constructor reference entries are encoded as follow: 'constructorRef/' TypeName '/' Arity
- * e.g. constructorRef/X/0
- * constructorRef/Y/1
- *
- */
- public static final char[] bestConstructorReferencePrefix(
- char[] typeName,
- int arity,
- int matchMode,
- boolean isCaseSensitive) {
-
- if (!isCaseSensitive || typeName == null)
- return CONSTRUCTOR_REF;
- switch (matchMode) {
- case EXACT_MATCH :
- if (arity >= 0) {
- char[] countChars;
- if (arity < 10) {
- countChars = COUNTS[arity];
- } else {
- countChars = String.valueOf(arity).toCharArray();
- }
- return concat(CONSTRUCTOR_REF, typeName, countChars, SEPARATOR);
- }
- case PREFIX_MATCH :
- return CharOperation.concat(CONSTRUCTOR_REF, typeName);
- case PATTERN_MATCH :
- int starPos = CharOperation.indexOf('*', typeName);
- switch (starPos) {
- case -1 :
- return CharOperation.concat(CONSTRUCTOR_REF, typeName);
- default :
- int refLength = CONSTRUCTOR_REF.length;
- char[] result = new char[refLength + starPos];
- System.arraycopy(CONSTRUCTOR_REF, 0, result, 0, refLength);
- System.arraycopy(typeName, 0, result, refLength, starPos);
- return result;
- case 0 : // fall through
- }
- default :
- return CONSTRUCTOR_REF;
+ // if the supertype name contains a $, then split it into: source name and append the $ prefix to the qualification
+ // e.g. p.A$B ---> p.A$ + B
+ char[] superTypeSourceName = CharOperation.lastSegment(superTypeSimpleName, '$');
+ if (superTypeSourceName != superTypeSimpleName){
+ int start = superQualification == null ? 0 : superQualification.length+1;
+ int prefixLength = superTypeSimpleName.length - superTypeSourceName.length;
+ char[] mangledQualification = new char[start + prefixLength];
+ if (superQualification != null){
+ System.arraycopy(superQualification, 0, mangledQualification, 0, start-1);
+ mangledQualification[start-1] = '.';
}
- }
-
- /**
- * Method declaration entries are encoded as follow: 'fieldDecl/' Name
- * e.g. fieldDecl/x
- *
- */
- public static final char[] bestFieldDeclarationPrefix(
- char[] name,
- int matchMode,
- boolean isCaseSensitive) {
+ System.arraycopy(superTypeSimpleName, 0, mangledQualification, start, prefixLength);
+ superQualification = mangledQualification;
+ superTypeSimpleName = superTypeSourceName;
+ }
+ this.output.addRef(concat(SUPER_REF, superTypeSimpleName, superQualification, superClassOrInterface, typeSimpleName, enclosingTypeName, packageName, classOrInterface, (char)modifiers, SEPARATOR));
+}
+public void addTypeReference(char[] typeName){
- if (!isCaseSensitive || name == null)
- return FIELD_DECL;
- switch (matchMode) {
- case EXACT_MATCH :
- case PREFIX_MATCH :
- return CharOperation.concat(FIELD_DECL, name);
- case PATTERN_MATCH :
- int starPos = CharOperation.indexOf('*', name);
- switch (starPos) {
- case -1 :
- return CharOperation.concat(FIELD_DECL, name);
- default :
- int refLength = FIELD_DECL.length;
- char[] result = new char[refLength + starPos];
- System.arraycopy(FIELD_DECL, 0, result, 0, refLength);
- System.arraycopy(name, 0, result, refLength, starPos);
- return result;
- case 0 : // fall through
+ this.output.addRef(CharOperation.concat(TYPE_REF, CharOperation.lastSegment(typeName, '.')));
+}
+/**
+ * Constructor declaration entries are encoded as follow: 'constructorDecl/' TypeName '/' Arity
+ * e.g. constructorDecl/X/0
+ * constructorDecl/Y/1
+ *
+ */
+ public static final char[] bestConstructorDeclarationPrefix(char[] typeName, int arity, int matchMode, boolean isCaseSensitive) {
+
+ if (!isCaseSensitive || typeName == null) return CONSTRUCTOR_DECL;
+ switch(matchMode){
+ case EXACT_MATCH :
+ if (arity >= 0){
+ char[] countChars;
+ if (arity < 10) {
+ countChars = COUNTS[arity];
+ } else {
+ countChars = String.valueOf(arity).toCharArray();
}
- default :
- return FIELD_DECL;
- }
+ return concat(CONSTRUCTOR_DECL, typeName, countChars, SEPARATOR);
+ }
+ case PREFIX_MATCH :
+ return CharOperation.concat(CONSTRUCTOR_DECL, typeName);
+ case PATTERN_MATCH :
+ int starPos = CharOperation.indexOf('*', typeName);
+ switch(starPos) {
+ case -1 :
+ return CharOperation.concat(CONSTRUCTOR_DECL, typeName);
+ default :
+ int refLength = CONSTRUCTOR_DECL.length;
+ char[] result = new char[refLength+starPos];
+ System.arraycopy(CONSTRUCTOR_DECL, 0, result, 0, refLength);
+ System.arraycopy(typeName, 0, result, refLength, starPos);
+ return result;
+ case 0 : // fall through
+ }
+ default:
+ return CONSTRUCTOR_DECL;
}
-
- /**
- * Method declaration entries are encoded as follow: 'methodDecl/' Selector '/' Arity
- * e.g. methodDecl/clone/0
- * methodDecl/append/1
- *
- */
- public static final char[] bestMethodDeclarationPrefix(
- char[] selector,
- int arity,
- int matchMode,
- boolean isCaseSensitive) {
-
- if (!isCaseSensitive || selector == null)
- return METHOD_DECL;
- switch (matchMode) {
- case EXACT_MATCH :
- if (arity >= 0) {
- char[] countChars;
- if (arity < 10) {
- countChars = COUNTS[arity];
- } else {
- countChars = String.valueOf(arity).toCharArray();
- }
- return concat(METHOD_DECL, selector, countChars, SEPARATOR);
- }
- case PREFIX_MATCH :
- return CharOperation.concat(METHOD_DECL, selector);
- case PATTERN_MATCH :
- int starPos = CharOperation.indexOf('*', selector);
- switch (starPos) {
- case -1 :
- return CharOperation.concat(METHOD_DECL, selector);
- default :
- int refLength = METHOD_DECL.length;
- char[] result = new char[refLength + starPos];
- System.arraycopy(METHOD_DECL, 0, result, 0, refLength);
- System.arraycopy(selector, 0, result, refLength, starPos);
- return result;
- case 0 : // fall through
+}
+/**
+ * Constructor reference entries are encoded as follow: 'constructorRef/' TypeName '/' Arity
+ * e.g. constructorRef/X/0
+ * constructorRef/Y/1
+ *
+ */
+ public static final char[] bestConstructorReferencePrefix(char[] typeName, int arity, int matchMode, boolean isCaseSensitive) {
+
+ if (!isCaseSensitive || typeName == null) return CONSTRUCTOR_REF;
+ switch(matchMode){
+ case EXACT_MATCH :
+ if (arity >= 0){
+ char[] countChars;
+ if (arity < 10) {
+ countChars = COUNTS[arity];
+ } else {
+ countChars = String.valueOf(arity).toCharArray();
}
- default :
- return METHOD_DECL;
- }
+ return concat(CONSTRUCTOR_REF, typeName, countChars, SEPARATOR);
+ }
+ case PREFIX_MATCH :
+ return CharOperation.concat(CONSTRUCTOR_REF, typeName);
+ case PATTERN_MATCH :
+ int starPos = CharOperation.indexOf('*', typeName);
+ switch(starPos) {
+ case -1 :
+ return CharOperation.concat(CONSTRUCTOR_REF, typeName);
+ default :
+ int refLength = CONSTRUCTOR_REF.length;
+ char[] result = new char[refLength+starPos];
+ System.arraycopy(CONSTRUCTOR_REF, 0, result, 0, refLength);
+ System.arraycopy(typeName, 0, result, refLength, starPos);
+ return result;
+ case 0 : // fall through
+ }
+ default:
+ return CONSTRUCTOR_REF;
}
-
- /**
- * Method reference entries are encoded as follow: 'methodRef/' Selector '/' Arity
- * e.g. methodRef/clone/0
- * methodRef/append/1
- *
- */
- public static final char[] bestMethodReferencePrefix(
- char[] selector,
- int arity,
- int matchMode,
- boolean isCaseSensitive) {
-
- if (!isCaseSensitive || selector == null)
- return METHOD_REF;
- switch (matchMode) {
- case EXACT_MATCH :
- if (arity >= 0) {
- char[] countChars;
- if (arity < 10) {
- countChars = COUNTS[arity];
- } else {
- countChars = String.valueOf(arity).toCharArray();
- }
- return concat(METHOD_REF, selector, countChars, SEPARATOR);
- }
- case PREFIX_MATCH :
- return CharOperation.concat(METHOD_REF, selector);
- case PATTERN_MATCH :
- int starPos = CharOperation.indexOf('*', selector);
- switch (starPos) {
- case -1 :
- return CharOperation.concat(METHOD_REF, selector);
- default :
- int refLength = METHOD_REF.length;
- char[] result = new char[refLength + starPos];
- System.arraycopy(METHOD_REF, 0, result, 0, refLength);
- System.arraycopy(selector, 0, result, refLength, starPos);
- return result;
- case 0 : // fall through
- }
- default :
- return METHOD_REF;
- }
+}
+/**
+ * Method declaration entries are encoded as follow: 'fieldDecl/' Name
+ * e.g. fieldDecl/x
+ *
+ */
+ public static final char[] bestFieldDeclarationPrefix(char[] name, int matchMode, boolean isCaseSensitive) {
+
+ if (!isCaseSensitive || name == null) return FIELD_DECL;
+ switch(matchMode){
+ case EXACT_MATCH :
+ case PREFIX_MATCH :
+ return CharOperation.concat(FIELD_DECL, name);
+ case PATTERN_MATCH :
+ int starPos = CharOperation.indexOf('*', name);
+ switch(starPos) {
+ case -1 :
+ return CharOperation.concat(FIELD_DECL, name);
+ default :
+ int refLength = FIELD_DECL.length;
+ char[] result = new char[refLength+starPos];
+ System.arraycopy(FIELD_DECL, 0, result, 0, refLength);
+ System.arraycopy(name, 0, result, refLength, starPos);
+ return result;
+ case 0 : // fall through
+ }
+ default:
+ return FIELD_DECL;
}
-
- /**
- * Type entries are encoded as follow: '<tag>/' Name
- * e.g. ref/Object
- * ref/x
- */
- public static final char[] bestReferencePrefix(
- char[] tag,
- char[] name,
- int matchMode,
- boolean isCaseSensitive) {
-
- if (!isCaseSensitive || name == null)
- return tag;
- switch (matchMode) {
- case EXACT_MATCH :
- case PREFIX_MATCH :
- return CharOperation.concat(tag, name);
- case PATTERN_MATCH :
- int starPos = CharOperation.indexOf('*', name);
- switch (starPos) {
- case -1 :
- return CharOperation.concat(tag, name);
- default :
- int refLength = tag.length;
- char[] result = new char[refLength + starPos];
- System.arraycopy(tag, 0, result, 0, refLength);
- System.arraycopy(name, 0, result, refLength, starPos);
- return result;
- case 0 : // fall through
+}
+/**
+ * Method declaration entries are encoded as follow: 'methodDecl/' Selector '/' Arity
+ * e.g. methodDecl/clone/0
+ * methodDecl/append/1
+ *
+ */
+ public static final char[] bestMethodDeclarationPrefix(char[] selector, int arity, int matchMode, boolean isCaseSensitive) {
+
+ if (!isCaseSensitive || selector == null) return METHOD_DECL;
+ switch(matchMode){
+ case EXACT_MATCH :
+ if (arity >= 0){
+ char[] countChars;
+ if (arity < 10) {
+ countChars = COUNTS[arity];
+ } else {
+ countChars = String.valueOf(arity).toCharArray();
}
- default :
- return tag;
- }
+ return concat(METHOD_DECL, selector, countChars, SEPARATOR);
+ }
+ case PREFIX_MATCH :
+ return CharOperation.concat(METHOD_DECL, selector);
+ case PATTERN_MATCH :
+ int starPos = CharOperation.indexOf('*', selector);
+ switch(starPos) {
+ case -1 :
+ return CharOperation.concat(METHOD_DECL, selector);
+ default :
+ int refLength = METHOD_DECL.length;
+ char[] result = new char[refLength+starPos];
+ System.arraycopy(METHOD_DECL, 0, result, 0, refLength);
+ System.arraycopy(selector, 0, result, refLength, starPos);
+ return result;
+ case 0 : // fall through
+ }
+ default:
+ return METHOD_DECL;
}
-
- /**
- * Type entries are encoded as follow: 'typeDecl/' ('C' | 'I') '/' PackageName '/' TypeName
- * e.g. typeDecl/C/java.lang/Object
- * typeDecl/I/java.lang/Cloneable
- *
- * Current encoding is optimized for queries: all classes/interfaces
- */
- public static final char[] bestTypeDeclarationPrefix(
- char[] packageName,
- char[] typeName,
- char classOrInterface,
- int matchMode,
- boolean isCaseSensitive) {
- // index is case sensitive, thus in case attempting case insensitive search, cannot consider
- // type name.
- if (!isCaseSensitive) {
- packageName = null;
- typeName = null;
- }
- switch (classOrInterface) {
- default :
- return TYPE_DECL; // cannot do better given encoding
- case CLASS_SUFFIX :
- if (packageName == null)
- return CLASS_DECL;
- break;
- case INTERFACE_SUFFIX :
- if (packageName == null)
- return INTERFACE_DECL;
- break;
- }
- switch (matchMode) {
- case EXACT_MATCH :
- case PREFIX_MATCH :
- break;
- case PATTERN_MATCH :
- if (typeName != null) {
- int starPos = CharOperation.indexOf('*', typeName);
- switch (starPos) {
- case -1 :
- break;
- case 0 :
- typeName = null;
- break;
- default :
- typeName = CharOperation.subarray(typeName, 0, starPos);
- }
+}
+/**
+ * Method reference entries are encoded as follow: 'methodRef/' Selector '/' Arity
+ * e.g. methodRef/clone/0
+ * methodRef/append/1
+ *
+ */
+ public static final char[] bestMethodReferencePrefix(char[] selector, int arity, int matchMode, boolean isCaseSensitive) {
+
+ if (!isCaseSensitive || selector == null) return METHOD_REF;
+ switch(matchMode){
+ case EXACT_MATCH :
+ if (arity >= 0){
+ char[] countChars;
+ if (arity < 10) {
+ countChars = COUNTS[arity];
+ } else {
+ countChars = String.valueOf(arity).toCharArray();
}
- }
- int packageLength = packageName.length;
- int typeLength = typeName == null ? 0 : typeName.length;
- int pos;
- char[] result = new char[TYPE_DECL_LENGTH + packageLength + typeLength + 3];
- System.arraycopy(TYPE_DECL, 0, result, 0, pos = TYPE_DECL_LENGTH);
- result[pos++] = classOrInterface;
- result[pos++] = SEPARATOR;
- System.arraycopy(packageName, 0, result, pos, packageLength);
- pos += packageLength;
- result[pos++] = SEPARATOR;
- if (typeLength > 0) {
- System.arraycopy(typeName, 0, result, pos, typeName.length);
- }
- return result;
+ return concat(METHOD_REF, selector, countChars, SEPARATOR);
+ }
+ case PREFIX_MATCH :
+ return CharOperation.concat(METHOD_REF, selector);
+ case PATTERN_MATCH :
+ int starPos = CharOperation.indexOf('*', selector);
+ switch(starPos) {
+ case -1 :
+ return CharOperation.concat(METHOD_REF, selector);
+ default :
+ int refLength = METHOD_REF.length;
+ char[] result = new char[refLength+starPos];
+ System.arraycopy(METHOD_REF, 0, result, 0, refLength);
+ System.arraycopy(selector, 0, result, refLength, starPos);
+ return result;
+ case 0 : // fall through
+ }
+ default:
+ return METHOD_REF;
}
-
- /**
- * Concat(first, second, third, fourth, fifth, sep) --> [first][second][sep][third][sep][fourth][sep][fifth]
- * i.e. no separator is inserted in between first and second
- */
- protected static final char[] concat(
- char[] firstWithSeparator,
- char[] second,
- char[] third,
- char[] fourth,
- char[] fifth,
- char separator) {
- int length1 = firstWithSeparator.length;
- int length2 = second == null ? 0 : second.length;
- int length3 = third == null ? 0 : third.length;
- int length4 = fourth == null ? 0 : fourth.length;
- int length5 = fifth == null ? 0 : fifth.length;
- char[] result = new char[length1 + length2 + length3 + length4 + length5 + 3];
- System.arraycopy(firstWithSeparator, 0, result, 0, length1);
- if (second != null)
- System.arraycopy(second, 0, result, length1, length2);
- int pos = length1 + length2;
- result[pos] = separator;
- if (third != null)
- System.arraycopy(third, 0, result, pos + 1, length3);
- pos += length3 + 1;
- result[pos] = separator;
- if (fourth != null)
- System.arraycopy(fourth, 0, result, pos + 1, length4);
- pos += length4 + 1;
- result[pos] = separator;
- if (fifth != null)
- System.arraycopy(fifth, 0, result, pos + 1, length5);
- return result;
+}
+/**
+ * Type entries are encoded as follow: '<tag>/' Name
+ * e.g. ref/Object
+ * ref/x
+ */
+ public static final char[] bestReferencePrefix(char[] tag, char[] name, int matchMode, boolean isCaseSensitive) {
+
+ if (!isCaseSensitive || name == null) return tag;
+ switch(matchMode){
+ case EXACT_MATCH :
+ case PREFIX_MATCH :
+ return CharOperation.concat(tag, name);
+ case PATTERN_MATCH :
+ int starPos = CharOperation.indexOf('*', name);
+ switch(starPos) {
+ case -1 :
+ return CharOperation.concat(tag, name);
+ default :
+ int refLength = tag.length;
+ char[] result = new char[refLength+starPos];
+ System.arraycopy(tag, 0, result, 0, refLength);
+ System.arraycopy(name, 0, result, refLength, starPos);
+ return result;
+ case 0 : // fall through
+ }
+ default:
+ return tag;
}
-
- /**
- * Concat(first, second, third, sep) --> [first][second][sep][third]
- * i.e. no separator is inserted in between first and second
- */
- protected static final char[] concat(
- char[] firstWithSeparator,
- char[] second,
- char[] third,
- char separator) {
- int length1 = firstWithSeparator.length;
- int length2 = second == null ? 0 : second.length;
- int length3 = third == null ? 0 : third.length;
- char[] result = new char[length1 + length2 + length3 + 1];
- System.arraycopy(firstWithSeparator, 0, result, 0, length1);
- if (second != null)
- System.arraycopy(second, 0, result, length1, length2);
- result[length1 + length2] = separator;
- if (third != null)
- System.arraycopy(third, 0, result, length1 + length2 + 1, length3);
- return result;
+}
+/**
+ * Type entries are encoded as follow: 'typeDecl/' ('C' | 'I') '/' PackageName '/' TypeName
+ * e.g. typeDecl/C/java.lang/Object
+ * typeDecl/I/java.lang/Cloneable
+ *
+ * Current encoding is optimized for queries: all classes/interfaces
+ */
+ public static final char[] bestTypeDeclarationPrefix(char[] packageName, char[] typeName, char classOrInterface, int matchMode, boolean isCaseSensitive) {
+ // index is case sensitive, thus in case attempting case insensitive search, cannot consider
+ // type name.
+ if (!isCaseSensitive){
+ packageName = null;
+ typeName = null;
}
-
- /**
- * Concat(first, second, third, charAfterThird, fourth, fifth, sixth, charAfterSixth, last, sep) --> [first][second][sep][third][sep][charAfterThird][sep][fourth][sep][fifth][sep][sixth][sep][charAfterSixth][last]
- * i.e. no separator is inserted in between first and second
- */
- protected static final char[] concat(
- char[] firstWithSeparator,
- char[] second,
- char[] third,
- char charAfterThird,
- char[] fourth,
- char[] fifth,
- char[] sixth,
- char charAfterSixth,
- char last,
- char separator) {
- int length1 = firstWithSeparator.length;
- int length2 = second == null ? 0 : second.length;
- int length3 = third == null ? 0 : third.length;
- int length4 = fourth == null ? 0 : fourth.length;
- int length5 = fifth == null ? 0 : fifth.length;
- int length6 = sixth == null ? 0 : sixth.length;
- char[] result =
- new char[length1 + length2 + length3 + length4 + length5 + length6 + 9];
- System.arraycopy(firstWithSeparator, 0, result, 0, length1);
- if (second != null)
- System.arraycopy(second, 0, result, length1, length2);
- int pos = length1 + length2;
- result[pos] = separator;
- if (third != null)
- System.arraycopy(third, 0, result, pos + 1, length3);
- pos += length3 + 1;
- result[pos] = separator;
- result[++pos] = charAfterThird;
- result[++pos] = separator;
- if (fourth != null)
- System.arraycopy(fourth, 0, result, pos + 1, length4);
- pos += length4 + 1;
- result[pos] = separator;
- if (fifth != null)
- System.arraycopy(fifth, 0, result, pos + 1, length5);
- pos += length5 + 1;
- result[pos] = separator;
- if (sixth != null)
- System.arraycopy(sixth, 0, result, pos + 1, length6);
- pos += length6 + 1;
- result[pos] = separator;
- result[++pos] = charAfterSixth;
- result[++pos] = last;
- return result;
+ switch(classOrInterface){
+ default :
+ return TYPE_DECL; // cannot do better given encoding
+ case CLASS_SUFFIX :
+ if (packageName == null) return CLASS_DECL;
+ break;
+ case INTERFACE_SUFFIX :
+ if (packageName == null) return INTERFACE_DECL;
+ break;
}
-
- /**
- * Type entries are encoded as follow: 'typeDecl/' ('C' | 'I') '/' PackageName '/' TypeName '/' EnclosingTypeName
- * e.g. typeDecl/C/java.lang/Object/
- * typeDecl/I/java.lang/Cloneable/
- * typeDecl/C/javax.swing/LazyValue/UIDefaults
- * Current encoding is optimized for queries: all classes/interfaces
- */
- protected static final char[] encodeTypeEntry(
- char[] packageName,
- char[][] enclosingTypeNames,
- char[] typeName,
- boolean isClass) {
- int packageLength = packageName == null ? 0 : packageName.length;
- int enclosingTypeNamesLength = 0;
- if (enclosingTypeNames != null) {
- for (int i = 0, length = enclosingTypeNames.length; i < length; i++) {
- enclosingTypeNamesLength += enclosingTypeNames[i].length + 1;
+ switch(matchMode){
+ case EXACT_MATCH :
+ case PREFIX_MATCH :
+ break;
+ case PATTERN_MATCH :
+ if (typeName != null){
+ int starPos = CharOperation.indexOf('*', typeName);
+ switch(starPos) {
+ case -1 :
+ break;
+ case 0 :
+ typeName = null;
+ break;
+ default :
+ typeName = CharOperation.subarray(typeName, 0, starPos);
+ }
}
- }
- int pos;
- char[] result =
- new char[TYPE_DECL_LENGTH
- + packageLength
- + typeName.length
- + enclosingTypeNamesLength
- + 4];
- System.arraycopy(TYPE_DECL, 0, result, 0, pos = TYPE_DECL_LENGTH);
- result[pos++] = isClass ? CLASS_SUFFIX : INTERFACE_SUFFIX;
- result[pos++] = SEPARATOR;
- if (packageName != null) {
- System.arraycopy(packageName, 0, result, pos, packageLength);
- pos += packageLength;
- }
- result[pos++] = SEPARATOR;
+ }
+ int packageLength = packageName.length;
+ int typeLength = typeName == null ? 0 : typeName.length;
+ int pos;
+ char[] result = new char[TYPE_DECL_LENGTH + packageLength + typeLength + 3];
+ System.arraycopy(TYPE_DECL, 0, result, 0, pos = TYPE_DECL_LENGTH);
+ result[pos++] = classOrInterface;
+ result[pos++] = SEPARATOR;
+ System.arraycopy(packageName, 0, result, pos, packageLength);
+ pos += packageLength;
+ result[pos++] = SEPARATOR;
+ if (typeLength > 0){
System.arraycopy(typeName, 0, result, pos, typeName.length);
- pos += typeName.length;
- result[pos++] = SEPARATOR;
- if (enclosingTypeNames != null) {
- for (int i = 0, length = enclosingTypeNames.length; i < length; i++) {
- int enclosingTypeNameLength = enclosingTypeNames[i].length;
- System.arraycopy(
- enclosingTypeNames[i],
- 0,
- result,
- pos,
- enclosingTypeNameLength);
- pos += enclosingTypeNameLength;
- result[pos++] = SEPARATOR;
- }
+ }
+ return result;
+}
+/**
+ * Concat(first, second, third, fourth, fifth, sep) --> [first][second][sep][third][sep][fourth][sep][fifth]
+ * i.e. no separator is inserted in between first and second
+ */
+protected static final char[] concat(char[] firstWithSeparator, char[] second, char[] third, char[] fourth, char[] fifth, char separator) {
+ int length1= firstWithSeparator.length;
+ int length2= second == null ? 0 : second.length;
+ int length3= third == null ? 0 : third.length;
+ int length4= fourth == null ? 0 : fourth.length;
+ int length5= fifth == null ? 0 : fifth.length;
+ char[] result= new char[length1 + length2 + length3 + length4 + length5 + 3 ];
+ System.arraycopy(firstWithSeparator, 0, result, 0, length1);
+ if (second != null) System.arraycopy(second, 0, result, length1 , length2);
+ int pos = length1 + length2;
+ result[pos]= separator;
+ if (third != null) System.arraycopy(third, 0, result, pos + 1, length3);
+ pos += length3+1;
+ result[pos]= separator;
+ if (fourth != null) System.arraycopy(fourth, 0, result, pos + 1, length4);
+ pos += length4+1;
+ result[pos]= separator;
+ if (fifth != null) System.arraycopy(fifth, 0, result, pos + 1, length5);
+ return result;
+}
+/**
+ * Concat(first, second, third, sep) --> [first][second][sep][third]
+ * i.e. no separator is inserted in between first and second
+ */
+protected static final char[] concat(char[] firstWithSeparator, char[] second, char[] third, char separator) {
+ int length1= firstWithSeparator.length;
+ int length2= second == null ? 0 : second.length;
+ int length3= third == null ? 0 : third.length;
+ char[] result= new char[length1 + length2 + length3 + 1];
+ System.arraycopy(firstWithSeparator, 0, result, 0, length1);
+ if (second != null) System.arraycopy(second, 0, result, length1 , length2);
+ result[length1 + length2]= separator;
+ if (third != null) System.arraycopy(third, 0, result, length1 + length2 + 1, length3);
+ return result;
+}
+/**
+ * Concat(first, second, third, charAfterThird, fourth, fifth, sixth, charAfterSixth, last, sep) --> [first][second][sep][third][sep][charAfterThird][sep][fourth][sep][fifth][sep][sixth][sep][charAfterSixth][last]
+ * i.e. no separator is inserted in between first and second
+ */
+protected static final char[] concat(char[] firstWithSeparator, char[] second, char[] third, char charAfterThird, char[] fourth, char[] fifth, char[] sixth, char charAfterSixth, char last, char separator) {
+ int length1= firstWithSeparator.length;
+ int length2= second == null ? 0 : second.length;
+ int length3= third == null ? 0 : third.length;
+ int length4= fourth == null ? 0 : fourth.length;
+ int length5= fifth == null ? 0 : fifth.length;
+ int length6 = sixth == null ? 0 : sixth.length;
+ char[] result= new char[length1 + length2 + length3 + length4 + length5 + length6 + 9 ];
+ System.arraycopy(firstWithSeparator, 0, result, 0, length1);
+ if (second != null) System.arraycopy(second, 0, result, length1 , length2);
+ int pos = length1 + length2;
+ result[pos]= separator;
+ if (third != null) System.arraycopy(third, 0, result, pos + 1, length3);
+ pos += length3+1;
+ result[pos]= separator;
+ result[++pos] = charAfterThird;
+ result[++pos] = separator;
+ if (fourth != null) System.arraycopy(fourth, 0, result, pos + 1, length4);
+ pos += length4+1;
+ result[pos]= separator;
+ if (fifth != null) System.arraycopy(fifth, 0, result, pos + 1, length5);
+ pos += length5+1;
+ result[pos]= separator;
+ if (sixth != null) System.arraycopy(sixth, 0, result, pos + 1, length6);
+ pos += length6+1;
+ result[pos]= separator;
+ result[++pos] = charAfterSixth;
+ result[++pos]=last;
+ return result;
+}
+/**
+ * Type entries are encoded as follow: 'typeDecl/' ('C' | 'I') '/' PackageName '/' TypeName '/' EnclosingTypeName
+ * e.g. typeDecl/C/java.lang/Object/
+ * typeDecl/I/java.lang/Cloneable/
+ * typeDecl/C/javax.swing/LazyValue/UIDefaults
+ * Current encoding is optimized for queries: all classes/interfaces
+ */
+ protected static final char[] encodeTypeEntry(char[] packageName, char[][] enclosingTypeNames, char[] typeName, boolean isClass) {
+ int packageLength = packageName == null ? 0 : packageName.length;
+ int enclosingTypeNamesLength = 0;
+ if (enclosingTypeNames != null) {
+ for (int i = 0, length = enclosingTypeNames.length; i < length; i++){
+ enclosingTypeNamesLength += enclosingTypeNames[i].length + 1;
}
- return result;
}
-
- /**
- * Returns the file types the <code>IIndexer</code> handles.
- */
-
- public abstract String[] getFileTypes();
- /**
- * @see IIndexer#index
- */
- public void index(IDocument document, IIndexerOutput output)
- throws IOException {
- this.output = output;
- if (shouldIndex(document))
- indexFile(document);
+ int pos;
+ char[] result = new char[TYPE_DECL_LENGTH + packageLength + typeName.length + enclosingTypeNamesLength + 4];
+ System.arraycopy(TYPE_DECL, 0, result, 0, pos = TYPE_DECL_LENGTH);
+ result[pos++] = isClass ? CLASS_SUFFIX : INTERFACE_SUFFIX;
+ result[pos++] = SEPARATOR;
+ if (packageName != null){
+ System.arraycopy(packageName, 0, result, pos, packageLength);
+ pos += packageLength;
}
-
- protected abstract void indexFile(IDocument document) throws IOException;
- /**
- * @see IIndexer#shouldIndex
- */
- public boolean shouldIndex(IDocument document) {
- String type = document.getType();
- String[] supportedTypes = this.getFileTypes();
- for (int i = 0; i < supportedTypes.length; ++i) {
- if (supportedTypes[i].equals(type))
- return true;
+ result[pos++] = SEPARATOR;
+ System.arraycopy(typeName, 0, result, pos, typeName.length);
+ pos += typeName.length;
+ result[pos++] = SEPARATOR;
+ if (enclosingTypeNames != null){
+ for (int i = 0, length = enclosingTypeNames.length; i < length; i++){
+ int enclosingTypeNameLength = enclosingTypeNames[i].length;
+ System.arraycopy(enclosingTypeNames[i], 0, result, pos, enclosingTypeNameLength);
+ pos += enclosingTypeNameLength;
+ result[pos++] = SEPARATOR;
}
- return false;
}
+ return result;
+}
+/**
+ * Returns the file types the <code>IIndexer</code> handles.
+ */
+public abstract String[] getFileTypes();
+/**
+ * @see IIndexer#index
+ */
+public void index(IDocument document, IIndexerOutput output) throws IOException {
+ this.output = output;
+ if (shouldIndex(document)) indexFile(document);
+}
+protected abstract void indexFile(IDocument document) throws IOException;
+/**
+ * @see IIndexer#shouldIndex
+ */
+public boolean shouldIndex(IDocument document) {
+ String type = document.getType();
+ String[] supportedTypes = this.getFileTypes();
+ for (int i = 0; i < supportedTypes.length; ++i) {
+ if (supportedTypes[i].equals(type))
+ return true;
+ }
+ return false;
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AddClassFileToIndex.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AddClassFileToIndex.java
index ad21c9cf11..ecadacfc8e 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AddClassFileToIndex.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AddClassFileToIndex.java
@@ -13,66 +13,61 @@ import org.eclipse.jdt.internal.core.index.impl.*;
import java.io.*;
+import org.eclipse.core.runtime.IPath;
+
class AddClassFileToIndex implements IJob, IJobConstants {
IFile resource;
IndexManager manager;
byte[] contents;
- public AddClassFileToIndex(IFile resource, IndexManager manager) {
- this.resource = resource;
- this.manager = manager;
- }
-
- public boolean belongsTo(String jobFamily) {
- return jobFamily.equals(resource.getProject().getName());
- }
-
- public boolean execute() {
- try {
- IProject project = resource.getProject();
- IIndex index = manager.getIndex(project.getFullPath());
- if (!resource.isLocal(IResource.DEPTH_ZERO)) {
- return FAILED;
- }
- /* ensure no concurrent write access to index */
- if (index == null)
- return COMPLETE;
- ReadWriteMonitor monitor = manager.getMonitorFor(index);
- if (monitor == null)
- return COMPLETE; // index got deleted since acquired
- try {
- monitor.enterWrite(); // ask permission to write
- byte[] contents = this.getContents();
- if (contents == null)
- return FAILED;
- index.add(new IFileDocument(resource, contents), new BinaryIndexer());
- } finally {
- monitor.exitWrite(); // free write lock
- }
- } catch (IOException e) {
+public AddClassFileToIndex(IFile resource, IndexManager manager){
+ this.resource = resource;
+ this.manager = manager;
+}
+public boolean belongsTo(String jobFamily){
+ return jobFamily.equals(resource.getProject().getName());
+}
+public boolean execute(){
+ try {
+ IProject project = resource.getProject();
+ IIndex index = manager.getIndex(project.getFullPath());
+ if (!resource.isLocal(IResource.DEPTH_ZERO)){
return FAILED;
}
- return COMPLETE;
- }
-
- private byte[] getContents() {
- if (this.contents == null)
- this.initializeContents();
- return this.contents;
+ /* ensure no concurrent write access to index */
+ if (index == null) return COMPLETE;
+ ReadWriteMonitor monitor = manager.getMonitorFor(index);
+ if (monitor == null) return COMPLETE; // index got deleted since acquired
+ try {
+ monitor.enterWrite(); // ask permission to write
+ byte[] contents = this.getContents();
+ if (contents == null) return FAILED;
+ index.add(new IFileDocument(resource, contents), new BinaryIndexer());
+ } finally {
+ monitor.exitWrite(); // free write lock
+ }
+ } catch (IOException e){
+ return FAILED;
}
-
- public void initializeContents() {
- if (!resource.isLocal(IResource.DEPTH_ZERO)) {
- return;
- } else {
- try {
+ return COMPLETE;
+}
+private byte[] getContents() {
+ if (this.contents == null) this.initializeContents();
+ return this.contents;
+}
+public void initializeContents() {
+ if (!resource.isLocal(IResource.DEPTH_ZERO)) {
+ return;
+ } else {
+ try {
+ IPath location = resource.getLocation();
+ if (location != null){;
this.contents = Util.getFileByteContent(resource.getLocation().toFile());
- } catch (IOException e) {
}
+ } catch (IOException e) {
}
}
-
- public String toString() {
- return "indexing " + resource.getName();
- }
-
+}
+public String toString(){
+ return "indexing " + resource.getName();
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AddCompilationUnitToIndex.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AddCompilationUnitToIndex.java
index 9814c3261e..41dc2dfc3a 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AddCompilationUnitToIndex.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AddCompilationUnitToIndex.java
@@ -14,66 +14,61 @@ import org.eclipse.jdt.internal.core.index.impl.*;
import java.io.*;
+import org.eclipse.core.runtime.IPath;
+
class AddCompilationUnitToIndex implements IJob, IJobConstants {
IFile resource;
IndexManager manager;
char[] contents;
- public AddCompilationUnitToIndex(IFile resource, IndexManager manager) {
- this.resource = resource;
- this.manager = manager;
- }
-
- public boolean belongsTo(String jobFamily) {
- return jobFamily.equals(resource.getProject().getName());
- }
-
- public boolean execute() {
- try {
- IProject project = resource.getProject();
- IIndex index = manager.getIndex(project.getFullPath());
- if (!resource.isLocal(IResource.DEPTH_ZERO)) {
- return FAILED;
- }
- /* ensure no concurrent write access to index */
- if (index == null)
- return COMPLETE;
- ReadWriteMonitor monitor = manager.getMonitorFor(index);
- if (monitor == null)
- return COMPLETE; // index got deleted since acquired
- try {
- monitor.enterWrite(); // ask permission to write
- char[] contents = this.getContents();
- if (contents == null)
- return FAILED;
- index.add(new IFileDocument(resource, contents), new SourceIndexer());
- } finally {
- monitor.exitWrite(); // free write lock
- }
- } catch (IOException e) {
+public AddCompilationUnitToIndex(IFile resource, IndexManager manager){
+ this.resource = resource;
+ this.manager = manager;
+}
+public boolean belongsTo(String jobFamily){
+ return jobFamily.equals(resource.getProject().getName());
+}
+public boolean execute(){
+ try {
+ IProject project = resource.getProject();
+ IIndex index = manager.getIndex(project.getFullPath());
+ if (!resource.isLocal(IResource.DEPTH_ZERO)){
return FAILED;
}
- return COMPLETE;
- }
-
- private char[] getContents() {
- if (this.contents == null)
- this.initializeContents();
- return contents;
+ /* ensure no concurrent write access to index */
+ if (index == null) return COMPLETE;
+ ReadWriteMonitor monitor = manager.getMonitorFor(index);
+ if (monitor == null) return COMPLETE; // index got deleted since acquired
+ try {
+ monitor.enterWrite(); // ask permission to write
+ char[] contents = this.getContents();
+ if (contents == null) return FAILED;
+ index.add(new IFileDocument(resource, contents), new SourceIndexer());
+ } finally {
+ monitor.exitWrite(); // free write lock
+ }
+ } catch (IOException e){
+ return FAILED;
}
-
- public void initializeContents() {
- if (!resource.isLocal(IResource.DEPTH_ZERO)) {
- return;
- } else {
- try {
- this.contents = Util.getFileCharContent(resource.getLocation().toFile());
- } catch (IOException e) {
+ return COMPLETE;
+}
+private char[] getContents() {
+ if (this.contents == null) this.initializeContents();
+ return contents;
+}
+public void initializeContents() {
+ if (!resource.isLocal(IResource.DEPTH_ZERO)) {
+ return;
+ } else {
+ try {
+ IPath location = resource.getLocation();
+ if (location != null){
+ this.contents = Util.getFileCharContent(location.toFile());
}
+ } catch (IOException e) {
}
}
-
- public String toString() {
- return "indexing " + resource.getName();
- }
-
+}
+public String toString(){
+ return "indexing " + resource.getName();
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java
index caa669cc4b..54da1f0655 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/AddJarFileToIndex.java
@@ -18,167 +18,163 @@ import java.io.*;
import java.util.zip.*;
import java.util.*;
+import org.eclipse.jdt.internal.core.Util;
+
class AddJarFileToIndex implements IJob, IJobConstants {
- JarPackageFragmentRoot jarRoot;
+
IndexManager manager;
String projectName;
IFile resource;
private String toString;
- public AddJarFileToIndex(
- IFile resource,
- IndexManager manager,
- String projectName) {
- this.resource = resource;
- this.manager = manager;
- this.projectName = projectName;
- }
-
- public AddJarFileToIndex(
- IPackageFragmentRoot jarRoot,
- IndexManager manager,
- String projectName) {
- this.jarRoot = (JarPackageFragmentRoot) jarRoot;
- this.manager = manager;
- this.projectName = projectName;
- }
+ IPath path;
- public boolean belongsTo(String jobFamily) {
- return jobFamily.equals(projectName);
- }
-
- public boolean execute() {
+public AddJarFileToIndex(IFile resource, IndexManager manager, String projectName) {
+ this.resource = resource;
+ this.path = resource.getFullPath();
+ this.manager = manager;
+ this.projectName = projectName;
+}
+public boolean belongsTo(String jobFamily){
+ return jobFamily.equals(projectName);
+}
+public boolean execute() {
+ try {
+ if (this.resource != null) {
+ if (!this.resource.isLocal(IResource.DEPTH_ZERO)) {
+ return FAILED;
+ }
+ }
+ IPath indexedPath = this.path;
+ // if index already cached, then do not perform any check
+ IIndex index = (IIndex) manager.getIndex(indexedPath, false);
+ if (index != null) return COMPLETE;
+
+ index = manager.getIndex(indexedPath);
+ if (index == null) return COMPLETE;
+ ReadWriteMonitor monitor = manager.getMonitorFor(index);
+ if (monitor == null) return COMPLETE; // index got deleted since acquired
+ ZipFile zip = null;
try {
- if (this.resource != null) {
- if (!this.resource.isLocal(IResource.DEPTH_ZERO)) {
- return FAILED;
- }
+ // this path will be a relative path to the workspace in case the zipfile in the workspace otherwise it will be a path in the
+ // local file system
+ Path zipFilePath = null;
+
+ monitor.enterWrite(); // ask permission to write
+ if (resource != null) {
+ IPath location = this.resource.getLocation();
+ if (location == null) return FAILED;
+ zip = new ZipFile(location.toFile());
+ zipFilePath = (Path) this.resource.getFullPath().makeRelative(); // absolute path relative to the workspace
+ } else {
+ zip = new ZipFile(this.path.toFile());
+ zipFilePath = (Path) this.path; // absolute path relative to the local file system
+ // make it a canonical path to avoid duplicate entries
+ zipFilePath = (Path)JavaProject.canonicalizedPath(zipFilePath);
}
- IPath indexedPath =
- this.jarRoot == null ? this.resource.getFullPath() : this.jarRoot.getPath();
- // if index already cached, then do not perform any check
- IIndex index = (IIndex) manager.getIndex(indexedPath, false);
- if (index != null)
- return COMPLETE;
-
- index = manager.getIndex(indexedPath);
- if (index == null)
- return COMPLETE;
- ReadWriteMonitor monitor = manager.getMonitorFor(index);
- if (monitor == null)
- return COMPLETE; // index got deleted since acquired
- ZipFile zip = null;
- try {
- // this path will be a relative path to the workspace in case the zipfile in the workspace otherwise it will be a path in the
- // local file system
- Path zipFilePath = null;
-
- monitor.enterWrite(); // ask permission to write
- if (resource != null) {
- zip = new ZipFile(this.resource.getLocation().toFile());
- zipFilePath = (Path) this.resource.getFullPath().makeRelative();
- // absolute path relative to the workspace
- } else {
- zip = new ZipFile(this.jarRoot.getPath().toFile());
- zipFilePath = (Path) this.jarRoot.getPath();
- // absolute path relative to the local file system
- // make it a canonical path to avoid duplicate entries
- zipFilePath = (Path) JavaProject.canonicalizedPath(zipFilePath);
- }
-
- if (JobManager.VERBOSE)
- System.out.println("INDEX : " + zip.getName());
- long initialTime = System.currentTimeMillis();
+
+ if (JobManager.VERBOSE)
+ System.out.println("INDEX : " + zip.getName());
+ long initialTime = System.currentTimeMillis();
- final Hashtable indexedFileNames = new Hashtable(100);
- IQueryResult[] results = index.queryInDocumentNames(""); // all file names
- int resultLength = results == null ? 0 : results.length;
- if (resultLength != 0) {
- /* check integrity of the existing index file
- * if the length is equal to 0, we want to index the whole jar again
- * If not, then we want to check that there is no missing entry, if
- * one entry is missing then we
- */
- for (int i = 0; i < resultLength; i++) {
- String fileName = results[i].getPath();
- indexedFileNames.put(fileName, fileName);
- }
- boolean needToReindex = false;
- for (Enumeration e = zip.entries(); e.hasMoreElements();) {
- // iterate each entry to index it
- ZipEntry ze = (ZipEntry) e.nextElement();
- if (ze.getName().toUpperCase().endsWith(".CLASS")) {
- JarFileEntryDocument entryDocument =
- new JarFileEntryDocument(ze, null, zipFilePath);
- if (indexedFileNames.remove(entryDocument.getName()) == null) {
- needToReindex = true;
- break;
- }
- }
- }
- if (!needToReindex && indexedFileNames.size() == 0) {
- return COMPLETE;
- }
- }
-
- /*
- * Index the jar for the first time or reindex the jar in case the previous index file has been corrupted
- */
- if (index != null) {
- // index already existed: recreate it so that we forget about previous entries
- index = manager.recreateIndex(indexedPath);
+ final Hashtable indexedFileNames = new Hashtable(100);
+ IQueryResult[] results = index.queryInDocumentNames(""); // all file names
+ int resultLength = results == null ? 0 : results.length;
+ if (resultLength != 0) {
+ /* check integrity of the existing index file
+ * if the length is equal to 0, we want to index the whole jar again
+ * If not, then we want to check that there is no missing entry, if
+ * one entry is missing then we
+ */
+ for (int i = 0; i < resultLength; i++) {
+ String fileName = results[i].getPath();
+ indexedFileNames.put(fileName, fileName);
}
+ boolean needToReindex = false;
for (Enumeration e = zip.entries(); e.hasMoreElements();) {
// iterate each entry to index it
ZipEntry ze = (ZipEntry) e.nextElement();
- if (ze.getName().toUpperCase().endsWith(".CLASS")) {
- InputStream zipInputStream = zip.getInputStream(ze);
- byte classFileBytes[] = new byte[(int) ze.getSize()];
- int length = classFileBytes.length;
- int len = 0;
- int readSize = 0;
- while ((readSize != -1) && (len != length)) {
- readSize = zipInputStream.read(classFileBytes, len, length - len);
- len += readSize;
+ if (Util.isClassFileName(ze.getName())) {
+ JarFileEntryDocument entryDocument = new JarFileEntryDocument(ze, null, zipFilePath);
+ if (indexedFileNames.remove(entryDocument.getName()) == null) {
+ needToReindex = true;
+ break;
}
- zipInputStream.close();
- // Add the name of the file to the index
- index.add(
- new JarFileEntryDocument(ze, classFileBytes, zipFilePath),
- new BinaryIndexer());
}
}
- if (JobManager.VERBOSE)
- System.out.println(
- "INDEX : "
- + zip.getName()
- + " COMPLETE in "
- + (System.currentTimeMillis() - initialTime)
- + " ms");
- } finally {
- if (zip != null)
- zip.close();
- monitor.exitWrite(); // free write lock
+ if (!needToReindex && indexedFileNames.size() == 0) {
+ return COMPLETE;
+ }
+ }
+
+ /*
+ * Index the jar for the first time or reindex the jar in case the previous index file has been corrupted
+ */
+ if (index != null) {
+ // index already existed: recreate it so that we forget about previous entries
+ index = manager.recreateIndex(indexedPath);
+ }
+ for (Enumeration e = zip.entries(); e.hasMoreElements();) {
+ // iterate each entry to index it
+ ZipEntry ze = (ZipEntry) e.nextElement();
+ if (Util.isClassFileName(ze.getName())) {
+ InputStream zipInputStream = zip.getInputStream(ze);
+ byte classFileBytes[] = new byte[(int) ze.getSize()];
+ int length = classFileBytes.length;
+ int len = 0;
+ int readSize = 0;
+ while ((readSize != -1) && (len != length)) {
+ readSize = zipInputStream.read(classFileBytes, len, length - len);
+ len += readSize;
+ }
+ zipInputStream.close();
+ // Add the name of the file to the index
+ index.add(
+ new JarFileEntryDocument(ze, classFileBytes, zipFilePath),
+ new BinaryIndexer());
+ }
}
- } catch (IOException e) {
- return FAILED;
+ if (JobManager.VERBOSE)
+ System.out.println(
+ "INDEX : "
+ + zip.getName()
+ + " COMPLETE in "
+ + (System.currentTimeMillis() - initialTime)
+ + " ms");
+ } finally {
+ if (zip != null)
+ zip.close();
+ monitor.exitWrite(); // free write lock
}
- return COMPLETE;
+ } catch (IOException e) {
+ return FAILED;
}
-
- /**
- * Insert the method's description here.
- * Creation date: (10/10/00 1:27:18 PM)
- * @return java.lang.String
- */
- public String toString() {
- if (toString == null) {
- if (resource != null) {
- toString = "indexing " + resource.getLocation().toFile().toString();
+ return COMPLETE;
+}
+/**
+ * Insert the method's description here.
+ * Creation date: (10/10/00 1:27:18 PM)
+ * @return java.lang.String
+ */
+public String toString() {
+ if (toString == null) {
+ if (resource != null) {
+ IPath location = resource.getLocation();
+ if (location == null){
+ toString = "indexing ";
} else {
- toString = "indexing " + jarRoot.getPath().toFile().toString();
+ toString = "indexing " + location.toFile().toString();
}
+ } else {
+ toString = "indexing " + this.path.toFile().toString();
}
- return toString;
}
+ return toString;
+}
+public AddJarFileToIndex(IPath path, IndexManager manager, String projectName) {
+ // external JAR scenario - no resource
+ this.path = path;
+ this.manager = manager;
+ this.projectName = projectName;
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
index a484969f7e..2ade21d11d 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/BinaryIndexer.java
@@ -13,7 +13,7 @@ import java.util.*;
import java.util.zip.*;
public class BinaryIndexer extends AbstractIndexer {
- public static final String[] FILE_TYPES = new String[] { "class" };
+ public static final String[] FILE_TYPES= new String[] {"class"};
private static final char[] BYTE = "byte".toCharArray();
private static final char[] CHAR = "char".toCharArray();
private static final char[] DOUBLE = "double".toCharArray();
@@ -27,636 +27,538 @@ public class BinaryIndexer extends AbstractIndexer {
private boolean needReferences;
private static final boolean DEBUG = false;
- /**
- * BinaryIndexer constructor comment.
- */
- public BinaryIndexer() {
- needReferences = false;
- }
-
- /**
- * BinaryIndexer constructor comment.
- */
- public BinaryIndexer(boolean retrieveReferences) {
- needReferences = retrieveReferences;
+/**
+ * BinaryIndexer constructor comment.
+ */
+public BinaryIndexer() {
+ needReferences = false;
+}
+/**
+ * BinaryIndexer constructor comment.
+ */
+public BinaryIndexer(boolean retrieveReferences) {
+ needReferences = retrieveReferences;
+}
+/**
+ * For example:
+ * - int foo(String[]) is ([Ljava/lang/String;)I => java.lang.String[] in a char[][]
+ * - void foo(int) is (I)V ==> int
+ */
+private void convertToArrayType(char[][] parameterTypes, int counter, int arrayDim) {
+ int length = parameterTypes[counter].length;
+ char[] arrayType = new char[length + arrayDim*2];
+ System.arraycopy(parameterTypes[counter], 0, arrayType, 0, length);
+ for (int i = 0; i < arrayDim; i++) {
+ arrayType[length + (i * 2)] = '[';
+ arrayType[length + (i * 2) + 1] = ']';
}
-
- /**
- * For example:
- * - int foo(String[]) is ([Ljava/lang/String;)I => java.lang.String[] in a char[][]
- * - void foo(int) is (I)V ==> int
- */
- private void convertToArrayType(
- char[][] parameterTypes,
- int counter,
- int arrayDim) {
- int length = parameterTypes[counter].length;
- char[] arrayType = new char[length + arrayDim * 2];
- System.arraycopy(parameterTypes[counter], 0, arrayType, 0, length);
- for (int i = 0; i < arrayDim; i++) {
- arrayType[length + (i * 2)] = '[';
- arrayType[length + (i * 2) + 1] = ']';
- }
- parameterTypes[counter] = arrayType;
+ parameterTypes[counter] = arrayType;
+}
+/**
+ * For example:
+ * - int foo(String[]) is ([Ljava/lang/String;)I => java.lang.String[] in a char[][]
+ * - void foo(int) is (I)V ==> int
+ */
+private char[] convertToArrayType(char[] typeName, int arrayDim) {
+ int length = typeName.length;
+ char[] arrayType = new char[length + arrayDim*2];
+ System.arraycopy(typeName, 0, arrayType, 0, length);
+ for (int i = 0; i < arrayDim; i++) {
+ arrayType[length + (i * 2)] = '[';
+ arrayType[length + (i * 2) + 1] = ']';
}
-
- /**
- * For example:
- * - int foo(String[]) is ([Ljava/lang/String;)I => java.lang.String[] in a char[][]
- * - void foo(int) is (I)V ==> int
- */
- private char[] convertToArrayType(char[] typeName, int arrayDim) {
- int length = typeName.length;
- char[] arrayType = new char[length + arrayDim * 2];
- System.arraycopy(typeName, 0, arrayType, 0, length);
- for (int i = 0; i < arrayDim; i++) {
- arrayType[length + (i * 2)] = '[';
- arrayType[length + (i * 2) + 1] = ']';
+ return arrayType;
+}
+private char[] decodeFieldType(char[] signature) throws ClassFormatException {
+ if (signature == null) return null;
+ int arrayDim = 0;
+ for (int i = 0, max = signature.length; i < max; i++) {
+ switch(signature[i]) {
+ case 'B':
+ if (arrayDim > 0) {
+ return convertToArrayType(BYTE, arrayDim);
+ } else {
+ return BYTE;
+ }
+ case 'C':
+ if (arrayDim > 0) {
+ return convertToArrayType(CHAR, arrayDim);
+ } else {
+ return CHAR;
+ }
+ case 'D':
+ if (arrayDim > 0) {
+ return convertToArrayType(DOUBLE, arrayDim);
+ } else {
+ return DOUBLE;
+ }
+ case 'F':
+ if (arrayDim > 0) {
+ return convertToArrayType(FLOAT, arrayDim);
+ } else {
+ return FLOAT;
+ }
+ case 'I':
+ if (arrayDim > 0) {
+ return convertToArrayType(INT, arrayDim);
+ } else {
+ return INT;
+ }
+ case 'J':
+ if (arrayDim > 0) {
+ return convertToArrayType(LONG, arrayDim);
+ } else {
+ return LONG;
+ }
+ case 'L':
+ int indexOfSemiColon = CharOperation.indexOf(';', signature, i+1);
+ if (indexOfSemiColon == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
+ if (arrayDim > 0) {
+ return convertToArrayType(replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)), arrayDim);
+ } else {
+ return replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon));
+ }
+ case 'S':
+ if (arrayDim > 0) {
+ return convertToArrayType(SHORT, arrayDim);
+ } else {
+ return SHORT;
+ }
+ case 'Z':
+ if (arrayDim > 0) {
+ return convertToArrayType(BOOLEAN, arrayDim);
+ } else {
+ return BOOLEAN;
+ }
+ case 'V':
+ return VOID;
+ case '[':
+ arrayDim++;
+ break;
+ default:
+ throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
}
- return arrayType;
}
-
- private char[] decodeFieldType(char[] signature) throws ClassFormatException {
- if (signature == null)
- return null;
- int arrayDim = 0;
- for (int i = 0, max = signature.length; i < max; i++) {
- switch (signature[i]) {
- case 'B' :
- if (arrayDim > 0) {
- return convertToArrayType(BYTE, arrayDim);
- } else {
- return BYTE;
- }
- case 'C' :
- if (arrayDim > 0) {
- return convertToArrayType(CHAR, arrayDim);
- } else {
- return CHAR;
- }
- case 'D' :
- if (arrayDim > 0) {
- return convertToArrayType(DOUBLE, arrayDim);
- } else {
- return DOUBLE;
- }
- case 'F' :
- if (arrayDim > 0) {
- return convertToArrayType(FLOAT, arrayDim);
- } else {
- return FLOAT;
- }
- case 'I' :
- if (arrayDim > 0) {
- return convertToArrayType(INT, arrayDim);
- } else {
- return INT;
- }
- case 'J' :
- if (arrayDim > 0) {
- return convertToArrayType(LONG, arrayDim);
- } else {
- return LONG;
- }
- case 'L' :
- int indexOfSemiColon = CharOperation.indexOf(';', signature, i + 1);
- if (indexOfSemiColon == -1)
- throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
- if (arrayDim > 0) {
- return convertToArrayType(
- replace('/', '.', CharOperation.subarray(signature, i + 1, indexOfSemiColon)),
- arrayDim);
- } else {
- return replace(
- '/',
- '.',
- CharOperation.subarray(signature, i + 1, indexOfSemiColon));
- }
- case 'S' :
- if (arrayDim > 0) {
- return convertToArrayType(SHORT, arrayDim);
- } else {
- return SHORT;
- }
- case 'Z' :
- if (arrayDim > 0) {
- return convertToArrayType(BOOLEAN, arrayDim);
- } else {
- return BOOLEAN;
- }
- case 'V' :
- return VOID;
- case '[' :
- arrayDim++;
- break;
- default :
- throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
- }
- }
+ return null;
+}
+/**
+ * For example:
+ * - int foo(String[]) is ([Ljava/lang/String;)I => java.lang.String[] in a char[][]
+ * - void foo(int) is (I)V ==> int
+ */
+private char[][] decodeParameterTypes(char[] signature) throws ClassFormatException {
+ if (signature == null) return null;
+ int indexOfClosingParen = CharOperation.lastIndexOf(')', signature);
+ if (indexOfClosingParen == 1) {
+ // there is no parameter
return null;
}
-
- /**
- * For example:
- * - int foo(String[]) is ([Ljava/lang/String;)I => java.lang.String[] in a char[][]
- * - void foo(int) is (I)V ==> int
- */
- private char[][] decodeParameterTypes(char[] signature)
- throws ClassFormatException {
- if (signature == null)
- return null;
- int indexOfClosingParen = CharOperation.lastIndexOf(')', signature);
- if (indexOfClosingParen == 1) {
- // there is no parameter
- return null;
- }
- if (indexOfClosingParen == -1) {
- throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
- }
- char[][] parameterTypes = new char[3][];
- int parameterTypesCounter = 0;
- int arrayDim = 0;
- for (int i = 1; i < indexOfClosingParen; i++) {
- if (parameterTypesCounter == parameterTypes.length) {
- // resize
- System.arraycopy(
- parameterTypes,
- 0,
- (parameterTypes = new char[parameterTypesCounter * 2][]),
- 0,
- parameterTypesCounter);
- }
- switch (signature[i]) {
- case 'B' :
- parameterTypes[parameterTypesCounter++] = BYTE;
- if (arrayDim > 0) {
- convertToArrayType(parameterTypes, parameterTypesCounter - 1, arrayDim);
- }
- arrayDim = 0;
- break;
- case 'C' :
- parameterTypes[parameterTypesCounter++] = CHAR;
- if (arrayDim > 0) {
- convertToArrayType(parameterTypes, parameterTypesCounter - 1, arrayDim);
- }
- arrayDim = 0;
- break;
- case 'D' :
- parameterTypes[parameterTypesCounter++] = DOUBLE;
- if (arrayDim > 0) {
- convertToArrayType(parameterTypes, parameterTypesCounter - 1, arrayDim);
- }
- arrayDim = 0;
- break;
- case 'F' :
- parameterTypes[parameterTypesCounter++] = FLOAT;
- if (arrayDim > 0) {
- convertToArrayType(parameterTypes, parameterTypesCounter - 1, arrayDim);
- }
- arrayDim = 0;
- break;
- case 'I' :
- parameterTypes[parameterTypesCounter++] = INT;
- if (arrayDim > 0) {
- convertToArrayType(parameterTypes, parameterTypesCounter - 1, arrayDim);
- }
- arrayDim = 0;
- break;
- case 'J' :
- parameterTypes[parameterTypesCounter++] = LONG;
- if (arrayDim > 0) {
- convertToArrayType(parameterTypes, parameterTypesCounter - 1, arrayDim);
- }
- arrayDim = 0;
- break;
- case 'L' :
- int indexOfSemiColon = CharOperation.indexOf(';', signature, i + 1);
- if (indexOfSemiColon == -1)
- throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
- parameterTypes[parameterTypesCounter++] =
- replace('/', '.', CharOperation.subarray(signature, i + 1, indexOfSemiColon));
- if (arrayDim > 0) {
- convertToArrayType(parameterTypes, parameterTypesCounter - 1, arrayDim);
- }
- i = indexOfSemiColon;
- arrayDim = 0;
- break;
- case 'S' :
- parameterTypes[parameterTypesCounter++] = SHORT;
- if (arrayDim > 0) {
- convertToArrayType(parameterTypes, parameterTypesCounter - 1, arrayDim);
- }
- arrayDim = 0;
- break;
- case 'Z' :
- parameterTypes[parameterTypesCounter++] = BOOLEAN;
- if (arrayDim > 0) {
- convertToArrayType(parameterTypes, parameterTypesCounter - 1, arrayDim);
- }
- arrayDim = 0;
- break;
- case '[' :
- arrayDim++;
- break;
- default :
- throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
- }
+ if (indexOfClosingParen == -1) {
+ throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
+ }
+ char[][] parameterTypes = new char[3][];
+ int parameterTypesCounter = 0;
+ int arrayDim = 0;
+ for (int i = 1; i < indexOfClosingParen; i++) {
+ if (parameterTypesCounter == parameterTypes.length) {
+ // resize
+ System.arraycopy(parameterTypes, 0, (parameterTypes = new char[parameterTypesCounter * 2][]), 0, parameterTypesCounter);
}
- if (parameterTypes.length != parameterTypesCounter) {
- System.arraycopy(
- parameterTypes,
- 0,
- parameterTypes = new char[parameterTypesCounter][],
- 0,
- parameterTypesCounter);
+ switch(signature[i]) {
+ case 'B':
+ parameterTypes[parameterTypesCounter++] = BYTE;
+ if (arrayDim > 0) {
+ convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim);
+ }
+ arrayDim = 0;
+ break;
+ case 'C':
+ parameterTypes[parameterTypesCounter++] = CHAR;
+ if (arrayDim > 0) {
+ convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim);
+ }
+ arrayDim = 0;
+ break;
+ case 'D':
+ parameterTypes[parameterTypesCounter++] = DOUBLE;
+ if (arrayDim > 0) {
+ convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim);
+ }
+ arrayDim = 0;
+ break;
+ case 'F':
+ parameterTypes[parameterTypesCounter++] = FLOAT;
+ if (arrayDim > 0) {
+ convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim);
+ }
+ arrayDim = 0;
+ break;
+ case 'I':
+ parameterTypes[parameterTypesCounter++] = INT;
+ if (arrayDim > 0) {
+ convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim);
+ }
+ arrayDim = 0;
+ break;
+ case 'J':
+ parameterTypes[parameterTypesCounter++] = LONG;
+ if (arrayDim > 0) {
+ convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim);
+ }
+ arrayDim = 0;
+ break;
+ case 'L':
+ int indexOfSemiColon = CharOperation.indexOf(';', signature, i+1);
+ if (indexOfSemiColon == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
+ parameterTypes[parameterTypesCounter++] = replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon));
+ if (arrayDim > 0) {
+ convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim);
+ }
+ i = indexOfSemiColon;
+ arrayDim = 0;
+ break;
+ case 'S':
+ parameterTypes[parameterTypesCounter++] = SHORT;
+ if (arrayDim > 0) {
+ convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim);
+ }
+ arrayDim = 0;
+ break;
+ case 'Z':
+ parameterTypes[parameterTypesCounter++] = BOOLEAN;
+ if (arrayDim > 0) {
+ convertToArrayType(parameterTypes, parameterTypesCounter-1, arrayDim);
+ }
+ arrayDim = 0;
+ break;
+ case '[':
+ arrayDim++;
+ break;
+ default:
+ throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
}
- return parameterTypes;
}
-
- private char[] decodeReturnType(char[] signature) throws ClassFormatException {
- if (signature == null)
- return null;
- int indexOfClosingParen = CharOperation.lastIndexOf(')', signature);
- if (indexOfClosingParen == -1)
- throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
- int arrayDim = 0;
- for (int i = indexOfClosingParen + 1, max = signature.length; i < max; i++) {
- switch (signature[i]) {
- case 'B' :
- if (arrayDim > 0) {
- return convertToArrayType(BYTE, arrayDim);
- } else {
- return BYTE;
- }
- case 'C' :
- if (arrayDim > 0) {
- return convertToArrayType(CHAR, arrayDim);
- } else {
- return CHAR;
- }
- case 'D' :
- if (arrayDim > 0) {
- return convertToArrayType(DOUBLE, arrayDim);
- } else {
- return DOUBLE;
- }
- case 'F' :
- if (arrayDim > 0) {
- return convertToArrayType(FLOAT, arrayDim);
- } else {
- return FLOAT;
- }
- case 'I' :
- if (arrayDim > 0) {
- return convertToArrayType(INT, arrayDim);
- } else {
- return INT;
- }
- case 'J' :
- if (arrayDim > 0) {
- return convertToArrayType(LONG, arrayDim);
- } else {
- return LONG;
- }
- case 'L' :
- int indexOfSemiColon = CharOperation.indexOf(';', signature, i + 1);
- if (indexOfSemiColon == -1)
- throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
- if (arrayDim > 0) {
- return convertToArrayType(
- replace('/', '.', CharOperation.subarray(signature, i + 1, indexOfSemiColon)),
- arrayDim);
- } else {
- return replace(
- '/',
- '.',
- CharOperation.subarray(signature, i + 1, indexOfSemiColon));
- }
- case 'S' :
- if (arrayDim > 0) {
- return convertToArrayType(SHORT, arrayDim);
- } else {
- return SHORT;
- }
- case 'Z' :
- if (arrayDim > 0) {
- return convertToArrayType(BOOLEAN, arrayDim);
- } else {
- return BOOLEAN;
- }
- case 'V' :
- return VOID;
- case '[' :
- arrayDim++;
- break;
- default :
- throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
- }
- }
- return null;
+ if (parameterTypes.length != parameterTypesCounter) {
+ System.arraycopy(parameterTypes, 0, parameterTypes = new char[parameterTypesCounter][], 0, parameterTypesCounter);
}
-
- private int extractArgCount(char[] signature) throws ClassFormatException {
- int indexOfClosingParen = CharOperation.lastIndexOf(')', signature);
- if (indexOfClosingParen == 1) {
- // there is no parameter
- return 0;
- }
- if (indexOfClosingParen == -1) {
- throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
- }
- int parameterTypesCounter = 0;
- for (int i = 1; i < indexOfClosingParen; i++) {
- switch (signature[i]) {
- case 'B' :
- case 'C' :
- case 'D' :
- case 'F' :
- case 'I' :
- case 'J' :
- case 'S' :
- case 'Z' :
- parameterTypesCounter++;
- break;
- case 'L' :
- int indexOfSemiColon = CharOperation.indexOf(';', signature, i + 1);
- if (indexOfSemiColon == -1)
- throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
- parameterTypesCounter++;
- i = indexOfSemiColon;
- break;
- case '[' :
- break;
- default :
- throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
- }
+ return parameterTypes;
+}
+private char[] decodeReturnType(char[] signature) throws ClassFormatException {
+ if (signature == null) return null;
+ int indexOfClosingParen = CharOperation.lastIndexOf(')', signature);
+ if (indexOfClosingParen == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
+ int arrayDim = 0;
+ for (int i = indexOfClosingParen + 1, max = signature.length; i < max; i++) {
+ switch(signature[i]) {
+ case 'B':
+ if (arrayDim > 0) {
+ return convertToArrayType(BYTE, arrayDim);
+ } else {
+ return BYTE;
+ }
+ case 'C':
+ if (arrayDim > 0) {
+ return convertToArrayType(CHAR, arrayDim);
+ } else {
+ return CHAR;
+ }
+ case 'D':
+ if (arrayDim > 0) {
+ return convertToArrayType(DOUBLE, arrayDim);
+ } else {
+ return DOUBLE;
+ }
+ case 'F':
+ if (arrayDim > 0) {
+ return convertToArrayType(FLOAT, arrayDim);
+ } else {
+ return FLOAT;
+ }
+ case 'I':
+ if (arrayDim > 0) {
+ return convertToArrayType(INT, arrayDim);
+ } else {
+ return INT;
+ }
+ case 'J':
+ if (arrayDim > 0) {
+ return convertToArrayType(LONG, arrayDim);
+ } else {
+ return LONG;
+ }
+ case 'L':
+ int indexOfSemiColon = CharOperation.indexOf(';', signature, i+1);
+ if (indexOfSemiColon == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
+ if (arrayDim > 0) {
+ return convertToArrayType(replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon)), arrayDim);
+ } else {
+ return replace('/','.',CharOperation.subarray(signature, i + 1, indexOfSemiColon));
+ }
+ case 'S':
+ if (arrayDim > 0) {
+ return convertToArrayType(SHORT, arrayDim);
+ } else {
+ return SHORT;
+ }
+ case 'Z':
+ if (arrayDim > 0) {
+ return convertToArrayType(BOOLEAN, arrayDim);
+ } else {
+ return BOOLEAN;
+ }
+ case 'V':
+ return VOID;
+ case '[':
+ arrayDim++;
+ break;
+ default:
+ throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
}
- return parameterTypesCounter;
}
-
- private final char[] extractClassName(
- int[] constantPoolOffsets,
- ClassFileReader reader,
- int index) {
- int constantPoolIndex = reader.u2At(constantPoolOffsets[index] + 1);
- int utf8Offset =
- constantPoolOffsets[reader.u2At(constantPoolOffsets[constantPoolIndex] + 1)];
- return reader.utf8At(utf8Offset + 3, reader.u2At(utf8Offset + 1));
+ return null;
+}
+private int extractArgCount(char[] signature) throws ClassFormatException {
+ int indexOfClosingParen = CharOperation.lastIndexOf(')', signature);
+ if (indexOfClosingParen == 1) {
+ // there is no parameter
+ return 0;
}
-
- private final char[] extractName(
- int[] constantPoolOffsets,
- ClassFileReader reader,
- int index) {
- int constantPoolIndex = reader.u2At(constantPoolOffsets[index] + 3);
- int utf8Offset =
- constantPoolOffsets[reader.u2At(constantPoolOffsets[constantPoolIndex] + 1)];
- return reader.utf8At(utf8Offset + 3, reader.u2At(utf8Offset + 1));
+ if (indexOfClosingParen == -1) {
+ throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
}
-
- /**
- * Extract all type, method, field and interface method references from the constant pool
- */
- private void extractReferenceFromConstantPool(
- byte[] contents,
- ClassFileReader reader)
- throws ClassFormatException {
- int[] constantPoolOffsets = reader.getConstantPoolOffsets();
- int constantPoolCount = constantPoolOffsets.length;
- for (int i = 1; i < constantPoolCount; i++) {
- int tag = reader.u1At(constantPoolOffsets[i]);
- /**
- * u1 tag
- * u2 class_index
- * u2 name_and_type_index
- */
- char[] className = null;
- char[] name = null;
- char[] type = null;
- switch (tag) {
- case ClassFileStruct.FieldRefTag :
- // add reference to the class/interface and field name and type
- // className = extractClassName(constantPoolOffsets, reader, i);
- name = extractName(constantPoolOffsets, reader, i);
- // type = extractType(constantPoolOffsets, reader, i);
- addFieldReference(name);
- break;
- case ClassFileStruct.MethodRefTag :
- // add reference to the class and method name and type
- case ClassFileStruct.InterfaceMethodRefTag :
- // add reference to the interface and method name and type
- name = extractName(constantPoolOffsets, reader, i);
- type = extractType(constantPoolOffsets, reader, i);
- addMethodReference(name, extractArgCount(type));
- }
+ int parameterTypesCounter = 0;
+ for (int i = 1; i < indexOfClosingParen; i++) {
+ switch(signature[i]) {
+ case 'B':
+ case 'C':
+ case 'D':
+ case 'F':
+ case 'I':
+ case 'J':
+ case 'S':
+ case 'Z':
+ parameterTypesCounter++;
+ break;
+ case 'L':
+ int indexOfSemiColon = CharOperation.indexOf(';', signature, i+1);
+ if (indexOfSemiColon == -1) throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
+ parameterTypesCounter++;
+ i = indexOfSemiColon;
+ break;
+ case '[':
+ break;
+ default:
+ throw new ClassFormatException(ClassFormatException.ErrInvalidMethodSignature);
}
}
-
- private final char[] extractType(
- int[] constantPoolOffsets,
- ClassFileReader reader,
- int index) {
- int constantPoolIndex = reader.u2At(constantPoolOffsets[index] + 3);
- int utf8Offset =
- constantPoolOffsets[reader.u2At(constantPoolOffsets[constantPoolIndex] + 3)];
- return reader.utf8At(utf8Offset + 3, reader.u2At(utf8Offset + 1));
- }
-
- /**
- * getFileTypes method comment.
- */
- public String[] getFileTypes() {
- return FILE_TYPES;
+ return parameterTypesCounter;
+}
+private final char[] extractClassName(int[] constantPoolOffsets, ClassFileReader reader, int index) {
+ int constantPoolIndex = reader.u2At(constantPoolOffsets[index] + 1);
+ int utf8Offset = constantPoolOffsets[reader.u2At(constantPoolOffsets[constantPoolIndex] + 1)];
+ return reader.utf8At(utf8Offset + 3, reader.u2At(utf8Offset + 1));
+}
+private final char[] extractName(int[] constantPoolOffsets, ClassFileReader reader, int index) {
+ int constantPoolIndex = reader.u2At(constantPoolOffsets[index] + 3);
+ int utf8Offset = constantPoolOffsets[reader.u2At(constantPoolOffsets[constantPoolIndex] + 1)];
+ return reader.utf8At(utf8Offset + 3, reader.u2At(utf8Offset + 1));
+}
+/**
+ * Extract all type, method, field and interface method references from the constant pool
+ */
+private void extractReferenceFromConstantPool(byte[] contents, ClassFileReader reader) throws ClassFormatException {
+ int[] constantPoolOffsets = reader.getConstantPoolOffsets();
+ int constantPoolCount = constantPoolOffsets.length;
+ for (int i = 1; i < constantPoolCount; i++) {
+ int tag = reader.u1At(constantPoolOffsets[i]);
+ /**
+ * u1 tag
+ * u2 class_index
+ * u2 name_and_type_index
+ */
+ char[] className = null;
+ char[] name = null;
+ char[] type = null;
+ switch (tag) {
+ case ClassFileStruct.FieldRefTag :
+ // add reference to the class/interface and field name and type
+// className = extractClassName(constantPoolOffsets, reader, i);
+ name = extractName(constantPoolOffsets, reader, i);
+// type = extractType(constantPoolOffsets, reader, i);
+ addFieldReference(name);
+ break;
+ case ClassFileStruct.MethodRefTag :
+ // add reference to the class and method name and type
+ case ClassFileStruct.InterfaceMethodRefTag :
+ // add reference to the interface and method name and type
+ name = extractName(constantPoolOffsets, reader, i);
+ type = extractType(constantPoolOffsets, reader, i);
+ addMethodReference(name, extractArgCount(type));
+ }
}
+}
+private final char[] extractType(int[] constantPoolOffsets, ClassFileReader reader, int index) {
+ int constantPoolIndex = reader.u2At(constantPoolOffsets[index] + 3);
+ int utf8Offset = constantPoolOffsets[reader.u2At(constantPoolOffsets[constantPoolIndex] + 3)];
+ return reader.utf8At(utf8Offset + 3, reader.u2At(utf8Offset + 1));
+}
+/**
+ * getFileTypes method comment.
+ */
+public String[] getFileTypes() {
+ return FILE_TYPES;
+}
+private void indexClassFile(byte[] contents, char[] documentName) throws IOException {
+ try {
+ ClassFileReader reader = new ClassFileReader(contents, documentName);
+ // we don't want to index local and anonymous classes
+ if (reader.isLocal() || reader.isAnonymous()) return;
- private void indexClassFile(byte[] contents, char[] documentName)
- throws IOException {
- try {
- ClassFileReader reader = new ClassFileReader(contents, documentName);
- // we don't want to index local and anonymous classes
- if (reader.isLocal() || reader.isAnonymous())
- return;
-
- int[] constantPoolOffsets = reader.getConstantPoolOffsets();
+ int[] constantPoolOffsets = reader.getConstantPoolOffsets();
- // first add type references
- char[] className = replace('/', '.', reader.getName());
- // looks like java/lang/String
- // need to extract the package name and the simple name
- int packageNameIndex = CharOperation.lastIndexOf('.', className);
- char[] packageName = null;
- char[] name = null;
- if (packageNameIndex >= 0) {
- packageName = CharOperation.subarray(className, 0, packageNameIndex);
- name =
- CharOperation.subarray(className, packageNameIndex + 1, className.length);
- } else {
- name = className;
+ // first add type references
+ char[] className = replace('/', '.', reader.getName()); // looks like java/lang/String
+ // need to extract the package name and the simple name
+ int packageNameIndex = CharOperation.lastIndexOf('.', className);
+ char[] packageName = null;
+ char[] name = null;
+ if (packageNameIndex >= 0) {
+ packageName = CharOperation.subarray(className, 0, packageNameIndex);
+ name = CharOperation.subarray(className, packageNameIndex + 1, className.length);
+ } else {
+ name = className;
+ }
+ char[] enclosingTypeName = null;
+ if (reader.isNestedType()) {
+ name = reader.getInnerSourceName();
+ char[] fullEnclosingName = reader.getEnclosingTypeName();
+ int nameLength = fullEnclosingName.length - packageNameIndex - 1;
+ enclosingTypeName = new char[nameLength];
+ System.arraycopy(fullEnclosingName, packageNameIndex + 1, enclosingTypeName, 0, nameLength);
+ }
+ // eliminate invalid innerclasses (1G4KCF7)
+ if (name == null) return;
+
+ char[][] superinterfaces = replace('/', '.', reader.getInterfaceNames());
+ if (DEBUG) {
+ if (packageName != null) {
+ System.out.println("package name = " + new String(packageName));
}
- char[] enclosingTypeName = null;
- if (reader.isNestedType()) {
- name = reader.getInnerSourceName();
- char[] fullEnclosingName = reader.getEnclosingTypeName();
- int nameLength = fullEnclosingName.length - packageNameIndex - 1;
- enclosingTypeName = new char[nameLength];
- System.arraycopy(
- fullEnclosingName,
- packageNameIndex + 1,
- enclosingTypeName,
- 0,
- nameLength);
+ if (name != null) {
+ System.out.println("class name = " + new String(name));
}
- // eliminate invalid innerclasses (1G4KCF7)
- if (name == null)
- return;
-
- char[][] superinterfaces = replace('/', '.', reader.getInterfaceNames());
- if (DEBUG) {
- if (packageName != null) {
- System.out.println("package name = " + new String(packageName));
+ if (superinterfaces != null) {
+ for (int i = 0, max = superinterfaces.length; i < max; i++) {
+ System.out.println("superinterfaces[" + i + "]= " + new String(superinterfaces[i]));
}
- if (name != null) {
- System.out.println("class name = " + new String(name));
- }
- if (superinterfaces != null) {
- for (int i = 0, max = superinterfaces.length; i < max; i++) {
- System.out.println(
- "superinterfaces[" + i + "]= " + new String(superinterfaces[i]));
- }
+ }
+ }
+ char[][] enclosingTypeNames = enclosingTypeName == null ? null : new char[][] {enclosingTypeName};
+ if (reader.isInterface()) {
+ addInterfaceDeclaration(reader.getModifiers(), packageName, name, enclosingTypeNames, superinterfaces);
+ } else {
+ char[] superclass = replace('/', '.', reader.getSuperclassName());
+ if (DEBUG) {
+ if (superclass != null) {
+ System.out.println("superclass name = " + new String(superclass));
}
}
- char[][] enclosingTypeNames =
- enclosingTypeName == null ? null : new char[][] { enclosingTypeName };
- if (reader.isInterface()) {
- addInterfaceDeclaration(
- reader.getModifiers(),
- packageName,
- name,
- enclosingTypeNames,
- superinterfaces);
- } else {
- char[] superclass = replace('/', '.', reader.getSuperclassName());
+ addClassDeclaration(reader.getModifiers(), packageName, name, enclosingTypeNames, superclass, superinterfaces);
+ }
+
+ // first reference all methods declarations and field declarations
+ MethodInfo[] methods = (MethodInfo[]) reader.getMethods();
+ if (methods != null) {
+ for (int i = 0, max = methods.length; i < max; i++) {
+ MethodInfo method = methods[i];
+ char[] descriptor = method.getMethodDescriptor();
+ char[][] parameterTypes = decodeParameterTypes(descriptor);
+ char[] returnType = decodeReturnType(descriptor);
+ char[][] exceptionTypes = replace('/', '.', method.getExceptionTypeNames());
if (DEBUG) {
- if (superclass != null) {
- System.out.println("superclass name = " + new String(superclass));
+ if (method.getSelector() != null) {
+ System.out.println("method selector = " + new String(method.getSelector()));
}
- }
- addClassDeclaration(
- reader.getModifiers(),
- packageName,
- name,
- enclosingTypeNames,
- superclass,
- superinterfaces);
- }
-
- // first reference all methods declarations and field declarations
- MethodInfo[] methods = (MethodInfo[]) reader.getMethods();
- if (methods != null) {
- for (int i = 0, max = methods.length; i < max; i++) {
- MethodInfo method = methods[i];
- char[] descriptor = method.getMethodDescriptor();
- char[][] parameterTypes = decodeParameterTypes(descriptor);
- char[] returnType = decodeReturnType(descriptor);
- char[][] exceptionTypes = replace('/', '.', method.getExceptionTypeNames());
- if (DEBUG) {
- if (method.getSelector() != null) {
- System.out.println("method selector = " + new String(method.getSelector()));
- }
- if (parameterTypes != null) {
- for (int j = 0, max2 = parameterTypes.length; j < max2; j++) {
- System.out.println(
- "parameterTypes[" + j + "]= " + new String(parameterTypes[j]));
- }
- }
- if (returnType != null) {
- System.out.println("return type = " + new String(returnType));
- }
- if (exceptionTypes != null) {
- for (int j = 0, max2 = exceptionTypes.length; j < max2; j++) {
- System.out.println(
- "exceptionTypes[" + j + "]= " + new String(exceptionTypes[j]));
- }
+ if (parameterTypes != null) {
+ for (int j = 0, max2 = parameterTypes.length; j < max2; j++) {
+ System.out.println("parameterTypes[" + j + "]= " + new String(parameterTypes[j]));
}
}
- if (method.isConstructor()) {
- addConstructorDeclaration(className, parameterTypes, exceptionTypes);
- } else {
- if (!method.isClinit()) {
- addMethodDeclaration(
- method.getSelector(),
- parameterTypes,
- returnType,
- exceptionTypes);
+ if (returnType != null) {
+ System.out.println("return type = " + new String(returnType));
+ }
+ if (exceptionTypes != null) {
+ for (int j = 0, max2 = exceptionTypes.length; j < max2; j++) {
+ System.out.println("exceptionTypes[" + j + "]= " + new String(exceptionTypes[j]));
}
}
}
- }
- FieldInfo[] fields = (FieldInfo[]) reader.getFields();
- if (fields != null) {
- for (int i = 0, max = fields.length; i < max; i++) {
- FieldInfo field = fields[i];
- char[] fieldName = field.getName();
- char[] fieldType = decodeFieldType(replace('/', '.', field.getTypeName()));
- if (DEBUG) {
- if (fieldName != null) {
- System.out.println("field name = " + new String(fieldName));
- }
- if (fieldType != null) {
- System.out.println("field type = " + new String(fieldType));
- }
+ if (method.isConstructor()) {
+ addConstructorDeclaration(className, parameterTypes, exceptionTypes);
+ } else {
+ if (!method.isClinit()) {
+ addMethodDeclaration(method.getSelector(), parameterTypes, returnType, exceptionTypes);
}
- addFieldDeclaration(fieldType, fieldName);
}
}
-
- // record all references found inside the .class file
- if (needReferences) {
- extractReferenceFromConstantPool(contents, reader);
+ }
+ FieldInfo[] fields = (FieldInfo[]) reader.getFields();
+ if (fields != null) {
+ for (int i = 0, max = fields.length; i < max; i++) {
+ FieldInfo field = fields[i];
+ char[] fieldName = field.getName();
+ char[] fieldType = decodeFieldType(replace('/', '.', field.getTypeName()));
+ if (DEBUG) {
+ if (fieldName != null) {
+ System.out.println("field name = " + new String(fieldName));
+ }
+ if (fieldType != null) {
+ System.out.println("field type = " + new String(fieldType));
+ }
+ }
+ addFieldDeclaration(fieldType, fieldName);
}
- } catch (ClassFormatException e) {
}
- }
- /**
- * indexFile method comment.
- */
- protected void indexFile(IDocument document) throws IOException {
- // Add the name of the file to the index
- output.addDocument(document);
- indexClassFile(document.getByteContent(), document.getName().toCharArray());
- }
-
- /**
- * Modify the array by replacing all occurences of toBeReplaced with newChar
- */
- private char[][] replace(char toBeReplaced, char newChar, char[][] array) {
- if (array == null)
- return null;
- for (int i = 0, max = array.length; i < max; i++) {
- replace(toBeReplaced, newChar, array[i]);
+ // record all references found inside the .class file
+ if (needReferences) {
+ extractReferenceFromConstantPool(contents, reader);
}
- return array;
+ } catch (ClassFormatException e) {
}
-
- /**
- * Modify the array by replacing all occurences of toBeReplaced with newChar
- */
- private char[] replace(char toBeReplaced, char newChar, char[] array) {
- if (array == null)
- return null;
- for (int i = 0, max = array.length; i < max; i++) {
- if (array[i] == toBeReplaced) {
- array[i] = newChar;
- }
- }
- return array;
+}
+/**
+ * indexFile method comment.
+ */
+protected void indexFile(IDocument document) throws IOException {
+ // Add the name of the file to the index
+ output.addDocument(document);
+ indexClassFile(document.getByteContent(), document.getName().toCharArray());
+}
+/**
+ * Modify the array by replacing all occurences of toBeReplaced with newChar
+ */
+private char[][] replace(char toBeReplaced, char newChar, char[][] array) {
+ if (array == null) return null;
+ for (int i = 0, max = array.length; i < max; i++) {
+ replace(toBeReplaced, newChar, array[i]);
}
-
- /**
- * setFileTypes method comment.
- */
- public void setFileTypes(String[] fileTypes) {
+ return array;
+}
+/**
+ * Modify the array by replacing all occurences of toBeReplaced with newChar
+ */
+private char[] replace(char toBeReplaced, char newChar, char[] array) {
+ if (array == null) return null;
+ for (int i = 0, max = array.length; i < max; i++) {
+ if (array[i] == toBeReplaced) {
+ array[i] = newChar;
+ }
}
-
+ return array;
+}
+/**
+ * setFileTypes method comment.
+ */
+public void setFileTypes(String[] fileTypes) {}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/IIndexConstants.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/IIndexConstants.java
index b7aca5a1d8..1397c72c52 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/IIndexConstants.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/IIndexConstants.java
@@ -9,40 +9,29 @@ import org.eclipse.jdt.internal.core.search.processing.*;
public interface IIndexConstants extends IJobConstants {
/* index encoding */
- char[] REF = "ref/".toCharArray();
- char[] FIELD_REF = "fieldRef/".toCharArray();
- char[] METHOD_REF = "methodRef/".toCharArray();
- char[] CONSTRUCTOR_REF = "constructorRef/".toCharArray();
- char[] TYPE_REF = "typeRef/".toCharArray();
+ char[] REF= "ref/".toCharArray();
+ char[] FIELD_REF= "fieldRef/".toCharArray();
+ char[] METHOD_REF= "methodRef/".toCharArray();
+ char[] CONSTRUCTOR_REF= "constructorRef/".toCharArray();
+ char[] TYPE_REF= "typeRef/".toCharArray();
char[] SUPER_REF = "superRef/".toCharArray();
char[] TYPE_DECL = "typeDecl/".toCharArray();
- int TYPE_DECL_LENGTH = 9;
- char[] CLASS_DECL = "typeDecl/C/".toCharArray();
- char[] INTERFACE_DECL = "typeDecl/I/".toCharArray();
- char[] METHOD_DECL = "methodDecl/".toCharArray();
- char[] CONSTRUCTOR_DECL = "constructorDecl/".toCharArray();
- char[] FIELD_DECL = "fieldDecl/".toCharArray();
+ int TYPE_DECL_LENGTH = 9;
+ char[] CLASS_DECL= "typeDecl/C/".toCharArray();
+ char[] INTERFACE_DECL= "typeDecl/I/".toCharArray();
+ char[] METHOD_DECL= "methodDecl/".toCharArray();
+ char[] CONSTRUCTOR_DECL= "constructorDecl/".toCharArray();
+ char[] FIELD_DECL= "fieldDecl/".toCharArray();
char[] OBJECT = "Object".toCharArray();
- char[][] COUNTS =
- new char[][] {
- new char[] { '0' },
- new char[] { '1' },
- new char[] { '2' },
- new char[] { '3' },
- new char[] { '4' },
- new char[] { '5' },
- new char[] { '6' },
- new char[] { '7' },
- new char[] { '8' },
- new char[] { '9' }
+ char[][] COUNTS=
+ new char[][] { new char[] {'0'}, new char[] {'1'}, new char[] {'2'}, new char[] {'3'}, new char[] {'4'}, new char[] {'5'}, new char[] {'6'}, new char[] {'7'}, new char[] {'8'}, new char[] {'9'}
};
-
char CLASS_SUFFIX = 'C';
char INTERFACE_SUFFIX = 'I';
char TYPE_SUFFIX = 0;
- char SEPARATOR = '/';
+ char SEPARATOR= '/';
- char[] ONE_STAR = new char[] { '*' };
+ char[] ONE_STAR = new char[] {'*'};
char[] NO_CHAR = new char[0];
char[][] NO_CHAR_CHAR = new char[0][];
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java
index 5f80fad717..6f33dcb46e 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/IndexAllProject.java
@@ -17,107 +17,97 @@ import java.util.*;
public class IndexAllProject implements IJob, IJobConstants {
IProject project;
IndexManager manager;
- public IndexAllProject(IProject project, IndexManager manager) {
- this.project = project;
- this.manager = manager;
- }
-
- public boolean belongsTo(String jobFamily) {
- return jobFamily.equals(project.getName());
- }
-
- /**
- * Ensure consistency of a project index. Need to walk all nested resources,
- * and discover resources which have either been changed, added or deleted
- * since the index was produced.
- */
- public boolean execute() {
-
- if (!project.isOpen())
- return COMPLETE; // nothing to do
+public IndexAllProject(IProject project, IndexManager manager){
+ this.project = project;
+ this.manager = manager;
+}
+public boolean belongsTo(String jobFamily){
+ return jobFamily.equals(project.getName());
+}
+/**
+ * Ensure consistency of a project index. Need to walk all nested resources,
+ * and discover resources which have either been changed, added or deleted
+ * since the index was produced.
+ */
+public boolean execute(){
- IIndex index = manager.getIndex(project.getFullPath());
- if (index == null)
- return COMPLETE;
- ReadWriteMonitor monitor = manager.getMonitorFor(index);
- if (monitor == null)
- return COMPLETE; // index got deleted since acquired
- try {
- monitor.enterRead(); // ask permission to read
+ if (!project.isOpen()) return COMPLETE; // nothing to do
+
+ IIndex index = manager.getIndex(project.getFullPath());
+ if (index == null) return COMPLETE;
+ ReadWriteMonitor monitor = manager.getMonitorFor(index);
+ if (monitor == null) return COMPLETE; // index got deleted since acquired
+ try {
+ monitor.enterRead(); // ask permission to read
- /* if index has changed, commit these before querying */
- if (index.hasChanged()) {
- try {
- monitor.exitRead(); // free read lock
- monitor.enterWrite(); // ask permission to write
- if (IndexManager.VERBOSE)
- System.out.println("-> merging index : " + index.getIndexFile());
- index.save();
- } catch (IOException e) {
- return FAILED;
- } finally {
- monitor.exitWrite(); // finished writing
- monitor.enterRead(); // reacquire read permission
- }
+ /* if index has changed, commit these before querying */
+ if (index.hasChanged()){
+ try {
+ monitor.exitRead(); // free read lock
+ monitor.enterWrite(); // ask permission to write
+ if (IndexManager.VERBOSE) System.out.println("-> merging index : "+index.getIndexFile());
+ index.save();
+ } catch(IOException e){
+ return FAILED;
+ } finally {
+ monitor.exitWrite(); // finished writing
+ monitor.enterRead(); // reacquire read permission
}
- final String OK = "OK";
- final String DELETED = "DELETED";
- final long indexLastModified = index.getIndexFile().lastModified();
+ }
+ final String OK = "OK";
+ final String DELETED = "DELETED";
+ final long indexLastModified = index.getIndexFile().lastModified();
- final Hashtable indexedFileNames = new Hashtable(100);
- IQueryResult[] results = index.queryInDocumentNames(""); // all file names
- for (int i = 0, max = results == null ? 0 : results.length; i < max; i++) {
- String fileName = results[i].getPath();
- indexedFileNames.put(fileName, DELETED);
- }
- project.accept(new IResourceVisitor() {
- public boolean visit(IResource resource) {
- if (resource.getType() == IResource.FILE) {
- String extension = resource.getFileExtension();
- if ((extension != null) && extension.equalsIgnoreCase("java")) {
- IPath path = resource.getLocation();
- if (path != null) {
- File resourceFile = path.toFile();
- String name = new IFileDocument((IFile) resource).getName();
- if (indexedFileNames.get(name) == null) {
- indexedFileNames.put(name, resource);
- } else {
- indexedFileNames.put(
- name,
- resourceFile.lastModified() > indexLastModified
- ? (Object) resource
- : (Object) OK);
- }
+ final Hashtable indexedFileNames = new Hashtable(100);
+ IQueryResult[] results = index.queryInDocumentNames(""); // all file names
+ for (int i = 0, max = results == null ? 0 : results.length; i < max; i++){
+ String fileName = results[i].getPath();
+ indexedFileNames.put(fileName, DELETED);
+ }
+ project.accept(new IResourceVisitor(){
+ public boolean visit(IResource resource) {
+ if (resource.getType() == IResource.FILE) {
+ String extension = resource.getFileExtension();
+ if ((extension != null) && extension.equalsIgnoreCase("java")) {
+ IPath path = resource.getLocation();
+ if (path != null){
+ File resourceFile = path.toFile();
+ String name = new IFileDocument((IFile)resource).getName();
+ if (indexedFileNames.get(name) == null){
+ indexedFileNames.put(name, resource);
+ } else {
+ indexedFileNames.put(
+ name,
+ resourceFile.lastModified() > indexLastModified
+ ? (Object)resource
+ : (Object)OK);
}
}
- return false;
}
- return true;
+ return false;
}
- });
- Enumeration names = indexedFileNames.keys();
- while (names.hasMoreElements()) {
- String name = (String) names.nextElement();
- Object value = indexedFileNames.get(name);
- if (value instanceof IFile) {
- manager.add((IFile) value);
- } else
- if (value == DELETED) {
- manager.remove(name, project);
- }
+ return true;
+ }});
+ Enumeration names = indexedFileNames.keys();
+ while (names.hasMoreElements()){
+ String name = (String)names.nextElement();
+ Object value = indexedFileNames.get(name);
+ if (value instanceof IFile){
+ manager.add((IFile)value);
+ } else if (value == DELETED){
+ manager.remove(name, project);
}
- } catch (CoreException e) {
- return FAILED;
- } catch (IOException e) {
- return FAILED;
- } finally {
- monitor.exitRead(); // free read lock
}
- return COMPLETE;
+ } catch (CoreException e){
+ return FAILED;
+ } catch (IOException e){
+ return FAILED;
+ } finally {
+ monitor.exitRead(); // free read lock
}
-
- public String toString() {
- return "indexing project " + project.getName();
- }
-
+ return COMPLETE;
+}
+public String toString(){
+ return "indexing project "+ project.getName();
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
index f158e89ba7..ad4fcd7177 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/IndexManager.java
@@ -25,7 +25,7 @@ import java.util.zip.*;
public class IndexManager extends JobManager implements IIndexConstants {
/* number of file contents in memory */
public static int MAX_FILES_IN_MEMORY = 0;
-
+
public IWorkspace workspace;
/* indexes */
@@ -38,363 +38,310 @@ public class IndexManager extends JobManager implements IIndexConstants {
private boolean needToSave = false;
private static final CRC32 checksumCalculator = new CRC32();
private IPath javaPluginLocation = null;
- /**
- * Before processing all jobs, need to ensure that the indexes are up to date.
- */
- public void activateProcessing() {
- try {
- Thread.currentThread().sleep(10000);
- // wait 10 seconds so as not to interfere with plugin startup
- } catch (InterruptedException ie) {
- }
- checkIndexConsistency();
- }
-
- /**
- * Trigger addition of a resource to an index
- * Note: the actual operation is performed in background
- */
- public void add(IFile resource) {
- if (JavaCore.getPlugin() == null || this.workspace == null)
- return;
- String extension = resource.getFileExtension();
- if ("java".equals(extension)) {
- AddCompilationUnitToIndex job = new AddCompilationUnitToIndex(resource, this);
- if (this.awaitingJobsCount() < MAX_FILES_IN_MEMORY) {
- job.initializeContents();
- }
- request(job);
- } else
- if ("class".equals(extension)) {
- AddClassFileToIndex job = new AddClassFileToIndex(resource, this);
- if (this.awaitingJobsCount() < MAX_FILES_IN_MEMORY) {
- job.initializeContents();
- }
- request(job);
- }
- }
-
- /**
- * Ensures that indexes are up to date with workbench content. Typically
- * it is invoked in background when activate the job processing.
- */
- public void checkIndexConsistency() {
-
- if (VERBOSE)
- System.out.println("STARTING - ensuring consistency");
-
- boolean wasEnabled = isEnabled();
- try {
- disable();
-
- if (this.workspace == null)
- return;
- IProject[] projects = this.workspace.getRoot().getProjects();
- for (int i = 0, max = projects.length; i < max; i++) {
- IProject project = projects[i];
- // not only java project, given at startup nature may not have been set yet
- if (project.isOpen()) {
- indexAll(project);
- }
- }
- } finally {
- if (wasEnabled)
- enable();
- if (VERBOSE)
- System.out.println("DONE - ensuring consistency");
- }
- }
-
- private String computeIndexName(String pathString) {
- byte[] pathBytes = pathString.getBytes();
- checksumCalculator.reset();
- checksumCalculator.update(pathBytes);
- String fileName = Long.toString(checksumCalculator.getValue()) + ".index";
- if (VERBOSE)
- System.out.println(" index name: " + pathString + " <----> " + fileName);
- IPath indexPath = getJavaPluginWorkingLocation();
- String indexDirectory = indexPath.toOSString();
- if (indexDirectory.endsWith(File.separator)) {
- return indexDirectory + fileName;
- } else {
- return indexDirectory + File.separator + fileName;
+/**
+ * Before processing all jobs, need to ensure that the indexes are up to date.
+ */
+public void activateProcessing() {
+ try {
+ Thread.currentThread().sleep(10000); // wait 10 seconds so as not to interfere with plugin startup
+ } catch (InterruptedException ie) {
+ }
+ checkIndexConsistency();
+ super.activateProcessing();
+}
+/**
+ * Trigger addition of a resource to an index
+ * Note: the actual operation is performed in background
+ */
+public void add(IFile resource){
+ if (JavaCore.getPlugin() == null || this.workspace == null) return;
+ String extension = resource.getFileExtension();
+ if ("java".equals(extension)){
+ AddCompilationUnitToIndex job = new AddCompilationUnitToIndex(resource, this);
+ if (this.awaitingJobsCount() < MAX_FILES_IN_MEMORY) {
+ job.initializeContents();
}
- }
-
- /**
- * About to delete a project.
- */
- public void deleting(IProject project) {
- discardJobsUntilNextProjectAddition(project.getName());
-
- IPath path = project.getFullPath();
- IIndex index = (IIndex) indexes.get(path);
- if (index != null) {
- indexes.remove(path);
- monitors.remove(index);
+ request(job);
+ } else if ("class".equals(extension)){
+ AddClassFileToIndex job = new AddClassFileToIndex(resource, this);
+ if (this.awaitingJobsCount() < MAX_FILES_IN_MEMORY) {
+ job.initializeContents();
}
+ request(job);
}
+}
+/**
+ * Ensures that indexes are up to date with workbench content. Typically
+ * it is invoked in background when activate the job processing.
+ */
+public void checkIndexConsistency() {
- /**
- * Remove the index from cache for a given project.
- * Passing null as a job family discards them all.
- */
- public void discardJobsUntilNextProjectAddition(String jobFamily) {
- boolean wasEnabled = isEnabled();
- try {
- disable();
+ if (VERBOSE) System.out.println("STARTING - ensuring consistency");
- // wait until current job has completed
- while (thread != null && executing) {
- try {
- Thread.currentThread().sleep(50);
- } catch (InterruptedException e) {
- }
- }
+ boolean wasEnabled = isEnabled();
+ try {
+ disable();
- // flush and compact awaiting jobs
- int loc = -1;
- boolean foundProjectAddition = false;
- for (int i = jobStart; i <= jobEnd; i++) {
- IJob currentJob = awaitingJobs[i];
- awaitingJobs[i] = null;
- if (jobFamily == null)
- continue; // discard
- if (currentJob.belongsTo(jobFamily)) { // might discard
- if (!(foundProjectAddition
- || (foundProjectAddition = currentJob instanceof IndexAllProject)))
- continue; // discard
- }
- awaitingJobs[++loc] = currentJob;
+ if (this.workspace == null) return;
+ IProject[] projects = this.workspace.getRoot().getProjects();
+ for (int i = 0, max = projects.length; i < max; i++){
+ IProject project = projects[i];
+ // not only java project, given at startup nature may not have been set yet
+ if (project.isOpen()) {
+ indexAll(project);
}
- jobStart = 0;
- jobEnd = loc;
- } finally {
- if (wasEnabled)
- enable();
}
+ } finally {
+ if (wasEnabled) enable();
+ if (VERBOSE) System.out.println("DONE - ensuring consistency");
}
-
- /**
- * Returns the index for a given project, if none then create an empty one.
- * Note: if there is an existing index file already, it will be reused.
- * Warning: Does not check whether index is consistent (not being used)
- */
- public IIndex getIndex(IPath path) {
- return this.getIndex(path, true);
+}
+private String computeIndexName(String pathString) {
+ byte[] pathBytes = pathString.getBytes();
+ checksumCalculator.reset();
+ checksumCalculator.update(pathBytes);
+ String fileName = Long.toString(checksumCalculator.getValue()) + ".index";
+ if (VERBOSE) System.out.println(" index name: " + pathString + " <----> " + fileName);
+ IPath indexPath = getJavaPluginWorkingLocation();
+ String indexDirectory = indexPath.toOSString();
+ if (indexDirectory.endsWith(File.separator)) {
+ return indexDirectory + fileName;
+ } else {
+ return indexDirectory + File.separator + fileName;
+ }
+}
+/**
+ * About to delete a project.
+ */
+public void deleting(IProject project) {
+ discardJobsUntilNextProjectAddition(project.getName());
+
+ IPath path = project.getFullPath();
+ IIndex index = (IIndex) indexes.get(path);
+ if (index != null){
+ indexes.remove(path);
+ monitors.remove(index);
}
+}
+/**
+ * Remove the index from cache for a given project.
+ * Passing null as a job family discards them all.
+ */
+public void discardJobsUntilNextProjectAddition(String jobFamily) {
+ boolean wasEnabled = isEnabled();
+ try {
+ disable();
- /**
- * Returns the index for a given project, if none and asked for then create an empty one.
- * Note: if there is an existing index file already, it will be reused.
- * Warning: Does not check whether index is consistent (not being used)
- */
- public synchronized IIndex getIndex(IPath path, boolean mustCreate) {
- IIndex index = (IIndex) indexes.get(path);
- if (index == null) {
+ // wait until current job has completed
+ while (thread != null && executing){
try {
- // Compute canonical path
- IPath canonicalPath = JavaProject.canonicalizedPath(path);
- index = (IIndex) indexes.get(canonicalPath);
- if (!mustCreate)
- return index;
- if (index == null) {
- // New index: add same index for given path and canonical path
- String indexPath = computeIndexName(canonicalPath.toOSString());
- index =
- IndexFactory.newIndex(indexPath, "Index for " + canonicalPath.toOSString());
- indexes.put(canonicalPath, index);
- indexes.put(path, index);
- monitors.put(index, new ReadWriteMonitor());
- } else {
- // Index existed for canonical path, add it for given path
- indexes.put(path, index);
- }
- } catch (IOException e) {
- // The file could not be created. Possible reason: the project has been deleted.
- return null;
+ Thread.currentThread().sleep(50);
+ } catch(InterruptedException e){
}
}
- //System.out.println(" index name: " + path.toOSString() + " <----> " + index.getIndexFile().getName());
- return index;
- }
- private IPath getJavaPluginWorkingLocation() {
- if (javaPluginLocation == null) {
- javaPluginLocation = JavaCore.getPlugin().getStateLocation();
- }
- return javaPluginLocation;
- }
-
- /**
- * Index access is controlled through a read-write monitor so as
- * to ensure there is no concurrent read and write operations
- * (only concurrent reading is allowed).
- */
- public ReadWriteMonitor getMonitorFor(IIndex index) {
-
- return (ReadWriteMonitor) monitors.get(index);
- }
-
- /**
- * Trigger addition of the entire content of a project
- * Note: the actual operation is performed in background
- */
- public void indexAll(IProject project) {
- if (JavaCore.getPlugin() == null || this.workspace == null)
- return;
-
- // Also request indexing of binaries on the classpath
- // determine the new children
- try {
- IJavaModel model = JavaModelManager.getJavaModel(this.workspace);
- IJavaProject javaProject = ((JavaModel) model).getJavaProject(project);
- IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
- for (int i = 0; i < entries.length; i++) {
- IClasspathEntry entry = entries[i];
- IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots(entry);
- for (int j = 0; j < roots.length; j++) {
- IPackageFragmentRoot root = roots[j];
- if (root.exists()) {
- if (root.isArchive()) {
- IResource rsc = root.getUnderlyingResource();
- if (rsc == null) {
- indexJarFile(root, project.getName());
- } else {
- indexJarFile((IFile) rsc, project.getName());
- }
- }
- }
- }
+ // flush and compact awaiting jobs
+ int loc = -1;
+ boolean foundProjectAddition = false;
+ for (int i = jobStart; i <= jobEnd; i++){
+ IJob currentJob = awaitingJobs[i];
+ awaitingJobs[i] = null;
+ if (jobFamily == null) continue; // discard
+ if (currentJob.belongsTo(jobFamily)){ // might discard
+ if (!(foundProjectAddition || (foundProjectAddition = currentJob instanceof IndexAllProject))) continue; // discard
}
- } catch (JavaModelException e) { // cannot retrieve classpath info
+ awaitingJobs[++loc] = currentJob;
}
- request(new IndexAllProject(project, this));
- }
-
- /**
- * Trigger addition of a resource to an index
- * Note: the actual operation is performed in background
- */
- public void indexJarFile(IFile resource, String projectName) {
- if (JavaCore.getPlugin() == null || this.workspace == null)
- return;
- request(new AddJarFileToIndex(resource, this, projectName));
- }
-
- /**
- * Trigger addition of a resource to an index
- * Note: the actual operation is performed in background
- */
- public void indexJarFile(IPackageFragmentRoot root, String projectName) {
- if (JavaCore.getPlugin() == null || this.workspace == null)
- return;
- // we want to request a indexing only if this index doesn't already exist
- request(new AddJarFileToIndex(root, this, projectName));
+ jobStart = 0;
+ jobEnd = loc;
+ } finally {
+ if (wasEnabled) enable();
}
-
- /**
- * Advance to the next available job, once the current one has been completed.
- * Note: clients awaiting until the job count is zero are still waiting at this point.
- */
- protected synchronized void moveToNextJob() {
-
- // remember that one job was executed, and we will need to save indexes at some point
- needToSave = true;
- super.moveToNextJob();
- }
-
- /**
- * No more job awaiting.
- */
- protected void notifyIdle(long idlingTime) {
- if (idlingTime > 1000 && needToSave)
- saveIndexes();
- }
-
- /**
- * Name of the background process
- */
- public String processName() {
- return "Java indexing: " + IndexManager.class.getName();
- }
-
- /**
- * Recreates the index for a given path, keeping the same read-write monitor.
- * Returns the new empty index or null if it didn't exist before.
- * Warning: Does not check whether index is consistent (not being used)
- */
- public synchronized IIndex recreateIndex(IPath path) {
- IIndex index = (IIndex) indexes.get(path);
- if (index != null) {
- try {
- // Compute canonical path
- IPath canonicalPath = JavaProject.canonicalizedPath(path);
- // Add same index for given path and canonical path
+}
+/**
+ * Returns the index for a given project, if none then create an empty one.
+ * Note: if there is an existing index file already, it will be reused.
+ * Warning: Does not check whether index is consistent (not being used)
+ */
+public IIndex getIndex(IPath path) {
+ return this.getIndex(path, true);
+}
+/**
+ * Returns the index for a given project, if none and asked for then create an empty one.
+ * Note: if there is an existing index file already, it will be reused.
+ * Warning: Does not check whether index is consistent (not being used)
+ */
+public synchronized IIndex getIndex(IPath path, boolean mustCreate) {
+ IIndex index = (IIndex) indexes.get(path);
+ if (index == null) {
+ try {
+ // Compute canonical path
+ IPath canonicalPath = JavaProject.canonicalizedPath(path);
+ index = (IIndex) indexes.get(canonicalPath);
+ if (!mustCreate) return index;
+ if (index == null) {
+ // New index: add same index for given path and canonical path
String indexPath = computeIndexName(canonicalPath.toOSString());
- ReadWriteMonitor monitor = (ReadWriteMonitor) monitors.remove(index);
- index =
- IndexFactory.newIndex(indexPath, "Index for " + canonicalPath.toOSString());
- index.empty();
+ index = IndexFactory.newIndex(indexPath, "Index for " + canonicalPath.toOSString());
indexes.put(canonicalPath, index);
indexes.put(path, index);
- monitors.put(index, monitor);
- } catch (IOException e) {
- // The file could not be created. Possible reason: the project has been deleted.
- return null;
+ monitors.put(index, new ReadWriteMonitor());
+ } else {
+ // Index existed for canonical path, add it for given path
+ indexes.put(path, index);
}
+ } catch (IOException e) {
+ // The file could not be created. Possible reason: the project has been deleted.
+ return null;
}
- //System.out.println(" index name: " + path.toOSString() + " <----> " + index.getIndexFile().getName());
- return index;
}
-
- /**
- * Trigger removal of a resource to an index
- * Note: the actual operation is performed in background
- */
- public void remove(String resourceName, IProject project) {
- request(new RemoveFromIndex(resourceName, project, this));
+ //System.out.println(" index name: " + path.toOSString() + " <----> " + index.getIndexFile().getName());
+ return index;
+}
+private IPath getJavaPluginWorkingLocation() {
+ if (javaPluginLocation == null) {
+ javaPluginLocation = JavaCore.getPlugin().getStateLocation();
}
+ return javaPluginLocation;
+}
+/**
+ * Index access is controlled through a read-write monitor so as
+ * to ensure there is no concurrent read and write operations
+ * (only concurrent reading is allowed).
+ */
+public ReadWriteMonitor getMonitorFor(IIndex index){
+
+ return (ReadWriteMonitor)monitors.get(index);
+}
+/**
+ * Trigger addition of the entire content of a project
+ * Note: the actual operation is performed in background
+ */
+public void indexAll(IProject project){
+ if (JavaCore.getPlugin() == null || this.workspace == null) return;
+
+ // Also request indexing of binaries on the classpath
+ // determine the new children
+ try {
+ IJavaModel model = JavaModelManager.getJavaModel(this.workspace);
+ IJavaProject javaProject = ((JavaModel) model).getJavaProject(project);
+ IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
+ for (int i = 0; i < entries.length; i++) {
+ IClasspathEntry entry= entries[i];
+ if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY){
+ indexJarFile(entry.getPath(), project.getName());
+ }
+ }
+ } catch(JavaModelException e){ // cannot retrieve classpath info
+ }
+ request(new IndexAllProject(project, this));
+}
+/**
+ * Advance to the next available job, once the current one has been completed.
+ * Note: clients awaiting until the job count is zero are still waiting at this point.
+ */
+protected synchronized void moveToNextJob() {
- /**
- * Flush current state
- */
- public void reset() {
-
- super.reset();
- if (indexes != null) {
- indexes = new Hashtable(5);
- monitors = new Hashtable(5);
+ // remember that one job was executed, and we will need to save indexes at some point
+ needToSave = true;
+ super.moveToNextJob();
+}
+/**
+ * No more job awaiting.
+ */
+protected void notifyIdle(long idlingTime){
+ if (idlingTime > 1000 && needToSave) saveIndexes();
+}
+/**
+ * Name of the background process
+ */
+public String processName(){
+ return "Java indexing: " + IndexManager.class.getName();
+}
+/**
+ * Recreates the index for a given path, keeping the same read-write monitor.
+ * Returns the new empty index or null if it didn't exist before.
+ * Warning: Does not check whether index is consistent (not being used)
+ */
+public synchronized IIndex recreateIndex(IPath path) {
+ IIndex index = (IIndex) indexes.get(path);
+ if (index != null) {
+ try {
+ // Compute canonical path
+ IPath canonicalPath = JavaProject.canonicalizedPath(path);
+ // Add same index for given path and canonical path
+ String indexPath = computeIndexName(canonicalPath.toOSString());
+ ReadWriteMonitor monitor = (ReadWriteMonitor)monitors.remove(index);
+ index = IndexFactory.newIndex(indexPath, "Index for " + canonicalPath.toOSString());
+ index.empty();
+ indexes.put(canonicalPath, index);
+ indexes.put(path, index);
+ monitors.put(index, monitor);
+ } catch (IOException e) {
+ // The file could not be created. Possible reason: the project has been deleted.
+ return null;
}
- javaPluginLocation = null;
}
+ //System.out.println(" index name: " + path.toOSString() + " <----> " + index.getIndexFile().getName());
+ return index;
+}
+/**
+ * Trigger removal of a resource to an index
+ * Note: the actual operation is performed in background
+ */
+public void remove(String resourceName, IProject project){
+ request(new RemoveFromIndex(resourceName, project, this));
+}
+/**
+ * Flush current state
+ */
+public void reset(){
- /**
- * Commit all index memory changes to disk
- */
- public void saveIndexes() {
- Enumeration indexList = indexes.elements();
- while (indexList.hasMoreElements()) {
+ super.reset();
+ if (indexes != null){
+ indexes = new Hashtable(5);
+ monitors = new Hashtable(5);
+ }
+ javaPluginLocation = null;
+}
+/**
+ * Commit all index memory changes to disk
+ */
+public void saveIndexes(){
+ Enumeration indexList = indexes.elements();
+ while (indexList.hasMoreElements()){
+ try {
+ IIndex index = (IIndex)indexList.nextElement();
+ if (index == null) continue; // index got deleted since acquired
+ ReadWriteMonitor monitor = getMonitorFor(index);
+ if (monitor == null) continue; // index got deleted since acquired
try {
- IIndex index = (IIndex) indexList.nextElement();
- if (index == null)
- continue; // index got deleted since acquired
- ReadWriteMonitor monitor = getMonitorFor(index);
- if (monitor == null)
- continue; // index got deleted since acquired
- try {
- monitor.enterWrite();
- if (IndexManager.VERBOSE)
- System.out.println("-> merging index : " + index.getIndexFile());
- index.save();
- } finally {
- monitor.exitWrite();
- }
- } catch (IOException e) {
- // Index file has been deleted
+ monitor.enterWrite();
+ if (IndexManager.VERBOSE) System.out.println("-> merging index : "+index.getIndexFile());
+ index.save();
+ } finally {
+ monitor.exitWrite();
}
+ } catch(IOException e){
+ // Index file has been deleted
}
- needToSave = false;
}
+ needToSave = false;
+}
+/**
+ * Trigger addition of a resource to an index
+ * Note: the actual operation is performed in background
+ */
+public void indexJarFile(IPath path, String projectName) {
+ if (JavaCore.getPlugin() == null || this.workspace == null) return;
+
+ Object target = JavaModel.getTarget(ResourcesPlugin.getWorkspace().getRoot(), path, true);
+
+ if (target instanceof IFile) {
+ request(new AddJarFileToIndex((IFile)target, this, projectName));
+ } else if (target instanceof java.io.File){
+ request(new AddJarFileToIndex(path, this, projectName));
+ }
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/ReadWriteMonitor.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/ReadWriteMonitor.java
index 6524658c58..c2e027d025 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/ReadWriteMonitor.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/ReadWriteMonitor.java
@@ -8,53 +8,47 @@ public class ReadWriteMonitor {
* >0 : reading (number of concurrent readers)
*/
private int status = 0;
- /**
- * Concurrent reading is allowed
- * Blocking only when already writing.
- */
- public synchronized void enterRead() {
-
- while (status < 0) {
- try {
- wait();
- } catch (InterruptedException e) {
- }
+/**
+ * Concurrent reading is allowed
+ * Blocking only when already writing.
+ */
+public synchronized void enterRead() {
+
+ while (status < 0){
+ try {
+ wait();
+ } catch(InterruptedException e){
}
- status++;
}
-
- /**
- * Only one writer at a time is allowed to perform
- * Blocking only when already writing or reading.
- */
- public synchronized void enterWrite() {
-
- while (status != 0) {
- try {
- wait();
- } catch (InterruptedException e) {
- }
+ status++;
+}
+/**
+ * Only one writer at a time is allowed to perform
+ * Blocking only when already writing or reading.
+ */
+public synchronized void enterWrite() {
+
+ while (status != 0){
+ try {
+ wait();
+ } catch(InterruptedException e){
}
- status--;
- }
-
- /**
- * Only notify waiting writer(s) if last reader
- */
- public synchronized void exitRead() {
-
- if (--status == 0)
- notifyAll();
}
+ status--;
+}
+/**
+ * Only notify waiting writer(s) if last reader
+ */
+public synchronized void exitRead() {
- /**
- * When writing is over, all readers and possible
- * writers are granted permission to restart concurrently
- */
- public synchronized void exitWrite() {
-
- if (++status == 0)
- notifyAll();
- }
+ if (--status == 0) notifyAll();
+}
+/**
+ * When writing is over, all readers and possible
+ * writers are granted permission to restart concurrently
+ */
+public synchronized void exitWrite() {
+ if (++status == 0) notifyAll();
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/RemoveFromIndex.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/RemoveFromIndex.java
index fd9edcb2c1..067c3d2b0d 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/RemoveFromIndex.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/RemoveFromIndex.java
@@ -4,58 +4,50 @@ package org.eclipse.jdt.internal.core.search.indexing;
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
-
+
import org.eclipse.core.resources.*;
import org.eclipse.jdt.internal.core.index.*;
import org.eclipse.jdt.internal.core.search.processing.*;
import org.eclipse.core.resources.*;
+
import java.io.*;
class RemoveFromIndex implements IJob, IJobConstants {
String resourceName;
IProject project;
IndexManager manager;
- public RemoveFromIndex(
- String resourceName,
- IProject project,
- IndexManager manager) {
- this.resourceName = resourceName;
- this.project = project;
- this.manager = manager;
- }
-
- public boolean belongsTo(String jobFamily) {
- return jobFamily.equals(project.getName());
- }
-
- public boolean execute() {
- try {
- if (project.exists() && project.isOpen()) {
- IIndex index = manager.getIndex(project.getFullPath());
- if (index == null)
- return COMPLETE;
-
- /* ensure no concurrent write access to index */
- ReadWriteMonitor monitor = manager.getMonitorFor(index);
- if (monitor == null)
- return COMPLETE; // index got deleted since acquired
- try {
- monitor.enterWrite(); // ask permission to write
- index.remove(resourceName);
- } finally {
- monitor.exitWrite(); // free write lock
- }
+public RemoveFromIndex(String resourceName, IProject project, IndexManager manager){
+ this.resourceName = resourceName;
+ this.project = project;
+ this.manager = manager;
+}
+public boolean belongsTo(String jobFamily){
+ return jobFamily.equals(project.getName());
+}
+public boolean execute(){
+ try {
+ if (project.exists() && project.isOpen()){
+ IIndex index = manager.getIndex(project.getFullPath());
+ if (index == null) return COMPLETE;
+
+ /* ensure no concurrent write access to index */
+ ReadWriteMonitor monitor = manager.getMonitorFor(index);
+ if (monitor == null) return COMPLETE; // index got deleted since acquired
+ try {
+ monitor.enterWrite(); // ask permission to write
+ index.remove(resourceName);
+ } finally {
+ monitor.exitWrite(); // free write lock
}
- } catch (IOException e) {
- return FAILED;
}
- return COMPLETE;
- }
-
- public String toString() {
- return "removing from index " + resourceName;
+ } catch (IOException e){
+ return FAILED;
}
-
+ return COMPLETE;
+}
+public String toString(){
+ return "removing from index "+resourceName;
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/SourceIndexer.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/SourceIndexer.java
index 02b019bb82..db9a6f56d5 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/SourceIndexer.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/SourceIndexer.java
@@ -30,51 +30,45 @@ import java.util.*;
* - Constructors.
*/
public class SourceIndexer extends AbstractIndexer {
+
+ public static final String[] FILE_TYPES= new String[] {"java"};
+ protected DefaultProblemFactory problemFactory= new DefaultProblemFactory(Locale.getDefault());
+
+/**
+ * Returns the file types the <code>IIndexer</code> handles.
+ */
- public static final String[] FILE_TYPES = new String[] { "java" };
- protected DefaultProblemFactory problemFactory =
- new DefaultProblemFactory(Locale.getDefault());
-
- /**
- * Returns the file types the <code>IIndexer</code> handles.
- */
-
- public String[] getFileTypes() {
- return FILE_TYPES;
- }
-
- protected void indexFile(IDocument document) throws IOException {
+public String[] getFileTypes(){
+ return FILE_TYPES;
+}
+protected void indexFile(IDocument document) throws IOException {
- // Add the name of the file to the index
- output.addDocument(document);
+ // Add the name of the file to the index
+ output.addDocument(document);
- // Create a new Parser
- SourceIndexerRequestor requestor = new SourceIndexerRequestor(this, document);
- SourceElementParser parser = new SourceElementParser(requestor, problemFactory);
+ // Create a new Parser
+ SourceIndexerRequestor requestor = new SourceIndexerRequestor(this, document);
+ SourceElementParser parser = new SourceElementParser(requestor, problemFactory);
- // Launch the parser
- char[] source = null;
- char[] name = null;
- try {
- source = document.getCharContent();
- name = document.getName().toCharArray();
- } catch (Exception e) {
- }
- if (source == null || name == null)
- return; // could not retrieve document info (e.g. resource was discarded)
- CompilationUnit compilationUnit = new CompilationUnit(source, name);
- try {
- parser.parseCompilationUnit(compilationUnit, true);
- } catch (Exception e) {
- e.printStackTrace();
- }
+ // Launch the parser
+ char[] source = null;
+ char[] name = null;
+ try {
+ source = document.getCharContent();
+ name = document.getName().toCharArray();
+ } catch(Exception e){
}
-
- /**
- * Sets the document types the <code>IIndexer</code> handles.
- */
-
- public void setFileTypes(String[] fileTypes) {
+ if (source == null || name == null) return; // could not retrieve document info (e.g. resource was discarded)
+ CompilationUnit compilationUnit = new CompilationUnit(source, name);
+ try {
+ parser.parseCompilationUnit(compilationUnit, true);
+ } catch (Exception e) {
+ e.printStackTrace();
}
+}
+/**
+ * Sets the document types the <code>IIndexer</code> handles.
+ */
+public void setFileTypes(String[] fileTypes){}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/SourceIndexerRequestor.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/SourceIndexerRequestor.java
index 9268483152..5b51b50c55 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/SourceIndexerRequestor.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/indexing/SourceIndexerRequestor.java
@@ -15,8 +15,7 @@ import java.io.File;
* This class is used by the JavaParserIndexer. When parsing the java file, the requestor
* recognises the java elements (methods, fields, ...) and add them to an index.
*/
-public class SourceIndexerRequestor
- implements ISourceElementRequestor, IIndexConstants {
+public class SourceIndexerRequestor implements ISourceElementRequestor, IIndexConstants {
SourceIndexer indexer;
IDocument document;
@@ -26,310 +25,199 @@ public class SourceIndexerRequestor
public SourceIndexerRequestor(SourceIndexer indexer, IDocument document) {
super();
this.indexer = indexer;
- this.document = document;
+ this.document= document;
}
-
- /**
- * acceptConstructorReference method comment.
- */
- public void acceptConstructorReference(
- char[] typeName,
- int argCount,
- int sourcePosition) {
- this.indexer.addConstructorReference(typeName, argCount);
- int lastDot = CharOperation.lastIndexOf('.', typeName);
- if (lastDot != -1) {
- char[][] qualification =
- CharOperation.splitOn('.', CharOperation.subarray(typeName, 0, lastDot));
- for (int i = 0, length = qualification.length; i < length; i++) {
- this.indexer.addNameReference(qualification[i]);
- }
- }
- }
-
- /**
- * acceptFieldReference method comment.
- */
- public void acceptFieldReference(char[] fieldName, int sourcePosition) {
- this.indexer.addFieldReference(fieldName);
- }
-
- /**
- * acceptImport method comment.
- */
- public void acceptImport(
- int declarationStart,
- int declarationEnd,
- char[] name,
- boolean onDemand) {
- char[][] qualification =
- CharOperation.splitOn(
- '.',
- CharOperation.subarray(name, 0, CharOperation.lastIndexOf('.', name)));
+/**
+ * acceptConstructorReference method comment.
+ */
+public void acceptConstructorReference(char[] typeName, int argCount, int sourcePosition) {
+ this.indexer.addConstructorReference(typeName, argCount);
+ int lastDot = CharOperation.lastIndexOf('.', typeName);
+ if (lastDot != -1) {
+ char[][] qualification = CharOperation.splitOn('.', CharOperation.subarray(typeName, 0, lastDot));
for (int i = 0, length = qualification.length; i < length; i++) {
this.indexer.addNameReference(qualification[i]);
}
}
-
- /**
- * acceptInitializer method comment.
- */
- public void acceptInitializer(
- int modifiers,
- int declarationSourceStart,
- int declarationSourceEnd) {
- }
-
- /**
- * acceptLineSeparatorPositions method comment.
- */
- public void acceptLineSeparatorPositions(int[] positions) {
- }
-
- /**
- * acceptMethodReference method comment.
- */
- public void acceptMethodReference(
- char[] methodName,
- int argCount,
- int sourcePosition) {
- this.indexer.addMethodReference(methodName, argCount);
- }
-
- /**
- * acceptPackage method comment.
- */
- public void acceptPackage(
- int declarationStart,
- int declarationEnd,
- char[] name) {
- this.packageName = name;
- }
-
- /**
- * acceptProblem method comment.
- */
- public void acceptProblem(IProblem problem) {
- }
-
- /**
- * acceptTypeReference method comment.
- */
- public void acceptTypeReference(
- char[][] typeName,
- int sourceStart,
- int sourceEnd) {
- int length = typeName.length;
- for (int i = 0; i < length - 1; i++)
- acceptUnknownReference(typeName[i], 0); // ?
- acceptTypeReference(typeName[length - 1], 0);
- }
-
- /**
- * acceptTypeReference method comment.
- */
- public void acceptTypeReference(char[] simpleTypeName, int sourcePosition) {
- this.indexer.addTypeReference(simpleTypeName);
- }
-
- /**
- * acceptUnknownReference method comment.
- */
- public void acceptUnknownReference(
- char[][] name,
- int sourceStart,
- int sourceEnd) {
- for (int i = 0; i < name.length; i++) {
- acceptUnknownReference(name[i], 0);
- }
- }
-
- /**
- * acceptUnknownReference method comment.
- */
- public void acceptUnknownReference(char[] name, int sourcePosition) {
- this.indexer.addNameReference(name);
- }
-
- /*
- * Rebuild the proper qualification for the current source type:
- *
- * java.lang.Object ---> null
- * java.util.Hashtable$Entry --> [Hashtable]
- * x.y.A$B$C --> [A, B]
- */
- public char[][] enclosingTypeNames() {
-
- if (depth == 0)
- return null;
-
- char[][] qualification = new char[this.depth][];
- System.arraycopy(this.enclosingTypeNames, 0, qualification, 0, this.depth);
- return qualification;
+}
+/**
+ * acceptFieldReference method comment.
+ */
+public void acceptFieldReference(char[] fieldName, int sourcePosition) {
+ this.indexer.addFieldReference(fieldName);
+}
+/**
+ * acceptImport method comment.
+ */
+public void acceptImport(int declarationStart, int declarationEnd, char[] name, boolean onDemand) {
+ char[][] qualification = CharOperation.splitOn('.', CharOperation.subarray(name, 0, CharOperation.lastIndexOf('.', name)));
+ for (int i = 0, length = qualification.length; i < length; i++) {
+ this.indexer.addNameReference(qualification[i]);
}
-
- /**
- * enterClass method comment.
- */
- public void enterClass(
- int declarationStart,
- int modifiers,
- char[] name,
- int nameSourceStart,
- int nameSourceEnd,
- char[] superclass,
- char[][] superinterfaces) {
-
- // eliminate possible qualifications, given they need to be fully resolved again
- if (superclass != null) {
- superclass = CharOperation.lastSegment(superclass, '.');
- }
- if (superinterfaces != null) {
- for (int i = 0, length = superinterfaces.length; i < length; i++) {
- superinterfaces[i] = CharOperation.lastSegment(superinterfaces[i], '.');
- }
- }
- this.indexer.addClassDeclaration(
- modifiers,
- packageName,
- name,
- enclosingTypeNames(),
- superclass,
- superinterfaces);
- this.pushTypeName(name);
+}
+/**
+ * acceptInitializer method comment.
+ */
+public void acceptInitializer(int modifiers, int declarationSourceStart, int declarationSourceEnd) {
+}
+/**
+ * acceptLineSeparatorPositions method comment.
+ */
+public void acceptLineSeparatorPositions(int[] positions) {
+}
+/**
+ * acceptMethodReference method comment.
+ */
+public void acceptMethodReference(char[] methodName, int argCount, int sourcePosition) {
+ this.indexer.addMethodReference(methodName, argCount);
+}
+/**
+ * acceptPackage method comment.
+ */
+public void acceptPackage(int declarationStart, int declarationEnd, char[] name) {
+ this.packageName = name;
+}
+/**
+ * acceptProblem method comment.
+ */
+public void acceptProblem(IProblem problem) {
+}
+/**
+ * acceptTypeReference method comment.
+ */
+public void acceptTypeReference(char[][] typeName, int sourceStart, int sourceEnd) {
+ int length = typeName.length;
+ for (int i = 0; i < length - 1; i++)
+ acceptUnknownReference(typeName[i], 0); // ?
+ acceptTypeReference(typeName[length - 1], 0);
+}
+/**
+ * acceptTypeReference method comment.
+ */
+public void acceptTypeReference(char[] simpleTypeName, int sourcePosition) {
+ this.indexer.addTypeReference(simpleTypeName);
+}
+/**
+ * acceptUnknownReference method comment.
+ */
+public void acceptUnknownReference(char[][] name, int sourceStart, int sourceEnd) {
+ for (int i = 0; i < name.length; i++) {
+ acceptUnknownReference(name[i], 0);
}
+}
+/**
+ * acceptUnknownReference method comment.
+ */
+public void acceptUnknownReference(char[] name, int sourcePosition) {
+ this.indexer.addNameReference(name);
+}
+/*
+ * Rebuild the proper qualification for the current source type:
+ *
+ * java.lang.Object ---> null
+ * java.util.Hashtable$Entry --> [Hashtable]
+ * x.y.A$B$C --> [A, B]
+ */
+public char[][] enclosingTypeNames(){
- /**
- * enterCompilationUnit method comment.
- */
- public void enterCompilationUnit() {
- }
+ if (depth == 0) return null;
- /**
- * enterConstructor method comment.
- */
- public void enterConstructor(
- int declarationStart,
- int modifiers,
- char[] name,
- int nameSourceStart,
- int nameSourceEnd,
- char[][] parameterTypes,
- char[][] parameterNames,
- char[][] exceptionTypes) {
- this.indexer.addConstructorDeclaration(name, parameterTypes, exceptionTypes);
- }
+ char[][] qualification = new char[this.depth][];
+ System.arraycopy(this.enclosingTypeNames, 0, qualification, 0, this.depth);
+ return qualification;
+}
+/**
+ * enterClass method comment.
+ */
+public void enterClass(int declarationStart, int modifiers, char[] name, int nameSourceStart, int nameSourceEnd, char[] superclass, char[][] superinterfaces) {
- /**
- * enterField method comment.
- */
- public void enterField(
- int declarationStart,
- int modifiers,
- char[] type,
- char[] name,
- int nameSourceStart,
- int nameSourceEnd) {
- this.indexer.addFieldDeclaration(type, name);
+ // eliminate possible qualifications, given they need to be fully resolved again
+ if (superclass != null){
+ superclass = CharOperation.lastSegment(superclass, '.');
}
-
- /**
- * enterInterface method comment.
- */
- public void enterInterface(
- int declarationStart,
- int modifiers,
- char[] name,
- int nameSourceStart,
- int nameSourceEnd,
- char[][] superinterfaces) {
- // eliminate possible qualifications, given they need to be fully resolved again
- if (superinterfaces != null) {
- for (int i = 0, length = superinterfaces.length; i < length; i++) {
- superinterfaces[i] = CharOperation.lastSegment(superinterfaces[i], '.');
- }
+ if (superinterfaces != null){
+ for (int i = 0, length = superinterfaces.length; i < length; i++){
+ superinterfaces[i] = CharOperation.lastSegment(superinterfaces[i], '.');
}
- this.indexer.addInterfaceDeclaration(
- modifiers,
- packageName,
- name,
- enclosingTypeNames(),
- superinterfaces);
- this.pushTypeName(name);
- }
-
- /**
- * enterMethod method comment.
- */
- public void enterMethod(
- int declarationStart,
- int modifiers,
- char[] returnType,
- char[] name,
- int nameSourceStart,
- int nameSourceEnd,
- char[][] parameterTypes,
- char[][] parameterNames,
- char[][] exceptionTypes) {
- this.indexer.addMethodDeclaration(
- name,
- parameterTypes,
- returnType,
- exceptionTypes);
- }
-
- /**
- * exitClass method comment.
- */
- public void exitClass(int declarationEnd) {
- popTypeName();
- }
-
- /**
- * exitCompilationUnit method comment.
- */
- public void exitCompilationUnit(int declarationEnd) {
}
-
- /**
- * exitConstructor method comment.
- */
- public void exitConstructor(int declarationEnd) {
- }
-
- /**
- * exitField method comment.
- */
- public void exitField(int declarationEnd) {
- }
-
- /**
- * exitInterface method comment.
- */
- public void exitInterface(int declarationEnd) {
- popTypeName();
- }
-
- /**
- * exitMethod method comment.
- */
- public void exitMethod(int declarationEnd) {
- }
-
- public void popTypeName() {
- enclosingTypeNames[depth--] = null;
- }
-
- public void pushTypeName(char[] typeName) {
- if (depth == enclosingTypeNames.length) {
- System.arraycopy(
- enclosingTypeNames,
- 0,
- enclosingTypeNames = new char[depth * 2][],
- 0,
- depth);
+ this.indexer.addClassDeclaration(modifiers, packageName, name, enclosingTypeNames(), superclass, superinterfaces);
+ this.pushTypeName(name);
+}
+/**
+ * enterCompilationUnit method comment.
+ */
+public void enterCompilationUnit() {
+}
+/**
+ * enterConstructor method comment.
+ */
+public void enterConstructor(int declarationStart, int modifiers, char[] name, int nameSourceStart, int nameSourceEnd, char[][] parameterTypes, char[][] parameterNames, char[][] exceptionTypes) {
+ this.indexer.addConstructorDeclaration(name, parameterTypes, exceptionTypes);
+}
+/**
+ * enterField method comment.
+ */
+public void enterField(int declarationStart, int modifiers, char[] type, char[] name, int nameSourceStart, int nameSourceEnd) {
+ this.indexer.addFieldDeclaration(type, name);
+}
+/**
+ * enterInterface method comment.
+ */
+public void enterInterface(int declarationStart, int modifiers, char[] name, int nameSourceStart, int nameSourceEnd, char[][] superinterfaces) {
+ // eliminate possible qualifications, given they need to be fully resolved again
+ if (superinterfaces != null){
+ for (int i = 0, length = superinterfaces.length; i < length; i++){
+ superinterfaces[i] = CharOperation.lastSegment(superinterfaces[i], '.');
}
- enclosingTypeNames[depth++] = typeName;
+ }
+ this.indexer.addInterfaceDeclaration(modifiers, packageName, name, enclosingTypeNames(), superinterfaces);
+ this.pushTypeName(name);
+}
+/**
+ * enterMethod method comment.
+ */
+public void enterMethod(int declarationStart, int modifiers, char[] returnType, char[] name, int nameSourceStart, int nameSourceEnd, char[][] parameterTypes, char[][] parameterNames, char[][] exceptionTypes) {
+ this.indexer.addMethodDeclaration(name, parameterTypes, returnType, exceptionTypes);
+}
+/**
+ * exitClass method comment.
+ */
+public void exitClass(int declarationEnd) {
+ popTypeName();
+}
+/**
+ * exitCompilationUnit method comment.
+ */
+public void exitCompilationUnit(int declarationEnd) {
+}
+/**
+ * exitConstructor method comment.
+ */
+public void exitConstructor(int declarationEnd) {
+}
+/**
+ * exitField method comment.
+ */
+public void exitField(int declarationEnd) {
+}
+/**
+ * exitInterface method comment.
+ */
+public void exitInterface(int declarationEnd) {
+ popTypeName();
+}
+/**
+ * exitMethod method comment.
+ */
+public void exitMethod(int declarationEnd) {
+}
+public void popTypeName(){
+ enclosingTypeNames[depth--] = null;
+}
+public void pushTypeName(char[] typeName){
+ if (depth == enclosingTypeNames.length){
+ System.arraycopy(enclosingTypeNames, 0, enclosingTypeNames = new char[depth*2][], 0, depth);
}
-
+ enclosingTypeNames[depth++] = typeName;
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/AndPattern.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/AndPattern.java
index e4aa770ce3..6c99607657 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/AndPattern.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/AndPattern.java
@@ -18,104 +18,93 @@ import java.io.IOException;
* Query the index multiple times and do an 'and' on the results.
*/
public abstract class AndPattern extends SearchPattern {
- public AndPattern(int matchMode, boolean isCaseSensitive) {
- super(matchMode, isCaseSensitive);
- }
-
- /**
- * Query a given index for matching entries.
- */
- public void findIndexMatches(
- IndexInput input,
- IIndexSearchRequestor requestor,
- int detailLevel,
- IProgressMonitor progressMonitor,
- IJavaSearchScope scope)
- throws IOException {
-
- if (progressMonitor != null && progressMonitor.isCanceled())
- throw new OperationCanceledException();
+public AndPattern(int matchMode, boolean isCaseSensitive) {
+ super(matchMode, isCaseSensitive);
+}
+/**
+ * Query a given index for matching entries.
+ */
+public void findIndexMatches(IndexInput input, IIndexSearchRequestor requestor, int detailLevel, IProgressMonitor progressMonitor, IJavaSearchScope scope) throws IOException {
- /* narrow down a set of entries using prefix criteria */
- long[] potentialRefs = null;
- int maxRefs = -1;
- this.resetQuery();
- do {
- IEntryResult[] entries = input.queryEntriesPrefixedBy(indexEntryPrefix());
- if (entries == null)
- break;
+ if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException();
+
+ /* narrow down a set of entries using prefix criteria */
+ long[] potentialRefs = null;
+ int maxRefs = -1;
+ this.resetQuery();
+ do {
+ IEntryResult[] entries = input.queryEntriesPrefixedBy(indexEntryPrefix());
+ if (entries == null) break;
- int numFiles = input.getNumFiles();
- long[] references = null;
- int referencesLength = -1;
- for (int i = 0, max = entries.length; i < max; i++) {
+ int numFiles = input.getNumFiles();
+ long[] references = null;
+ int referencesLength = -1;
+ for (int i = 0, max = entries.length; i < max; i++){
- if (progressMonitor != null && progressMonitor.isCanceled())
- throw new OperationCanceledException();
+ if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException();
- /* retrieve and decode entry */
- IEntryResult entry = entries[i];
- decodeIndexEntry(entry);
- if (matchIndexEntry()) {
- /* accumulate references in an array of bits : 1 if the reference is present, 0 otherwise */
- int[] fileReferences = entry.getFileReferences();
- for (int j = 0, refLength = fileReferences.length; j < refLength; j++) {
- int fileReference = fileReferences[j];
- int vectorIndex = fileReference / 64; // a long has 64 bits
- if (references == null) {
- referencesLength = (numFiles / 64) + 1;
- references = new long[referencesLength];
- }
- long mask = 1L << (fileReference % 64);
- references[vectorIndex] |= mask;
+ /* retrieve and decode entry */
+ IEntryResult entry = entries[i];
+ decodeIndexEntry(entry);
+ if (matchIndexEntry()) {
+ /* accumulate references in an array of bits : 1 if the reference is present, 0 otherwise */
+ int[] fileReferences = entry.getFileReferences();
+ for (int j = 0, refLength = fileReferences.length; j < refLength; j++) {
+ int fileReference = fileReferences[j];
+ int vectorIndex = fileReference / 64; // a long has 64 bits
+ if (references == null) {
+ referencesLength = (numFiles / 64) + 1;
+ references = new long[referencesLength];
}
+ long mask = 1L << (fileReference % 64);
+ references[vectorIndex] |= mask;
}
}
-
- /* only select entries which actually match the entire search pattern */
- if (references == null) {
- /* no references */
- return;
+ }
+
+ /* only select entries which actually match the entire search pattern */
+ if (references == null) {
+ /* no references */
+ return;
+ } else {
+ if (potentialRefs == null) {
+ /* first query : these are the potential references */
+ potentialRefs = references;
+ maxRefs = numFiles;
} else {
- if (potentialRefs == null) {
- /* first query : these are the potential references */
- potentialRefs = references;
- maxRefs = numFiles;
- } else {
- /* eliminate potential references that don't match the current references */
- for (int i = 0, length = references.length; i < length; i++) {
- if (i < potentialRefs.length) {
- potentialRefs[i] &= references[i];
- } else {
- potentialRefs[i] = 0;
- }
+ /* eliminate potential references that don't match the current references */
+ for (int i = 0, length = references.length; i < length; i++) {
+ if (i < potentialRefs.length) {
+ potentialRefs[i] &= references[i];
+ } else {
+ potentialRefs[i] = 0;
}
}
- }
- } while (this.hasNextQuery());
-
- /* report potential references that remain */
- if (potentialRefs != null) {
- int[] refs = new int[maxRefs];
- int refsLength = 0;
- for (int reference = 1; reference <= maxRefs; reference++) {
- int vectorIndex = reference / 64; // a long has 64 bits
- if ((potentialRefs[vectorIndex] & (1L << (reference % 64))) != 0) {
- refs[refsLength++] = reference;
- }
+ }
+ }
+ } while (this.hasNextQuery());
+ /* report potential references that remain */
+ if (potentialRefs != null) {
+ int[] refs = new int[maxRefs];
+ int refsLength = 0;
+ for (int reference = 1; reference <= maxRefs; reference++) {
+ int vectorIndex = reference / 64; // a long has 64 bits
+ if ((potentialRefs[vectorIndex] & (1L << (reference % 64))) != 0) {
+ refs[refsLength++] = reference;
}
- System.arraycopy(refs, 0, refs = new int[refsLength], 0, refsLength);
- this.feedIndexRequestor(requestor, detailLevel, refs, input, scope);
+
}
+ System.arraycopy(refs, 0, refs = new int[refsLength], 0, refsLength);
+ this.feedIndexRequestor(requestor, detailLevel, refs, input, scope);
}
-
- /**
- * Returns whether another query must be done.
- */
- protected abstract boolean hasNextQuery();
- /**
- * Resets the query and prepares this pattern to be queried.
- */
- protected abstract void resetQuery();
+}
+/**
+ * Returns whether another query must be done.
+ */
+protected abstract boolean hasNextQuery();
+/**
+ * Resets the query and prepares this pattern to be queried.
+ */
+protected abstract void resetQuery();
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/ConstructorDeclarationPattern.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/ConstructorDeclarationPattern.java
index 3b07ebb5f7..dfd27470f9 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/ConstructorDeclarationPattern.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/ConstructorDeclarationPattern.java
@@ -20,307 +20,228 @@ import java.io.*;
/**
* The selector is unused, the constructor name is specified by the type simple name.
- */
+ */
public class ConstructorDeclarationPattern extends MethodDeclarationPattern {
- private char[] decodedTypeName;
- public ConstructorDeclarationPattern(
- char[] declaringSimpleName,
- int matchMode,
- boolean isCaseSensitive,
- char[] declaringQualification,
- char[][] parameterQualifications,
- char[][] parameterSimpleNames) {
- super(
- null,
- matchMode,
- isCaseSensitive,
- declaringQualification,
- declaringSimpleName,
- null,
- null,
- parameterQualifications,
- parameterSimpleNames);
- }
-
- public void decodeIndexEntry(IEntryResult entryResult) {
-
- char[] word = entryResult.getWord();
- int size = word.length;
- int lastSeparatorIndex = CharOperation.lastIndexOf(SEPARATOR, word);
+ private char[] decodedTypeName;
+public ConstructorDeclarationPattern(char[] declaringSimpleName, int matchMode, boolean isCaseSensitive, char[] declaringQualification, char[][] parameterQualifications, char[][] parameterSimpleNames) {
+ super(null, matchMode, isCaseSensitive, declaringQualification, declaringSimpleName, null, null, parameterQualifications, parameterSimpleNames);
+}
+public void decodeIndexEntry(IEntryResult entryResult){
- decodedParameterCount =
- Integer.parseInt(
- new String(word, lastSeparatorIndex + 1, size - lastSeparatorIndex - 1));
- decodedTypeName =
- CharOperation.subarray(word, CONSTRUCTOR_DECL.length, lastSeparatorIndex);
- }
+ char[] word = entryResult.getWord();
+ int size = word.length;
+ int lastSeparatorIndex = CharOperation.lastIndexOf(SEPARATOR, word);
- /**
- * see SearchPattern.feedIndexRequestor
- */
- public void feedIndexRequestor(
- IIndexSearchRequestor requestor,
- int detailLevel,
- int[] references,
- IndexInput input,
- IJavaSearchScope scope)
- throws IOException {
- for (int i = 0, max = references.length; i < max; i++) {
- IndexedFile file = input.getIndexedFile(references[i]);
- String path;
- if (file != null
- && scope.encloses(path = IndexedFile.convertPath(file.getPath()))) {
- requestor.acceptConstructorDeclaration(
- path,
- decodedTypeName,
- decodedParameterCount);
- }
+ decodedParameterCount = Integer.parseInt(new String(word, lastSeparatorIndex + 1, size - lastSeparatorIndex - 1));
+ decodedTypeName = CharOperation.subarray(word, CONSTRUCTOR_DECL.length, lastSeparatorIndex);
+}
+/**
+ * see SearchPattern.feedIndexRequestor
+ */
+public void feedIndexRequestor(IIndexSearchRequestor requestor, int detailLevel, int[] references, IndexInput input, IJavaSearchScope scope) throws IOException {
+ for (int i = 0, max = references.length; i < max; i++) {
+ IndexedFile file = input.getIndexedFile(references[i]);
+ String path;
+ if (file != null && scope.encloses(path = IndexedFile.convertPath(file.getPath()))) {
+ requestor.acceptConstructorDeclaration(path, decodedTypeName, decodedParameterCount);
}
}
+}
+/**
+ * @see SearchPattern#indexEntryPrefix
+ */
+public char[] indexEntryPrefix() {
- /**
- * @see SearchPattern#indexEntryPrefix
- */
- public char[] indexEntryPrefix() {
-
- return AbstractIndexer.bestConstructorDeclarationPrefix(
- declaringSimpleName,
- parameterSimpleNames == null ? -1 : parameterSimpleNames.length,
- matchMode,
+ return AbstractIndexer.bestConstructorDeclarationPrefix(
+ declaringSimpleName,
+ parameterSimpleNames == null ? -1 : parameterSimpleNames.length,
+ matchMode,
isCaseSensitive);
- }
-
- /**
- * @see SearchPattern#matches(AstNode, boolean)
- */
- protected boolean matches(AstNode node, boolean resolve) {
- if (!(node instanceof ConstructorDeclaration))
- return false;
+}
+/**
+ * @see SearchPattern#matches(AstNode, boolean)
+ */
+protected boolean matches(AstNode node, boolean resolve) {
+ if (!(node instanceof ConstructorDeclaration)) return false;
- ConstructorDeclaration constructor = (ConstructorDeclaration) node;
+ ConstructorDeclaration constructor = (ConstructorDeclaration)node;
- // constructor name is stored in selector field
- if (this.declaringSimpleName != null
+ // constructor name is stored in selector field
+ if (this.declaringSimpleName != null
&& !this.matchesName(this.declaringSimpleName, constructor.selector))
- return false;
+ return false;
- // declaring type
- MethodBinding binding = constructor.binding;
- if (resolve && binding != null) {
- ReferenceBinding declaringBinding = binding.declaringClass;
- if (!this
- .matchesType(
- this.declaringSimpleName,
- this.declaringQualification,
- declaringBinding))
- return false;
- }
-
- // argument types
- int argumentCount =
- this.parameterSimpleNames == null ? -1 : this.parameterSimpleNames.length;
- if (argumentCount > -1) {
- int parameterCount =
- constructor.arguments == null ? 0 : constructor.arguments.length;
- if (parameterCount != argumentCount)
- return false;
-
- if (resolve && binding != null) {
- for (int i = 0; i < parameterCount; i++) {
- char[] qualification = this.parameterQualifications[i];
- char[] type = this.parameterSimpleNames[i];
- if (!this.matchesType(type, qualification, binding.parameters[i]))
- return false;
- }
- }
- }
-
- return true;
- }
-
- /**
- * @see SearchPattern#matches(Binding)
- */
- public boolean matches(Binding binding) {
- if (!(binding instanceof MethodBinding))
+ // declaring type
+ MethodBinding binding = constructor.binding;
+ if (resolve && binding != null) {
+ ReferenceBinding declaringBinding = binding.declaringClass;
+ if (!this.matchesType(this.declaringSimpleName, this.declaringQualification, declaringBinding))
return false;
-
- MethodBinding method = (MethodBinding) binding;
-
- // must be a constructor
- if (!method.isConstructor())
+ }
+
+ // argument types
+ int argumentCount = this.parameterSimpleNames == null ? -1 : this.parameterSimpleNames.length;
+ if (argumentCount > -1) {
+ int parameterCount = constructor.arguments == null ? 0 : constructor.arguments.length;
+ if (parameterCount != argumentCount)
return false;
- // declaring type
- ReferenceBinding declaringType = method.declaringClass;
- if (declaringType != null) {
- if (!method.isStatic() && !method.isPrivate()) {
- if (!this
- .matchesAsSubtype(
- declaringType,
- this.declaringSimpleName,
- this.declaringQualification))
- return false;
- } else {
- if (!this
- .matchesType(
- this.declaringSimpleName,
- this.declaringQualification,
- declaringType))
- return false;
- }
- }
-
- // parameter types
- int parameterCount =
- this.parameterSimpleNames == null ? -1 : this.parameterSimpleNames.length;
- if (parameterCount > -1) {
- int argumentCount = method.parameters == null ? 0 : method.parameters.length;
- if (parameterCount != argumentCount)
- return false;
+ if (resolve && binding != null) {
for (int i = 0; i < parameterCount; i++) {
char[] qualification = this.parameterQualifications[i];
char[] type = this.parameterSimpleNames[i];
- if (!this.matchesType(type, qualification, method.parameters[i]))
+ if (!this.matchesType(type, qualification, binding.parameters[i]))
return false;
}
}
-
- return true;
}
- /**
- * @see SearchPattern#matchesBinary(Object, Object)
- */
- public boolean matchesBinary(Object binaryInfo, Object enclosingBinaryInfo) {
- if (!(binaryInfo instanceof IBinaryMethod))
- return false;
-
- IBinaryMethod method = (IBinaryMethod) binaryInfo;
-
- // must be a constructor
- if (!method.isConstructor())
- return false;
-
- // declaring type
- IBinaryType declaringType = (IBinaryType) enclosingBinaryInfo;
- if (declaringType != null) {
- char[] declaringTypeName = (char[]) declaringType.getName().clone();
- CharOperation.replace(declaringTypeName, '/', '.');
- if (!this
- .matchesType(
- this.declaringSimpleName,
- this.declaringQualification,
- declaringTypeName)) {
+ return true;
+}
+/**
+ * @see SearchPattern#matches(Binding)
+ */
+public boolean matches(Binding binding) {
+ if (!(binding instanceof MethodBinding)) return false;
+
+ MethodBinding method = (MethodBinding)binding;
+
+ // must be a constructor
+ if (!method.isConstructor()) return false;
+
+ // declaring type
+ ReferenceBinding declaringType = method.declaringClass;
+ if (declaringType != null) {
+ if (!method.isStatic() && !method.isPrivate()) {
+ if (!this.matchesAsSubtype(declaringType, this.declaringSimpleName, this.declaringQualification))
+ return false;
+ } else {
+ if (!this.matchesType(this.declaringSimpleName, this.declaringQualification, declaringType))
return false;
- }
}
+ }
- // parameter types
- int parameterCount =
- this.parameterSimpleNames == null ? -1 : this.parameterSimpleNames.length;
- if (parameterCount > -1) {
- String methodDescriptor =
- new String(method.getMethodDescriptor()).replace('/', '.');
- String[] arguments = Signature.getParameterTypes(methodDescriptor);
- int argumentCount = arguments.length;
- if (parameterCount != argumentCount)
+ // parameter types
+ int parameterCount = this.parameterSimpleNames == null ? -1 : this.parameterSimpleNames.length;
+ if (parameterCount > -1) {
+ int argumentCount = method.parameters == null ? 0 : method.parameters.length;
+ if (parameterCount != argumentCount)
+ return false;
+ for (int i = 0; i < parameterCount; i++) {
+ char[] qualification = this.parameterQualifications[i];
+ char[] type = this.parameterSimpleNames[i];
+ if (!this.matchesType(type, qualification, method.parameters[i]))
return false;
- for (int i = 0; i < parameterCount; i++) {
- char[] qualification = this.parameterQualifications[i];
- char[] type = this.parameterSimpleNames[i];
- if (!this
- .matchesType(
- type,
- qualification,
- Signature.toString(arguments[i]).toCharArray()))
- return false;
- }
}
-
- return true;
}
- /**
- * @see SearchPattern#matchIndexEntry
- */
- protected boolean matchIndexEntry() {
-
- /* check selector matches */
- if (declaringSimpleName != null) {
- switch (matchMode) {
- case EXACT_MATCH :
- if (!CharOperation
- .equals(declaringSimpleName, decodedTypeName, isCaseSensitive)) {
- return false;
- }
- break;
- case PREFIX_MATCH :
- if (!CharOperation
- .prefixEquals(declaringSimpleName, decodedTypeName, isCaseSensitive)) {
- return false;
- }
- break;
- case PATTERN_MATCH :
- if (!CharOperation
- .match(declaringSimpleName, decodedTypeName, isCaseSensitive)) {
- return false;
- }
- }
+ return true;
+}
+/**
+ * @see SearchPattern#matchesBinary(Object, Object)
+ */
+public boolean matchesBinary(Object binaryInfo, Object enclosingBinaryInfo) {
+ if (!(binaryInfo instanceof IBinaryMethod)) return false;
+
+ IBinaryMethod method = (IBinaryMethod)binaryInfo;
+
+ // must be a constructor
+ if (!method.isConstructor()) return false;
+
+ // declaring type
+ IBinaryType declaringType = (IBinaryType)enclosingBinaryInfo;
+ if (declaringType != null) {
+ char[] declaringTypeName = (char[])declaringType.getName().clone();
+ CharOperation.replace(declaringTypeName, '/', '.');
+ if (!this.matchesType(this.declaringSimpleName, this.declaringQualification, declaringTypeName)) {
+ return false;
}
- if (parameterSimpleNames != null) {
- if (parameterSimpleNames.length != decodedParameterCount)
+ }
+
+ // parameter types
+ int parameterCount = this.parameterSimpleNames == null ? -1 : this.parameterSimpleNames.length;
+ if (parameterCount > -1) {
+ String methodDescriptor = new String(method.getMethodDescriptor()).replace('/', '.');
+ String[] arguments = Signature.getParameterTypes(methodDescriptor);
+ int argumentCount = arguments.length;
+ if (parameterCount != argumentCount)
+ return false;
+ for (int i = 0; i < parameterCount; i++) {
+ char[] qualification = this.parameterQualifications[i];
+ char[] type = this.parameterSimpleNames[i];
+ if (!this.matchesType(type, qualification, Signature.toString(arguments[i]).toCharArray()))
return false;
}
- return true;
}
- public String toString() {
-
- StringBuffer buffer = new StringBuffer(20);
- buffer.append("ConstructorDeclarationPattern: ");
- if (declaringQualification != null)
- buffer.append(declaringQualification).append('.');
- if (declaringSimpleName != null)
- buffer.append(declaringSimpleName);
- else
- if (declaringQualification != null)
- buffer.append("*");
+ return true;
+}
+/**
+ * @see SearchPattern#matchIndexEntry
+ */
+protected boolean matchIndexEntry() {
- buffer.append('(');
- if (parameterSimpleNames == null) {
- buffer.append("...");
- } else {
- for (int i = 0, max = parameterSimpleNames.length; i < max; i++) {
- if (i > 0)
- buffer.append(", ");
- if (parameterQualifications[i] != null)
- buffer.append(parameterQualifications[i]).append('.');
- if (parameterSimpleNames[i] == null)
- buffer.append('*');
- else
- buffer.append(parameterSimpleNames[i]);
- }
- }
- buffer.append(')');
- buffer.append(", ");
- switch (matchMode) {
+ /* check selector matches */
+ if (declaringSimpleName != null){
+ switch(matchMode){
case EXACT_MATCH :
- buffer.append("exact match, ");
+ if (!CharOperation.equals(declaringSimpleName, decodedTypeName, isCaseSensitive)){
+ return false;
+ }
break;
case PREFIX_MATCH :
- buffer.append("prefix match, ");
+ if (!CharOperation.prefixEquals(declaringSimpleName, decodedTypeName, isCaseSensitive)){
+ return false;
+ }
break;
case PATTERN_MATCH :
- buffer.append("pattern match, ");
- break;
+ if (!CharOperation.match(declaringSimpleName, decodedTypeName, isCaseSensitive)){
+ return false;
+ }
}
- if (isCaseSensitive)
- buffer.append("case sensitive");
- else
- buffer.append("case insensitive");
- return buffer.toString();
}
-
+ if (parameterSimpleNames != null){
+ if (parameterSimpleNames.length != decodedParameterCount) return false;
+ }
+ return true;
+}
+public String toString(){
+
+ StringBuffer buffer = new StringBuffer(20);
+ buffer.append("ConstructorDeclarationPattern: ");
+ if (declaringQualification != null) buffer.append(declaringQualification).append('.');
+ if (declaringSimpleName != null)
+ buffer.append(declaringSimpleName);
+ else if (declaringQualification != null) buffer.append("*");
+
+ buffer.append('(');
+ if (parameterSimpleNames == null) {
+ buffer.append("...");
+ } else {
+ for (int i = 0, max = parameterSimpleNames.length; i < max; i++){
+ if (i > 0) buffer.append(", ");
+ if (parameterQualifications[i] != null) buffer.append(parameterQualifications[i]).append('.');
+ if (parameterSimpleNames[i] == null) buffer.append('*'); else buffer.append(parameterSimpleNames[i]);
+ }
+ }
+ buffer.append(')');
+ buffer.append(", ");
+ switch(matchMode){
+ case EXACT_MATCH :
+ buffer.append("exact match, ");
+ break;
+ case PREFIX_MATCH :
+ buffer.append("prefix match, ");
+ break;
+ case PATTERN_MATCH :
+ buffer.append("pattern match, ");
+ break;
+ }
+ if (isCaseSensitive)
+ buffer.append("case sensitive");
+ else
+ buffer.append("case insensitive");
+ return buffer.toString();
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/ConstructorReferencePattern.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/ConstructorReferencePattern.java
index d27d454544..817f70fbb2 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/ConstructorReferencePattern.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/ConstructorReferencePattern.java
@@ -18,254 +18,193 @@ import java.io.*;
/**
* The selector is unused, the constructor name is specified by the type simple name.
- */
+ */
public class ConstructorReferencePattern extends MethodReferencePattern {
private char[] decodedTypeName;
- public ConstructorReferencePattern(
- char[] declaringSimpleName,
- int matchMode,
- boolean isCaseSensitive,
- char[] declaringQualification,
- char[][] parameterQualifications,
- char[][] parameterSimpleNames) {
- super(
- null,
- matchMode,
- isCaseSensitive,
- declaringQualification,
- declaringSimpleName,
- null,
- null,
- parameterQualifications,
- parameterSimpleNames);
- }
-
- public void decodeIndexEntry(IEntryResult entryResult) {
+public ConstructorReferencePattern(char[] declaringSimpleName, int matchMode, boolean isCaseSensitive, char[] declaringQualification, char[][] parameterQualifications, char[][] parameterSimpleNames) {
+ super(null, matchMode, isCaseSensitive, declaringQualification, declaringSimpleName, null, null, parameterQualifications, parameterSimpleNames);
+}
+public void decodeIndexEntry(IEntryResult entryResult){
- char[] word = entryResult.getWord();
- int size = word.length;
- int lastSeparatorIndex = CharOperation.lastIndexOf(SEPARATOR, word);
+ char[] word = entryResult.getWord();
+ int size = word.length;
+ int lastSeparatorIndex = CharOperation.lastIndexOf(SEPARATOR, word);
- decodedParameterCount =
- Integer.parseInt(
- new String(word, lastSeparatorIndex + 1, size - lastSeparatorIndex - 1));
- decodedTypeName =
- CharOperation.subarray(word, CONSTRUCTOR_REF.length, lastSeparatorIndex);
- }
-
- /**
- * see SearchPattern.feedIndexRequestor
- */
- public void feedIndexRequestor(
- IIndexSearchRequestor requestor,
- int detailLevel,
- int[] references,
- IndexInput input,
- IJavaSearchScope scope)
- throws IOException {
- for (int i = 0, max = references.length; i < max; i++) {
- IndexedFile file = input.getIndexedFile(references[i]);
- String path;
- if (file != null
- && scope.encloses(path = IndexedFile.convertPath(file.getPath()))) {
- requestor.acceptConstructorReference(
- path,
- decodedTypeName,
- decodedParameterCount);
- }
+ decodedParameterCount = Integer.parseInt(new String(word, lastSeparatorIndex + 1, size - lastSeparatorIndex - 1));
+ decodedTypeName = CharOperation.subarray(word, CONSTRUCTOR_REF.length, lastSeparatorIndex);
+}
+/**
+ * see SearchPattern.feedIndexRequestor
+ */
+public void feedIndexRequestor(IIndexSearchRequestor requestor, int detailLevel, int[] references, IndexInput input, IJavaSearchScope scope) throws IOException {
+ for (int i = 0, max = references.length; i < max; i++) {
+ IndexedFile file = input.getIndexedFile(references[i]);
+ String path;
+ if (file != null && scope.encloses(path = IndexedFile.convertPath(file.getPath()))) {
+ requestor.acceptConstructorReference(path, decodedTypeName, decodedParameterCount);
}
}
+}
+/**
+ * @see SearchPattern#indexEntryPrefix
+ */
+public char[] indexEntryPrefix() {
- /**
- * @see SearchPattern#indexEntryPrefix
- */
- public char[] indexEntryPrefix() {
-
- return AbstractIndexer.bestConstructorReferencePrefix(
- declaringSimpleName,
- parameterSimpleNames == null ? -1 : parameterSimpleNames.length,
- matchMode,
+ return AbstractIndexer.bestConstructorReferencePrefix(
+ declaringSimpleName,
+ parameterSimpleNames == null ? -1 : parameterSimpleNames.length,
+ matchMode,
isCaseSensitive);
- }
+}
+/**
+ * Returns whether this constructor pattern matches the given allocation expression.
+ * Look at resolved information only if specified.
+ */
+private boolean matches(AllocationExpression allocation, boolean resolve) {
- /**
- * Returns whether this constructor pattern matches the given allocation expression.
- * Look at resolved information only if specified.
- */
- private boolean matches(AllocationExpression allocation, boolean resolve) {
+ // constructor name is simple type name
+ char[][] typeName = allocation.type.getTypeName();
+ if (this.declaringSimpleName != null
+ && !this.matchesName(this.declaringSimpleName, typeName[typeName.length-1]))
+ return false;
- // constructor name is simple type name
- char[][] typeName = allocation.type.getTypeName();
- if (this.declaringSimpleName != null
- && !this.matchesName(this.declaringSimpleName, typeName[typeName.length - 1]))
+ // declaring type
+ MethodBinding binding = allocation.binding;
+ if (resolve && binding != null) {
+ ReferenceBinding declaringBinding = binding.declaringClass;
+ if (!this.matchesType(this.declaringSimpleName, this.declaringQualification, declaringBinding))
+ return false;
+ }
+
+ // argument types
+ int argumentCount = this.parameterSimpleNames == null ? -1 : this.parameterSimpleNames.length;
+ if (argumentCount > -1) {
+ int parameterCount = allocation.arguments == null ? 0 : allocation.arguments.length;
+ if (parameterCount != argumentCount)
return false;
- // declaring type
- MethodBinding binding = allocation.binding;
if (resolve && binding != null) {
- ReferenceBinding declaringBinding = binding.declaringClass;
- if (!this
- .matchesType(
- this.declaringSimpleName,
- this.declaringQualification,
- declaringBinding))
- return false;
- }
-
- // argument types
- int argumentCount =
- this.parameterSimpleNames == null ? -1 : this.parameterSimpleNames.length;
- if (argumentCount > -1) {
- int parameterCount =
- allocation.arguments == null ? 0 : allocation.arguments.length;
- if (parameterCount != argumentCount)
- return false;
-
- if (resolve && binding != null) {
- for (int i = 0; i < parameterCount; i++) {
- char[] qualification = this.parameterQualifications[i];
- char[] type = this.parameterSimpleNames[i];
- if (!this.matchesType(type, qualification, binding.parameters[i]))
- return false;
- }
+ for (int i = 0; i < parameterCount; i++) {
+ char[] qualification = this.parameterQualifications[i];
+ char[] type = this.parameterSimpleNames[i];
+ if (!this.matchesType(type, qualification, binding.parameters[i]))
+ return false;
}
}
-
- return true;
}
- /**
- * @see SearchPattern#matches(AstNode, boolean)
- */
- protected boolean matches(AstNode node, boolean resolve) {
- if (node instanceof AllocationExpression) {
- return this.matches((AllocationExpression) node, resolve);
- } else
- if (node instanceof ExplicitConstructorCall) {
- return this.matches((ExplicitConstructorCall) node, resolve);
- }
- return false;
+ return true;
+}
+/**
+ * @see SearchPattern#matches(AstNode, boolean)
+ */
+protected boolean matches(AstNode node, boolean resolve) {
+ if (node instanceof AllocationExpression) {
+ return this.matches((AllocationExpression)node, resolve);
+ } else if (node instanceof ExplicitConstructorCall) {
+ return this.matches((ExplicitConstructorCall)node, resolve);
}
-
- /**
- * Returns whether this constructor pattern matches the given explicit constructor call.
- * Look at resolved information only if specified.
- */
- private boolean matches(ExplicitConstructorCall call, boolean resolve) {
- // TBD: constructor name is super simple type name
-
- // declaring type
- MethodBinding binding = call.binding;
- if (resolve && binding != null) {
- ReferenceBinding declaringBinding = binding.declaringClass;
- if (!this
- .matchesType(
- this.declaringSimpleName,
- this.declaringQualification,
- declaringBinding))
- return false;
- }
-
- // argument types
- int argumentCount =
- this.parameterSimpleNames == null ? -1 : this.parameterSimpleNames.length;
- if (argumentCount > -1) {
- int parameterCount = call.arguments == null ? 0 : call.arguments.length;
- if (parameterCount != argumentCount)
- return false;
-
- if (resolve && binding != null) {
- for (int i = 0; i < parameterCount; i++) {
- char[] qualification = this.parameterQualifications[i];
- char[] type = this.parameterSimpleNames[i];
- if (!this.matchesType(type, qualification, binding.parameters[i]))
- return false;
- }
- }
- }
-
- return true;
+ return false;
+}
+/**
+ * Returns whether this constructor pattern matches the given explicit constructor call.
+ * Look at resolved information only if specified.
+ */
+private boolean matches(ExplicitConstructorCall call, boolean resolve) {
+ // TBD: constructor name is super simple type name
+
+ // declaring type
+ MethodBinding binding = call.binding;
+ if (resolve && binding != null) {
+ ReferenceBinding declaringBinding = binding.declaringClass;
+ if (!this.matchesType(this.declaringSimpleName, this.declaringQualification, declaringBinding))
+ return false;
}
+
+ // argument types
+ int argumentCount = this.parameterSimpleNames == null ? -1 : this.parameterSimpleNames.length;
+ if (argumentCount > -1) {
+ int parameterCount = call.arguments == null ? 0 : call.arguments.length;
+ if (parameterCount != argumentCount)
+ return false;
- /**
- * @see SearchPattern#matchIndexEntry
- */
- protected boolean matchIndexEntry() {
-
- /* check selector matches */
- if (declaringSimpleName != null) {
- switch (matchMode) {
- case EXACT_MATCH :
- if (!CharOperation
- .equals(declaringSimpleName, decodedTypeName, isCaseSensitive)) {
- return false;
- }
- break;
- case PREFIX_MATCH :
- if (!CharOperation
- .prefixEquals(declaringSimpleName, decodedTypeName, isCaseSensitive)) {
- return false;
- }
- break;
- case PATTERN_MATCH :
- if (!CharOperation
- .match(declaringSimpleName, decodedTypeName, isCaseSensitive)) {
- return false;
- }
+ if (resolve && binding != null) {
+ for (int i = 0; i < parameterCount; i++) {
+ char[] qualification = this.parameterQualifications[i];
+ char[] type = this.parameterSimpleNames[i];
+ if (!this.matchesType(type, qualification, binding.parameters[i]))
+ return false;
}
}
- if (parameterSimpleNames != null) {
- if (parameterSimpleNames.length != decodedParameterCount)
- return false;
- }
- return true;
}
- public String toString() {
+ return true;
+}
+/**
+ * @see SearchPattern#matchIndexEntry
+ */
+protected boolean matchIndexEntry() {
- StringBuffer buffer = new StringBuffer(20);
- buffer.append("ConstructorReferencePattern: ");
- if (declaringQualification != null)
- buffer.append(declaringQualification).append('.');
- if (declaringSimpleName != null)
- buffer.append(declaringSimpleName);
- else
- if (declaringQualification != null)
- buffer.append("*");
- buffer.append('(');
- if (parameterSimpleNames == null) {
- buffer.append("...");
- } else {
- for (int i = 0, max = parameterSimpleNames.length; i < max; i++) {
- if (i > 0)
- buffer.append(", ");
- if (parameterQualifications[i] != null)
- buffer.append(parameterQualifications[i]).append('.');
- if (parameterSimpleNames[i] == null)
- buffer.append('*');
- else
- buffer.append(parameterSimpleNames[i]);
- }
- }
- buffer.append(')');
- buffer.append(", ");
- switch (matchMode) {
+ /* check selector matches */
+ if (declaringSimpleName != null){
+ switch(matchMode){
case EXACT_MATCH :
- buffer.append("exact match, ");
+ if (!CharOperation.equals(declaringSimpleName, decodedTypeName, isCaseSensitive)){
+ return false;
+ }
break;
case PREFIX_MATCH :
- buffer.append("prefix match, ");
+ if (!CharOperation.prefixEquals(declaringSimpleName, decodedTypeName, isCaseSensitive)){
+ return false;
+ }
break;
case PATTERN_MATCH :
- buffer.append("pattern match, ");
- break;
+ if (!CharOperation.match(declaringSimpleName, decodedTypeName, isCaseSensitive)){
+ return false;
+ }
}
- if (isCaseSensitive)
- buffer.append("case sensitive");
- else
- buffer.append("case insensitive");
- return buffer.toString();
}
-
+ if (parameterSimpleNames != null){
+ if (parameterSimpleNames.length != decodedParameterCount) return false;
+ }
+ return true;
+}
+public String toString(){
+
+ StringBuffer buffer = new StringBuffer(20);
+ buffer.append("ConstructorReferencePattern: ");
+ if (declaringQualification != null) buffer.append(declaringQualification).append('.');
+ if (declaringSimpleName != null)
+ buffer.append(declaringSimpleName);
+ else if (declaringQualification != null) buffer.append("*");
+ buffer.append('(');
+ if (parameterSimpleNames == null) {
+ buffer.append("...");
+ } else {
+ for (int i = 0, max = parameterSimpleNames.length; i < max; i++){
+ if (i > 0) buffer.append(", ");
+ if (parameterQualifications[i] != null) buffer.append(parameterQualifications[i]).append('.');
+ if (parameterSimpleNames[i] == null) buffer.append('*'); else buffer.append(parameterSimpleNames[i]);
+ }
+ }
+ buffer.append(')');
+ buffer.append(", ");
+ switch(matchMode){
+ case EXACT_MATCH :
+ buffer.append("exact match, ");
+ break;
+ case PREFIX_MATCH :
+ buffer.append("prefix match, ");
+ break;
+ case PATTERN_MATCH :
+ buffer.append("pattern match, ");
+ break;
+ }
+ if (isCaseSensitive)
+ buffer.append("case sensitive");
+ else
+ buffer.append("case insensitive");
+ return buffer.toString();
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/FieldDeclarationPattern.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/FieldDeclarationPattern.java
index ea344b45f8..5a3515516a 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/FieldDeclarationPattern.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/FieldDeclarationPattern.java
@@ -22,7 +22,7 @@ public class FieldDeclarationPattern extends SearchPattern {
// selector
protected char[] name;
-
+
// declaring type
protected char[] declaringQualification;
protected char[] declaringSimpleName;
@@ -32,286 +32,228 @@ public class FieldDeclarationPattern extends SearchPattern {
protected char[] typeSimpleName;
protected char[] decodedName;
- public FieldDeclarationPattern(
- char[] name,
- int matchMode,
- boolean isCaseSensitive,
- char[] declaringQualification,
- char[] declaringSimpleName,
- char[] typeQualification,
- char[] typeSimpleName) {
-
- super(matchMode, isCaseSensitive);
-
- this.name = isCaseSensitive ? name : CharOperation.toLowerCase(name);
- this.declaringQualification =
- isCaseSensitive
- ? declaringQualification
- : CharOperation.toLowerCase(declaringQualification);
- this.declaringSimpleName =
- isCaseSensitive
- ? declaringSimpleName
- : CharOperation.toLowerCase(declaringSimpleName);
- this.typeQualification =
- isCaseSensitive
- ? typeQualification
- : CharOperation.toLowerCase(typeQualification);
- this.typeSimpleName =
- isCaseSensitive ? typeSimpleName : CharOperation.toLowerCase(typeSimpleName);
-
- this.needsResolve = this.needsResolve();
- }
-
- public void decodeIndexEntry(IEntryResult entryResult) {
-
- char[] word = entryResult.getWord();
- decodedName = CharOperation.subarray(word, FIELD_DECL.length, word.length);
- }
+public FieldDeclarationPattern(
+ char[] name,
+ int matchMode,
+ boolean isCaseSensitive,
+ char[] declaringQualification,
+ char[] declaringSimpleName,
+ char[] typeQualification,
+ char[] typeSimpleName) {
+
+ super(matchMode, isCaseSensitive);
+
+ this.name = isCaseSensitive ? name : CharOperation.toLowerCase(name);
+ this.declaringQualification = isCaseSensitive ? declaringQualification : CharOperation.toLowerCase(declaringQualification);
+ this.declaringSimpleName = isCaseSensitive ? declaringSimpleName : CharOperation.toLowerCase(declaringSimpleName);
+ this.typeQualification = isCaseSensitive ? typeQualification : CharOperation.toLowerCase(typeQualification);
+ this.typeSimpleName = isCaseSensitive ? typeSimpleName : CharOperation.toLowerCase(typeSimpleName);
+
+ this.needsResolve = this.needsResolve();
+}
+public void decodeIndexEntry(IEntryResult entryResult){
- /**
- * see SearchPattern.feedIndexRequestor
- */
- public void feedIndexRequestor(
- IIndexSearchRequestor requestor,
- int detailLevel,
- int[] references,
- IndexInput input,
- IJavaSearchScope scope)
- throws IOException {
- for (int i = 0, max = references.length; i < max; i++) {
- IndexedFile file = input.getIndexedFile(references[i]);
- String path;
- if (file != null
- && scope.encloses(path = IndexedFile.convertPath(file.getPath()))) {
- requestor.acceptFieldDeclaration(path, decodedName);
- }
+ char[] word = entryResult.getWord();
+ decodedName = CharOperation.subarray(word, FIELD_DECL.length, word.length);
+}
+/**
+ * see SearchPattern.feedIndexRequestor
+ */
+public void feedIndexRequestor(IIndexSearchRequestor requestor, int detailLevel, int[] references, IndexInput input, IJavaSearchScope scope) throws IOException {
+ for (int i = 0, max = references.length; i < max; i++) {
+ IndexedFile file = input.getIndexedFile(references[i]);
+ String path;
+ if (file != null && scope.encloses(path = IndexedFile.convertPath(file.getPath()))) {
+ requestor.acceptFieldDeclaration(path, decodedName);
}
}
+}
+/**
+ * @see SearchPattern#indexEntryPrefix
+ */
+public char[] indexEntryPrefix() {
- /**
- * @see SearchPattern#indexEntryPrefix
- */
- public char[] indexEntryPrefix() {
-
- return AbstractIndexer.bestFieldDeclarationPrefix(
- name,
- matchMode,
+ return AbstractIndexer.bestFieldDeclarationPrefix(
+ name,
+ matchMode,
isCaseSensitive);
- }
-
- /**
- * @see SearchPattern#matchContainer()
- */
- protected int matchContainer() {
- return CLASS;
- }
-
- /**
- * @see SearchPattern#matches(AstNode, boolean)
- */
- protected boolean matches(AstNode node, boolean resolve) {
- if (!(node instanceof FieldDeclaration))
- return false;
-
- FieldDeclaration field = (FieldDeclaration) node;
- if (!field.isField())
- return false; // ignore field initializers
+}
+/**
+ * @see SearchPattern#matchContainer()
+ */
+protected int matchContainer() {
+ return CLASS;
+}
+/**
+ * @see SearchPattern#matches(AstNode, boolean)
+ */
+protected boolean matches(AstNode node, boolean resolve) {
+ if (!(node instanceof FieldDeclaration)) return false;
+
+ FieldDeclaration field = (FieldDeclaration)node;
+ if (!field.isField()) return false; // ignore field initializers
+
+ // field name
+ if (!this.matchesName(this.name, field.name))
+ return false;
- // field name
- if (!this.matchesName(this.name, field.name))
+ // declaring type
+ FieldBinding binding = field.binding;
+ if (resolve && binding != null) {
+ ReferenceBinding declaringBinding = binding.declaringClass;
+ if (declaringBinding != null && !this.matchesType(this.declaringSimpleName, this.declaringQualification, declaringBinding))
return false;
-
- // declaring type
- FieldBinding binding = field.binding;
- if (resolve && binding != null) {
- ReferenceBinding declaringBinding = binding.declaringClass;
- if (declaringBinding != null
- && !this.matchesType(
- this.declaringSimpleName,
- this.declaringQualification,
- declaringBinding))
- return false;
- }
-
- // field type
- if (this.typeQualification == null) {
- TypeReference fieldType = field.type;
- char[][] fieldTypeName = fieldType.getTypeName();
- char[] sourceName =
- this.toArrayName(
- fieldTypeName[fieldTypeName.length - 1],
- fieldType.dimensions());
- if (!this.matchesName(this.typeSimpleName, sourceName))
- return false;
- } else {
- if (resolve
- && binding != null
- && !this.matchesType(this.typeSimpleName, this.typeQualification, binding.type))
- return false;
- }
- return true;
}
- /**
- * @see SearchPattern#matches(Binding)
- */
- public boolean matches(Binding binding) {
- if (!(binding instanceof FieldBinding))
- return false;
-
- FieldBinding field = (FieldBinding) binding;
-
- // field name
- if (!this.matchesName(this.name, field.readableName()))
- return false;
-
- // declaring type
- ReferenceBinding declaringBinding = field.declaringClass;
- if (declaringBinding != null
- && !this.matchesType(
- this.declaringSimpleName,
- this.declaringQualification,
- declaringBinding)) {
-
+ // field type
+ if (this.typeQualification == null) {
+ TypeReference fieldType = field.type;
+ char[][] fieldTypeName = fieldType.getTypeName();
+ char[] sourceName = this.toArrayName(
+ fieldTypeName[fieldTypeName.length-1],
+ fieldType.dimensions());
+ if (!this.matchesName(this.typeSimpleName, sourceName))
return false;
- }
-
- // field type
- if (!this
- .matchesType(this.typeSimpleName, this.typeQualification, field.type)) {
+ } else {
+ if (resolve
+ && binding != null
+ && !this.matchesType(this.typeSimpleName, this.typeQualification, binding.type))
return false;
- }
-
- return true;
}
+ return true;
+}
+/**
+ * @see SearchPattern#matches(Binding)
+ */
+public boolean matches(Binding binding) {
+ if (!(binding instanceof FieldBinding)) return false;
- /**
- * @see SearchPattern#matchesBinary(Object, Object)
- */
- public boolean matchesBinary(Object binaryInfo, Object enclosingBinaryInfo) {
- if (!(binaryInfo instanceof IBinaryField))
- return false;
-
- IBinaryField field = (IBinaryField) binaryInfo;
-
- // field name
- if (!this.matchesName(this.name, field.getName()))
- return false;
-
- // declaring type
- IBinaryType declaringType = (IBinaryType) enclosingBinaryInfo;
- if (declaringType != null) {
- char[] declaringTypeName = (char[]) declaringType.getName().clone();
- CharOperation.replace(declaringTypeName, '/', '.');
- if (!this
- .matchesType(
- this.declaringSimpleName,
- this.declaringQualification,
- declaringTypeName)) {
- return false;
- }
- }
+ FieldBinding field = (FieldBinding)binding;
+
+ // field name
+ if (!this.matchesName(this.name, field.readableName()))
+ return false;
- // field type
- String fieldTypeSignature = new String(field.getTypeName()).replace('/', '.');
- if (!this
- .matchesType(
- this.typeSimpleName,
- this.typeQualification,
- Signature.toString(fieldTypeSignature).toCharArray())) {
- return false;
- }
+ // declaring type
+ ReferenceBinding declaringBinding = field.declaringClass;
+ if (declaringBinding != null
+ && !this.matchesType(this.declaringSimpleName, this.declaringQualification, declaringBinding)) {
+
+ return false;
+ }
- return true;
+ // field type
+ if(!this.matchesType(this.typeSimpleName, this.typeQualification, field.type)) {
+ return false;
}
+
+ return true;
+}
+/**
+ * @see SearchPattern#matchesBinary(Object, Object)
+ */
+public boolean matchesBinary(Object binaryInfo, Object enclosingBinaryInfo) {
+ if (!(binaryInfo instanceof IBinaryField)) return false;
- /**
- * @see SearchPattern#matchIndexEntry
- */
- protected boolean matchIndexEntry() {
+ IBinaryField field = (IBinaryField)binaryInfo;
+
+ // field name
+ if (!this.matchesName(this.name, field.getName()))
+ return false;
- /* check name matches */
- if (name != null) {
- switch (matchMode) {
- case EXACT_MATCH :
- if (!CharOperation.equals(name, decodedName, isCaseSensitive)) {
- return false;
- }
- break;
- case PREFIX_MATCH :
- if (!CharOperation.prefixEquals(name, decodedName, isCaseSensitive)) {
- return false;
- }
- break;
- case PATTERN_MATCH :
- if (!CharOperation.match(name, decodedName, isCaseSensitive)) {
- return false;
- }
- }
+ // declaring type
+ IBinaryType declaringType = (IBinaryType)enclosingBinaryInfo;
+ if (declaringType != null) {
+ char[] declaringTypeName = (char[])declaringType.getName().clone();
+ CharOperation.replace(declaringTypeName, '/', '.');
+ if (!this.matchesType(this.declaringSimpleName, this.declaringQualification, declaringTypeName)) {
+ return false;
}
- return true;
}
- /**
- * Returns whether a method declaration or message send will need to be resolved to
- * find out if this method pattern matches it.
- */
- private boolean needsResolve() {
-
- // declaring type
- if (declaringSimpleName != null || declaringQualification != null)
- return true;
-
- // return type
- if (typeSimpleName != null || typeQualification != null)
- return true;
-
+ // field type
+ String fieldTypeSignature = new String(field.getTypeName()).replace('/', '.');
+ if(!this.matchesType(this.typeSimpleName, this.typeQualification, Signature.toString(fieldTypeSignature).toCharArray())) {
return false;
}
+
+ return true;
+}
+/**
+ * @see SearchPattern#matchIndexEntry
+ */
+protected boolean matchIndexEntry() {
- public String toString() {
-
- StringBuffer buffer = new StringBuffer(20);
- buffer.append("FieldDeclarationPattern: ");
- if (declaringQualification != null)
- buffer.append(declaringQualification).append('.');
- if (declaringSimpleName != null)
- buffer.append(declaringSimpleName).append('.');
- else
- if (declaringQualification != null)
- buffer.append("*.");
- if (name == null) {
- buffer.append("*");
- } else {
- buffer.append(name);
- }
- if (typeQualification != null)
- buffer.append(" --> ").append(typeQualification).append('.');
- else
- if (typeSimpleName != null)
- buffer.append(" --> ");
- if (typeSimpleName != null)
- buffer.append(typeSimpleName);
- else
- if (typeQualification != null)
- buffer.append("*");
- buffer.append(", ");
- switch (matchMode) {
+ /* check name matches */
+ if (name != null){
+ switch(matchMode){
case EXACT_MATCH :
- buffer.append("exact match, ");
+ if (!CharOperation.equals(name, decodedName, isCaseSensitive)){
+ return false;
+ }
break;
case PREFIX_MATCH :
- buffer.append("prefix match, ");
+ if (!CharOperation.prefixEquals(name, decodedName, isCaseSensitive)){
+ return false;
+ }
break;
case PATTERN_MATCH :
- buffer.append("pattern match, ");
- break;
+ if (!CharOperation.match(name, decodedName, isCaseSensitive)){
+ return false;
+ }
}
- if (isCaseSensitive)
- buffer.append("case sensitive");
- else
- buffer.append("case insensitive");
- return buffer.toString();
}
+ return true;
+}
+/**
+ * Returns whether a method declaration or message send will need to be resolved to
+ * find out if this method pattern matches it.
+ */
+private boolean needsResolve() {
+
+ // declaring type
+ if (declaringSimpleName != null || declaringQualification != null) return true;
+
+ // return type
+ if (typeSimpleName != null || typeQualification != null) return true;
+ return false;
+}
+public String toString(){
+
+ StringBuffer buffer = new StringBuffer(20);
+ buffer.append("FieldDeclarationPattern: ");
+ if (declaringQualification != null) buffer.append(declaringQualification).append('.');
+ if (declaringSimpleName != null)
+ buffer.append(declaringSimpleName).append('.');
+ else if (declaringQualification != null) buffer.append("*.");
+ if (name == null) {
+ buffer.append("*");
+ } else {
+ buffer.append(name);
+ }
+ if (typeQualification != null)
+ buffer.append(" --> ").append(typeQualification).append('.');
+ else if (typeSimpleName != null) buffer.append(" --> ");
+ if (typeSimpleName != null)
+ buffer.append(typeSimpleName);
+ else if (typeQualification != null) buffer.append("*");
+ buffer.append(", ");
+ switch(matchMode){
+ case EXACT_MATCH :
+ buffer.append("exact match, ");
+ break;
+ case PREFIX_MATCH :
+ buffer.append("prefix match, ");
+ break;
+ case PATTERN_MATCH :
+ buffer.append("pattern match, ");
+ break;
+ }
+ if (isCaseSensitive)
+ buffer.append("case sensitive");
+ else
+ buffer.append("case insensitive");
+ return buffer.toString();
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/FieldReferencePattern.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/FieldReferencePattern.java
index ef6fb55fa5..28dc7a6bde 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/FieldReferencePattern.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/FieldReferencePattern.java
@@ -23,7 +23,7 @@ public class FieldReferencePattern extends MultipleSearchPattern {
// selector
protected char[] name;
-
+
// declaring type
protected char[] declaringQualification;
protected char[] declaringSimpleName;
@@ -35,389 +35,302 @@ public class FieldReferencePattern extends MultipleSearchPattern {
protected char[] decodedName;
private static char[][] TAGS = { FIELD_REF, REF };
- public ReferenceBinding[] declaringTypes;
-
- public FieldReferencePattern(
- char[] name,
- int matchMode,
- boolean isCaseSensitive,
- char[] declaringQualification,
- char[] declaringSimpleName,
- char[] typeQualification,
- char[] typeSimpleName) {
-
- super(matchMode, isCaseSensitive);
-
- this.name = isCaseSensitive ? name : CharOperation.toLowerCase(name);
- this.declaringQualification =
- isCaseSensitive
- ? declaringQualification
- : CharOperation.toLowerCase(declaringQualification);
- this.declaringSimpleName =
- isCaseSensitive
- ? declaringSimpleName
- : CharOperation.toLowerCase(declaringSimpleName);
- this.typeQualification =
- isCaseSensitive
- ? typeQualification
- : CharOperation.toLowerCase(typeQualification);
- this.typeSimpleName =
- isCaseSensitive ? typeSimpleName : CharOperation.toLowerCase(typeSimpleName);
-
- this.needsResolve = this.needsResolve();
- }
-
- /**
- * Either decode ref/name, fieldRef/name
- */
- public void decodeIndexEntry(IEntryResult entryResult) {
-
- char[] word = entryResult.getWord();
- int size = word.length;
- int tagLength = currentTag.length;
- int nameLength = CharOperation.indexOf(SEPARATOR, word, tagLength);
- if (nameLength < 0)
- nameLength = size;
- decodedName = CharOperation.subarray(word, tagLength, nameLength);
+ public char[][][] allSuperDeclaringTypeNames;
+
+public FieldReferencePattern(
+ char[] name,
+ int matchMode,
+ boolean isCaseSensitive,
+ char[] declaringQualification,
+ char[] declaringSimpleName,
+ char[] typeQualification,
+ char[] typeSimpleName) {
+
+ super(matchMode, isCaseSensitive);
+
+ this.name = isCaseSensitive ? name : CharOperation.toLowerCase(name);
+ this.declaringQualification = isCaseSensitive ? declaringQualification : CharOperation.toLowerCase(declaringQualification);
+ this.declaringSimpleName = isCaseSensitive ? declaringSimpleName : CharOperation.toLowerCase(declaringSimpleName);
+ this.typeQualification = isCaseSensitive ? typeQualification : CharOperation.toLowerCase(typeQualification);
+ this.typeSimpleName = isCaseSensitive ? typeSimpleName : CharOperation.toLowerCase(typeSimpleName);
+
+ this.needsResolve = this.needsResolve();
+}
+/**
+ * Either decode ref/name, fieldRef/name
+ */
+public void decodeIndexEntry(IEntryResult entryResult){
+
+ char[] word = entryResult.getWord();
+ int size = word.length;
+ int tagLength = currentTag.length;
+ int nameLength = CharOperation.indexOf(SEPARATOR, word, tagLength);
+ if (nameLength < 0) nameLength = size;
+ decodedName = CharOperation.subarray(word, tagLength, nameLength);}
+/**
+ * see SearchPattern.feedIndexRequestor
+ */
+public void feedIndexRequestor(IIndexSearchRequestor requestor, int detailLevel, int[] references, IndexInput input, IJavaSearchScope scope) throws IOException {
+ if (currentTag == REF) {
+ foundAmbiguousIndexMatches = true;
}
-
- /**
- * see SearchPattern.feedIndexRequestor
- */
- public void feedIndexRequestor(
- IIndexSearchRequestor requestor,
- int detailLevel,
- int[] references,
- IndexInput input,
- IJavaSearchScope scope)
- throws IOException {
- if (currentTag == REF) {
- foundAmbiguousIndexMatches = true;
- }
- for (int i = 0, max = references.length; i < max; i++) {
- int reference = references[i];
- if (reference != -1) { // if the reference has not been eliminated
- IndexedFile file = input.getIndexedFile(reference);
- String path;
- if (file != null
- && scope.encloses(path = IndexedFile.convertPath(file.getPath()))) {
- requestor.acceptFieldReference(path, decodedName);
- }
+ for (int i = 0, max = references.length; i < max; i++) {
+ int reference = references[i];
+ if (reference != -1) { // if the reference has not been eliminated
+ IndexedFile file = input.getIndexedFile(reference);
+ String path;
+ if (file != null && scope.encloses(path = IndexedFile.convertPath(file.getPath()))) {
+ requestor.acceptFieldReference(path, decodedName);
}
}
}
+}
+protected char[][] getPossibleTags(){
+ return TAGS;
+}
+/**
+ * @see AndPattern#hasNextQuery
+ */
+protected boolean hasNextQuery() {
+ return false;
+}
+/**
+ * see SearchPattern.indexEntryPrefix()
+ */
+public char[] indexEntryPrefix(){
- protected char[][] getPossibleTags() {
- return TAGS;
- }
-
- /**
- * @see AndPattern#hasNextQuery
- */
- protected boolean hasNextQuery() {
- return false;
- }
-
- /**
- * see SearchPattern.indexEntryPrefix()
- */
- public char[] indexEntryPrefix() {
-
- return AbstractIndexer.bestReferencePrefix(
+ return AbstractIndexer.bestReferencePrefix(
currentTag,
name,
- matchMode,
+ matchMode,
isCaseSensitive);
+}
+/**
+ * @see SearchPattern#matchContainer()
+ */
+protected int matchContainer() {
+ return METHOD | FIELD;
+}
+/**
+ * @see SearchPattern#matches(AstNode, boolean)
+ */
+protected boolean matches(AstNode node, boolean resolve) {
+ if (node instanceof FieldReference) {
+ return this.matches((FieldReference)node, resolve);
+ } else if (node instanceof NameReference) {
+ return this.matches((NameReference)node, resolve);
}
-
- /**
- * @see SearchPattern#matchContainer()
- */
- protected int matchContainer() {
- return METHOD | FIELD;
- }
-
- /**
- * @see SearchPattern#matches(AstNode, boolean)
- */
- protected boolean matches(AstNode node, boolean resolve) {
- if (node instanceof FieldReference) {
- return this.matches((FieldReference) node, resolve);
- } else
- if (node instanceof NameReference) {
- return this.matches((NameReference) node, resolve);
- }
+ return false;
+}
+/**
+ * Returns whether this field reference pattern matches the given field reference.
+ * Look at resolved information only if specified.
+ */
+private boolean matches(FieldReference fieldRef, boolean resolve) {
+ // field name
+ if (!this.matchesName(this.name, fieldRef.token))
return false;
- }
- /**
- * Returns whether this field reference pattern matches the given field reference.
- * Look at resolved information only if specified.
- */
- private boolean matches(FieldReference fieldRef, boolean resolve) {
- // field name
- if (!this.matchesName(this.name, fieldRef.token))
+ if (resolve) {
+ // receiver type and field type
+ FieldBinding binding = fieldRef.binding;
+ if (binding != null && !this.matches(fieldRef.receiverType, fieldRef.isSuperAccess(), binding))
return false;
-
- if (resolve) {
- // declaring type and field type
- FieldBinding binding = fieldRef.binding;
- if (binding != null && !this.matches(binding))
- return false;
- }
-
- return true;
}
- /**
- * Returns whether this field reference pattern matches the given name reference.
- * Look at resolved information only if specified.
- */
- private boolean matches(NameReference nameRef, boolean resolve) {
- // field name
- boolean nameMatch = true;
- if (this.name != null) {
- if (nameRef instanceof SingleNameReference) {
- nameMatch = matchesName(this.name, ((SingleNameReference) nameRef).token);
- } else { // QualifiedNameReference
- nameMatch = false;
- QualifiedNameReference qNameRef = (QualifiedNameReference) nameRef;
- char[][] tokens = qNameRef.tokens;
- for (int i = qNameRef.indexOfFirstFieldBinding - 1, max = tokens.length;
- i < max && !nameMatch;
- i++) {
- if (i >= 0)
- nameMatch = matchesName(this.name, tokens[i]);
- }
- }
- }
- if (!nameMatch)
- return false;
-
- if (resolve) {
- Binding binding = nameRef.binding;
- if (binding != null) {
- if (nameRef instanceof SingleNameReference) {
- if (binding instanceof FieldBinding) {
- if (!this.matches((FieldBinding) binding)) {
- return false;
- }
- } else {
- return false; // must be a field binding
- }
- } else { // QualifiedNameReference
- QualifiedNameReference qNameRef = (QualifiedNameReference) nameRef;
- if (!(binding instanceof FieldBinding && matches((FieldBinding) binding))) {
- boolean otherMatch = false;
- int otherMax =
- qNameRef.otherBindings == null ? 0 : qNameRef.otherBindings.length;
- for (int i = 0; i < otherMax && !otherMatch; i++) {
- otherMatch = matches(qNameRef.otherBindings[i]);
- }
- if (!otherMatch)
- return false;
- }
- }
+ return true;
+}
+/**
+ * Returns whether this field reference pattern matches the given name reference.
+ * Look at resolved information only if specified.
+ */
+private boolean matches(NameReference nameRef, boolean resolve) {
+ // field name
+ boolean nameMatch = true;
+ if (this.name != null) {
+ if (nameRef instanceof SingleNameReference) {
+ nameMatch = matchesName(this.name, ((SingleNameReference)nameRef).token);
+ } else { // QualifiedNameReference
+ nameMatch = false;
+ QualifiedNameReference qNameRef = (QualifiedNameReference)nameRef;
+ char[][] tokens = qNameRef.tokens;
+ for (int i = qNameRef.indexOfFirstFieldBinding-1, max = tokens.length; i < max && !nameMatch; i++){
+ if (i >= 0) nameMatch = matchesName(this.name, tokens[i]);
}
- }
- return true;
- }
-
- /**
- * Returns whether this field reference pattern matches the given field binding.
- * Look at declaring type and filed type.
- */
- private boolean matches(FieldBinding binding) {
- // declaring type
- ReferenceBinding declaringBinding = binding.declaringClass;
- if (declaringBinding != null
- && !this.matchesType(
- this.declaringSimpleName,
- this.declaringQualification,
- declaringBinding)
- && !this.matchesAsSubtype(this.declaringTypes, declaringBinding)) {
- return false;
- }
-
- // field type
- if (!this
- .matchesType(this.typeSimpleName, this.typeQualification, binding.type))
- return false;
-
- return true;
- }
-
- /**
- * @see SearchPattern#matchIndexEntry
- */
- protected boolean matchIndexEntry() {
-
- /* check name matches */
- if (name != null) {
- switch (matchMode) {
- case EXACT_MATCH :
- if (!CharOperation.equals(name, decodedName, isCaseSensitive)) {
+ }
+ }
+ if (!nameMatch) return false;
+
+ if (resolve){
+ Binding binding = nameRef.binding;
+ if (binding != null){
+ if (nameRef instanceof SingleNameReference){
+ if (binding instanceof FieldBinding){
+ if (!this.matches(nameRef.receiverType, false, (FieldBinding) binding)){
return false;
}
- break;
- case PREFIX_MATCH :
- if (!CharOperation.prefixEquals(name, decodedName, isCaseSensitive)) {
- return false;
+ } else {
+ return false; // must be a field binding
+ }
+ } else { // QualifiedNameReference
+ QualifiedNameReference qNameRef = (QualifiedNameReference)nameRef;
+ TypeBinding receiverType = qNameRef.receiverType;
+ FieldBinding fieldBinding = null;
+ if (!(binding instanceof FieldBinding
+ && matchesName(this.name, (fieldBinding = (FieldBinding)binding).name)
+ && matches(receiverType, false, fieldBinding))){
+ if (binding instanceof VariableBinding){
+ receiverType = ((VariableBinding) binding).type;
}
- break;
- case PATTERN_MATCH :
- if (!CharOperation.match(name, decodedName, isCaseSensitive)) {
- return false;
+ boolean otherMatch = false;
+ int otherMax = qNameRef.otherBindings == null ? 0 : qNameRef.otherBindings.length;
+ for (int i = 0; i < otherMax && !otherMatch; i++){
+ FieldBinding otherBinding = qNameRef.otherBindings[i];
+ if (otherBinding == null) break;
+ otherMatch = matchesName(this.name, otherBinding.name) && matches(receiverType, false, otherBinding);
+ receiverType = otherBinding.type;
}
+ if (!otherMatch) return false;
+ }
}
}
- return true;
}
+ return true;
+}
+/**
+ * @see SearchPattern#matchIndexEntry
+ */
+protected boolean matchIndexEntry() {
- /**
- * Finds out whether the given ast node matches this search pattern.
- * Returns IMPOSSIBLE_MATCH if it doesn't.
- * Returns TRUSTED_MATCH if it matches exactly this search pattern (ie.
- * it doesn't need to be resolved or it has already been resolved.)
- * Returns POSSIBLE_MATCH if it potentially matches
- * this search pattern and it needs to be resolved to get more information.
- */
- public int matchLevel(AstNode node) {
- if (this.matches(node, false)) {
- if (this.needsResolve
- || node instanceof NameReference) { // ensure it is a field
- return POSSIBLE_MATCH;
- } else {
- return TRUSTED_MATCH;
- }
+ /* check name matches */
+ if (name != null){
+ switch(matchMode){
+ case EXACT_MATCH :
+ if (!CharOperation.equals(name, decodedName, isCaseSensitive)){
+ return false;
+ }
+ break;
+ case PREFIX_MATCH :
+ if (!CharOperation.prefixEquals(name, decodedName, isCaseSensitive)){
+ return false;
+ }
+ break;
+ case PATTERN_MATCH :
+ if (!CharOperation.match(name, decodedName, isCaseSensitive)){
+ return false;
+ }
}
- return IMPOSSIBLE_MATCH;
}
-
- /**
- * @see SearchPattern#matchReportReference
- */
- protected void matchReportReference(
- AstNode reference,
- IJavaElement element,
- int accuracy,
- MatchLocator locator)
- throws CoreException {
- char[] declaringTypeName =
- CharOperation.concat(
- this.declaringQualification,
- this.declaringSimpleName,
- '.');
- char[][] qualifiedName =
- CharOperation.splitOn(
- '.',
- CharOperation.concat(declaringTypeName, this.name, '.'));
- locator.reportQualifiedReference(
- reference.sourceStart,
- reference.sourceEnd,
- qualifiedName,
- element,
- accuracy);
+ return true;
+}
+/**
+ * Finds out whether the given ast node matches this search pattern.
+ * Returns IMPOSSIBLE_MATCH if it doesn't.
+ * Returns TRUSTED_MATCH if it matches exactly this search pattern (ie.
+ * it doesn't need to be resolved or it has already been resolved.)
+ * Returns POSSIBLE_MATCH if it potentially matches
+ * this search pattern and it needs to be resolved to get more information.
+ */
+public int matchLevel(AstNode node) {
+ if (this.matches(node, false)) {
+ if (this.needsResolve
+ || node instanceof NameReference) { // ensure it is a field
+ return POSSIBLE_MATCH;
+ } else {
+ return TRUSTED_MATCH;
+ }
}
+ return IMPOSSIBLE_MATCH;
+}
+/**
+ * @see SearchPattern#matchReportReference
+ */
+protected void matchReportReference(AstNode reference, IJavaElement element, int accuracy, MatchLocator locator) throws CoreException {
+ char[] declaringTypeName = CharOperation.concat(this.declaringQualification, this.declaringSimpleName, '.');
+ char[][] qualifiedName = CharOperation.splitOn('.', CharOperation.concat(declaringTypeName, this.name, '.'));
+ locator.reportQualifiedReference(reference.sourceStart, reference.sourceEnd, qualifiedName, element, accuracy);
+}
+/**
+ * Returns whether a method declaration or message send will need to be resolved to
+ * find out if this method pattern matches it.
+ */
+private boolean needsResolve() {
- /**
- * Returns whether a method declaration or message send will need to be resolved to
- * find out if this method pattern matches it.
- */
- private boolean needsResolve() {
-
- // declaring type
- if (declaringSimpleName != null || declaringQualification != null)
- return true;
+ // declaring type
+ if (declaringSimpleName != null || declaringQualification != null) return true;
- // return type
- if (typeSimpleName != null || typeQualification != null)
- return true;
+ // return type
+ if (typeSimpleName != null || typeQualification != null) return true;
- return false;
+ return false;
+}
+/**
+ * @see AndPattern#resetQuery
+ */
+protected void resetQuery() {
+}
+public String toString(){
+
+ StringBuffer buffer = new StringBuffer(20);
+ buffer.append("FieldReferencePattern: ");
+ if (declaringQualification != null) buffer.append(declaringQualification).append('.');
+ if (declaringSimpleName != null)
+ buffer.append(declaringSimpleName).append('.');
+ else if (declaringQualification != null) buffer.append("*.");
+ if (name != null) {
+ buffer.append(name);
+ } else {
+ buffer.append("*");
}
-
- /**
- * @see AndPattern#resetQuery
- */
- protected void resetQuery() {
+ if (typeQualification != null)
+ buffer.append(" --> ").append(typeQualification).append('.');
+ else if (typeSimpleName != null) buffer.append(" --> ");
+ if (typeSimpleName != null)
+ buffer.append(typeSimpleName);
+ else if (typeQualification != null) buffer.append("*");
+ buffer.append(", ");
+ switch(matchMode){
+ case EXACT_MATCH :
+ buffer.append("exact match, ");
+ break;
+ case PREFIX_MATCH :
+ buffer.append("prefix match, ");
+ break;
+ case PATTERN_MATCH :
+ buffer.append("pattern match, ");
+ break;
}
+ if (isCaseSensitive)
+ buffer.append("case sensitive");
+ else
+ buffer.append("case insensitive");
+ return buffer.toString();
+}
- public String toString() {
+public boolean initializeFromLookupEnvironment(LookupEnvironment env) {
+ this.allSuperDeclaringTypeNames = this.collectSuperTypeNames(this.declaringQualification, this.declaringSimpleName, this.matchMode, env);
+ return this.allSuperDeclaringTypeNames == null || this.allSuperDeclaringTypeNames != NOT_FOUND_DECLARING_TYPE;
+}
- StringBuffer buffer = new StringBuffer(20);
- buffer.append("FieldReferencePattern: ");
- if (declaringQualification != null)
- buffer.append(declaringQualification).append('.');
- if (declaringSimpleName != null)
- buffer.append(declaringSimpleName).append('.');
- else
- if (declaringQualification != null)
- buffer.append("*.");
- if (name != null) {
- buffer.append(name);
- } else {
- buffer.append("*");
- }
- if (typeQualification != null)
- buffer.append(" --> ").append(typeQualification).append('.');
- else
- if (typeSimpleName != null)
- buffer.append(" --> ");
- if (typeSimpleName != null)
- buffer.append(typeSimpleName);
- else
- if (typeQualification != null)
- buffer.append("*");
- buffer.append(", ");
- switch (matchMode) {
- case EXACT_MATCH :
- buffer.append("exact match, ");
- break;
- case PREFIX_MATCH :
- buffer.append("prefix match, ");
- break;
- case PATTERN_MATCH :
- buffer.append("pattern match, ");
- break;
- }
- if (isCaseSensitive)
- buffer.append("case sensitive");
- else
- buffer.append("case insensitive");
- return buffer.toString();
+/**
+ * Returns whether this field reference pattern matches the given field binding and receiver type.
+ */
+private boolean matches(TypeBinding receiverType, boolean isSuperAccess, FieldBinding binding) {
+ // receiver type
+ ReferenceBinding receiverBinding =
+ isSuperAccess || binding.isStatic() ?
+ binding.declaringClass :
+ (ReferenceBinding)receiverType;
+ if (receiverBinding != null
+ && !this.matchesAsSubtype(receiverBinding, this.declaringSimpleName, this.declaringQualification)
+ && !this.matchesType(this.allSuperDeclaringTypeNames, receiverBinding)) {
+ return false;
}
- public boolean initializeFromLookupEnvironment(LookupEnvironment env) {
-
- char[][] declaringTypeName = null;
- if ((this.declaringQualification != null)
- && (this.declaringSimpleName != null)
- && (this.matchMode == EXACT_MATCH)) {
- char[][] qualification =
- CharOperation.splitOn('.', this.declaringQualification);
- declaringTypeName =
- CharOperation.arrayConcat(qualification, this.declaringSimpleName);
- }
- if (declaringTypeName != null) {
- for (int i = 0, max = declaringTypeName.length; i < max; i++) {
- ReferenceBinding matchingDeclaringType = env.getCachedType(declaringTypeName);
- if (matchingDeclaringType != null && matchingDeclaringType.isValidBinding()) {
- this.declaringTypes = new ReferenceBinding[] { matchingDeclaringType };
- return true;
- }
- // if nothing is in the cache, it could have been a member type (A.B.C.D --> A.B.C$D)
- int last = declaringTypeName.length - 1;
- if (last == 0)
- break;
- declaringTypeName[last - 1] =
- CharOperation.concat(declaringTypeName[last - 1], declaringTypeName[last], '$');
- // try nested type
- declaringTypeName = CharOperation.subarray(declaringTypeName, 0, last);
- }
- return false;
- }
+ // field type
+ if (!this.matchesType(this.typeSimpleName, this.typeQualification, binding.type))
return false;
- }
+ return true;
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
index cb5b14f416..359681a86c 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MatchLocator.java
@@ -55,837 +55,723 @@ public class MatchLocator implements ITypeRequestor {
private LookupEnvironment lookupEnvironment;
private IResource currentResource;
private Openable currentOpenable;
- public MatchLocator(
- SearchPattern pattern,
- int detailLevel,
- IJavaSearchResultCollector collector,
- IJavaSearchScope scope) {
-
- this.pattern = pattern;
- this.detailLevel = detailLevel;
- this.collector = collector;
- this.scope = scope;
- }
+public MatchLocator(
+ SearchPattern pattern,
+ int detailLevel,
+ IJavaSearchResultCollector collector,
+ IJavaSearchScope scope) {
+
+ this.pattern = pattern;
+ this.detailLevel = detailLevel;
+ this.collector = collector;
+ this.scope = scope;
+}
+/**
+ * Add an additional binary type
+ */
+public void accept(IBinaryType binaryType, PackageBinding packageBinding) {
+ this.lookupEnvironment.createBinaryTypeFrom(binaryType, packageBinding);
+}
+/**
+ * Add an additional compilation unit.
+ */
+public void accept(ICompilationUnit sourceUnit) {
+ CompilationResult result = new CompilationResult(sourceUnit, 1, 1);
+ CompilationUnitDeclaration parsedUnit = this.parser.dietParse(sourceUnit, result);
- /**
- * Add an additional binary type
- */
- public void accept(IBinaryType binaryType, PackageBinding packageBinding) {
- this.lookupEnvironment.createBinaryTypeFrom(binaryType, packageBinding);
+ this.lookupEnvironment.buildTypeBindings(parsedUnit);
+ this.lookupEnvironment.completeTypeBindings(parsedUnit, true);
+}
+/**
+ * Add an additional source type
+ */
+public void accept(ISourceType sourceType, PackageBinding packageBinding) {
+ while (sourceType.getEnclosingType() != null) sourceType = sourceType.getEnclosingType();
+ CompilationResult result = new CompilationResult(sourceType.getFileName(), 1, 1); // need to hold onto this
+ CompilationUnitDeclaration unit =
+ SourceTypeConverter.buildCompilationUnit(sourceType, true, true, lookupEnvironment.problemReporter, result);
+
+ if (unit != null) {
+ this.lookupEnvironment.buildTypeBindings(unit);
+ this.lookupEnvironment.completeTypeBindings(unit, true);
}
-
- /**
- * Add an additional compilation unit.
- */
- public void accept(ICompilationUnit sourceUnit) {
- CompilationResult result = new CompilationResult(sourceUnit, 1, 1);
- CompilationUnitDeclaration parsedUnit =
- this.parser.dietParse(sourceUnit, result);
-
- this.lookupEnvironment.buildTypeBindings(parsedUnit);
- this.lookupEnvironment.completeTypeBindings(parsedUnit, true);
+}
+/**
+ * Creates an IField from the given field declaration and simple type names.
+ */
+private IField createFieldHandle(FieldDeclaration field, char[][] definingTypeNames) {
+ IType type = this.createTypeHandle(definingTypeNames);
+ return type.getField(new String(field.name));
+}
+/**
+ * Creates an IImportDeclaration from the given import statement
+ */
+private IImportDeclaration createImportHandle(ImportReference importRef) {
+ char[] importName = CharOperation.concatWith(importRef.getImportName(), '.');
+ if (importRef.onDemand) {
+ importName = CharOperation.concat(importName, ".*".toCharArray());
}
-
- /**
- * Add an additional source type
- */
- public void accept(ISourceType sourceType, PackageBinding packageBinding) {
- CompilationResult result =
- new CompilationResult(sourceType.getFileName(), 1, 1);
- // need to hold onto this
- CompilationUnitDeclaration unit =
- SourceTypeConverter.buildCompilationUnit(
- sourceType,
- true,
- true,
- lookupEnvironment.problemReporter,
- result);
-
- if (unit != null) {
- this.lookupEnvironment.buildTypeBindings(unit);
- this.lookupEnvironment.completeTypeBindings(unit, true);
+ return ((CompilationUnit)this.currentOpenable).getImport(
+ new String(importName));
+}
+/**
+ * Creates an IInitializer from the given field declaration and simple type names.
+ */
+private IInitializer createInitializerHandle(TypeDeclaration typeDecl, FieldDeclaration initializer, char[][] definingTypeNames) {
+ IType type = this.createTypeHandle(definingTypeNames);
+
+ // find occurence count of the given initializer in its type declaration
+ int occurrenceCount = 0;
+ FieldDeclaration[] fields = typeDecl.fields;
+ for (int i = 0, length = fields.length; i < length; i++) {
+ FieldDeclaration field = fields[i];
+ if (!field.isField()) {
+ occurrenceCount++;
+ if (field.equals(initializer)) {
+ break;
+ }
}
}
-
- /**
- * Creates an IField from the given field declaration and simple type names.
- */
- private IField createFieldHandle(
- FieldDeclaration field,
- char[][] definingTypeNames) {
- IType type = this.createTypeHandle(definingTypeNames);
- return type.getField(new String(field.name));
- }
-
- /**
- * Creates an IImportDeclaration from the given import statement
- */
- private IImportDeclaration createImportHandle(ImportReference importRef) {
- char[] importName = CharOperation.concatWith(importRef.getImportName(), '.');
- if (importRef.onDemand) {
- importName = CharOperation.concat(importName, ".*".toCharArray());
+
+ return type.getInitializer(occurrenceCount);
+}
+/**
+ * Creates an IMethod from the given method declaration and simple type names.
+ */
+private IMethod createMethodHandle(AbstractMethodDeclaration method, char[][] definingTypeNames) {
+ IType type = this.createTypeHandle(definingTypeNames);
+ Argument[] arguments = method.arguments;
+ int length = arguments == null ? 0 : arguments.length;
+ String[] parameterTypeSignatures = new String[length];
+ for (int i = 0; i < length; i++) {
+ TypeReference parameterType = arguments[i].type;
+ char[] typeName = CharOperation.concatWith(parameterType.getTypeName(), '.');
+ for (int j = 0; j < parameterType.dimensions(); j++) {
+ typeName = CharOperation.concat(typeName, "[]".toCharArray());
}
- return ((CompilationUnit) this.currentOpenable).getImport(
- new String(importName));
+ parameterTypeSignatures[i] = Signature.createTypeSignature(typeName, false);
}
-
- /**
- * Creates an IInitializer from the given field declaration and simple type names.
- */
- private IInitializer createInitializerHandle(
- TypeDeclaration typeDecl,
- FieldDeclaration initializer,
- char[][] definingTypeNames) {
- IType type = this.createTypeHandle(definingTypeNames);
-
- // find occurence count of the given initializer in its type declaration
- int occurrenceCount = 0;
- FieldDeclaration[] fields = typeDecl.fields;
- for (int i = 0, length = fields.length; i < length; i++) {
- FieldDeclaration field = fields[i];
- if (!field.isField()) {
- occurrenceCount++;
- if (field.equals(initializer)) {
- break;
- }
- }
- }
-
- return type.getInitializer(occurrenceCount);
+ return type.getMethod(
+ new String(method.selector),
+ parameterTypeSignatures);
+}
+/**
+ * Creates an IType from the given simple type names.
+ */
+private IType createTypeHandle(char[][] simpleTypeNames) {
+ // creates compilation unit
+ CompilationUnit unit = (CompilationUnit) this.currentOpenable;
+
+ // create type
+ int length = simpleTypeNames.length;
+ IType type = unit.getType(new String(simpleTypeNames[0]));
+ for (int i = 1; i < length; i++) {
+ type = type.getType(new String(simpleTypeNames[i]));
}
-
- /**
- * Creates an IMethod from the given method declaration and simple type names.
- */
- private IMethod createMethodHandle(
- AbstractMethodDeclaration method,
- char[][] definingTypeNames) {
- IType type = this.createTypeHandle(definingTypeNames);
- Argument[] arguments = method.arguments;
- int length = arguments == null ? 0 : arguments.length;
- String[] parameterTypeSignatures = new String[length];
- for (int i = 0; i < length; i++) {
- TypeReference parameterType = arguments[i].type;
- char[] typeName = CharOperation.concatWith(parameterType.getTypeName(), '.');
- for (int j = 0; j < parameterType.dimensions(); j++) {
- typeName = CharOperation.concat(typeName, "[]".toCharArray());
+ return type;
+}
+private char[] getContents(IFile file) {
+ BufferedInputStream input = null;
+ try {
+ input = new BufferedInputStream(file.getContents(true));
+ StringBuffer buffer= new StringBuffer();
+ int nextChar = input.read();
+ while (nextChar != -1) {
+ buffer.append( (char)nextChar );
+ nextChar = input.read();
+ }
+ int length = buffer.length();
+ char[] result = new char[length];
+ buffer.getChars(0, length, result, 0);
+ return result;
+ } catch (IOException e) {
+ return null;
+ } catch (CoreException e) {
+ return null;
+ } finally {
+ if (input != null) {
+ try {
+ input.close();
+ } catch (IOException e) {
+ // nothing can be done if the file cannot be closed
}
- parameterTypeSignatures[i] = Signature.createTypeSignature(typeName, false);
}
- return type.getMethod(new String(method.selector), parameterTypeSignatures);
}
-
- /**
- * Creates an IType from the given simple type names.
- */
- private IType createTypeHandle(char[][] simpleTypeNames) {
- // creates compilation unit
- CompilationUnit unit = (CompilationUnit) this.currentOpenable;
-
- // create type
- int length = simpleTypeNames.length;
- IType type = unit.getType(new String(simpleTypeNames[0]));
- for (int i = 1; i < length; i++) {
- type = type.getType(new String(simpleTypeNames[i]));
+}
+protected IResource getCurrentResource() {
+ return this.currentResource;
+}
+protected Scanner getScanner() {
+ return this.parser == null ? null : this.parser.scanner;
+}
+/**
+ * Locate the matches in the given files and report them using the search requestor.
+ */
+public void locateMatches(String[] filePaths, IWorkspace workspace) throws JavaModelException {
+ Util.sort(filePaths); // sort by projects
+ JavaModelManager manager = JavaModelManager.getJavaModelManager();
+ HandleFactory factory = new HandleFactory(workspace.getRoot(), manager);
+ JavaProject previousJavaProject = null;
+ int length = filePaths.length;
+ double increment = 100.0 / length;
+ double totalWork = 0;
+ int lastProgress = 0;
+ boolean couldInitializePattern = false;
+ for (int i = 0; i < length; i++) {
+ IProgressMonitor monitor = this.collector.getProgressMonitor();
+ if (monitor != null && monitor.isCanceled()) {
+ throw new OperationCanceledException();
}
- return type;
- }
+ String pathString = filePaths[i];
+ this.currentOpenable = factory.createOpenable(pathString);
+ if (this.currentOpenable == null) continue; // match is outside classpath
- private char[] getContents(IFile file) {
- BufferedInputStream input = null;
+ // create new parser and lookup environment if this is a new project
try {
- input = new BufferedInputStream(file.getContents(true));
- StringBuffer buffer = new StringBuffer();
- int nextChar = input.read();
- while (nextChar != -1) {
- buffer.append((char) nextChar);
- nextChar = input.read();
+ JavaProject javaProject = (JavaProject)this.currentOpenable.getJavaProject();
+ this.currentResource = this.currentOpenable.getUnderlyingResource();
+ if (this.currentResource == null) { // case of a file in an external jar
+ this.currentResource = javaProject.getProject();
}
- int length = buffer.length();
- char[] result = new char[length];
- buffer.getChars(0, length, result, 0);
- return result;
- } catch (IOException e) {
- return null;
- } catch (CoreException e) {
- return null;
- } finally {
- if (input != null) {
- try {
- input.close();
- } catch (IOException e) {
- // nothing can be done if the file cannot be closed
- }
+ if (!javaProject.equals(previousJavaProject)) {
+ // create parser for this project
+ couldInitializePattern = this.createParser(javaProject);
+ previousJavaProject = javaProject;
}
+ if (!couldInitializePattern) continue; // the pattern could not be initialized: the match cannot be in this project
+ } catch (JavaModelException e) {
+ // file doesn't exist -> skip it
+ continue;
}
- }
-
- protected IResource getCurrentResource() {
- return this.currentResource;
- }
-
- protected Scanner getScanner() {
- return this.parser == null ? null : this.parser.scanner;
- }
-
- /**
- * Locate the matches in the given files and report them using the search requestor.
- */
- public void locateMatches(String[] filePaths, IWorkspace workspace)
- throws JavaModelException {
- Util.sort(filePaths); // sort by projects
- JavaModelManager manager = JavaModelManager.getJavaModelManager();
- HandleFactory factory = new HandleFactory(workspace.getRoot(), manager);
- JavaProject previousJavaProject = null;
- int length = filePaths.length;
- double increment = 100.0 / length;
- double totalWork = 0;
- int lastProgress = 0;
- boolean couldInitializePattern = false;
- for (int i = 0; i < length; i++) {
- IProgressMonitor monitor = this.collector.getProgressMonitor();
- if (monitor != null && monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
- String pathString = filePaths[i];
- this.currentOpenable = factory.createOpenable(pathString);
- if (this.currentOpenable == null)
- continue; // match is outside classpath
-
- // create new parser and lookup environment if this is a new project
- try {
- JavaProject javaProject = (JavaProject) this.currentOpenable.getJavaProject();
- this.currentResource = this.currentOpenable.getUnderlyingResource();
- if (this.currentResource == null) { // case of a file in an external jar
- this.currentResource = javaProject.getProject();
- }
- if (!javaProject.equals(previousJavaProject)) {
- // create parser for this project
- couldInitializePattern = this.createParser(javaProject);
- previousJavaProject = javaProject;
- }
- if (!couldInitializePattern)
- continue;
- // the pattern could not be initialized: the match cannot be in this project
- } catch (JavaModelException e) {
- // file doesn't exist -> skip it
- continue;
- }
- // locate matches in current file and report them
- try {
- if (this.currentOpenable instanceof CompilationUnit) {
- this.locateMatchesInCompilationUnit();
- } else
- if (this.currentOpenable instanceof org.eclipse.jdt.internal.core.ClassFile) {
- this.locateMatchesInClassFile();
- }
- } catch (AbortCompilation e) {
- // problem with class path: it could not find base classes
- throw new JavaModelException(
- e,
- IJavaModelStatusConstants.BUILDER_INITIALIZATION_ERROR);
- } catch (CoreException e) {
- if (e instanceof JavaModelException) {
- throw (JavaModelException) e;
- } else {
- throw new JavaModelException(e);
- }
+ // locate matches in current file and report them
+ try {
+ if (this.currentOpenable instanceof CompilationUnit) {
+ this.locateMatchesInCompilationUnit();
+ } else if (this.currentOpenable instanceof org.eclipse.jdt.internal.core.ClassFile) {
+ this.locateMatchesInClassFile();
}
- if (monitor != null) {
- totalWork = totalWork + increment;
- int worked = (int) totalWork - lastProgress;
- monitor.worked(worked);
- lastProgress = (int) totalWork;
+ } catch (AbortCompilation e) {
+ // problem with class path: it could not find base classes
+ throw new JavaModelException(e, IJavaModelStatusConstants.BUILDER_INITIALIZATION_ERROR);
+ } catch (CoreException e) {
+ if (e instanceof JavaModelException) {
+ throw (JavaModelException)e;
+ } else {
+ throw new JavaModelException(e);
}
}
+ if (monitor != null) {
+ totalWork = totalWork + increment;
+ int worked = (int)totalWork - lastProgress;
+ monitor.worked(worked);
+ lastProgress = (int)totalWork;
+ }
}
-
- /**
- * Locate declaration in the current class file. This class file is always in a jar.
- */
- private void locateMatchesInClassFile()
- throws CoreException, JavaModelException {
- org.eclipse.jdt.internal.core.ClassFile classFile =
- (org.eclipse.jdt.internal.core.ClassFile) this.currentOpenable;
- BinaryType binaryType = (BinaryType) classFile.getType();
- IBinaryType info;
- if (classFile.isOpen()) {
- // reuse the info from the java model cache
- info = (IBinaryType) binaryType.getRawInfo();
- } else {
- // create a temporary info
- try {
- IJavaElement pkg = classFile.getParent();
- PackageFragmentRoot root = (PackageFragmentRoot) pkg.getParent();
- if (root.isArchive()) {
- // class file in a jar
- String pkgPath = pkg.getElementName().replace('.', '/');
- String classFilePath =
- (pkgPath.length() > 0)
- ? pkgPath + "/" + classFile.getElementName()
- : classFile.getElementName();
- ZipFile zipFile = null;
- try {
- zipFile = ((JarPackageFragmentRoot) root).getJar();
- info =
- org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(
- zipFile,
- classFilePath);
- } finally {
- if (zipFile != null) {
- try {
- zipFile.close();
- } catch (IOException e) {
- // ignore
- }
+}
+/**
+ * Locate declaration in the current class file. This class file is always in a jar.
+ */
+private void locateMatchesInClassFile() throws CoreException, JavaModelException {
+ org.eclipse.jdt.internal.core.ClassFile classFile = (org.eclipse.jdt.internal.core.ClassFile)this.currentOpenable;
+ BinaryType binaryType = (BinaryType)classFile.getType();
+ IBinaryType info;
+ if (classFile.isOpen()) {
+ // reuse the info from the java model cache
+ info = (IBinaryType)binaryType.getRawInfo();
+ } else {
+ // create a temporary info
+ try {
+ IJavaElement pkg = classFile.getParent();
+ PackageFragmentRoot root = (PackageFragmentRoot)pkg.getParent();
+ if (root.isArchive()) {
+ // class file in a jar
+ String pkgPath = pkg.getElementName().replace('.', '/');
+ String classFilePath =
+ (pkgPath.length() > 0) ?
+ pkgPath + "/" + classFile.getElementName() :
+ classFile.getElementName();
+ ZipFile zipFile = null;
+ try {
+ zipFile = ((JarPackageFragmentRoot)root).getJar();
+ info = org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(
+ zipFile,
+ classFilePath);
+ } finally {
+ if (zipFile != null) {
+ try {
+ zipFile.close();
+ } catch (IOException e) {
+ // ignore
}
}
- } else {
- // class file in a directory
- String osPath = this.currentResource.getFullPath().toOSString();
- info = org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(osPath);
}
- } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException e) {
- e.printStackTrace();
- return;
- } catch (java.io.IOException e) {
- throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
+ } else {
+ // class file in a directory
+ String osPath = this.currentResource.getFullPath().toOSString();
+ info = org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(osPath);
}
-
+ } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException e) {
+ e.printStackTrace();
+ return;
+ } catch (java.io.IOException e) {
+ throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
}
+
+ }
- // check class definition
- if (this.pattern.matchesBinary(info, null)) {
- this.reportBinaryMatch(
- binaryType,
- info,
- IJavaSearchResultCollector.EXACT_MATCH);
- }
+ // check class definition
+ if (this.pattern.matchesBinary(info, null)) {
+ this.reportBinaryMatch(binaryType, info, IJavaSearchResultCollector.EXACT_MATCH);
+ }
- boolean compilationAborted = false;
- if (this.pattern.needsResolve) {
- // resolve
- BinaryTypeBinding binding = null;
- try {
- binding = this.lookupEnvironment.cacheBinaryType(info);
- if (binding == null) {
- // it was already cached as a result of a previous query
- char[][] compoundName =
- CharOperation.splitOn('.', binaryType.getFullyQualifiedName().toCharArray());
- ReferenceBinding referenceBinding =
- this.lookupEnvironment.getCachedType(compoundName);
- if (referenceBinding != null
- && (referenceBinding instanceof BinaryTypeBinding)) {
- // if the binding could be found and if it comes from a source type,
- binding = (BinaryTypeBinding) referenceBinding;
- }
+ boolean compilationAborted = false;
+ if (this.pattern.needsResolve) {
+ // resolve
+ BinaryTypeBinding binding = null;
+ try {
+ binding = this.lookupEnvironment.cacheBinaryType(info);
+ if (binding == null) { // it was already cached as a result of a previous query
+ char[][] compoundName = CharOperation.splitOn('.', binaryType.getFullyQualifiedName().toCharArray());
+ ReferenceBinding referenceBinding = this.lookupEnvironment.getCachedType(compoundName);
+ if (referenceBinding != null && (referenceBinding instanceof BinaryTypeBinding)) {
+ // if the binding could be found and if it comes from a source type,
+ binding = (BinaryTypeBinding)referenceBinding;
}
+ }
- // check methods
- if (binding != null) {
- MethodBinding[] methods = binding.methods();
- for (int i = 0; i < methods.length; i++) {
- MethodBinding method = methods[i];
- if (this.pattern.matches(method)) {
- IMethod methodHandle =
- binaryType.getMethod(
- new String(
- method.isConstructor()
- ? binding.compoundName[binding.compoundName.length - 1]
- : method.selector),
- Signature.getParameterTypes(new String(method.signature()).replace('/', '.')));
- this.reportBinaryMatch(
- methodHandle,
- info,
- IJavaSearchResultCollector.EXACT_MATCH);
- }
+ // check methods
+ if (binding != null) {
+ MethodBinding[] methods = binding.methods();
+ for (int i = 0; i < methods.length; i++) {
+ MethodBinding method = methods[i];
+ if (this.pattern.matches(method)) {
+ IMethod methodHandle =
+ binaryType.getMethod(
+ new String(method.isConstructor() ? binding.compoundName[binding.compoundName.length-1] : method.selector),
+ Signature.getParameterTypes(new String(method.signature()).replace('/', '.'))
+ );
+ this.reportBinaryMatch(methodHandle, info, IJavaSearchResultCollector.EXACT_MATCH);
}
}
-
- // check fields
- if (binding != null) {
- FieldBinding[] fields = binding.fields();
- for (int i = 0; i < fields.length; i++) {
- FieldBinding field = fields[i];
- if (this.pattern.matches(field)) {
- IField fieldHandle = binaryType.getField(new String(field.name));
- this.reportBinaryMatch(
- fieldHandle,
- info,
- IJavaSearchResultCollector.EXACT_MATCH);
- }
+ }
+
+ // check fields
+ if (binding != null) {
+ FieldBinding[] fields = binding.fields();
+ for (int i = 0; i < fields.length; i++) {
+ FieldBinding field = fields[i];
+ if (this.pattern.matches(field)) {
+ IField fieldHandle = binaryType.getField(new String(field.name));
+ this.reportBinaryMatch(fieldHandle, info, IJavaSearchResultCollector.EXACT_MATCH);
}
}
- } catch (AbortCompilation e) {
- binding = null;
}
-
- // no need to check binary info if resolve was successful
- compilationAborted = binding == null;
- if (!compilationAborted)
- return;
+ } catch (AbortCompilation e) {
+ binding = null;
}
- // if compilation was aborted it is a problem with the class path:
- // report as a potential match if binary info matches the pattern
- int accuracy =
- compilationAborted
- ? IJavaSearchResultCollector.POTENTIAL_MATCH
- : IJavaSearchResultCollector.EXACT_MATCH;
-
- // check methods
- IBinaryMethod[] methods = info.getMethods();
- int length = methods == null ? 0 : methods.length;
- for (int i = 0; i < length; i++) {
- IBinaryMethod method = methods[i];
- if (this.pattern.matchesBinary(method, info)) {
- IMethod methodHandle =
- binaryType.getMethod(
- new String(method.isConstructor() ? info.getName() : method.getSelector()),
- Signature.getParameterTypes(
- new String(method.getMethodDescriptor()).replace('/', '.')));
- this.reportBinaryMatch(methodHandle, info, accuracy);
- }
+ // no need to check binary info if resolve was successful
+ compilationAborted = binding == null;
+ if (!compilationAborted) return;
+ }
+
+ // if compilation was aborted it is a problem with the class path:
+ // report as a potential match if binary info matches the pattern
+ int accuracy = compilationAborted ? IJavaSearchResultCollector.POTENTIAL_MATCH : IJavaSearchResultCollector.EXACT_MATCH;
+
+ // check methods
+ IBinaryMethod[] methods = info.getMethods();
+ int length = methods == null ? 0 : methods.length;
+ for (int i = 0; i < length; i++) {
+ IBinaryMethod method = methods[i];
+ if (this.pattern.matchesBinary(method, info)) {
+ IMethod methodHandle =
+ binaryType.getMethod(
+ new String(method.isConstructor() ? info.getName() : method.getSelector()),
+ Signature.getParameterTypes(new String(method.getMethodDescriptor()).replace('/', '.'))
+ );
+ this.reportBinaryMatch(methodHandle, info, accuracy);
}
+ }
- // check fields
- IBinaryField[] fields = info.getFields();
- length = fields == null ? 0 : fields.length;
- for (int i = 0; i < length; i++) {
- IBinaryField field = fields[i];
- if (this.pattern.matchesBinary(field, info)) {
- IField fieldHandle = binaryType.getField(new String(field.getName()));
- this.reportBinaryMatch(fieldHandle, info, accuracy);
- }
+ // check fields
+ IBinaryField[] fields = info.getFields();
+ length = fields == null ? 0 : fields.length;
+ for (int i = 0; i < length; i++) {
+ IBinaryField field = fields[i];
+ if (this.pattern.matchesBinary(field, info)) {
+ IField fieldHandle = binaryType.getField(new String(field.getName()));
+ this.reportBinaryMatch(fieldHandle, info, accuracy);
}
}
+}
+private void locateMatchesInCompilationUnit() throws CoreException {
+ // get source
+ final char[] source = getContents((IFile)this.currentResource);
+
+ // get main type name
+ String pathString = this.currentResource.toString();
+ int lastDot = pathString.lastIndexOf('/');
+ // remove folder path and extension ".java"
+ final char[] mainTypeName = pathString.substring(lastDot+1, pathString.length()-5).toCharArray();
+
+ // parse
+ ICompilationUnit sourceUnit = new ICompilationUnit() {
+ public char[] getContents() {
+ return source;
+ }
+ public char[] getFileName() {
+ return MatchLocator.this.currentResource.getName().toCharArray();
+ }
+ public char[] getMainTypeName() {
+ return mainTypeName;
+ }
+ };
+ MatchSet set = new MatchSet(this);
+ this.parser.matchSet = set;
+ CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0);
+ CompilationUnitDeclaration parsedUnit = this.parser.parse(sourceUnit, compilationResult);
+
+ if (parsedUnit != null) {
+ // report matches that don't need resolve
+ set.cuHasBeenResolved = false;
+ set.accuracy = IJavaSearchResultCollector.EXACT_MATCH;
+ set.reportMatching(parsedUnit);
+
+ // resolve if needed
+ if (set.needsResolve()) {
+ if (parsedUnit.types != null) {
+ /**
+ * First approximation: reset the lookup environment -> this will recreate the bindings for the current CU
+ * Optimization: the binding resolution should be done for all compilation units at once
+ */
+ this.lookupEnvironment.reset();
- private void locateMatchesInCompilationUnit() throws CoreException {
- // get source
- final char[] source = getContents((IFile) this.currentResource);
-
- // get main type name
- String pathString = this.currentResource.toString();
- int lastDot = pathString.lastIndexOf('/');
- // remove folder path and extension ".java"
- final char[] mainTypeName =
- pathString.substring(lastDot + 1, pathString.length() - 5).toCharArray();
-
- // parse
- ICompilationUnit sourceUnit = new ICompilationUnit() {
- public char[] getContents() {
- return source;
- }
- public char[] getFileName() {
- return MatchLocator.this.currentResource.getName().toCharArray();
- }
- public char[] getMainTypeName() {
- return mainTypeName;
- }
- };
- MatchSet set = new MatchSet(this);
- this.parser.matchSet = set;
- CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0);
- CompilationUnitDeclaration parsedUnit =
- this.parser.parse(sourceUnit, compilationResult);
-
- if (parsedUnit != null) {
- // report matches that don't need resolve
- set.cuHasBeenResolved = false;
- set.accuracy = IJavaSearchResultCollector.EXACT_MATCH;
- set.reportMatching(parsedUnit);
-
- // resolve if needed
- if (set.needsResolve()) {
- if (parsedUnit.types != null) {
- /**
- * First approximation: reset the lookup environment -> this will recreate the bindings for the current CU
- * Optimization: the binding resolution should be done for all compilation units at once
- */
- this.lookupEnvironment.reset();
-
- try {
- lookupEnvironment.buildTypeBindings(parsedUnit);
- if (parsedUnit.scope != null) {
- lookupEnvironment.completeTypeBindings(parsedUnit, true);
- parsedUnit.scope.faultInTypes();
- parsedUnit.resolve();
- this.pattern.initializeFromLookupEnvironment(this.lookupEnvironment);
- }
- // report matches that needed resolve
- set.cuHasBeenResolved = true;
- set.accuracy = IJavaSearchResultCollector.EXACT_MATCH;
- set.reportMatching(parsedUnit);
- } catch (AbortCompilation e) {
- // could not resolve (reasons include "could not find library class") -> ignore and report the unresolved nodes
- set.cuHasBeenResolved = false;
- set.accuracy = IJavaSearchResultCollector.POTENTIAL_MATCH;
- set.reportMatching(parsedUnit);
+ try {
+ lookupEnvironment.buildTypeBindings(parsedUnit);
+ if (parsedUnit.scope != null) {
+ lookupEnvironment.completeTypeBindings(parsedUnit, true);
+ parsedUnit.scope.faultInTypes();
+ parsedUnit.resolve();
+ //this.pattern.initializeFromLookupEnvironment(this.lookupEnvironment);
}
+ // report matches that needed resolve
+ set.cuHasBeenResolved = true;
+ set.accuracy = IJavaSearchResultCollector.EXACT_MATCH;
+ set.reportMatching(parsedUnit);
+ } catch (AbortCompilation e) {
+ // could not resolve (reasons include "could not find library class") -> ignore and report the unresolved nodes
+ set.cuHasBeenResolved = false;
+ set.accuracy = IJavaSearchResultCollector.POTENTIAL_MATCH;
+ set.reportMatching(parsedUnit);
}
}
}
}
-
- /**
- * Locates the package declarations corresponding to this locator's pattern.
- */
- public void locatePackageDeclarations(IWorkspace workspace)
- throws JavaModelException {
- this.locatePackageDeclarations(this.pattern, workspace);
- }
-
- /**
- * Locates the package declarations corresponding to the search pattern.
- */
- private void locatePackageDeclarations(
- SearchPattern searchPattern,
- IWorkspace workspace)
- throws JavaModelException {
- if (searchPattern instanceof OrPattern) {
- OrPattern orPattern = (OrPattern) searchPattern;
- this.locatePackageDeclarations(orPattern.leftPattern, workspace);
- this.locatePackageDeclarations(orPattern.rightPattern, workspace);
- } else
- if (searchPattern instanceof PackageDeclarationPattern) {
- PackageDeclarationPattern pkgPattern =
- (PackageDeclarationPattern) searchPattern;
- String pkgName = new String(pkgPattern.pkgName);
- IJavaProject[] projects =
- JavaModelManager.getJavaModel(workspace).getJavaProjects();
- for (int i = 0, length = projects.length; i < length; i++) {
- IJavaProject javaProject = projects[i];
- IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
- for (int j = 0, rootsLength = roots.length; j < rootsLength; j++) {
- IJavaElement[] pkgs = roots[j].getChildren();
- for (int k = 0, pksLength = pkgs.length; k < pksLength; k++) {
- IJavaElement pkg = pkgs[k];
- if (pkgPattern
- .matchesName(pkgPattern.pkgName, pkg.getElementName().toCharArray())) {
- this.currentResource = pkg.getUnderlyingResource();
- if (this.currentResource == null) { // case of a file in an external jar
- this.currentResource = javaProject.getProject();
- }
- try {
- this.report(-1, -2, pkg, IJavaSearchResultCollector.EXACT_MATCH);
- } catch (CoreException e) {
- if (e instanceof JavaModelException) {
- throw (JavaModelException) e;
- } else {
- throw new JavaModelException(e);
- }
- }
+}
+/**
+ * Locates the package declarations corresponding to this locator's pattern.
+ */
+public void locatePackageDeclarations(IWorkspace workspace) throws JavaModelException {
+ this.locatePackageDeclarations(this.pattern, workspace);
+}
+/**
+ * Locates the package declarations corresponding to the search pattern.
+ */
+private void locatePackageDeclarations(SearchPattern searchPattern, IWorkspace workspace) throws JavaModelException {
+ if (searchPattern instanceof OrPattern) {
+ OrPattern orPattern = (OrPattern)searchPattern;
+ this.locatePackageDeclarations(orPattern.leftPattern, workspace);
+ this.locatePackageDeclarations(orPattern.rightPattern, workspace);
+ } else if (searchPattern instanceof PackageDeclarationPattern) {
+ PackageDeclarationPattern pkgPattern = (PackageDeclarationPattern)searchPattern;
+ String pkgName = new String(pkgPattern.pkgName);
+ IJavaProject[] projects = JavaModelManager.getJavaModel(workspace).getJavaProjects();
+ for (int i = 0, length = projects.length; i < length; i++) {
+ IJavaProject javaProject = projects[i];
+ IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
+ for (int j = 0, rootsLength = roots.length; j < rootsLength; j++) {
+ IJavaElement[] pkgs = roots[j].getChildren();
+ for (int k = 0, pksLength = pkgs.length; k < pksLength; k++) {
+ IJavaElement pkg = pkgs[k];
+ if (pkgPattern.matchesName(pkgPattern.pkgName, pkg.getElementName().toCharArray())) {
+ this.currentResource = pkg.getUnderlyingResource();
+ if (this.currentResource == null) { // case of a file in an external jar
+ this.currentResource = javaProject.getProject();
+ }
+ try {
+ this.report(-1, -2, pkg, IJavaSearchResultCollector.EXACT_MATCH);
+ } catch (CoreException e) {
+ if (e instanceof JavaModelException) {
+ throw (JavaModelException)e;
+ } else {
+ throw new JavaModelException(e);
}
}
}
}
}
- }
-
- public void report(
- int sourceStart,
- int sourceEnd,
- IJavaElement element,
- int accuracy)
- throws CoreException {
- if (this.scope.encloses(element)) {
- this.collector.accept(
- this.currentResource,
- sourceStart,
- sourceEnd + 1,
- element,
- accuracy);
}
}
-
- private void reportBinaryMatch(
- IMember binaryMember,
- IBinaryType info,
- int accuracy)
- throws CoreException, JavaModelException {
- ISourceRange range = binaryMember.getNameRange();
- if (range.getOffset() == -1) {
- ClassFile classFile = (ClassFile) binaryMember.getClassFile();
- SourceMapper mapper = classFile.getSourceMapper();
- if (mapper != null) {
- IType type = classFile.getType();
- char[] contents = mapper.findSource(type, info);
- if (contents != null) {
- range = mapper.mapSource(type, contents, binaryMember);
- }
+}
+public void report(int sourceStart, int sourceEnd, IJavaElement element, int accuracy) throws CoreException {
+ if (this.scope.encloses(element)) {
+ this.collector.accept(
+ this.currentResource,
+ sourceStart,
+ sourceEnd + 1,
+ element,
+ accuracy
+ );
+ }
+}
+private void reportBinaryMatch(IMember binaryMember, IBinaryType info, int accuracy) throws CoreException, JavaModelException {
+ ISourceRange range = binaryMember.getNameRange();
+ if (range.getOffset() == -1) {
+ ClassFile classFile = (ClassFile)binaryMember.getClassFile();
+ SourceMapper mapper = classFile.getSourceMapper();
+ if (mapper != null) {
+ IType type = classFile.getType();
+ char[] contents = mapper.findSource(type, info);
+ if (contents != null) {
+ range = mapper.mapSource(type, contents, binaryMember);
}
}
- int startIndex = range.getOffset();
- int endIndex = startIndex + range.getLength() - 1;
- this.report(startIndex, endIndex, binaryMember, accuracy);
- }
-
- /**
- * Reports the given field declaration to the search requestor.
- * Its defining types have the given simple names.
- */
- public void reportFieldDeclaration(
- FieldDeclaration fieldDeclaration,
- char[][] definingTypeNames,
- int accuracy)
- throws CoreException {
-
- // create field handle
- IType type = this.createTypeHandle(definingTypeNames);
- IField field = type.getField(new String(fieldDeclaration.name));
-
- // accept field declaration
- this.report(
- fieldDeclaration.sourceStart,
- fieldDeclaration.sourceEnd,
- field,
- accuracy);
}
+ int startIndex = range.getOffset();
+ int endIndex = startIndex + range.getLength() - 1;
+ this.report(startIndex, endIndex, binaryMember, accuracy);
+}
+/**
+ * Reports the given field declaration to the search requestor.
+ * Its defining types have the given simple names.
+ */
+public void reportFieldDeclaration(
+ FieldDeclaration fieldDeclaration,
+ char[][] definingTypeNames,
+ int accuracy) throws CoreException {
+
+ // create field handle
+ IType type = this.createTypeHandle(definingTypeNames);
+ IField field = type.getField(new String(fieldDeclaration.name));
+
+ // accept field declaration
+ this.report(fieldDeclaration.sourceStart, fieldDeclaration.sourceEnd, field, accuracy);
+}
+/**
+ * Reports the given import to the search requestor.
+ */
+public void reportImport(ImportReference reference, int accuracy) throws CoreException {
- /**
- * Reports the given import to the search requestor.
- */
- public void reportImport(ImportReference reference, int accuracy)
- throws CoreException {
-
- // create defining import handle
- IImportDeclaration importHandle = this.createImportHandle(reference);
-
- // accept reference
- this.pattern.matchReportReference(reference, importHandle, accuracy, this);
+ // create defining import handle
+ IImportDeclaration importHandle = this.createImportHandle(reference);
+
+ // accept reference
+ this.pattern.matchReportReference(reference, importHandle, accuracy, this);
+}
+/**
+ * Reports the given method declaration to the search requestor.
+ * Its defining types have the given simple names.
+ */
+public void reportMethodDeclaration(
+ AbstractMethodDeclaration methodDeclaration,
+ char[][] definingTypeNames,
+ int accuracy) throws CoreException {
+
+ // create method handle
+ IMethod method = this.createMethodHandle(methodDeclaration, definingTypeNames);
+
+ // compute source positions of the selector
+ Scanner scanner = parser.scanner;
+ int nameSourceStart = methodDeclaration.sourceStart;
+ scanner.resetTo(nameSourceStart, methodDeclaration.sourceEnd);
+ try {
+ scanner.getNextToken();
+ } catch(InvalidInputException e) {
}
+ int nameSourceEnd = scanner.currentPosition-1;
- /**
- * Reports the given method declaration to the search requestor.
- * Its defining types have the given simple names.
- */
- public void reportMethodDeclaration(
- AbstractMethodDeclaration methodDeclaration,
- char[][] definingTypeNames,
- int accuracy)
- throws CoreException {
-
- // create method handle
- IMethod method = this.createMethodHandle(methodDeclaration, definingTypeNames);
-
- // compute source positions of the selector
- Scanner scanner = parser.scanner;
- int nameSourceStart = methodDeclaration.sourceStart;
- scanner.resetTo(nameSourceStart, methodDeclaration.sourceEnd);
+ // accept method declaration
+ this.report(nameSourceStart, nameSourceEnd, method, accuracy);
+}
+/**
+ * Reports the given package declaration to the search requestor.
+ */
+public void reportPackageDeclaration(ImportReference node) {
+ // TBD
+}
+/**
+ * Reports the given package reference to the search requestor.
+ */
+public void reportPackageReference(ImportReference node) {
+ // TBD
+}
+/**
+ * Reports the given qualified reference to the search requestor.
+ */
+public void reportQualifiedReference(
+ int sourceStart,
+ int sourceEnd,
+ char[][] qualifiedName,
+ IJavaElement element,
+ int accuracy) throws CoreException {
+
+ // compute source positions of the qualified reference
+ Scanner scanner = parser.scanner;
+ scanner.resetTo(sourceStart, sourceEnd);
+
+ int refSourceStart = -1, refSourceEnd = -1;
+ int tokenNumber = qualifiedName.length;
+ int token = -1;
+ int previousValid = -1;
+ int i = 0;
+ do {
+ int currentPosition = scanner.currentPosition;
+ // read token
try {
- scanner.getNextToken();
- } catch (InvalidInputException e) {
+ token = scanner.getNextToken();
+ } catch(InvalidInputException e) {
}
- int nameSourceEnd = scanner.currentPosition - 1;
-
- // accept method declaration
- this.report(nameSourceStart, nameSourceEnd, method, accuracy);
- }
-
- /**
- * Reports the given package declaration to the search requestor.
- */
- public void reportPackageDeclaration(ImportReference node) {
- // TBD
- }
-
- /**
- * Reports the given package reference to the search requestor.
- */
- public void reportPackageReference(ImportReference node) {
- // TBD
- }
-
- /**
- * Reports the given qualified reference to the search requestor.
- */
- public void reportQualifiedReference(
- int sourceStart,
- int sourceEnd,
- char[][] qualifiedName,
- IJavaElement element,
- int accuracy)
- throws CoreException {
-
- // compute source positions of the qualified reference
- Scanner scanner = parser.scanner;
- scanner.resetTo(sourceStart, sourceEnd);
-
- int refSourceStart = -1, refSourceEnd = -1;
- int tokenNumber = qualifiedName.length;
- int token = -1;
- int previousValid = -1;
- int i = 0;
- do {
- int currentPosition = scanner.currentPosition;
- // read token
- try {
- token = scanner.getNextToken();
- } catch (InvalidInputException e) {
+ if (token != TerminalSymbols.TokenNameEOF) {
+ char[] currentTokenSource = scanner.getCurrentTokenSource();
+ while (i < tokenNumber && !CharOperation.equals(currentTokenSource, qualifiedName[i++])) {
}
- if (token != TerminalSymbols.TokenNameEOF) {
- char[] currentTokenSource = scanner.getCurrentTokenSource();
- while (i < tokenNumber
- && !CharOperation.equals(currentTokenSource, qualifiedName[i++])) {
- }
- if (CharOperation.equals(currentTokenSource, qualifiedName[i - 1])
- && (previousValid == -1 || previousValid == i - 2)) {
- previousValid = i - 1;
- if (refSourceStart == -1) {
- refSourceStart = currentPosition;
- }
- refSourceEnd = scanner.currentPosition - 1;
- } else {
- i = 0;
- refSourceStart = -1;
- previousValid = -1;
- }
- // read '.'
- try {
- token = scanner.getNextToken();
- } catch (InvalidInputException e) {
+ if (CharOperation.equals(currentTokenSource, qualifiedName[i-1]) && (previousValid == -1 || previousValid == i-2)) {
+ previousValid = i-1;
+ if (refSourceStart == -1) {
+ refSourceStart = currentPosition;
}
+ refSourceEnd = scanner.currentPosition-1;
+ } else {
+ i = 0;
+ refSourceStart = -1;
+ previousValid = -1;
}
- }
- while (token != TerminalSymbols.TokenNameEOF && i < tokenNumber);
-
- // accept method declaration
- if (refSourceStart != -1) {
- this.report(refSourceStart, refSourceEnd, element, accuracy);
- } else {
- this.report(sourceStart, sourceEnd, element, accuracy);
- }
+ // read '.'
+ try {
+ token = scanner.getNextToken();
+ } catch(InvalidInputException e) {
+ }
+ }
+ } while (token != TerminalSymbols.TokenNameEOF && i < tokenNumber);
+
+ // accept method declaration
+ if (refSourceStart != -1) {
+ this.report(refSourceStart, refSourceEnd, element, accuracy);
+ } else {
+ this.report(sourceStart, sourceEnd, element, accuracy);
}
-
- /**
- * Reports the given reference to the search requestor.
- * It is done in the given method and the method's defining types
- * have the given simple names.
- */
- public void reportReference(
- AstNode reference,
- AbstractMethodDeclaration methodDeclaration,
- char[][] definingTypeNames,
- int accuracy)
- throws CoreException {
-
- // create defining method handle
- IMethod method = this.createMethodHandle(methodDeclaration, definingTypeNames);
-
+}
+/**
+ * Reports the given reference to the search requestor.
+ * It is done in the given method and the method's defining types
+ * have the given simple names.
+ */
+public void reportReference(
+ AstNode reference,
+ AbstractMethodDeclaration methodDeclaration,
+ char[][] definingTypeNames,
+ int accuracy) throws CoreException {
+
+ // create defining method handle
+ IMethod method = this.createMethodHandle(methodDeclaration, definingTypeNames);
+
+ // accept reference
+ if (reference instanceof QualifiedNameReference || reference instanceof QualifiedTypeReference) {
+ this.pattern.matchReportReference((AstNode)reference, method, accuracy, this);
+ } else if (reference instanceof MessageSend) { // message ref are starting at the selector start
+ this.report((int)(((MessageSend)reference).nameSourcePosition >> 32), reference.sourceEnd, method, accuracy);
+ } else {
+ this.report(reference.sourceStart, reference.sourceEnd, method, accuracy);
+ }
+}
+/**
+ * Reports the given reference to the search requestor.
+ * It is done in the given field and given type.
+ * The field's defining types have the given simple names.
+ */
+public void reportReference(
+ AstNode reference,
+ TypeDeclaration typeDeclaration,
+ FieldDeclaration fieldDeclaration,
+ char[][] definingTypeNames,
+ int accuracy) throws CoreException {
+
+ if (fieldDeclaration.isField()) {
+ // create defining field handle
+ IField field = this.createFieldHandle(fieldDeclaration, definingTypeNames);
+
// accept reference
- if (reference instanceof QualifiedNameReference
- || reference instanceof QualifiedTypeReference) {
- this.pattern.matchReportReference((AstNode) reference, method, accuracy, this);
+ if (reference instanceof QualifiedNameReference || reference instanceof QualifiedTypeReference) {
+ this.pattern.matchReportReference((AstNode)reference, field, accuracy, this);
+ } else if (reference instanceof MessageSend) { // message ref are starting at the selector start
+ this.report((int)(((MessageSend)reference).nameSourcePosition >> 32), reference.sourceEnd, field, accuracy);
} else {
- this.report(reference.sourceStart, reference.sourceEnd, method, accuracy);
+ this.report(reference.sourceStart, reference.sourceEnd, field, accuracy);
}
- }
-
- /**
- * Reports the given reference to the search requestor.
- * It is done in the given field and given type.
- * The field's defining types have the given simple names.
- */
- public void reportReference(
- AstNode reference,
- TypeDeclaration typeDeclaration,
- FieldDeclaration fieldDeclaration,
- char[][] definingTypeNames,
- int accuracy)
- throws CoreException {
-
- if (fieldDeclaration.isField()) {
- // create defining field handle
- IField field = this.createFieldHandle(fieldDeclaration, definingTypeNames);
-
- // accept reference
- if (reference instanceof QualifiedNameReference
- || reference instanceof QualifiedTypeReference) {
- this.pattern.matchReportReference((AstNode) reference, field, accuracy, this);
- } else {
- this.report(reference.sourceStart, reference.sourceEnd, field, accuracy);
- }
- } else { // initializer
- // create defining initializer
- IInitializer initializer =
- this.createInitializerHandle(
- typeDeclaration,
- fieldDeclaration,
- definingTypeNames);
-
- // accept reference
- if (reference instanceof QualifiedNameReference
- || reference instanceof QualifiedTypeReference) {
- this.pattern.matchReportReference(
- (AstNode) reference,
- initializer,
- accuracy,
- this);
- } else {
- this.report(reference.sourceStart, reference.sourceEnd, initializer, accuracy);
- }
+ } else { // initializer
+ // create defining initializer
+ IInitializer initializer = this.createInitializerHandle(typeDeclaration, fieldDeclaration, definingTypeNames);
+
+ // accept reference
+ if (reference instanceof QualifiedNameReference || reference instanceof QualifiedTypeReference) {
+ this.pattern.matchReportReference((AstNode)reference, initializer, accuracy, this);
+ } else if (reference instanceof MessageSend) { // message ref are starting at the selector start
+ this.report((int)(((MessageSend)reference).nameSourcePosition >> 32), reference.sourceEnd, initializer, accuracy);
+ } else {
+ this.report(reference.sourceStart, reference.sourceEnd, initializer, accuracy);
}
}
+}
+/**
+ * Reports the given super type reference to the search requestor.
+ * It is done in the given defining type (with the given simple names).
+ */
+public void reportSuperTypeReference(
+ TypeReference typeRef,
+ char[][] definingTypeNames,
+ int accuracy) throws CoreException {
+
+ // create defining type handle
+ IType type = this.createTypeHandle(definingTypeNames);
+
+ // accept type reference
+ this.pattern.matchReportReference(typeRef, type, accuracy, this);
+}
+/**
+ * Reports the given type declaration to the search requestor.
+ * Its simple names are the names of its outer most type to this type.
+ */
+public void reportTypeDeclaration(
+ TypeDeclaration typeDeclaration,
+ char[][] simpleTypeNames,
+ int accuracy) throws CoreException {
+
+ // create type handle
+ IType type = this.createTypeHandle(simpleTypeNames);
+
+ // accept class or interface declaration
+ this.report(typeDeclaration.sourceStart, typeDeclaration.sourceEnd, type, accuracy);
+}
- /**
- * Reports the given super type reference to the search requestor.
- * It is done in the given defining type (with the given simple names).
- */
- public void reportSuperTypeReference(
- TypeReference typeRef,
- char[][] definingTypeNames,
- int accuracy)
- throws CoreException {
-
- // create defining type handle
- IType type = this.createTypeHandle(definingTypeNames);
-
- // accept type reference
- this.pattern.matchReportReference(typeRef, type, accuracy, this);
- }
-
- /**
- * Reports the given type declaration to the search requestor.
- * Its simple names are the names of its outer most type to this type.
- */
- public void reportTypeDeclaration(
- TypeDeclaration typeDeclaration,
- char[][] simpleTypeNames,
- int accuracy)
- throws CoreException {
-
- // create type handle
- IType type = this.createTypeHandle(simpleTypeNames);
-
- // accept class or interface declaration
- this.report(
- typeDeclaration.sourceStart,
- typeDeclaration.sourceEnd,
- type,
- accuracy);
- }
-
- /**
- * Create a new parser for the given project, as well as a lookup environment.
- * Asks the pattern to initialize itself from the lookup environment.
- * Returns whether it was able to initialize the pattern.
- */
- private boolean createParser(JavaProject project) throws JavaModelException {
- INameEnvironment nameEnvironment = project.getSearchableNameEnvironment();
- IProblemFactory problemFactory = new ProblemFactory();
-
- CompilerOptions options = new CompilerOptions(null);
- ProblemReporter problemReporter =
- new ProblemReporter(
- DefaultErrorHandlingPolicies.proceedWithAllProblems(),
- options,
- problemFactory);
- this.lookupEnvironment =
- new LookupEnvironment(this, options, problemReporter, nameEnvironment);
- this.parser = new MatchLocatorParser(problemReporter);
- return true;
- //this.pattern.initializeFromLookupEnvironment(this.lookupEnvironment);
- }
-
+/**
+ * Create a new parser for the given project, as well as a lookup environment.
+ * Asks the pattern to initialize itself from the lookup environment.
+ * Returns whether it was able to initialize the pattern.
+ */
+private boolean createParser(JavaProject project) throws JavaModelException {
+ INameEnvironment nameEnvironment = project.getSearchableNameEnvironment();
+ IProblemFactory problemFactory = new DefaultProblemFactory();
+
+ CompilerOptions options = new CompilerOptions(null);
+ ProblemReporter problemReporter =
+ new ProblemReporter(
+ DefaultErrorHandlingPolicies.proceedWithAllProblems(),
+ options,
+ problemFactory);
+ this.lookupEnvironment = new LookupEnvironment(this, options, problemReporter, nameEnvironment);
+ this.parser = new MatchLocatorParser(problemReporter);
+ return this.pattern.initializeFromLookupEnvironment(this.lookupEnvironment);
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MatchLocatorParser.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MatchLocatorParser.java
index 2f36288e06..4370011145 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MatchLocatorParser.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MatchLocatorParser.java
@@ -19,159 +19,135 @@ import java.util.*;
public class MatchLocatorParser extends Parser {
public MatchSet matchSet;
- public MatchLocatorParser(ProblemReporter problemReporter) {
- super(problemReporter);
- }
-
- protected void classInstanceCreation(boolean alwaysQualified) {
- super.classInstanceCreation(alwaysQualified);
- this.matchSet.checkMatching(this.expressionStack[this.expressionPtr]);
- }
-
- protected void consumeExplicitConstructorInvocation(int flag, int recFlag) {
- super.consumeExplicitConstructorInvocation(flag, recFlag);
- this.matchSet.checkMatching(this.astStack[this.astPtr]);
- }
-
- protected void consumeFieldAccess(boolean isSuperAccess) {
- super.consumeFieldAccess(isSuperAccess);
- this.matchSet.checkMatching(this.expressionStack[this.expressionPtr]);
- }
-
- protected void consumeMethodInvocationName() {
- super.consumeMethodInvocationName();
- this.matchSet.checkMatching(this.expressionStack[this.expressionPtr]);
- }
-
- protected void consumeMethodInvocationPrimary() {
- super.consumeMethodInvocationPrimary();
- this.matchSet.checkMatching(this.expressionStack[this.expressionPtr]);
- }
-
- protected void consumeMethodInvocationSuper() {
- super.consumeMethodInvocationSuper();
- this.matchSet.checkMatching(this.expressionStack[this.expressionPtr]);
- }
-
- protected void consumeSingleTypeImportDeclarationName() {
- super.consumeSingleTypeImportDeclarationName();
- this.matchSet.checkMatching(this.astStack[this.astPtr]);
- }
-
- protected void consumeTypeImportOnDemandDeclarationName() {
- super.consumeTypeImportOnDemandDeclarationName();
- this.matchSet.checkMatching(this.astStack[this.astPtr]);
- }
-
- protected TypeReference getTypeReference(int dim) {
- TypeReference typeRef = super.getTypeReference(dim);
- this.matchSet.checkMatching(typeRef);
- // NB: Don't check container since type reference can happen anywhere
- return typeRef;
- }
-
- protected NameReference getUnspecifiedReference() {
- NameReference nameRef = super.getUnspecifiedReference();
- this.matchSet.checkMatching(nameRef);
- // NB: Don't check container since unspecified reference can happen anywhere
- return nameRef;
- }
-
- protected NameReference getUnspecifiedReferenceOptimized() {
- NameReference nameRef = super.getUnspecifiedReferenceOptimized();
- this.matchSet.checkMatching(nameRef);
- // NB: Don't check container since unspecified reference can happen anywhere
- return nameRef;
- }
-
- /**
- * Parses the given source unit in 2 times:
- * - first do a diet parse to determine the structure of the compilation unit
- * - then do a method body parse of each method to determine the references
- */
- public CompilationUnitDeclaration parse(
- ICompilationUnit sourceUnit,
- CompilationResult compilationResult) {
-
- this.diet = true;
- CompilationUnitDeclaration unit = super.parse(sourceUnit, compilationResult);
- this.diet = false;
- this.parseBodies(unit);
- return unit;
- }
-
- /**
- * Parses the method bodies in the given compilation unit
- */
- private void parseBodies(CompilationUnitDeclaration unit) {
- TypeDeclaration[] types = unit.types;
- if (types != null) {
- for (int i = 0; i < types.length; i++) {
- TypeDeclaration type = types[i];
- if ((this.matchSet.matchContainer & SearchPattern.COMPILATION_UNIT) != 0
- // type declaration in compilation unit
- || (this.matchSet.matchContainer & SearchPattern.CLASS) != 0
- // or in another type
- || (this.matchSet.matchContainer & SearchPattern.METHOD) != 0) {
- // or in a local class
-
- this.matchSet.checkMatching(type);
- }
- this.parseBodies(type, unit);
+public MatchLocatorParser(ProblemReporter problemReporter) {
+ super(problemReporter);
+}
+protected void classInstanceCreation(boolean alwaysQualified) {
+ super.classInstanceCreation(alwaysQualified);
+ this.matchSet.checkMatching(this.expressionStack[this.expressionPtr]);
+}
+protected void consumeExplicitConstructorInvocation(int flag, int recFlag) {
+ super.consumeExplicitConstructorInvocation(flag, recFlag);
+ this.matchSet.checkMatching(this.astStack[this.astPtr]);
+}
+protected void consumeFieldAccess(boolean isSuperAccess) {
+ super.consumeFieldAccess(isSuperAccess);
+ this.matchSet.checkMatching(this.expressionStack[this.expressionPtr]);
+}
+protected void consumeMethodInvocationName() {
+ super.consumeMethodInvocationName();
+ this.matchSet.checkMatching(this.expressionStack[this.expressionPtr]);
+}
+protected void consumeMethodInvocationPrimary() {
+ super.consumeMethodInvocationPrimary();
+ this.matchSet.checkMatching(this.expressionStack[this.expressionPtr]);
+}
+protected void consumeMethodInvocationSuper() {
+ super.consumeMethodInvocationSuper();
+ this.matchSet.checkMatching(this.expressionStack[this.expressionPtr]);
+}
+protected void consumeSingleTypeImportDeclarationName() {
+ super.consumeSingleTypeImportDeclarationName();
+ this.matchSet.checkMatching(this.astStack[this.astPtr]);
+}
+protected void consumeTypeImportOnDemandDeclarationName() {
+ super.consumeTypeImportOnDemandDeclarationName();
+ this.matchSet.checkMatching(this.astStack[this.astPtr]);
+}
+protected TypeReference getTypeReference(int dim) {
+ TypeReference typeRef = super.getTypeReference(dim);
+ this.matchSet.checkMatching(typeRef); // NB: Don't check container since type reference can happen anywhere
+ return typeRef;
+}
+protected NameReference getUnspecifiedReference() {
+ NameReference nameRef = super.getUnspecifiedReference();
+ this.matchSet.checkMatching(nameRef); // NB: Don't check container since unspecified reference can happen anywhere
+ return nameRef;
+}
+protected NameReference getUnspecifiedReferenceOptimized() {
+ NameReference nameRef = super.getUnspecifiedReferenceOptimized();
+ this.matchSet.checkMatching(nameRef); // NB: Don't check container since unspecified reference can happen anywhere
+ return nameRef;
+}
+/**
+ * Parses the given source unit in 2 times:
+ * - first do a diet parse to determine the structure of the compilation unit
+ * - then do a method body parse of each method to determine the references
+ */
+public CompilationUnitDeclaration parse(
+ ICompilationUnit sourceUnit,
+ CompilationResult compilationResult) {
+
+ this.diet = true;
+ CompilationUnitDeclaration unit = super.parse(sourceUnit, compilationResult);
+ this.diet = false;
+ this.parseBodies(unit);
+ return unit;
+}
+/**
+ * Parses the method bodies in the given compilation unit
+ */
+private void parseBodies(CompilationUnitDeclaration unit) {
+ TypeDeclaration[] types = unit.types;
+ if (types != null) {
+ for (int i = 0; i < types.length; i++) {
+ TypeDeclaration type = types[i];
+ if ((this.matchSet.matchContainer & SearchPattern.COMPILATION_UNIT) != 0 // type declaration in compilation unit
+ || (this.matchSet.matchContainer & SearchPattern.CLASS) != 0 // or in another type
+ || (this.matchSet.matchContainer & SearchPattern.METHOD) != 0) { // or in a local class
+
+ this.matchSet.checkMatching(type);
}
+ this.parseBodies(type, unit);
}
}
-
- /**
- * Parses the member bodies in the given type.
- */
- private void parseBodies(
- TypeDeclaration type,
- CompilationUnitDeclaration unit) {
- // fields
- FieldDeclaration[] fields = type.fields;
- if (fields != null) {
- for (int i = 0; i < fields.length; i++) {
- FieldDeclaration field = fields[i];
- if ((this.matchSet.matchContainer & SearchPattern.CLASS) != 0) {
- this.matchSet.checkMatching(field);
- }
- if (field instanceof Initializer) { // initializer block
- this.parse((Initializer) field, type, unit);
- }
+}
+/**
+ * Parses the member bodies in the given type.
+ */
+private void parseBodies(TypeDeclaration type, CompilationUnitDeclaration unit) {
+ // fields
+ FieldDeclaration[] fields = type.fields;
+ if (fields != null) {
+ for (int i = 0; i < fields.length; i++) {
+ FieldDeclaration field = fields[i];
+ if ((this.matchSet.matchContainer & SearchPattern.CLASS) != 0) {
+ this.matchSet.checkMatching(field);
+ }
+ if (field instanceof Initializer) { // initializer block
+ this.parse((Initializer)field, type, unit);
}
}
-
- // methods
- AbstractMethodDeclaration[] methods = type.methods;
- if (methods != null) {
- for (int i = 0; i < methods.length; i++) {
- AbstractMethodDeclaration method = methods[i];
- if ((this.matchSet.matchContainer & SearchPattern.CLASS) != 0) {
- this.matchSet.checkMatching(method);
- }
- if (method.sourceStart >= type.bodyStart) { // if not synthetic
- if (method instanceof MethodDeclaration) {
- this.parse((MethodDeclaration) method, unit);
- } else
- if (method instanceof ConstructorDeclaration) {
- this.parse((ConstructorDeclaration) method, unit);
- }
- }
+ }
+
+ // methods
+ AbstractMethodDeclaration[] methods = type.methods;
+ if (methods != null) {
+ for (int i = 0; i < methods.length; i++) {
+ AbstractMethodDeclaration method = methods[i];
+ if ((this.matchSet.matchContainer & SearchPattern.CLASS) != 0) {
+ this.matchSet.checkMatching(method);
}
+ if (method.sourceStart >= type.bodyStart) { // if not synthetic
+ if (method instanceof MethodDeclaration) {
+ this.parse((MethodDeclaration)method, unit);
+ } else if (method instanceof ConstructorDeclaration) {
+ this.parse((ConstructorDeclaration)method, unit);
+ }
+ }
}
+ }
- // member types
- MemberTypeDeclaration[] memberTypes = type.memberTypes;
- if (memberTypes != null) {
- for (int i = 0; i < memberTypes.length; i++) {
- MemberTypeDeclaration memberType = memberTypes[i];
- if ((this.matchSet.matchContainer & SearchPattern.CLASS) != 0) {
- this.matchSet.checkMatching(memberType);
- }
- this.parseBodies(memberType, unit);
+ // member types
+ MemberTypeDeclaration[] memberTypes = type.memberTypes;
+ if (memberTypes != null) {
+ for (int i = 0; i < memberTypes.length; i++) {
+ MemberTypeDeclaration memberType = memberTypes[i];
+ if ((this.matchSet.matchContainer & SearchPattern.CLASS) != 0) {
+ this.matchSet.checkMatching(memberType);
}
+ this.parseBodies(memberType, unit);
}
}
-
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MatchSet.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MatchSet.java
index 2b391f8934..b65a9e96a3 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MatchSet.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MatchSet.java
@@ -18,9 +18,9 @@ import java.util.*;
* A set of matches and potential matches.
*/
public class MatchSet {
-
+
private static final char[][] EMPTY_CHAR_CHAR = new char[0][];
-
+
private MatchLocator locator;
int matchContainer;
boolean cuHasBeenResolved = false;
@@ -37,296 +37,247 @@ public class MatchSet {
*/
private Hashtable potentialMatchingNodes = new Hashtable(5);
- public MatchSet(MatchLocator locator) {
- this.locator = locator;
- this.matchContainer = locator.pattern.matchContainer();
- }
-
- public void addPossibleMatch(AstNode node) {
- this.potentialMatchingNodes.put(node, node);
- }
-
- public void addTrustedMatch(AstNode node) {
- this.matchingNodes.put(node, node);
+public MatchSet(MatchLocator locator) {
+ this.locator = locator;
+ this.matchContainer = locator.pattern.matchContainer();
+}
+public void addPossibleMatch(AstNode node) {
+ this.potentialMatchingNodes.put(node, node);
+}
+public void addTrustedMatch(AstNode node) {
+ this.matchingNodes.put(node, node);
+}
+public void checkMatching(AstNode node) {
+ int matchLevel = this.locator.pattern.matchLevel(node);
+ switch (matchLevel) {
+ case SearchPattern.POSSIBLE_MATCH:
+ this.addPossibleMatch(node);
+ break;
+ case SearchPattern.TRUSTED_MATCH:
+ this.addTrustedMatch(node);
}
-
- public void checkMatching(AstNode node) {
- int matchLevel = this.locator.pattern.matchLevel(node);
- switch (matchLevel) {
- case SearchPattern.POSSIBLE_MATCH :
- this.addPossibleMatch(node);
- break;
- case SearchPattern.TRUSTED_MATCH :
- this.addTrustedMatch(node);
+}
+/**
+ * Returns the matching nodes that are in the given range.
+ */
+private AstNode[] matchingNodes(int start, int end) {
+ return this.nodesInRange(start, end, this.matchingNodes);
+}
+public boolean needsResolve() {
+ return this.potentialMatchingNodes.size() > 0;
+}
+/**
+ * Returns the matching nodes that are in the given range in the source order.
+ */
+private AstNode[] nodesInRange(int start, int end, Hashtable set) {
+ // collect nodes in the given range
+ Vector nodes = new Vector();
+ for (Enumeration keys = set.keys(); keys.hasMoreElements();) {
+ AstNode node = (AstNode)keys.nextElement();
+ if (start <= node.sourceStart && node.sourceEnd <= end) {
+ nodes.addElement(node);
}
}
-
- /**
- * Returns the matching nodes that are in the given range.
- */
- private AstNode[] matchingNodes(int start, int end) {
- return this.nodesInRange(start, end, this.matchingNodes);
- }
-
- public boolean needsResolve() {
- return this.potentialMatchingNodes.size() > 0;
- }
-
- /**
- * Returns the matching nodes that are in the given range in the source order.
- */
- private AstNode[] nodesInRange(int start, int end, Hashtable set) {
- // collect nodes in the given range
- Vector nodes = new Vector();
- for (Enumeration keys = set.keys(); keys.hasMoreElements();) {
- AstNode node = (AstNode) keys.nextElement();
- if (start <= node.sourceStart && node.sourceEnd <= end) {
- nodes.addElement(node);
- }
+ AstNode[] result = new AstNode[nodes.size()];
+ nodes.copyInto(result);
+
+ // sort nodes by source starts
+ Util.Comparer comparer = new Util.Comparer() {
+ public int compare(Object o1, Object o2) {
+ AstNode node1 = (AstNode) o1;
+ AstNode node2 = (AstNode) o2;
+ return node1.sourceStart - node2.sourceStart;
+ }
+ };
+ Util.sort(result, comparer);
+
+ return result;
+}
+/**
+ * Returns the potential matching nodes that are in the given range.
+ */
+private AstNode[] potentialMatchingNodes(int start, int end) {
+ return this.nodesInRange(start, end, this.potentialMatchingNodes);
+}
+/**
+ * Visit the given method declaration and report the nodes that match exactly the
+ * search pattern (ie. the ones in the matching nodes set)
+ * Note that the method declaration has already been checked.
+ */
+private void reportMatching(AbstractMethodDeclaration method, char[][] definingTypeNames) throws CoreException {
+ // references in this method
+ AstNode[] nodes = this.matchingNodes(method.declarationSourceStart, method.declarationSourceEnd);
+ for (int i = 0; i < nodes.length; i++) {
+ AstNode node = nodes[i];
+ this.matchingNodes.remove(node);
+ if ((this.matchContainer & SearchPattern.METHOD) != 0) {
+ this.locator.reportReference(node, method, definingTypeNames, this.accuracy);
}
- AstNode[] result = new AstNode[nodes.size()];
- nodes.copyInto(result);
-
- // sort nodes by source starts
- Util.Comparer comparer = new Util.Comparer() {
- public int compare(Object o1, Object o2) {
- AstNode node1 = (AstNode) o1;
- AstNode node2 = (AstNode) o2;
- return node1.sourceStart - node2.sourceStart;
- }
- };
- Util.sort(result, comparer);
-
- return result;
}
-
- /**
- * Returns the potential matching nodes that are in the given range.
- */
- private AstNode[] potentialMatchingNodes(int start, int end) {
- return this.nodesInRange(start, end, this.potentialMatchingNodes);
+ if (this.potentialMatchingNodes(method.declarationSourceStart, method.declarationSourceEnd).length == 0) {
+ // no need to resolve the statements in the method
+ method.statements = null;
}
-
- /**
- * Visit the given method declaration and report the nodes that match exactly the
- * search pattern (ie. the ones in the matching nodes set)
- * Note that the method declaration has already been checked.
- */
- private void reportMatching(
- AbstractMethodDeclaration method,
- char[][] definingTypeNames)
- throws CoreException {
- // references in this method
- AstNode[] nodes =
- this.matchingNodes(method.declarationSourceStart, method.declarationSourceEnd);
- for (int i = 0; i < nodes.length; i++) {
- AstNode node = nodes[i];
- this.matchingNodes.remove(node);
- if ((this.matchContainer & SearchPattern.METHOD) != 0) {
- this.locator.reportReference(node, method, definingTypeNames, this.accuracy);
+}
+/**
+ * Visit the given parse tree and report the nodes that match exactly the
+ * search pattern.
+ */
+public void reportMatching(CompilationUnitDeclaration unit) throws CoreException {
+ if (this.cuHasBeenResolved) {
+ // move the potential matching nodes that exactly match the search pattern to the matching nodes set
+ for (Enumeration potentialMatches = this.potentialMatchingNodes.keys(); potentialMatches.hasMoreElements();) {
+ AstNode node = (AstNode) potentialMatches.nextElement();
+ if (this.locator.pattern.matches(node)) {
+ this.matchingNodes.put(node, node);
}
}
- if (this
- .potentialMatchingNodes(
- method.declarationSourceStart,
- method.declarationSourceEnd)
- .length
- == 0) {
- // no need to resolve the statements in the method
- method.statements = null;
- }
+ this.potentialMatchingNodes = new Hashtable();
}
-
- /**
- * Visit the given parse tree and report the nodes that match exactly the
- * search pattern.
- */
- public void reportMatching(CompilationUnitDeclaration unit)
- throws CoreException {
- if (this.cuHasBeenResolved) {
- // move the potential matching nodes that exactly match the search pattern to the matching nodes set
- for (Enumeration potentialMatches = this.potentialMatchingNodes.keys();
- potentialMatches.hasMoreElements();
- ) {
- AstNode node = (AstNode) potentialMatches.nextElement();
- if (this.locator.pattern.matches(node)) {
- this.matchingNodes.put(node, node);
- }
- }
- this.potentialMatchingNodes = new Hashtable();
- }
-
- // package declaration
- ImportReference pkg = unit.currentPackage;
- if (pkg != null && this.matchingNodes.get(pkg) == pkg) {
- this.matchingNodes.remove(pkg);
- if ((this.matchContainer & SearchPattern.COMPILATION_UNIT) != 0) {
- this.locator.reportPackageDeclaration(pkg);
- }
+
+ // package declaration
+ ImportReference pkg = unit.currentPackage;
+ if (pkg != null && this.matchingNodes.get(pkg) == pkg) {
+ this.matchingNodes.remove(pkg);
+ if ((this.matchContainer & SearchPattern.COMPILATION_UNIT) != 0) {
+ this.locator.reportPackageDeclaration(pkg);
}
+ }
- // import declarations
- ImportReference[] imports = unit.imports;
- if (imports != null) {
- for (int i = 0; i < imports.length; i++) {
- ImportReference importRef = imports[i];
- if (this.matchingNodes.get(importRef) == importRef) {
- this.matchingNodes.remove(importRef);
- if ((this.matchContainer & SearchPattern.COMPILATION_UNIT) != 0) {
- this.locator.reportImport(importRef, this.accuracy);
- }
+ // import declarations
+ ImportReference[] imports = unit.imports;
+ if (imports != null) {
+ for (int i = 0; i < imports.length; i++) {
+ ImportReference importRef = imports[i];
+ if (this.matchingNodes.get(importRef) == importRef) {
+ this.matchingNodes.remove(importRef);
+ if ((this.matchContainer & SearchPattern.COMPILATION_UNIT) != 0) {
+ this.locator.reportImport(importRef, this.accuracy);
}
}
}
+ }
- // types
- TypeDeclaration[] types = unit.types;
- if (types != null) {
- for (int i = 0; i < types.length; i++) {
- TypeDeclaration type = types[i];
- if (this.matchingNodes.get(type) == type) {
- this.matchingNodes.remove(type);
- if ((this.matchContainer & SearchPattern.COMPILATION_UNIT) != 0) {
- this.locator.reportTypeDeclaration(
- type,
- new char[][] { type.name },
- this.accuracy);
- }
+ // types
+ TypeDeclaration[] types = unit.types;
+ if (types != null) {
+ for (int i = 0; i < types.length; i++) {
+ TypeDeclaration type = types[i];
+ if (this.matchingNodes.get(type) == type) {
+ this.matchingNodes.remove(type);
+ if ((this.matchContainer & SearchPattern.COMPILATION_UNIT) != 0) {
+ this.locator.reportTypeDeclaration(type, new char[][] {type.name}, this.accuracy);
}
- this.reportMatching(type, EMPTY_CHAR_CHAR);
}
+ this.reportMatching(type, EMPTY_CHAR_CHAR);
}
}
-
- /**
- * Visit the given field declaration and report the nodes that match exactly the
- * search pattern (ie. the ones in the matching nodes set)
- * Note that the field declaration has already been checked.
- */
- private void reportMatching(
- FieldDeclaration field,
- char[][] definingTypeNames,
- TypeDeclaration type)
- throws CoreException {
- AstNode[] nodes =
- this.matchingNodes(field.declarationSourceStart, field.declarationSourceEnd);
- for (int i = 0; i < nodes.length; i++) {
- AstNode node = nodes[i];
- this.matchingNodes.remove(node);
- if ((this.matchContainer & SearchPattern.FIELD) != 0) {
- this.locator.reportReference(
- node,
- type,
- field,
- definingTypeNames,
- this.accuracy);
- }
+}
+/**
+ * Visit the given field declaration and report the nodes that match exactly the
+ * search pattern (ie. the ones in the matching nodes set)
+ * Note that the field declaration has already been checked.
+ */
+private void reportMatching(FieldDeclaration field, char[][] definingTypeNames, TypeDeclaration type) throws CoreException {
+ AstNode[] nodes = this.matchingNodes(field.declarationSourceStart, field.declarationSourceEnd);
+ for (int i = 0; i < nodes.length; i++) {
+ AstNode node = nodes[i];
+ this.matchingNodes.remove(node);
+ if ((this.matchContainer & SearchPattern.FIELD) != 0) {
+ this.locator.reportReference(node, type, field, definingTypeNames, this.accuracy);
}
}
-
- /**
- * Visit the given type declaration and report the nodes that match exactly the
- * search pattern (ie. the ones in the matching nodes set)
- * Note that the type declaration has already been checked.
- */
- private void reportMatching(TypeDeclaration type, char[][] enclosingTypeNames)
- throws CoreException {
- char[][] definingTypeNames =
- CharOperation.arrayConcat(enclosingTypeNames, type.name);
-
- // fields
- FieldDeclaration[] fields = type.fields;
- if (fields != null) {
- for (int i = 0; i < fields.length; i++) {
- FieldDeclaration field = fields[i];
- if (this.matchingNodes.get(field) == field) {
- this.matchingNodes.remove(field);
- if ((this.matchContainer & SearchPattern.CLASS) != 0) {
- this.locator.reportFieldDeclaration(field, definingTypeNames, this.accuracy);
- }
+}
+/**
+ * Visit the given type declaration and report the nodes that match exactly the
+ * search pattern (ie. the ones in the matching nodes set)
+ * Note that the type declaration has already been checked.
+ */
+private void reportMatching(TypeDeclaration type, char[][] enclosingTypeNames) throws CoreException {
+ char[][] definingTypeNames = CharOperation.arrayConcat(enclosingTypeNames, type.name);
+
+ // fields
+ FieldDeclaration[] fields = type.fields;
+ if (fields != null) {
+ for (int i = 0; i < fields.length; i++) {
+ FieldDeclaration field = fields[i];
+ if (this.matchingNodes.get(field) == field) {
+ this.matchingNodes.remove(field);
+ if ((this.matchContainer & SearchPattern.CLASS) != 0) {
+ this.locator.reportFieldDeclaration(field, definingTypeNames, this.accuracy);
}
- this.reportMatching(field, definingTypeNames, type);
}
+ this.reportMatching(field, definingTypeNames, type);
}
+ }
- // methods
- AbstractMethodDeclaration[] methods = type.methods;
- if (methods != null) {
- for (int i = 0; i < methods.length; i++) {
- AbstractMethodDeclaration method = methods[i];
- if (this.matchingNodes.get(method) == method) {
- this.matchingNodes.remove(method);
- if ((this.matchContainer & SearchPattern.CLASS) != 0) {
- this.locator.reportMethodDeclaration(method, definingTypeNames, this.accuracy);
- }
+ // methods
+ AbstractMethodDeclaration[] methods = type.methods;
+ if (methods != null) {
+ for (int i = 0; i < methods.length; i++) {
+ AbstractMethodDeclaration method = methods[i];
+ if (this.matchingNodes.get(method) == method) {
+ this.matchingNodes.remove(method);
+ if ((this.matchContainer & SearchPattern.CLASS) != 0) {
+ this.locator.reportMethodDeclaration(method, definingTypeNames, this.accuracy);
}
- this.reportMatching(method, definingTypeNames);
}
+ this.reportMatching(method, definingTypeNames);
}
+ }
- // member types
- MemberTypeDeclaration[] memberTypes = type.memberTypes;
- if (memberTypes != null) {
- for (int i = 0; i < memberTypes.length; i++) {
- MemberTypeDeclaration memberType = memberTypes[i];
- if (this.matchingNodes.get(memberType) == memberType) {
- this.matchingNodes.remove(memberType);
- if ((this.matchContainer & SearchPattern.CLASS) != 0) {
- char[][] memberTypeNames =
- CharOperation.arrayConcat(definingTypeNames, memberType.name);
- this.locator.reportTypeDeclaration(memberType, memberTypeNames, this.accuracy);
- }
+ // member types
+ MemberTypeDeclaration[] memberTypes = type.memberTypes;
+ if (memberTypes != null) {
+ for (int i = 0; i < memberTypes.length; i++) {
+ MemberTypeDeclaration memberType = memberTypes[i];
+ if (this.matchingNodes.get(memberType) == memberType) {
+ this.matchingNodes.remove(memberType);
+ if ((this.matchContainer & SearchPattern.CLASS) != 0) {
+ char[][] memberTypeNames = CharOperation.arrayConcat(definingTypeNames, memberType.name);
+ this.locator.reportTypeDeclaration(memberType, memberTypeNames, this.accuracy);
}
- this.reportMatching(memberType, definingTypeNames);
}
+ this.reportMatching(memberType, definingTypeNames);
}
+ }
- // super types
- TypeReference superClass = type.superclass;
- if (superClass != null && this.matchingNodes.get(superClass) == superClass) {
- this.matchingNodes.remove(superClass);
- if ((this.matchContainer & SearchPattern.CLASS) != 0) {
- this.locator.reportSuperTypeReference(
- superClass,
- definingTypeNames,
- this.accuracy);
- }
+ // super types
+ TypeReference superClass = type.superclass;
+ if (superClass != null && this.matchingNodes.get(superClass) == superClass) {
+ this.matchingNodes.remove(superClass);
+ if ((this.matchContainer & SearchPattern.CLASS) != 0) {
+ this.locator.reportSuperTypeReference(superClass, definingTypeNames, this.accuracy);
}
- TypeReference[] superInterfaces = type.superInterfaces;
- if (superInterfaces != null) {
- for (int i = 0; i < superInterfaces.length; i++) {
- TypeReference superInterface = superInterfaces[i];
- if (this.matchingNodes.get(superInterface) == superInterface) {
- this.matchingNodes.remove(superInterface);
- if ((this.matchContainer & SearchPattern.CLASS) != 0) {
- this.locator.reportSuperTypeReference(
- superInterface,
- definingTypeNames,
- this.accuracy);
- }
+ }
+ TypeReference[] superInterfaces = type.superInterfaces;
+ if (superInterfaces != null) {
+ for (int i = 0; i < superInterfaces.length; i++) {
+ TypeReference superInterface = superInterfaces[i];
+ if (this.matchingNodes.get(superInterface) == superInterface) {
+ this.matchingNodes.remove(superInterface);
+ if ((this.matchContainer & SearchPattern.CLASS) != 0) {
+ this.locator.reportSuperTypeReference(superInterface, definingTypeNames, this.accuracy);
}
}
}
-
}
- public String toString() {
- StringBuffer result = new StringBuffer();
- result.append("Exact matches:");
- for (Enumeration enum = this.matchingNodes.keys(); enum.hasMoreElements();) {
- result.append("\n");
- AstNode node = (AstNode) enum.nextElement();
- result.append(node.toString(1));
- }
- result.append("\nPotential matches:");
- for (Enumeration enum = this.potentialMatchingNodes.keys();
- enum.hasMoreElements();
- ) {
- result.append("\n");
- AstNode node = (AstNode) enum.nextElement();
- result.append(node.toString(1));
- }
- return result.toString();
+}
+public String toString() {
+ StringBuffer result = new StringBuffer();
+ result.append("Exact matches:");
+ for (Enumeration enum = this.matchingNodes.keys(); enum.hasMoreElements();) {
+ result.append("\n");
+ AstNode node = (AstNode)enum.nextElement();
+ result.append(node.toString(1));
}
-
+ result.append("\nPotential matches:");
+ for (Enumeration enum = this.potentialMatchingNodes.keys(); enum.hasMoreElements();) {
+ result.append("\n");
+ AstNode node = (AstNode)enum.nextElement();
+ result.append(node.toString(1));
+ }
+ return result.toString();
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MethodDeclarationPattern.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MethodDeclarationPattern.java
index c5fc8312b4..06768d4f1e 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MethodDeclarationPattern.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MethodDeclarationPattern.java
@@ -19,313 +19,231 @@ import org.eclipse.jdt.internal.core.search.*;
import java.io.*;
public class MethodDeclarationPattern extends MethodPattern {
- public MethodDeclarationPattern(
- char[] selector,
- int matchMode,
- boolean isCaseSensitive,
- char[] declaringQualification,
- char[] declaringSimpleName,
- char[] returnQualification,
- char[] returnSimpleName,
- char[][] parameterQualifications,
- char[][] parameterSimpleNames) {
-
- super(matchMode, isCaseSensitive);
-
- this.selector =
- isCaseSensitive ? selector : CharOperation.toLowerCase(selector);
- this.declaringQualification =
- isCaseSensitive
- ? declaringQualification
- : CharOperation.toLowerCase(declaringQualification);
- this.declaringSimpleName =
- isCaseSensitive
- ? declaringSimpleName
- : CharOperation.toLowerCase(declaringSimpleName);
- this.returnQualification =
- isCaseSensitive
- ? returnQualification
- : CharOperation.toLowerCase(returnQualification);
- this.returnSimpleName =
- isCaseSensitive
- ? returnSimpleName
- : CharOperation.toLowerCase(returnSimpleName);
-
- if (parameterSimpleNames != null) {
- this.parameterQualifications = new char[parameterSimpleNames.length][];
- this.parameterSimpleNames = new char[parameterSimpleNames.length][];
- for (int i = 0, max = parameterSimpleNames.length; i < max; i++) {
- this.parameterQualifications[i] =
- isCaseSensitive
- ? parameterQualifications[i]
- : CharOperation.toLowerCase(parameterQualifications[i]);
- this.parameterSimpleNames[i] =
- isCaseSensitive
- ? parameterSimpleNames[i]
- : CharOperation.toLowerCase(parameterSimpleNames[i]);
- }
+public MethodDeclarationPattern(
+ char[] selector,
+ int matchMode,
+ boolean isCaseSensitive,
+ char[] declaringQualification,
+ char[] declaringSimpleName,
+ char[] returnQualification,
+ char[] returnSimpleName,
+ char[][] parameterQualifications,
+ char[][] parameterSimpleNames) {
+
+ super(matchMode, isCaseSensitive);
+
+ this.selector = isCaseSensitive ? selector : CharOperation.toLowerCase(selector);
+ this.declaringQualification = isCaseSensitive ? declaringQualification : CharOperation.toLowerCase(declaringQualification);
+ this.declaringSimpleName = isCaseSensitive ? declaringSimpleName : CharOperation.toLowerCase(declaringSimpleName);
+ this.returnQualification = isCaseSensitive ? returnQualification : CharOperation.toLowerCase(returnQualification);
+ this.returnSimpleName = isCaseSensitive ? returnSimpleName : CharOperation.toLowerCase(returnSimpleName);
+
+ if (parameterSimpleNames != null){
+ this.parameterQualifications = new char[parameterSimpleNames.length][];
+ this.parameterSimpleNames = new char[parameterSimpleNames.length][];
+ for (int i = 0, max = parameterSimpleNames.length; i < max; i++){
+ this.parameterQualifications[i] = isCaseSensitive ? parameterQualifications[i] : CharOperation.toLowerCase(parameterQualifications[i]);
+ this.parameterSimpleNames[i] = isCaseSensitive ? parameterSimpleNames[i] : CharOperation.toLowerCase(parameterSimpleNames[i]);
}
- this.needsResolve = this.needsResolve();
- }
-
- public void decodeIndexEntry(IEntryResult entryResult) {
-
- char[] word = entryResult.getWord();
- int size = word.length;
- int lastSeparatorIndex = CharOperation.lastIndexOf(SEPARATOR, word);
+ }
+ this.needsResolve = this.needsResolve();
+}
+public void decodeIndexEntry(IEntryResult entryResult){
- decodedParameterCount =
- Integer.parseInt(
- new String(word, lastSeparatorIndex + 1, size - lastSeparatorIndex - 1));
- decodedSelector =
- CharOperation.subarray(word, METHOD_DECL.length, lastSeparatorIndex);
- }
+ char[] word = entryResult.getWord();
+ int size = word.length;
+ int lastSeparatorIndex = CharOperation.lastIndexOf(SEPARATOR, word);
- /**
- * see SearchPattern.feedIndexRequestor
- */
- public void feedIndexRequestor(
- IIndexSearchRequestor requestor,
- int detailLevel,
- int[] references,
- IndexInput input,
- IJavaSearchScope scope)
- throws IOException {
- for (int i = 0, max = references.length; i < max; i++) {
- IndexedFile file = input.getIndexedFile(references[i]);
- String path;
- if (file != null
- && scope.encloses(path = IndexedFile.convertPath(file.getPath()))) {
- requestor.acceptMethodDeclaration(path, decodedSelector, decodedParameterCount);
- }
+ decodedParameterCount = Integer.parseInt(new String(word, lastSeparatorIndex + 1, size - lastSeparatorIndex - 1));
+ decodedSelector = CharOperation.subarray(word, METHOD_DECL.length, lastSeparatorIndex);
+}
+/**
+ * see SearchPattern.feedIndexRequestor
+ */
+public void feedIndexRequestor(IIndexSearchRequestor requestor, int detailLevel, int[] references, IndexInput input, IJavaSearchScope scope) throws IOException {
+ for (int i = 0, max = references.length; i < max; i++) {
+ IndexedFile file = input.getIndexedFile(references[i]);
+ String path;
+ if (file != null && scope.encloses(path = IndexedFile.convertPath(file.getPath()))) {
+ requestor.acceptMethodDeclaration(path, decodedSelector, decodedParameterCount);
}
}
+}
+public String getPatternName(){
+ return "MethodDeclarationPattern: ";
+}
+/**
+ * @see SearchPattern#indexEntryPrefix
+ */
+public char[] indexEntryPrefix() {
- public String getPatternName() {
- return "MethodDeclarationPattern: ";
- }
-
- /**
- * @see SearchPattern#indexEntryPrefix
- */
- public char[] indexEntryPrefix() {
-
- return AbstractIndexer.bestMethodDeclarationPrefix(
- selector,
- parameterSimpleNames == null ? -1 : parameterSimpleNames.length,
- matchMode,
+ return AbstractIndexer.bestMethodDeclarationPrefix(
+ selector,
+ parameterSimpleNames == null ? -1 : parameterSimpleNames.length,
+ matchMode,
isCaseSensitive);
- }
-
- /**
- * @see SearchPattern#matchContainer()
- */
- protected int matchContainer() {
- return CLASS;
- }
-
- /**
- * @see SearchPattern#matches(AstNode, boolean)
- */
- protected boolean matches(AstNode node, boolean resolve) {
- if (!(node instanceof MethodDeclaration))
- return false;
-
- MethodDeclaration method = (MethodDeclaration) node;
-
- // selector
- if (!this.matchesName(this.selector, method.selector))
- return false;
-
- // declaring type
- MethodBinding binding = method.binding;
- if (resolve && binding != null) {
- ReferenceBinding declaringType = binding.declaringClass;
- if (declaringType != null) {
- if (!binding.isStatic() && !binding.isPrivate()) {
- if (!this
- .matchesAsSubtype(
- declaringType,
- this.declaringSimpleName,
- this.declaringQualification))
- return false;
- } else {
- if (!this
- .matchesType(
- this.declaringSimpleName,
- this.declaringQualification,
- declaringType))
- return false;
- }
- }
- }
-
- // return type
- if (this.returnQualification == null) {
- if (this.returnSimpleName != null) {
- TypeReference methodReturnType = method.returnType;
- if (methodReturnType != null) {
- char[][] methodReturnTypeName = methodReturnType.getTypeName();
- char[] sourceName =
- this.toArrayName(
- methodReturnTypeName[methodReturnTypeName.length - 1],
- methodReturnType.dimensions());
- if (!this.matchesName(this.returnSimpleName, sourceName))
- return false;
- }
- }
- } else {
- if (resolve
- && binding != null
- && !this.matchesType(
- this.returnSimpleName,
- this.returnQualification,
- binding.returnType))
- return false;
- }
-
- // parameter types
- int parameterCount =
- this.parameterSimpleNames == null ? -1 : this.parameterSimpleNames.length;
- if (parameterCount > -1) {
- int argumentCount = method.arguments == null ? 0 : method.arguments.length;
- if (parameterCount != argumentCount)
- return false;
-
- if (resolve && binding != null) {
- for (int i = 0; i < parameterCount; i++) {
- char[] qualification = this.parameterQualifications[i];
- char[] type = this.parameterSimpleNames[i];
- if (!this.matchesType(type, qualification, binding.parameters[i]))
- return false;
- }
- }
- }
-
- return true;
- }
-
- /**
- * @see SearchPattern#matches(Binding)
- */
- public boolean matches(Binding binding) {
- if (!(binding instanceof MethodBinding))
- return false;
-
- MethodBinding method = (MethodBinding) binding;
-
- // selector
- if (!this.matchesName(this.selector, method.selector))
- return false;
-
- // declaring type
- ReferenceBinding declaringType = method.declaringClass;
+}
+/**
+ * @see SearchPattern#matchContainer()
+ */
+protected int matchContainer() {
+ return CLASS;
+}
+/**
+ * @see SearchPattern#matches(AstNode, boolean)
+ */
+protected boolean matches(AstNode node, boolean resolve) {
+ if (!(node instanceof MethodDeclaration)) return false;
+
+ MethodDeclaration method = (MethodDeclaration)node;
+
+ // selector
+ if (!this.matchesName(this.selector, method.selector))
+ return false;
+
+ // declaring type
+ MethodBinding binding = method.binding;
+ if (resolve && binding != null) {
+ ReferenceBinding declaringType = binding.declaringClass;
if (declaringType != null) {
- if (!method.isStatic() && !method.isPrivate()) {
- if (!this
- .matchesAsSubtype(
- declaringType,
- this.declaringSimpleName,
- this.declaringQualification))
+ if (!binding.isStatic() && !binding.isPrivate()) {
+ if (!this.matchesAsSubtype(declaringType, this.declaringSimpleName, this.declaringQualification))
return false;
} else {
- if (!this
- .matchesType(
- this.declaringSimpleName,
- this.declaringQualification,
- declaringType))
+ if (!this.matchesType(this.declaringSimpleName, this.declaringQualification, declaringType))
return false;
}
}
+ }
- // return type
- if (!this
- .matchesType(
- this.returnSimpleName,
- this.returnQualification,
- method.returnType)) {
- return false;
+ // return type
+ if (this.returnQualification == null) {
+ if (this.returnSimpleName != null) {
+ TypeReference methodReturnType = method.returnType;
+ if (methodReturnType != null) {
+ char[][] methodReturnTypeName = methodReturnType.getTypeName();
+ char[] sourceName = this.toArrayName(
+ methodReturnTypeName[methodReturnTypeName.length-1],
+ methodReturnType.dimensions());
+ if (!this.matchesName(this.returnSimpleName, sourceName))
+ return false;
+ }
}
-
- // parameter types
- int parameterCount =
- this.parameterSimpleNames == null ? -1 : this.parameterSimpleNames.length;
- if (parameterCount > -1) {
- int argumentCount = method.parameters == null ? 0 : method.parameters.length;
- if (parameterCount != argumentCount)
- return false;
+ } else {
+ if (resolve
+ && binding != null
+ && !this.matchesType(this.returnSimpleName, this.returnQualification, binding.returnType))
+ return false;
+ }
+
+ // parameter types
+ int parameterCount = this.parameterSimpleNames == null ? -1 : this.parameterSimpleNames.length;
+ if (parameterCount > -1) {
+ int argumentCount = method.arguments == null ? 0 : method.arguments.length;
+ if (parameterCount != argumentCount)
+ return false;
+
+ if (resolve && binding != null) {
for (int i = 0; i < parameterCount; i++) {
char[] qualification = this.parameterQualifications[i];
char[] type = this.parameterSimpleNames[i];
- if (!this.matchesType(type, qualification, method.parameters[i]))
+ if (!this.matchesType(type, qualification, binding.parameters[i]))
return false;
}
}
-
- return true;
}
- /**
- * @see SearchPattern#matchesBinary(Object, Object)
- */
- public boolean matchesBinary(Object binaryInfo, Object enclosingBinaryInfo) {
- if (!(binaryInfo instanceof IBinaryMethod))
- return false;
-
- IBinaryMethod method = (IBinaryMethod) binaryInfo;
+ return true;
+}
+/**
+ * @see SearchPattern#matches(Binding)
+ */
+public boolean matches(Binding binding) {
+ if (!(binding instanceof MethodBinding)) return false;
+
+ MethodBinding method = (MethodBinding)binding;
+
+ // selector
+ if (!this.matchesName(this.selector, method.selector))
+ return false;
+
+ // declaring type
+ ReferenceBinding declaringType = method.declaringClass;
+ if (declaringType != null) {
+ if (!method.isStatic() && !method.isPrivate()) {
+ if (!this.matchesAsSubtype(declaringType, this.declaringSimpleName, this.declaringQualification))
+ return false;
+ } else {
+ if (!this.matchesType(this.declaringSimpleName, this.declaringQualification, declaringType))
+ return false;
+ }
+ }
- // selector
- if (!this.matchesName(this.selector, method.getSelector()))
+ // return type
+ if (!this.matchesType(this.returnSimpleName, this.returnQualification, method.returnType)) {
+ return false;
+ }
+
+ // parameter types
+ int parameterCount = this.parameterSimpleNames == null ? -1 : this.parameterSimpleNames.length;
+ if (parameterCount > -1) {
+ int argumentCount = method.parameters == null ? 0 : method.parameters.length;
+ if (parameterCount != argumentCount)
return false;
-
- // declaring type
- IBinaryType declaringType = (IBinaryType) enclosingBinaryInfo;
- if (declaringType != null) {
- char[] declaringTypeName = (char[]) declaringType.getName().clone();
- CharOperation.replace(declaringTypeName, '/', '.');
- if (!this
- .matchesType(
- this.declaringSimpleName,
- this.declaringQualification,
- declaringTypeName)) {
+ for (int i = 0; i < parameterCount; i++) {
+ char[] qualification = this.parameterQualifications[i];
+ char[] type = this.parameterSimpleNames[i];
+ if (!this.matchesType(type, qualification, method.parameters[i]))
return false;
- }
}
+ }
- // return type
- String methodDescriptor =
- new String(method.getMethodDescriptor()).replace('/', '.');
- String returnTypeSignature =
- Signature.toString(Signature.getReturnType(methodDescriptor));
- if (!this
- .matchesType(
- this.returnSimpleName,
- this.returnQualification,
- returnTypeSignature.toCharArray())) {
+ return true;
+}
+/**
+ * @see SearchPattern#matchesBinary(Object, Object)
+ */
+public boolean matchesBinary(Object binaryInfo, Object enclosingBinaryInfo) {
+ if (!(binaryInfo instanceof IBinaryMethod)) return false;
+
+ IBinaryMethod method = (IBinaryMethod)binaryInfo;
+
+ // selector
+ if (!this.matchesName(this.selector, method.getSelector()))
+ return false;
+
+ // declaring type
+ IBinaryType declaringType = (IBinaryType)enclosingBinaryInfo;
+ if (declaringType != null) {
+ char[] declaringTypeName = (char[])declaringType.getName().clone();
+ CharOperation.replace(declaringTypeName, '/', '.');
+ if (!this.matchesType(this.declaringSimpleName, this.declaringQualification, declaringTypeName)) {
return false;
}
+ }
- // parameter types
- int parameterCount =
- this.parameterSimpleNames == null ? -1 : this.parameterSimpleNames.length;
- if (parameterCount > -1) {
- String[] arguments = Signature.getParameterTypes(methodDescriptor);
- int argumentCount = arguments.length;
- if (parameterCount != argumentCount)
+ // return type
+ String methodDescriptor = new String(method.getMethodDescriptor()).replace('/', '.');
+ String returnTypeSignature = Signature.toString(Signature.getReturnType(methodDescriptor));
+ if (!this.matchesType(this.returnSimpleName, this.returnQualification, returnTypeSignature.toCharArray())) {
+ return false;
+ }
+
+ // parameter types
+ int parameterCount = this.parameterSimpleNames == null ? -1 : this.parameterSimpleNames.length;
+ if (parameterCount > -1) {
+ String[] arguments = Signature.getParameterTypes(methodDescriptor);
+ int argumentCount = arguments.length;
+ if (parameterCount != argumentCount)
+ return false;
+ for (int i = 0; i < parameterCount; i++) {
+ char[] qualification = this.parameterQualifications[i];
+ char[] type = this.parameterSimpleNames[i];
+ if (!this.matchesType(type, qualification, Signature.toString(arguments[i]).toCharArray()))
return false;
- for (int i = 0; i < parameterCount; i++) {
- char[] qualification = this.parameterQualifications[i];
- char[] type = this.parameterSimpleNames[i];
- if (!this
- .matchesType(
- type,
- qualification,
- Signature.toString(arguments[i]).toCharArray()))
- return false;
- }
}
-
- return true;
}
+ return true;
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MethodPattern.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MethodPattern.java
index e41cb7a45f..52f4c32c12 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MethodPattern.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MethodPattern.java
@@ -10,7 +10,7 @@ public abstract class MethodPattern extends SearchPattern {
// selector
protected char[] selector;
-
+
// declaring type
protected char[] declaringQualification;
protected char[] declaringSimpleName;
@@ -24,126 +24,106 @@ public abstract class MethodPattern extends SearchPattern {
protected char[][] parameterSimpleNames;
protected char[] decodedSelector;
- protected int decodedParameterCount;
- public MethodPattern(int matchMode, boolean isCaseSensitive) {
- super(matchMode, isCaseSensitive);
- }
-
- public abstract String getPatternName();
- /**
- * @see SearchPattern#matchIndexEntry
- */
- protected boolean matchIndexEntry() {
+ protected int decodedParameterCount;
+public MethodPattern(int matchMode, boolean isCaseSensitive) {
+ super(matchMode, isCaseSensitive);
+}
+public abstract String getPatternName();
+/**
+ * @see SearchPattern#matchIndexEntry
+ */
+protected boolean matchIndexEntry() {
- /* check selector matches */
- if (selector != null) {
- switch (matchMode) {
- case EXACT_MATCH :
- if (!CharOperation.equals(selector, decodedSelector, isCaseSensitive)) {
- return false;
- }
- break;
- case PREFIX_MATCH :
- if (!CharOperation.prefixEquals(selector, decodedSelector, isCaseSensitive)) {
- return false;
- }
- break;
- case PATTERN_MATCH :
- if (!CharOperation.match(selector, decodedSelector, isCaseSensitive)) {
- return false;
- }
- }
- }
- if (parameterSimpleNames != null) {
- if (parameterSimpleNames.length != decodedParameterCount)
- return false;
+ /* check selector matches */
+ if (selector != null){
+ switch(matchMode){
+ case EXACT_MATCH :
+ if (!CharOperation.equals(selector, decodedSelector, isCaseSensitive)){
+ return false;
+ }
+ break;
+ case PREFIX_MATCH :
+ if (!CharOperation.prefixEquals(selector, decodedSelector, isCaseSensitive)){
+ return false;
+ }
+ break;
+ case PATTERN_MATCH :
+ if (!CharOperation.match(selector, decodedSelector, isCaseSensitive)){
+ return false;
+ }
}
- return true;
}
+ if (parameterSimpleNames != null){
+ if (parameterSimpleNames.length != decodedParameterCount) return false;
+ }
+ return true;
+}
+/**
+ * Returns whether a method declaration or message send will need to be resolved to
+ * find out if this method pattern matches it.
+ */
+protected boolean needsResolve() {
- /**
- * Returns whether a method declaration or message send will need to be resolved to
- * find out if this method pattern matches it.
- */
- protected boolean needsResolve() {
-
- // declaring type
- if (declaringSimpleName != null || declaringQualification != null)
- return true;
+ // declaring type
+ if (declaringSimpleName != null || declaringQualification != null) return true;
- // return type
- if (returnSimpleName != null || returnQualification != null)
- return true;
+ // return type
+ if (returnSimpleName != null || returnQualification != null) return true;
- // parameter types
- if (parameterSimpleNames != null) {
- for (int i = 0, max = parameterSimpleNames.length; i < max; i++) {
- if (parameterQualifications[i] != null || parameterSimpleNames[i] != null)
- return true;
- }
+ // parameter types
+ if (parameterSimpleNames != null){
+ for (int i = 0, max = parameterSimpleNames.length; i < max; i++){
+ if (parameterQualifications[i] != null || parameterSimpleNames[i] != null) return true;
}
- return false;
}
-
- public String toString() {
-
- StringBuffer buffer = new StringBuffer(20);
- buffer.append(this.getPatternName());
- if (declaringQualification != null)
- buffer.append(declaringQualification).append('.');
- if (declaringSimpleName != null)
- buffer.append(declaringSimpleName).append('.');
- else
- if (declaringQualification != null)
- buffer.append("*.");
- if (selector != null) {
- buffer.append(selector);
- } else {
- buffer.append("*");
- }
- buffer.append('(');
- if (parameterSimpleNames == null) {
- buffer.append("...");
- } else {
- for (int i = 0, max = parameterSimpleNames.length; i < max; i++) {
- if (i > 0)
- buffer.append(", ");
- if (parameterQualifications[i] != null)
- buffer.append(parameterQualifications[i]).append('.');
- if (parameterSimpleNames[i] == null)
- buffer.append('*');
- else
- buffer.append(parameterSimpleNames[i]);
- }
- }
- buffer.append(')');
- if (returnQualification != null)
- buffer.append(" --> ").append(returnQualification).append('.');
- else
- if (returnSimpleName != null)
- buffer.append(" --> ");
- if (returnSimpleName != null)
- buffer.append(returnSimpleName);
- else
- if (returnQualification != null)
- buffer.append("*");
- buffer.append(", ");
- switch (matchMode) {
- case EXACT_MATCH :
- buffer.append("exact match, ");
- break;
- case PREFIX_MATCH :
- buffer.append("prefix match, ");
- break;
- case PATTERN_MATCH :
- buffer.append("pattern match, ");
- break;
+ return false;
+}
+public String toString(){
+
+ StringBuffer buffer = new StringBuffer(20);
+ buffer.append(this.getPatternName());
+ if (declaringQualification != null) buffer.append(declaringQualification).append('.');
+ if (declaringSimpleName != null)
+ buffer.append(declaringSimpleName).append('.');
+ else if (declaringQualification != null) buffer.append("*.");
+ if (selector != null) {
+ buffer.append(selector);
+ } else {
+ buffer.append("*");
+ }
+ buffer.append('(');
+ if (parameterSimpleNames == null) {
+ buffer.append("...");
+ } else {
+ for (int i = 0, max = parameterSimpleNames.length; i < max; i++){
+ if (i > 0) buffer.append(", ");
+ if (parameterQualifications[i] != null) buffer.append(parameterQualifications[i]).append('.');
+ if (parameterSimpleNames[i] == null) buffer.append('*'); else buffer.append(parameterSimpleNames[i]);
}
- if (isCaseSensitive)
- buffer.append("case sensitive");
- else
- buffer.append("case insensitive");
- return buffer.toString();
}
-
+ buffer.append(')');
+ if (returnQualification != null)
+ buffer.append(" --> ").append(returnQualification).append('.');
+ else if (returnSimpleName != null) buffer.append(" --> ");
+ if (returnSimpleName != null)
+ buffer.append(returnSimpleName);
+ else if (returnQualification != null) buffer.append("*");
+ buffer.append(", ");
+ switch(matchMode){
+ case EXACT_MATCH :
+ buffer.append("exact match, ");
+ break;
+ case PREFIX_MATCH :
+ buffer.append("prefix match, ");
+ break;
+ case PATTERN_MATCH :
+ buffer.append("pattern match, ");
+ break;
+ }
+ if (isCaseSensitive)
+ buffer.append("case sensitive");
+ else
+ buffer.append("case insensitive");
+ return buffer.toString();
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MethodReferencePattern.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MethodReferencePattern.java
index e4f79b838d..925016baeb 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MethodReferencePattern.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MethodReferencePattern.java
@@ -17,223 +17,143 @@ import org.eclipse.jdt.internal.core.search.*;
import java.io.*;
public class MethodReferencePattern extends MethodPattern {
- public ReferenceBinding[] declaringTypes;
-
- public MethodReferencePattern(
- char[] selector,
- int matchMode,
- boolean isCaseSensitive,
- char[] declaringQualification,
- char[] declaringSimpleName,
- char[] returnQualification,
- char[] returnSimpleName,
- char[][] parameterQualifications,
- char[][] parameterSimpleNames) {
-
- super(matchMode, isCaseSensitive);
-
- this.selector =
- isCaseSensitive ? selector : CharOperation.toLowerCase(selector);
- this.declaringQualification =
- isCaseSensitive
- ? declaringQualification
- : CharOperation.toLowerCase(declaringQualification);
- this.declaringSimpleName =
- isCaseSensitive
- ? declaringSimpleName
- : CharOperation.toLowerCase(declaringSimpleName);
- this.returnQualification =
- isCaseSensitive
- ? returnQualification
- : CharOperation.toLowerCase(returnQualification);
- this.returnSimpleName =
- isCaseSensitive
- ? returnSimpleName
- : CharOperation.toLowerCase(returnSimpleName);
- if (parameterSimpleNames != null) {
- this.parameterQualifications = new char[parameterSimpleNames.length][];
- this.parameterSimpleNames = new char[parameterSimpleNames.length][];
- for (int i = 0, max = parameterSimpleNames.length; i < max; i++) {
- this.parameterQualifications[i] =
- isCaseSensitive
- ? parameterQualifications[i]
- : CharOperation.toLowerCase(parameterQualifications[i]);
- this.parameterSimpleNames[i] =
- isCaseSensitive
- ? parameterSimpleNames[i]
- : CharOperation.toLowerCase(parameterSimpleNames[i]);
- }
+ public char[][][] allSuperDeclaringTypeNames;
+
+public MethodReferencePattern(
+ char[] selector,
+ int matchMode,
+ boolean isCaseSensitive,
+ char[] declaringQualification,
+ char[] declaringSimpleName,
+ char[] returnQualification,
+ char[] returnSimpleName,
+ char[][] parameterQualifications,
+ char[][] parameterSimpleNames) {
+
+ super(matchMode, isCaseSensitive);
+
+ this.selector = isCaseSensitive ? selector : CharOperation.toLowerCase(selector);
+ this.declaringQualification = isCaseSensitive ? declaringQualification : CharOperation.toLowerCase(declaringQualification);
+ this.declaringSimpleName = isCaseSensitive ? declaringSimpleName : CharOperation.toLowerCase(declaringSimpleName);
+ this.returnQualification = isCaseSensitive ? returnQualification : CharOperation.toLowerCase(returnQualification);
+ this.returnSimpleName = isCaseSensitive ? returnSimpleName : CharOperation.toLowerCase(returnSimpleName);
+ if (parameterSimpleNames != null){
+ this.parameterQualifications = new char[parameterSimpleNames.length][];
+ this.parameterSimpleNames = new char[parameterSimpleNames.length][];
+ for (int i = 0, max = parameterSimpleNames.length; i < max; i++){
+ this.parameterQualifications[i] = isCaseSensitive ? parameterQualifications[i] : CharOperation.toLowerCase(parameterQualifications[i]);
+ this.parameterSimpleNames[i] = isCaseSensitive ? parameterSimpleNames[i] : CharOperation.toLowerCase(parameterSimpleNames[i]);
}
-
- this.needsResolve = this.needsResolve();
}
- public void decodeIndexEntry(IEntryResult entryResult) {
+ this.needsResolve = this.needsResolve();
+}
+public void decodeIndexEntry(IEntryResult entryResult){
- char[] word = entryResult.getWord();
- int size = word.length;
- int lastSeparatorIndex = CharOperation.lastIndexOf(SEPARATOR, word);
+ char[] word = entryResult.getWord();
+ int size = word.length;
+ int lastSeparatorIndex = CharOperation.lastIndexOf(SEPARATOR, word);
- decodedParameterCount =
- Integer.parseInt(
- new String(word, lastSeparatorIndex + 1, size - lastSeparatorIndex - 1));
- decodedSelector =
- CharOperation.subarray(word, METHOD_REF.length, lastSeparatorIndex);
- }
-
- /**
- * see SearchPattern.feedIndexRequestor
- */
- public void feedIndexRequestor(
- IIndexSearchRequestor requestor,
- int detailLevel,
- int[] references,
- IndexInput input,
- IJavaSearchScope scope)
- throws IOException {
- for (int i = 0, max = references.length; i < max; i++) {
- IndexedFile file = input.getIndexedFile(references[i]);
- String path;
- if (file != null
- && scope.encloses(path = IndexedFile.convertPath(file.getPath()))) {
- requestor.acceptMethodReference(path, decodedSelector, decodedParameterCount);
- }
+ decodedParameterCount = Integer.parseInt(new String(word, lastSeparatorIndex + 1, size - lastSeparatorIndex - 1));
+ decodedSelector = CharOperation.subarray(word, METHOD_REF.length, lastSeparatorIndex);
+}
+/**
+ * see SearchPattern.feedIndexRequestor
+ */
+public void feedIndexRequestor(IIndexSearchRequestor requestor, int detailLevel, int[] references, IndexInput input, IJavaSearchScope scope) throws IOException {
+ for (int i = 0, max = references.length; i < max; i++) {
+ IndexedFile file = input.getIndexedFile(references[i]);
+ String path;
+ if (file != null && scope.encloses(path = IndexedFile.convertPath(file.getPath()))) {
+ requestor.acceptMethodReference(path, decodedSelector, decodedParameterCount);
}
}
+}
+public String getPatternName(){
+ return "MethodReferencePattern: ";
+}
+/**
+ * @see SearchPattern#indexEntryPrefix
+ */
+public char[] indexEntryPrefix() {
- public String getPatternName() {
- return "MethodReferencePattern: ";
- }
-
- /**
- * @see SearchPattern#indexEntryPrefix
- */
- public char[] indexEntryPrefix() {
-
- return AbstractIndexer.bestMethodReferencePrefix(
- selector,
- parameterSimpleNames == null ? -1 : parameterSimpleNames.length,
- matchMode,
+ return AbstractIndexer.bestMethodReferencePrefix(
+ selector,
+ parameterSimpleNames == null ? -1 : parameterSimpleNames.length,
+ matchMode,
isCaseSensitive);
+}
+/**
+ * Returns whether the code gen will use an invoke virtual for
+ * this message send or not.
+ */
+private boolean isVirtualInvoke(MessageSend messageSend) {
+ return !messageSend.binding.isStatic() && !messageSend.isSuperAccess() && !messageSend.binding.isPrivate();
+}
+/**
+ * @see SearchPattern#matchContainer()
+ */
+protected int matchContainer() {
+ return METHOD | FIELD;
+}
+/**
+ * @see SearchPattern#matches(AstNode, boolean)
+ */
+protected boolean matches(AstNode node, boolean resolve) {
+ if (!(node instanceof MessageSend)) return false;
+
+ MessageSend messageSend = (MessageSend)node;
+
+ // selector
+ if (this.selector != null && !this.matchesName(this.selector, messageSend.selector))
+ return false;
+
+ // receiver type
+ MethodBinding binding = messageSend.binding;
+ ReferenceBinding receiverType =
+ binding == null ?
+ null :
+ (!isVirtualInvoke(messageSend) ? binding.declaringClass : (ReferenceBinding)messageSend.receiverType);
+ if (resolve && receiverType != null) {
+ if (this.isVirtualInvoke(messageSend)) {
+ if (!this.matchesAsSubtype(receiverType, this.declaringSimpleName, this.declaringQualification)
+ && !this.matchesType(this.allSuperDeclaringTypeNames, receiverType)) {
+ return false;
+ }
+ } else {
+ if (!this.matchesType(this.declaringSimpleName, this.declaringQualification, receiverType))
+ return false;
+ }
}
- /**
- * Returns whether the code gen will use an invoke virtual for
- * this message send or not.
- */
- private boolean isVirtualInvoke(MessageSend messageSend) {
- return !messageSend.binding.isStatic()
- && !messageSend.isSuperAccess()
- && !messageSend.binding.isPrivate();
- }
-
- /**
- * @see SearchPattern#matchContainer()
- */
- protected int matchContainer() {
- return METHOD | FIELD;
- }
-
- /**
- * @see SearchPattern#matches(AstNode, boolean)
- */
- protected boolean matches(AstNode node, boolean resolve) {
- if (!(node instanceof MessageSend))
+ // return type
+ if (resolve && binding != null) {
+ if (!this.matchesType(this.returnSimpleName, this.returnQualification, binding.returnType))
return false;
-
- MessageSend messageSend = (MessageSend) node;
-
- // selector
- if (this.selector != null
- && !this.matchesName(this.selector, messageSend.selector))
+ }
+
+ // argument types
+ int argumentCount = this.parameterSimpleNames == null ? -1 : this.parameterSimpleNames.length;
+ if (argumentCount > -1) {
+ int parameterCount = messageSend.arguments == null ? 0 : messageSend.arguments.length;
+ if (parameterCount != argumentCount)
return false;
- // declaring type
- MethodBinding binding = messageSend.binding;
if (resolve && binding != null) {
- ReferenceBinding receiverType = binding.declaringClass;
- if (this.isVirtualInvoke(messageSend)) {
- if (!this
- .matchesAsSubtype(
- receiverType,
- this.declaringSimpleName,
- this.declaringQualification)
- && !this.matchesAsSubtype(this.declaringTypes, receiverType)) {
- return false;
- }
- } else {
- if (!this
- .matchesType(
- this.declaringSimpleName,
- this.declaringQualification,
- receiverType))
+ for (int i = 0; i < parameterCount; i++) {
+ char[] qualification = this.parameterQualifications[i];
+ char[] type = this.parameterSimpleNames[i];
+ if (!this.matchesType(type, qualification, binding.parameters[i]))
return false;
}
}
-
- // return type
- if (resolve && binding != null) {
- if (!this
- .matchesType(
- this.returnSimpleName,
- this.returnQualification,
- binding.returnType))
- return false;
- }
-
- // argument types
- int argumentCount =
- this.parameterSimpleNames == null ? -1 : this.parameterSimpleNames.length;
- if (argumentCount > -1) {
- int parameterCount =
- messageSend.arguments == null ? 0 : messageSend.arguments.length;
- if (parameterCount != argumentCount)
- return false;
-
- if (resolve && binding != null) {
- for (int i = 0; i < parameterCount; i++) {
- char[] qualification = this.parameterQualifications[i];
- char[] type = this.parameterSimpleNames[i];
- if (!this.matchesType(type, qualification, binding.parameters[i]))
- return false;
- }
- }
- }
-
- return true;
}
- public boolean initializeFromLookupEnvironment(LookupEnvironment env) {
-
- char[][] declaringTypeName = null;
- if ((this.declaringQualification != null)
- && (this.declaringSimpleName != null)
- && (this.matchMode == EXACT_MATCH)) {
- char[][] qualification =
- CharOperation.splitOn('.', this.declaringQualification);
- declaringTypeName =
- CharOperation.arrayConcat(qualification, this.declaringSimpleName);
- }
- if (declaringTypeName != null) {
- for (int i = 0, max = declaringTypeName.length; i < max; i++) {
- ReferenceBinding matchingDeclaringType = env.getCachedType(declaringTypeName);
- if (matchingDeclaringType != null && matchingDeclaringType.isValidBinding()) {
- this.declaringTypes = new ReferenceBinding[] { matchingDeclaringType };
- return true;
- }
- // if nothing is in the cache, it could have been a member type (A.B.C.D --> A.B.C$D)
- int last = declaringTypeName.length - 1;
- if (last == 0)
- break;
- declaringTypeName[last - 1] =
- CharOperation.concat(declaringTypeName[last - 1], declaringTypeName[last], '$');
- // try nested type
- declaringTypeName = CharOperation.subarray(declaringTypeName, 0, last);
- }
- return false;
- } else {
- return true;
- }
- }
+ return true;
+}
+public boolean initializeFromLookupEnvironment(LookupEnvironment env) {
+ this.allSuperDeclaringTypeNames = this.collectSuperTypeNames(this.declaringQualification, this.declaringSimpleName, this.matchMode, env);
+ return this.allSuperDeclaringTypeNames == null || this.allSuperDeclaringTypeNames != NOT_FOUND_DECLARING_TYPE;
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MultipleSearchPattern.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MultipleSearchPattern.java
index 864c22db8c..80c91e2161 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MultipleSearchPattern.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/MultipleSearchPattern.java
@@ -16,33 +16,24 @@ import java.io.*;
public abstract class MultipleSearchPattern extends AndPattern {
protected char[] currentTag;
- public boolean foundAmbiguousIndexMatches = false;
- public MultipleSearchPattern(int matchMode, boolean isCaseSensitive) {
- super(matchMode, isCaseSensitive);
- }
-
- /**
- * Query a given index for matching entries.
- */
- public void findIndexMatches(
- IndexInput input,
- IIndexSearchRequestor requestor,
- int detailLevel,
- IProgressMonitor progressMonitor,
- IJavaSearchScope scope)
- throws IOException {
-
- char[][] possibleTags = getPossibleTags();
+ public boolean foundAmbiguousIndexMatches = false;
+public MultipleSearchPattern(int matchMode, boolean isCaseSensitive) {
+ super(matchMode, isCaseSensitive);
+}
+/**
+ * Query a given index for matching entries.
+ */
+public void findIndexMatches(IndexInput input, IIndexSearchRequestor requestor, int detailLevel, IProgressMonitor progressMonitor, IJavaSearchScope scope) throws IOException {
- if (progressMonitor != null && progressMonitor.isCanceled())
- throw new OperationCanceledException();
+ char[][] possibleTags = getPossibleTags();
+
+ if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException();
- /* narrow down a set of entries using prefix criteria */
- for (int i = 0, max = possibleTags.length; i < max; i++) {
- currentTag = possibleTags[i];
- super.findIndexMatches(input, requestor, detailLevel, progressMonitor, scope);
- }
+ /* narrow down a set of entries using prefix criteria */
+ for (int i = 0, max = possibleTags.length; i < max; i++){
+ currentTag = possibleTags[i];
+ super.findIndexMatches(input, requestor, detailLevel, progressMonitor, scope);
}
-
- protected abstract char[][] getPossibleTags();
+}
+protected abstract char[][] getPossibleTags();
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/OrNameCombiner.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/OrNameCombiner.java
index ff4410d3a3..5e829f990a 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/OrNameCombiner.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/OrNameCombiner.java
@@ -14,81 +14,25 @@ public class OrNameCombiner implements IIndexSearchRequestor {
IIndexSearchRequestor targetRequestor;
HashtableOfObject acceptedAnswers = new HashtableOfObject(5);
+
+public OrNameCombiner(IIndexSearchRequestor targetRequestor){
+ this.targetRequestor = targetRequestor;
+}
+public void acceptClassDeclaration(String resourcePath, char[] simpleTypeName, char[][] enclosingTypeNames, char[] packageName){
- public OrNameCombiner(IIndexSearchRequestor targetRequestor) {
- this.targetRequestor = targetRequestor;
- }
-
- public void acceptClassDeclaration(
- String resourcePath,
- char[] simpleTypeName,
- char[][] enclosingTypeNames,
- char[] packageName) {
-
- if (!this
- .acceptedAnswers
- .containsKey(CharOperation.concat(packageName, simpleTypeName, '.'))) {
- this.targetRequestor.acceptClassDeclaration(
- resourcePath,
- simpleTypeName,
- enclosingTypeNames,
- packageName);
- }
- }
-
- public void acceptConstructorDeclaration(
- String resourcePath,
- char[] typeName,
- int parameterCount) {
- }
-
- public void acceptConstructorReference(
- String resourcePath,
- char[] typeName,
- int parameterCount) {
- }
-
- public void acceptFieldDeclaration(String resourcePath, char[] fieldName) {
- }
-
- public void acceptFieldReference(String resourcePath, char[] fieldName) {
- }
-
- public void acceptInterfaceDeclaration(
- String resourcePath,
- char[] simpleTypeName,
- char[][] enclosingTypeNames,
- char[] packageName) {
- }
-
- public void acceptMethodDeclaration(
- String resourcePath,
- char[] methodName,
- int parameterCount) {
- }
-
- public void acceptMethodReference(
- String resourcePath,
- char[] methodName,
- int parameterCount) {
- }
-
- public void acceptPackageReference(String resourcePath, char[] packageName) {
- }
-
- public void acceptSuperTypeReference(
- String resourcePath,
- char[] qualification,
- char[] typeName,
- char[] enclosingTypeName,
- char classOrInterface,
- char[] superQualification,
- char[] superTypeName,
- char superClassOrInterface,
- int modifiers) {
- }
-
- public void acceptTypeReference(String resourcePath, char[] typeName) {
+ if (!this.acceptedAnswers.containsKey(CharOperation.concat(packageName, simpleTypeName, '.'))){
+ this.targetRequestor.acceptClassDeclaration(resourcePath, simpleTypeName, enclosingTypeNames, packageName);
}
-
+}
+public void acceptConstructorDeclaration(String resourcePath, char[] typeName, int parameterCount) {}
+public void acceptConstructorReference(String resourcePath, char[] typeName, int parameterCount) {}
+public void acceptFieldDeclaration(String resourcePath, char[] fieldName) {}
+public void acceptFieldReference(String resourcePath, char[] fieldName) {}
+public void acceptInterfaceDeclaration(String resourcePath, char[] simpleTypeName, char[][] enclosingTypeNames, char[] packageName) {}
+public void acceptMethodDeclaration(String resourcePath, char[] methodName, int parameterCount) {}
+public void acceptMethodReference(String resourcePath, char[] methodName, int parameterCount) {}
+public void acceptPackageReference(String resourcePath, char[] packageName) {}
+public void acceptSuperTypeReference(String resourcePath, char[] qualification, char[] typeName, char[] enclosingTypeName, char classOrInterface, char[] superQualification, char[] superTypeName, char superClassOrInterface, int modifiers){
+}
+public void acceptTypeReference(String resourcePath, char[] typeName) {}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/OrPathCombiner.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/OrPathCombiner.java
index 6453f299e2..7d08444346 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/OrPathCombiner.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/OrPathCombiner.java
@@ -13,144 +13,74 @@ public class OrPathCombiner implements IIndexSearchRequestor {
IIndexSearchRequestor targetRequestor;
Hashtable acceptedAnswers = new Hashtable(5);
- public OrPathCombiner(IIndexSearchRequestor targetRequestor) {
- this.targetRequestor = targetRequestor;
- }
-
- public void acceptClassDeclaration(
- String resourcePath,
- char[] simpleTypeName,
- char[][] enclosingTypeNames,
- char[] packageName) {
-
- if (!this.acceptedAnswers.containsKey(resourcePath)) {
- this.acceptedAnswers.put(resourcePath, resourcePath);
- this.targetRequestor.acceptClassDeclaration(
- resourcePath,
- simpleTypeName,
- enclosingTypeNames,
- packageName);
- }
- }
-
- public void acceptConstructorDeclaration(
- String resourcePath,
- char[] typeName,
- int parameterCount) {
- if (!this.acceptedAnswers.containsKey(resourcePath)) {
- this.acceptedAnswers.put(resourcePath, resourcePath);
- this.targetRequestor.acceptConstructorDeclaration(
- resourcePath,
- typeName,
- parameterCount);
- }
- }
-
- public void acceptConstructorReference(
- String resourcePath,
- char[] typeName,
- int parameterCount) {
- if (!this.acceptedAnswers.containsKey(resourcePath)) {
- this.acceptedAnswers.put(resourcePath, resourcePath);
- this.targetRequestor.acceptConstructorReference(
- resourcePath,
- typeName,
- parameterCount);
- }
- }
-
- public void acceptFieldDeclaration(String resourcePath, char[] fieldName) {
- if (!this.acceptedAnswers.containsKey(resourcePath)) {
- this.acceptedAnswers.put(resourcePath, resourcePath);
- this.targetRequestor.acceptFieldDeclaration(resourcePath, fieldName);
- }
- }
-
- public void acceptFieldReference(String resourcePath, char[] fieldName) {
- if (!this.acceptedAnswers.containsKey(resourcePath)) {
- this.acceptedAnswers.put(resourcePath, resourcePath);
- this.targetRequestor.acceptFieldReference(resourcePath, fieldName);
- }
- }
-
- public void acceptInterfaceDeclaration(
- String resourcePath,
- char[] simpleTypeName,
- char[][] enclosingTypeNames,
- char[] packageName) {
- if (!this.acceptedAnswers.containsKey(resourcePath)) {
- this.acceptedAnswers.put(resourcePath, resourcePath);
- this.targetRequestor.acceptInterfaceDeclaration(
- resourcePath,
- simpleTypeName,
- enclosingTypeNames,
- packageName);
- }
- }
-
- public void acceptMethodDeclaration(
- String resourcePath,
- char[] methodName,
- int parameterCount) {
- if (!this.acceptedAnswers.containsKey(resourcePath)) {
- this.acceptedAnswers.put(resourcePath, resourcePath);
- this.targetRequestor.acceptMethodDeclaration(
- resourcePath,
- methodName,
- parameterCount);
- }
- }
-
- public void acceptMethodReference(
- String resourcePath,
- char[] methodName,
- int parameterCount) {
- if (!this.acceptedAnswers.containsKey(resourcePath)) {
- this.acceptedAnswers.put(resourcePath, resourcePath);
- this.targetRequestor.acceptMethodReference(
- resourcePath,
- methodName,
- parameterCount);
- }
- }
+public OrPathCombiner(IIndexSearchRequestor targetRequestor){
+ this.targetRequestor = targetRequestor;
+}
+public void acceptClassDeclaration(String resourcePath, char[] simpleTypeName, char[][] enclosingTypeNames, char[] packageName){
- public void acceptPackageReference(String resourcePath, char[] packageName) {
- if (!this.acceptedAnswers.containsKey(resourcePath)) {
- this.acceptedAnswers.put(resourcePath, resourcePath);
- this.targetRequestor.acceptPackageReference(resourcePath, packageName);
- }
+ if (!this.acceptedAnswers.containsKey(resourcePath)){
+ this.acceptedAnswers.put(resourcePath, resourcePath);
+ this.targetRequestor.acceptClassDeclaration(resourcePath, simpleTypeName, enclosingTypeNames, packageName);
}
-
- public void acceptSuperTypeReference(
- String resourcePath,
- char[] qualification,
- char[] typeName,
- char[] enclosingTypeName,
- char classOrInterface,
- char[] superQualification,
- char[] superTypeName,
- char superClassOrInterface,
- int modifiers) {
- if (!this.acceptedAnswers.containsKey(resourcePath)) {
- this.acceptedAnswers.put(resourcePath, resourcePath);
- this.targetRequestor.acceptSuperTypeReference(
- resourcePath,
- qualification,
- typeName,
- enclosingTypeName,
- classOrInterface,
- superQualification,
- superTypeName,
- superClassOrInterface,
- modifiers);
- }
+}
+public void acceptConstructorDeclaration(String resourcePath, char[] typeName, int parameterCount) {
+ if (!this.acceptedAnswers.containsKey(resourcePath)){
+ this.acceptedAnswers.put(resourcePath, resourcePath);
+ this.targetRequestor.acceptConstructorDeclaration(resourcePath, typeName, parameterCount);
+ }
+}
+public void acceptConstructorReference(String resourcePath, char[] typeName, int parameterCount) {
+ if (!this.acceptedAnswers.containsKey(resourcePath)){
+ this.acceptedAnswers.put(resourcePath, resourcePath);
+ this.targetRequestor.acceptConstructorReference(resourcePath, typeName, parameterCount);
+ }
+}
+public void acceptFieldDeclaration(String resourcePath, char[] fieldName) {
+ if (!this.acceptedAnswers.containsKey(resourcePath)){
+ this.acceptedAnswers.put(resourcePath, resourcePath);
+ this.targetRequestor.acceptFieldDeclaration(resourcePath, fieldName);
+ }
+}
+public void acceptFieldReference(String resourcePath, char[] fieldName) {
+ if (!this.acceptedAnswers.containsKey(resourcePath)){
+ this.acceptedAnswers.put(resourcePath, resourcePath);
+ this.targetRequestor.acceptFieldReference(resourcePath, fieldName);
+ }
+}
+public void acceptInterfaceDeclaration(String resourcePath, char[] simpleTypeName, char[][] enclosingTypeNames, char[] packageName) {
+ if (!this.acceptedAnswers.containsKey(resourcePath)){
+ this.acceptedAnswers.put(resourcePath, resourcePath);
+ this.targetRequestor.acceptInterfaceDeclaration(resourcePath, simpleTypeName, enclosingTypeNames, packageName);
+ }
+}
+public void acceptMethodDeclaration(String resourcePath, char[] methodName, int parameterCount) {
+ if (!this.acceptedAnswers.containsKey(resourcePath)){
+ this.acceptedAnswers.put(resourcePath, resourcePath);
+ this.targetRequestor.acceptMethodDeclaration(resourcePath, methodName, parameterCount);
+ }
+}
+public void acceptMethodReference(String resourcePath, char[] methodName, int parameterCount) {
+ if (!this.acceptedAnswers.containsKey(resourcePath)){
+ this.acceptedAnswers.put(resourcePath, resourcePath);
+ this.targetRequestor.acceptMethodReference(resourcePath, methodName, parameterCount);
+ }
+}
+public void acceptPackageReference(String resourcePath, char[] packageName) {
+ if (!this.acceptedAnswers.containsKey(resourcePath)){
+ this.acceptedAnswers.put(resourcePath, resourcePath);
+ this.targetRequestor.acceptPackageReference(resourcePath, packageName);
+ }
+}
+public void acceptSuperTypeReference(String resourcePath, char[] qualification, char[] typeName, char[] enclosingTypeName, char classOrInterface, char[] superQualification, char[] superTypeName, char superClassOrInterface, int modifiers){
+ if (!this.acceptedAnswers.containsKey(resourcePath)){
+ this.acceptedAnswers.put(resourcePath, resourcePath);
+ this.targetRequestor.acceptSuperTypeReference(resourcePath, qualification, typeName, enclosingTypeName, classOrInterface, superQualification, superTypeName, superClassOrInterface, modifiers);
}
-
- public void acceptTypeReference(String resourcePath, char[] typeName) {
- if (!this.acceptedAnswers.containsKey(resourcePath)) {
- this.acceptedAnswers.put(resourcePath, resourcePath);
- this.targetRequestor.acceptTypeReference(resourcePath, typeName);
- }
+}
+public void acceptTypeReference(String resourcePath, char[] typeName) {
+ if (!this.acceptedAnswers.containsKey(resourcePath)){
+ this.acceptedAnswers.put(resourcePath, resourcePath);
+ this.targetRequestor.acceptTypeReference(resourcePath, typeName);
}
-
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/OrPattern.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/OrPattern.java
index b01d4b2988..bd3115074b 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/OrPattern.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/OrPattern.java
@@ -12,12 +12,13 @@ import org.eclipse.jdt.core.search.*;
import org.eclipse.jdt.internal.compiler.ast.*;
import org.eclipse.jdt.internal.compiler.lookup.Binding;
-import org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
import org.eclipse.jdt.internal.core.index.impl.*;
import org.eclipse.jdt.internal.core.search.*;
import java.io.*;
+import org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
+
public class OrPattern extends SearchPattern {
public SearchPattern leftPattern;
@@ -69,14 +70,6 @@ public char[] indexEntryPrefix() {
return null;
}
/**
- * see SearchPattern.initializeFromLookupEnvironment
- */
-public boolean initializeFromLookupEnvironment(LookupEnvironment env) {
- return
- this.leftPattern.initializeFromLookupEnvironment(env)
- || this.rightPattern.initializeFromLookupEnvironment(env);
-}
-/**
* @see SearchPattern#matchContainer()
*/
protected int matchContainer() {
@@ -116,4 +109,15 @@ protected void matchReportReference(AstNode reference, IJavaElement element, int
public String toString(){
return this.leftPattern.toString() + "\n| " + this.rightPattern.toString();
}
+
+/**
+ * see SearchPattern.initializeFromLookupEnvironment
+ */
+public boolean initializeFromLookupEnvironment(LookupEnvironment env) {
+
+ // need to perform both operand initialization due to side-effects.
+ boolean leftInit = this.leftPattern.initializeFromLookupEnvironment(env);
+ boolean rightInit = this.rightPattern.initializeFromLookupEnvironment(env);
+ return leftInit || rightInit;
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/PackageDeclarationPattern.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/PackageDeclarationPattern.java
index b5aeb308ee..82d9baa05a 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/PackageDeclarationPattern.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/PackageDeclarationPattern.java
@@ -14,101 +14,76 @@ import org.eclipse.jdt.internal.core.index.IEntryResult;
public class PackageDeclarationPattern extends SearchPattern {
char[] pkgName;
- public PackageDeclarationPattern(
- char[] pkgName,
- int matchMode,
- boolean isCaseSensitive) {
- super(matchMode, isCaseSensitive);
- this.pkgName = pkgName;
- }
-
- /**
- * @see SearchPattern#decodeIndexEntry
- */
- protected void decodeIndexEntry(IEntryResult entryResult) {
- // not used
- }
-
- /**
- * @see SearchPattern#feedIndexRequestor
- */
- public void feedIndexRequestor(
- IIndexSearchRequestor requestor,
- int detailLevel,
- int[] references,
- IndexInput input,
- IJavaSearchScope scope)
- throws java.io.IOException {
- // not used
- }
-
- /**
- * see SearchPattern#findMatches
- */
- public void findIndexMatches(
- IndexInput input,
- IIndexSearchRequestor requestor,
- int detailLevel,
- IProgressMonitor progressMonitor,
- IJavaSearchScope scope)
- throws IOException {
- // package declarations are not indexed
- }
-
- /**
- * @see SearchPattern#indexEntryPrefix
- */
- public char[] indexEntryPrefix() {
- // not used
- return null;
- }
-
- /**
- * @see SearchPattern#matchContainer
- */
- protected int matchContainer() {
- // used only in the case of a OrPattern
- return 0;
- }
-
- /**
- * @see SearchPattern#matches(AstNode, boolean)
- */
- protected boolean matches(AstNode node, boolean resolve) {
- // used only in the case of a OrPattern
- return true;
- }
-
- /**
- * @see SearchPattern#matchIndexEntry
- */
- protected boolean matchIndexEntry() {
- // used only in the case of a OrPattern
- return true;
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer(20);
- buffer.append("PackageDeclarationPattern: <");
- if (this.pkgName != null)
- buffer.append(this.pkgName);
- buffer.append(">, ");
- switch (matchMode) {
- case EXACT_MATCH :
- buffer.append("exact match, ");
- break;
- case PREFIX_MATCH :
- buffer.append("prefix match, ");
- break;
- case PATTERN_MATCH :
- buffer.append("pattern match, ");
- break;
- }
- if (isCaseSensitive)
- buffer.append("case sensitive");
- else
- buffer.append("case insensitive");
- return buffer.toString();
+public PackageDeclarationPattern(char[] pkgName, int matchMode, boolean isCaseSensitive) {
+ super(matchMode, isCaseSensitive);
+ this.pkgName = pkgName;
+}
+/**
+ * @see SearchPattern#decodeIndexEntry
+ */
+protected void decodeIndexEntry(IEntryResult entryResult) {
+ // not used
+}
+/**
+ * @see SearchPattern#feedIndexRequestor
+ */
+public void feedIndexRequestor(IIndexSearchRequestor requestor, int detailLevel, int[] references, IndexInput input, IJavaSearchScope scope) throws java.io.IOException {
+ // not used
+}
+/**
+ * see SearchPattern#findMatches
+ */
+public void findIndexMatches(IndexInput input, IIndexSearchRequestor requestor, int detailLevel, IProgressMonitor progressMonitor, IJavaSearchScope scope) throws IOException {
+ // package declarations are not indexed
+}
+/**
+ * @see SearchPattern#indexEntryPrefix
+ */
+public char[] indexEntryPrefix() {
+ // not used
+ return null;
+}
+/**
+ * @see SearchPattern#matchContainer
+ */
+protected int matchContainer() {
+ // used only in the case of a OrPattern
+ return 0;
+}
+/**
+ * @see SearchPattern#matches(AstNode, boolean)
+ */
+protected boolean matches(AstNode node, boolean resolve) {
+ // used only in the case of a OrPattern
+ return true;
+}
+/**
+ * @see SearchPattern#matchIndexEntry
+ */
+protected boolean matchIndexEntry() {
+ // used only in the case of a OrPattern
+ return true;
+}
+public String toString(){
+ StringBuffer buffer = new StringBuffer(20);
+ buffer.append("PackageDeclarationPattern: <");
+ if (this.pkgName != null) buffer.append(this.pkgName);
+ buffer.append(">, ");
+ switch(matchMode){
+ case EXACT_MATCH :
+ buffer.append("exact match, ");
+ break;
+ case PREFIX_MATCH :
+ buffer.append("prefix match, ");
+ break;
+ case PATTERN_MATCH :
+ buffer.append("pattern match, ");
+ break;
}
-
+ if (isCaseSensitive)
+ buffer.append("case sensitive");
+ else
+ buffer.append("case insensitive");
+ return buffer.toString();
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/PackageReferencePattern.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/PackageReferencePattern.java
index be2671fc79..9a3bf39a2a 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/PackageReferencePattern.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/PackageReferencePattern.java
@@ -28,314 +28,242 @@ public class PackageReferencePattern extends AndPattern {
private char[][] segments;
private int currentSegment;
private char[] decodedSegment;
- public PackageReferencePattern(
- char[] pkgName,
- int matchMode,
- boolean isCaseSensitive) {
- super(matchMode, isCaseSensitive);
- this.pkgName = pkgName;
- char[][] splittedName = CharOperation.splitOn('.', pkgName);
- this.segments =
- splittedName == TypeConstants.NoCharChar ? new char[][] { pkgName }
- : splittedName;
- this.needsResolve = pkgName != null;
- }
-
- /**
- * ref/name (where name is the last segment of the package name)
- * @see SearchPattern#decodeIndexEntry
- */
- public void decodeIndexEntry(IEntryResult entryResult) {
-
- char[] word = entryResult.getWord();
- int size = word.length;
- int tagLength = REF.length;
- int nameLength = CharOperation.indexOf(SEPARATOR, word, tagLength);
- if (nameLength < 0)
- nameLength = size;
- this.decodedSegment = CharOperation.subarray(word, tagLength, nameLength);
- }
+public PackageReferencePattern(char[] pkgName, int matchMode, boolean isCaseSensitive) {
+ super(matchMode, isCaseSensitive);
+ this.pkgName = pkgName;
+ char[][] splittedName = CharOperation.splitOn('.', pkgName);
+ this.segments = splittedName == TypeConstants.NoCharChar ? new char[][]{ pkgName } : splittedName;
+ this.needsResolve = pkgName != null;
+}
+/**
+ * ref/name (where name is the last segment of the package name)
+ * @see SearchPattern#decodeIndexEntry
+ */
+public void decodeIndexEntry(IEntryResult entryResult){
- /**
- * @see SearchPattern#feedIndexRequestor
- */
- public void feedIndexRequestor(
- IIndexSearchRequestor requestor,
- int detailLevel,
- int[] references,
- IndexInput input,
- IJavaSearchScope scope)
- throws IOException {
- for (int i = 0, max = references.length; i < max; i++) {
- int reference = references[i];
- if (reference != -1) { // if the reference has not been eliminated
- IndexedFile file = input.getIndexedFile(reference);
- String path;
- if (file != null
- && scope.encloses(path = IndexedFile.convertPath(file.getPath()))) {
- requestor.acceptPackageReference(path, this.pkgName);
- }
+ char[] word = entryResult.getWord();
+ int size = word.length;
+ int tagLength = REF.length;
+ int nameLength = CharOperation.indexOf(SEPARATOR, word, tagLength);
+ if (nameLength < 0) nameLength = size;
+ this.decodedSegment = CharOperation.subarray(word, tagLength, nameLength);
+}
+/**
+ * @see SearchPattern#feedIndexRequestor
+ */
+public void feedIndexRequestor(IIndexSearchRequestor requestor, int detailLevel, int[] references, IndexInput input, IJavaSearchScope scope) throws IOException {
+ for (int i = 0, max = references.length; i < max; i++) {
+ int reference = references[i];
+ if (reference != -1) { // if the reference has not been eliminated
+ IndexedFile file = input.getIndexedFile(reference);
+ String path;
+ if (file != null && scope.encloses(path = IndexedFile.convertPath(file.getPath()))) {
+ requestor.acceptPackageReference(path, this.pkgName);
}
}
}
-
- protected char[][] getPossibleTags() {
- return TAGS;
- }
-
- /**
- * @see AndPattern#hasNextQuery
- */
- protected boolean hasNextQuery() {
- if (this.segments.length > 2) {
- // if package has more than 2 segments, don't look at the first 2 since they are mostly
- // redundant (eg. in 'org.eclipse.jdt.core.*', 'com.ibm' is used all the time)
- return --this.currentSegment >= 2;
- } else {
- return --this.currentSegment >= 0;
- }
- }
-
- /**
- * @see SearchPattern#indexEntryPrefix
- */
- public char[] indexEntryPrefix() {
- return AbstractIndexer.bestReferencePrefix(
- REF,
- this.segments[this.currentSegment],
- matchMode,
- isCaseSensitive);
- }
-
- /**
- * @see SearchPattern#matchContainer
- */
- protected int matchContainer() {
- return COMPILATION_UNIT | CLASS | METHOD | FIELD;
+}
+protected char[][] getPossibleTags() {
+ return TAGS;
+}
+/**
+ * @see AndPattern#hasNextQuery
+ */
+protected boolean hasNextQuery() {
+ if (this.segments.length > 2) {
+ // if package has more than 2 segments, don't look at the first 2 since they are mostly
+ // redundant (eg. in 'org.eclipse.jdt.core.*', 'com.ibm' is used all the time)
+ return --this.currentSegment >= 2;
+ } else {
+ return --this.currentSegment >= 0;
}
-
- /**
- * Returns whether this package reference pattern matches the given tokens.
- */
- private boolean matches(char[][] tokens) {
- char[] name = CharOperation.concatWith(tokens, '.');
- return this.matchesName(this.pkgName, name);
+}
+/**
+ * @see SearchPattern#indexEntryPrefix
+ */
+public char[] indexEntryPrefix() {
+ return AbstractIndexer.bestReferencePrefix(
+ REF,
+ this.segments[this.currentSegment],
+ matchMode,
+ isCaseSensitive);
+}
+/**
+ * @see SearchPattern#matchContainer
+ */
+protected int matchContainer() {
+ return COMPILATION_UNIT | CLASS | METHOD | FIELD;
+}
+/**
+ * Returns whether this package reference pattern matches the given tokens.
+ */
+private boolean matches(char[][] tokens) {
+ char[] name = CharOperation.concatWith(tokens, '.');
+ return this.matchesName(this.pkgName, name);
+}
+/**
+ * @see SearchPattern#matches(AstNode, boolean)
+ */
+protected boolean matches(AstNode node, boolean resolve) {
+ if (node instanceof QualifiedTypeReference) {
+ return this.matches((QualifiedTypeReference)node, resolve);
+ } else if (node instanceof ImportReference) {
+ return this.matches((ImportReference)node, resolve);
+ } else if (node instanceof QualifiedNameReference) {
+ return this.matches((QualifiedNameReference)node, resolve);
}
-
- /**
- * @see SearchPattern#matches(AstNode, boolean)
- */
- protected boolean matches(AstNode node, boolean resolve) {
- if (node instanceof QualifiedTypeReference) {
- return this.matches((QualifiedTypeReference) node, resolve);
- } else
- if (node instanceof ImportReference) {
- return this.matches((ImportReference) node, resolve);
- } else
- if (node instanceof QualifiedNameReference) {
- return this.matches((QualifiedNameReference) node, resolve);
- }
- return false;
+ return false;
+}
+/**
+ * Returns whether this package reference pattern matches the given import reference.
+ * Look at resolved information only if specified.
+ */
+private boolean matches(ImportReference importRef, boolean resolve) {
+ if (importRef.onDemand) {
+ return this.matches(importRef.tokens);
+ } else {
+ int length = importRef.tokens.length - 1;
+ char[][] tokens = new char[length][];
+ System.arraycopy(importRef.tokens, 0, tokens, 0, length);
+ return this.matches(tokens);
}
-
- /**
- * Returns whether this package reference pattern matches the given import reference.
- * Look at resolved information only if specified.
- */
- private boolean matches(ImportReference importRef, boolean resolve) {
- if (importRef.onDemand) {
- return this.matches(importRef.tokens);
- } else {
- int length = importRef.tokens.length - 1;
- char[][] tokens = new char[length][];
- System.arraycopy(importRef.tokens, 0, tokens, 0, length);
- return this.matches(tokens);
+}
+/**
+ * Returns whether this package reference pattern matches the given qualified name reference.
+ * Look at resolved information only if specified.
+ */
+private boolean matches(QualifiedNameReference qNameRef, boolean resolve) {
+ Binding binding = qNameRef.binding;
+ if (!resolve || binding == null || !binding.isValidBinding()) {
+ if (this.pkgName != null) {
+ switch (this.matchMode) {
+ case EXACT_MATCH:
+ case PREFIX_MATCH:
+ return CharOperation.prefixEquals(this.pkgName, CharOperation.concatWith(qNameRef.tokens, '.'), this.isCaseSensitive);
+ case PATTERN_MATCH:
+ char[] pattern = this.pkgName[this.pkgName.length-1] == '*' ? this.pkgName : CharOperation.concat(this.pkgName, ".*".toCharArray());
+ return CharOperation.match(pattern, CharOperation.concatWith(qNameRef.tokens, '.'), this.isCaseSensitive);
+ }
+ }
+ } else {
+ TypeBinding typeBinding = null;
+ char[][] tokens = qNameRef.tokens;
+ int lastIndex = tokens.length-1;
+ switch (qNameRef.bits & Statement.RestrictiveFlagMASK) {
+ case BindingIds.FIELD : // reading a field
+ typeBinding = ((FieldBinding)binding).declaringClass;
+ // no valid match amongst fields
+ int otherBindingsCount = qNameRef.otherBindings == null ? 0 : qNameRef.otherBindings.length;
+ lastIndex -= otherBindingsCount + 1;
+ if (lastIndex < 0) return false;
+ break;
+ case BindingIds.LOCAL : // reading a local variable
+ return false; // no package match in it
+ case BindingIds.TYPE : //=============only type ==============
+ typeBinding = (TypeBinding)binding;
}
+ if (typeBinding instanceof ArrayBinding) {
+ typeBinding = ((ArrayBinding)typeBinding).leafComponentType;
+ }
+ if (typeBinding instanceof ReferenceBinding) {
+ PackageBinding pkgBinding = ((ReferenceBinding)typeBinding).fPackage;
+ return this.matches(pkgBinding.compoundName);
+ }
+ return false;
}
-
- /**
- * Returns whether this package reference pattern matches the given qualified name reference.
- * Look at resolved information only if specified.
- */
- private boolean matches(QualifiedNameReference qNameRef, boolean resolve) {
- Binding binding = qNameRef.binding;
- if (!resolve || binding == null || !binding.isValidBinding()) {
- if (this.pkgName != null) {
- switch (this.matchMode) {
- case EXACT_MATCH :
- case PREFIX_MATCH :
- return CharOperation.prefixEquals(
- this.pkgName,
- CharOperation.concatWith(qNameRef.tokens, '.'),
- this.isCaseSensitive);
- case PATTERN_MATCH :
- char[] pattern =
- this.pkgName[this.pkgName.length - 1] == '*'
- ? this.pkgName
- : CharOperation.concat(this.pkgName, ".*".toCharArray());
- return CharOperation.match(
- pattern,
- CharOperation.concatWith(qNameRef.tokens, '.'),
- this.isCaseSensitive);
- }
- }
- } else {
- TypeBinding typeBinding = null;
- char[][] tokens = qNameRef.tokens;
- int lastIndex = tokens.length - 1;
- switch (qNameRef.bits & Statement.RestrictiveFlagMASK) {
- case BindingIds.FIELD : // reading a field
- typeBinding = ((FieldBinding) binding).declaringClass;
- // no valid match amongst fields
- int otherBindingsCount =
- qNameRef.otherBindings == null ? 0 : qNameRef.otherBindings.length;
- lastIndex -= otherBindingsCount + 1;
- if (lastIndex < 0)
- return false;
- break;
- case BindingIds.LOCAL : // reading a local variable
- return false; // no package match in it
- case BindingIds.TYPE : //=============only type ==============
- typeBinding = (TypeBinding) binding;
+ return true;
+}
+/**
+ * Returns whether this package reference pattern matches the given type reference.
+ * Look at resolved information only if specified.
+ */
+private boolean matches(QualifiedTypeReference typeRef, boolean resolve) {
+ if (!resolve) {
+ if (this.pkgName != null) {
+ switch (this.matchMode) {
+ case EXACT_MATCH:
+ case PREFIX_MATCH:
+ return CharOperation.prefixEquals(this.pkgName, CharOperation.concatWith(typeRef.tokens, '.'), this.isCaseSensitive);
+ case PATTERN_MATCH:
+ char[] pattern = this.pkgName[this.pkgName.length-1] == '*' ? this.pkgName : CharOperation.concat(this.pkgName, ".*".toCharArray());
+ return CharOperation.match(pattern, CharOperation.concatWith(typeRef.tokens, '.'), this.isCaseSensitive);
}
+ }
+ } else {
+ TypeBinding typeBinding = typeRef.binding;
+ if (typeBinding != null){
if (typeBinding instanceof ArrayBinding) {
- typeBinding = ((ArrayBinding) typeBinding).leafComponentType;
+ typeBinding = ((ArrayBinding)typeBinding).leafComponentType;
}
if (typeBinding instanceof ReferenceBinding) {
- PackageBinding pkgBinding = ((ReferenceBinding) typeBinding).fPackage;
+ PackageBinding pkgBinding = ((ReferenceBinding)typeBinding).fPackage;
return this.matches(pkgBinding.compoundName);
}
return false;
}
- return true;
+
}
-
- /**
- * Returns whether this package reference pattern matches the given type reference.
- * Look at resolved information only if specified.
- */
- private boolean matches(QualifiedTypeReference typeRef, boolean resolve) {
- if (!resolve) {
- if (this.pkgName != null) {
- switch (this.matchMode) {
- case EXACT_MATCH :
- case PREFIX_MATCH :
- return CharOperation.prefixEquals(
- this.pkgName,
- CharOperation.concatWith(typeRef.tokens, '.'),
- this.isCaseSensitive);
- case PATTERN_MATCH :
- char[] pattern =
- this.pkgName[this.pkgName.length - 1] == '*'
- ? this.pkgName
- : CharOperation.concat(this.pkgName, ".*".toCharArray());
- return CharOperation.match(
- pattern,
- CharOperation.concatWith(typeRef.tokens, '.'),
- this.isCaseSensitive);
- }
+ return true;
+}
+/**
+ * @see SearchPattern#matchIndexEntry
+ */
+protected boolean matchIndexEntry() {
+ switch(matchMode){
+ case EXACT_MATCH :
+ if (!CharOperation.equals(this.segments[this.currentSegment], this.decodedSegment, isCaseSensitive)){
+ return false;
}
- } else {
- TypeBinding typeBinding = typeRef.binding;
- if (typeBinding != null) {
- if (typeBinding instanceof ArrayBinding) {
- typeBinding = ((ArrayBinding) typeBinding).leafComponentType;
- }
- if (typeBinding instanceof ReferenceBinding) {
- PackageBinding pkgBinding = ((ReferenceBinding) typeBinding).fPackage;
- return this.matches(pkgBinding.compoundName);
- }
+ break;
+ case PREFIX_MATCH :
+ if (!CharOperation.prefixEquals(this.segments[this.currentSegment], this.decodedSegment, isCaseSensitive)){
+ return false;
+ }
+ break;
+ case PATTERN_MATCH :
+ if (!CharOperation.match(this.segments[this.currentSegment], this.decodedSegment, isCaseSensitive)){
return false;
}
-
- }
- return true;
- }
-
- /**
- * @see SearchPattern#matchIndexEntry
- */
- protected boolean matchIndexEntry() {
- switch (matchMode) {
- case EXACT_MATCH :
- if (!CharOperation
- .equals(
- this.segments[this.currentSegment],
- this.decodedSegment,
- isCaseSensitive)) {
- return false;
- }
- break;
- case PREFIX_MATCH :
- if (!CharOperation
- .prefixEquals(
- this.segments[this.currentSegment],
- this.decodedSegment,
- isCaseSensitive)) {
- return false;
- }
- break;
- case PATTERN_MATCH :
- if (!CharOperation
- .match(
- this.segments[this.currentSegment],
- this.decodedSegment,
- isCaseSensitive)) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * @see SearchPattern#matchReportReference
- */
- protected void matchReportReference(
- AstNode reference,
- IJavaElement element,
- int accuracy,
- MatchLocator locator)
- throws CoreException {
- char[][] splitName =
- CharOperation.splitOn('.', this.pkgName == null ? new char[0] : this.pkgName);
- locator.reportQualifiedReference(
- reference.sourceStart,
- reference.sourceEnd,
- splitName,
- element,
- accuracy);
- }
-
- /**
- * @see AndPattern#resetQuery
- */
- protected void resetQuery() {
- /* walk the segments from end to start as it will find less potential references using 'lang' than 'java' */
- this.currentSegment = this.segments.length - 1;
}
-
- public String toString() {
- StringBuffer buffer = new StringBuffer(20);
- buffer.append("PackageReferencePattern: <");
- if (this.pkgName != null)
- buffer.append(this.pkgName);
- buffer.append(">, ");
- switch (matchMode) {
- case EXACT_MATCH :
- buffer.append("exact match, ");
- break;
- case PREFIX_MATCH :
- buffer.append("prefix match, ");
- break;
- case PATTERN_MATCH :
- buffer.append("pattern match, ");
- break;
- }
- if (isCaseSensitive)
- buffer.append("case sensitive");
- else
- buffer.append("case insensitive");
- return buffer.toString();
+ return true;
+}
+/**
+ * @see SearchPattern#matchReportReference
+ */
+protected void matchReportReference(AstNode reference, IJavaElement element, int accuracy, MatchLocator locator) throws CoreException {
+ char[][] splitName = CharOperation.splitOn('.',
+ this.pkgName == null ?
+ new char[0] :
+ this.pkgName);
+ locator.reportQualifiedReference(reference.sourceStart, reference.sourceEnd, splitName, element, accuracy);
+}
+/**
+ * @see AndPattern#resetQuery
+ */
+protected void resetQuery() {
+ /* walk the segments from end to start as it will find less potential references using 'lang' than 'java' */
+ this.currentSegment = this.segments.length - 1;
+}
+public String toString(){
+ StringBuffer buffer = new StringBuffer(20);
+ buffer.append("PackageReferencePattern: <");
+ if (this.pkgName != null) buffer.append(this.pkgName);
+ buffer.append(">, ");
+ switch(matchMode){
+ case EXACT_MATCH :
+ buffer.append("exact match, ");
+ break;
+ case PREFIX_MATCH :
+ buffer.append("prefix match, ");
+ break;
+ case PATTERN_MATCH :
+ buffer.append("pattern match, ");
+ break;
}
-
+ if (isCaseSensitive)
+ buffer.append("case sensitive");
+ else
+ buffer.append("case insensitive");
+ return buffer.toString();
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/SearchPattern.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/SearchPattern.java
index 45b3a22f23..53fef87e7a 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/SearchPattern.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/SearchPattern.java
@@ -24,8 +24,7 @@ import org.eclipse.jdt.internal.core.search.indexing.*;
import java.io.*;
import java.util.*;
-public abstract class SearchPattern
- implements ISearchPattern, IIndexConstants, IJavaSearchConstants {
+public abstract class SearchPattern implements ISearchPattern, IIndexConstants, IJavaSearchConstants {
protected int matchMode;
protected boolean isCaseSensitive;
@@ -41,1414 +40,978 @@ public abstract class SearchPattern
public static final int CLASS = 2;
public static final int FIELD = 4;
public static final int METHOD = 8;
+
+ public static final char[][][] NOT_FOUND_DECLARING_TYPE = new char[0][][];
- public SearchPattern(int matchMode, boolean isCaseSensitive) {
- this.matchMode = matchMode;
- this.isCaseSensitive = isCaseSensitive;
- }
-
- /**
- * Constructor pattern are formed by [declaringQualification.]type[(parameterTypes)]
- * e.g. java.lang.Runnable.run() void
- * main(*)
- */
- private static SearchPattern createConstructorPattern(
- String patternString,
- int limitTo,
- int matchMode,
- boolean isCaseSensitive) {
-
- StringTokenizer tokenizer = new StringTokenizer(patternString, " .(,)", true);
- final int InsideName = 1;
- final int InsideParameter = 2;
- String lastToken = null;
-
- String declaringQualification = null, typeName = null, parameterType = null;
- String[] parameterTypes = null;
- int parameterCount = -1;
- String returnType = null;
- boolean foundClosingParenthesis = false;
- int mode = InsideName;
- while (tokenizer.hasMoreTokens()) {
- String token = tokenizer.nextToken();
- switch (mode) {
-
- // read declaring type and selector
- case InsideName :
- if (token.equals(".")) {
- if (declaringQualification == null) {
- if (typeName == null)
- return null;
- declaringQualification = typeName;
- } else {
- declaringQualification += token + typeName;
+public SearchPattern(int matchMode, boolean isCaseSensitive) {
+ this.matchMode = matchMode;
+ this.isCaseSensitive = isCaseSensitive;
+}
+/**
+ * Constructor pattern are formed by [declaringQualification.]type[(parameterTypes)]
+ * e.g. java.lang.Runnable.run() void
+ * main(*)
+ */
+private static SearchPattern createConstructorPattern(String patternString, int limitTo, int matchMode, boolean isCaseSensitive) {
+
+ StringTokenizer tokenizer = new StringTokenizer(patternString, " .(,)", true);
+ final int InsideName = 1;
+ final int InsideParameter = 2;
+ String lastToken = null;
+
+ String declaringQualification = null, typeName = null, parameterType = null;
+ String[] parameterTypes = null;
+ int parameterCount = -1;
+ String returnType = null;
+ boolean foundClosingParenthesis = false;
+ int mode = InsideName;
+ while (tokenizer.hasMoreTokens()){
+ String token = tokenizer.nextToken();
+ switch(mode){
+
+ // read declaring type and selector
+ case InsideName :
+ if (token.equals(".")){
+ if (declaringQualification == null){
+ if (typeName == null) return null;
+ declaringQualification = typeName;
+ } else {
+ declaringQualification += token + typeName;
+ }
+ typeName = null;
+ } else if (token.equals("(")){
+ parameterTypes = new String[5];
+ parameterCount = 0;
+ mode = InsideParameter;
+ } else if (token.equals(" ")){
+ if (!(" ".equals(lastToken) || ".".equals(lastToken))){
+ break;
+ }
+ } else { // name
+ if (typeName != null) return null;
+ typeName = token;
+ }
+ break;
+ // read parameter types
+ case InsideParameter :
+ if (token.equals(" ")){
+ } else if (token.equals(",")){
+ if (parameterType == null) return null;
+ if (parameterTypes.length == parameterCount){
+ System.arraycopy(parameterTypes, 0, parameterTypes = new String[parameterCount*2], 0, parameterCount);
+ }
+ parameterTypes[parameterCount++] = parameterType;
+ parameterType = null;
+ } else if (token.equals (")")){
+ foundClosingParenthesis = true;
+ if (parameterType != null){
+ if (parameterTypes.length == parameterCount){
+ System.arraycopy(parameterTypes, 0, parameterTypes = new String[parameterCount*2], 0, parameterCount);
}
- typeName = null;
- } else
- if (token.equals("(")) {
- parameterTypes = new String[5];
- parameterCount = 0;
- mode = InsideParameter;
- } else
- if (token.equals(" ")) {
- if (!(" ".equals(lastToken) || ".".equals(lastToken))) {
- break;
- }
- } else { // name
- if (typeName != null)
- return null;
- typeName = token;
- }
- break;
- // read parameter types
- case InsideParameter :
- if (token.equals(" ")) {
- } else
- if (token.equals(",")) {
- if (parameterType == null)
- return null;
- if (parameterTypes.length == parameterCount) {
- System.arraycopy(
- parameterTypes,
- 0,
- parameterTypes = new String[parameterCount * 2],
- 0,
- parameterCount);
- }
- parameterTypes[parameterCount++] = parameterType;
- parameterType = null;
- } else
- if (token.equals(")")) {
- foundClosingParenthesis = true;
- if (parameterType != null) {
- if (parameterTypes.length == parameterCount) {
- System.arraycopy(
- parameterTypes,
- 0,
- parameterTypes = new String[parameterCount * 2],
- 0,
- parameterCount);
- }
- parameterTypes[parameterCount++] = parameterType;
- }
- break;
- } else {
- if (parameterType == null) {
- parameterType = token;
- } else {
- if (!(".".equals(lastToken) || ".".equals(token) || "[]".equals(token)))
- return null;
- parameterType += token;
- }
- }
+ parameterTypes[parameterCount++] = parameterType;
+ }
break;
- }
- lastToken = token;
- }
- // parenthesis mismatch
- if (parameterCount > 0 && !foundClosingParenthesis)
- return null;
- if (typeName == null)
- return null;
-
- char[] typeNameChars = typeName.toCharArray();
- if (typeNameChars.length == 1 && typeNameChars[0] == '*')
- typeNameChars = null;
-
- char[] declaringQualificationChars = null;
- if (declaringQualification != null)
- declaringQualificationChars = declaringQualification.toCharArray();
- char[][] parameterTypeQualifications = null, parameterTypeSimpleNames = null;
-
- // extract parameter types infos
- if (parameterCount >= 0) {
- parameterTypeQualifications = new char[parameterCount][];
- parameterTypeSimpleNames = new char[parameterCount][];
- for (int i = 0; i < parameterCount; i++) {
- char[] parameterTypePart = parameterTypes[i].toCharArray();
- int lastDotPosition = CharOperation.lastIndexOf('.', parameterTypePart);
- if (lastDotPosition >= 0) {
- parameterTypeQualifications[i] =
- CharOperation.subarray(parameterTypePart, 0, lastDotPosition);
- if (parameterTypeQualifications[i].length == 1
- && parameterTypeQualifications[i][0] == '*')
- parameterTypeQualifications[i] = null;
- parameterTypeSimpleNames[i] =
- CharOperation.subarray(
- parameterTypePart,
- lastDotPosition + 1,
- parameterTypePart.length);
} else {
- parameterTypeQualifications[i] = null;
- parameterTypeSimpleNames[i] = parameterTypePart;
+ if (parameterType == null){
+ parameterType = token;
+ } else {
+ if (!(".".equals(lastToken) || ".".equals(token) || "[]".equals(token))) return null;
+ parameterType += token;
+ }
}
- if (parameterTypeSimpleNames[i].length == 1
- && parameterTypeSimpleNames[i][0] == '*')
- parameterTypeSimpleNames[i] = null;
- }
- }
- SearchPattern searchPattern = null;
- switch (limitTo) {
- case IJavaSearchConstants.DECLARATIONS :
- searchPattern =
- new ConstructorDeclarationPattern(
- typeNameChars,
- matchMode,
- isCaseSensitive,
- declaringQualificationChars,
- parameterTypeQualifications,
- parameterTypeSimpleNames);
- break;
- case IJavaSearchConstants.REFERENCES :
- searchPattern =
- new ConstructorReferencePattern(
- typeNameChars,
- matchMode,
- isCaseSensitive,
- declaringQualificationChars,
- parameterTypeQualifications,
- parameterTypeSimpleNames);
- break;
- case IJavaSearchConstants.ALL_OCCURRENCES :
- searchPattern =
- new OrPattern(
- new ConstructorDeclarationPattern(
- typeNameChars,
- matchMode,
- isCaseSensitive,
- declaringQualificationChars,
- parameterTypeQualifications,
- parameterTypeSimpleNames),
- new ConstructorReferencePattern(
- typeNameChars,
- matchMode,
- isCaseSensitive,
- declaringQualificationChars,
- parameterTypeQualifications,
- parameterTypeSimpleNames));
break;
}
- return searchPattern;
-
+ lastToken = token;
}
-
- /**
- * Field pattern are formed by [declaringType.]name[type]
- * e.g. java.lang.Runnable.run() void
- * main(*)
- */
- private static SearchPattern createFieldPattern(
- String patternString,
- int limitTo,
- int matchMode,
- boolean isCaseSensitive) {
-
- StringTokenizer tokenizer = new StringTokenizer(patternString, " .(,)", true);
- final int InsideDeclaringPart = 1;
- final int InsideType = 2;
- String lastToken = null;
-
- String declaringType = null, fieldName = null, parameterType = null;
- String type = null;
- boolean foundClosingParenthesis = false;
- int mode = InsideDeclaringPart;
- while (tokenizer.hasMoreTokens()) {
- String token = tokenizer.nextToken();
- switch (mode) {
-
- // read declaring type and fieldName
- case InsideDeclaringPart :
- if (token.equals(".")) {
- if (declaringType == null) {
- if (fieldName == null)
- return null;
- declaringType = fieldName;
- } else {
- declaringType += token + fieldName;
- }
- fieldName = null;
- } else
- if (token.equals(" ")) {
- if (!(" ".equals(lastToken) || ".".equals(lastToken))) {
- mode = InsideType;
- }
- } else { // name
- if (fieldName != null)
- return null;
- fieldName = token;
- }
- break;
- // read type
- case InsideType :
- if (!token.equals(" ")) {
- if (type == null) {
- type = token;
- } else {
- if (!(!(".".equals(lastToken) || ".".equals(token) || "[]".equals(token))))
- return null;
- type += token;
- }
- }
- }
- lastToken = token;
- }
- if (fieldName == null)
- return null;
-
- char[] fieldNameChars = fieldName.toCharArray();
- if (fieldNameChars.length == 1 && fieldNameChars[0] == '*')
- fieldNameChars = null;
-
- char[] declaringTypeQualification = null, declaringTypeSimpleName = null;
- char[] typeQualification = null, typeSimpleName = null;
-
- // extract declaring type infos
- if (declaringType != null) {
- char[] declaringTypePart = declaringType.toCharArray();
- int lastDotPosition = CharOperation.lastIndexOf('.', declaringTypePart);
- if (lastDotPosition >= 0) {
- declaringTypeQualification =
- CharOperation.subarray(declaringTypePart, 0, lastDotPosition);
- if (declaringTypeQualification.length == 1
- && declaringTypeQualification[0] == '*')
- declaringTypeQualification = null;
- declaringTypeSimpleName =
- CharOperation.subarray(
- declaringTypePart,
- lastDotPosition + 1,
- declaringTypePart.length);
+ // parenthesis mismatch
+ if (parameterCount>0 && !foundClosingParenthesis) return null;
+ if (typeName == null) return null;
+
+ char[] typeNameChars = typeName.toCharArray();
+ if (typeNameChars.length == 1 && typeNameChars[0] == '*') typeNameChars = null;
+
+ char[] declaringQualificationChars = null;
+ if (declaringQualification != null) declaringQualificationChars = declaringQualification.toCharArray();
+ char[][] parameterTypeQualifications = null, parameterTypeSimpleNames = null;
+
+ // extract parameter types infos
+ if (parameterCount >= 0){
+ parameterTypeQualifications = new char[parameterCount][];
+ parameterTypeSimpleNames = new char[parameterCount][];
+ for (int i = 0; i < parameterCount; i++){
+ char[] parameterTypePart = parameterTypes[i].toCharArray();
+ int lastDotPosition = CharOperation.lastIndexOf('.', parameterTypePart);
+ if (lastDotPosition >= 0){
+ parameterTypeQualifications[i] = CharOperation.subarray(parameterTypePart, 0, lastDotPosition);
+ if (parameterTypeQualifications[i].length == 1 && parameterTypeQualifications[i][0] == '*') parameterTypeQualifications[i] = null;
+ parameterTypeSimpleNames[i] = CharOperation.subarray(parameterTypePart, lastDotPosition+1, parameterTypePart.length);
} else {
- declaringTypeQualification = null;
- declaringTypeSimpleName = declaringTypePart;
+ parameterTypeQualifications[i] = null;
+ parameterTypeSimpleNames[i] = parameterTypePart;
}
- if (declaringTypeSimpleName.length == 1 && declaringTypeSimpleName[0] == '*')
- declaringTypeSimpleName = null;
+ if (parameterTypeSimpleNames[i].length == 1 && parameterTypeSimpleNames[i][0] == '*') parameterTypeSimpleNames[i] = null;
}
- // extract type infos
- if (type != null) {
- char[] typePart = type.toCharArray();
- int lastDotPosition = CharOperation.lastIndexOf('.', typePart);
- if (lastDotPosition >= 0) {
- typeQualification = CharOperation.subarray(typePart, 0, lastDotPosition);
- if (typeQualification.length == 1 && typeQualification[0] == '*')
- typeQualification = null;
- typeSimpleName =
- CharOperation.subarray(typePart, lastDotPosition + 1, typePart.length);
- } else {
- typeQualification = null;
- typeSimpleName = typePart;
- }
- if (typeSimpleName.length == 1 && typeSimpleName[0] == '*')
- typeSimpleName = null;
- }
- SearchPattern searchPattern = null;
- switch (limitTo) {
- case IJavaSearchConstants.DECLARATIONS :
- searchPattern =
- new FieldDeclarationPattern(
- fieldNameChars,
- matchMode,
- isCaseSensitive,
- declaringTypeQualification,
- declaringTypeSimpleName,
- typeQualification,
- typeSimpleName);
- break;
- case IJavaSearchConstants.REFERENCES :
- searchPattern =
- new FieldReferencePattern(
- fieldNameChars,
- matchMode,
- isCaseSensitive,
- declaringTypeQualification,
- declaringTypeSimpleName,
- typeQualification,
- typeSimpleName);
- break;
- case IJavaSearchConstants.ALL_OCCURRENCES :
- searchPattern =
- new OrPattern(
- new FieldDeclarationPattern(
- fieldNameChars,
- matchMode,
- isCaseSensitive,
- declaringTypeQualification,
- declaringTypeSimpleName,
- typeQualification,
- typeSimpleName),
- new FieldReferencePattern(
- fieldNameChars,
- matchMode,
- isCaseSensitive,
- declaringTypeQualification,
- declaringTypeSimpleName,
- typeQualification,
- typeSimpleName));
- break;
- }
- return searchPattern;
-
+ }
+ SearchPattern searchPattern = null;
+ switch (limitTo){
+ case IJavaSearchConstants.DECLARATIONS :
+ searchPattern = new ConstructorDeclarationPattern(typeNameChars, matchMode, isCaseSensitive, declaringQualificationChars, parameterTypeQualifications, parameterTypeSimpleNames);
+ break;
+ case IJavaSearchConstants.REFERENCES :
+ searchPattern = new ConstructorReferencePattern(typeNameChars, matchMode, isCaseSensitive, declaringQualificationChars, parameterTypeQualifications, parameterTypeSimpleNames);
+ break;
+ case IJavaSearchConstants.ALL_OCCURRENCES :
+ searchPattern = new OrPattern(
+ new ConstructorDeclarationPattern(typeNameChars, matchMode, isCaseSensitive, declaringQualificationChars, parameterTypeQualifications, parameterTypeSimpleNames),
+ new ConstructorReferencePattern(typeNameChars, matchMode, isCaseSensitive, declaringQualificationChars, parameterTypeQualifications, parameterTypeSimpleNames));
+ break;
}
+ return searchPattern;
- /**
- * Method pattern are formed by [declaringType.]selector[(parameterTypes)][returnType]
- * e.g. java.lang.Runnable.run() void
- * main(*)
- */
- private static SearchPattern createMethodPattern(
- String patternString,
- int limitTo,
- int matchMode,
- boolean isCaseSensitive) {
-
- StringTokenizer tokenizer = new StringTokenizer(patternString, " .(,)", true);
- final int InsideSelector = 1;
- final int InsideParameter = 2;
- final int InsideReturnType = 3;
- String lastToken = null;
-
- String declaringType = null, selector = null, parameterType = null;
- String[] parameterTypes = null;
- int parameterCount = -1;
- String returnType = null;
- boolean foundClosingParenthesis = false;
- int mode = InsideSelector;
- while (tokenizer.hasMoreTokens()) {
- String token = tokenizer.nextToken();
- switch (mode) {
-
- // read declaring type and selector
- case InsideSelector :
- if (token.equals(".")) {
- if (declaringType == null) {
- if (selector == null)
- return null;
- declaringType = selector;
- } else {
- declaringType += token + selector;
- }
- selector = null;
- } else
- if (token.equals("(")) {
- parameterTypes = new String[5];
- parameterCount = 0;
- mode = InsideParameter;
- } else
- if (token.equals(" ")) {
- if (!(" ".equals(lastToken) || ".".equals(lastToken))) {
- mode = InsideReturnType;
- }
- } else { // name
- if (selector != null)
- return null;
- selector = token;
- }
- break;
- // read parameter types
- case InsideParameter :
- if (token.equals(" ")) {
- } else
- if (token.equals(",")) {
- if (parameterType == null)
- return null;
- if (parameterTypes.length == parameterCount) {
- System.arraycopy(
- parameterTypes,
- 0,
- parameterTypes = new String[parameterCount * 2],
- 0,
- parameterCount);
- }
- parameterTypes[parameterCount++] = parameterType;
- parameterType = null;
- } else
- if (token.equals(")")) {
- foundClosingParenthesis = true;
- if (parameterType != null) {
- if (parameterTypes.length == parameterCount) {
- System.arraycopy(
- parameterTypes,
- 0,
- parameterTypes = new String[parameterCount * 2],
- 0,
- parameterCount);
- }
- parameterTypes[parameterCount++] = parameterType;
- }
- mode = InsideReturnType;
- } else {
- if (parameterType == null) {
- parameterType = token;
- } else {
- if (!(".".equals(lastToken) || ".".equals(token) || "[]".equals(token)))
- return null;
- parameterType += token;
- }
- }
- break;
- // read return type
- case InsideReturnType :
- if (!token.equals(" ")) {
- if (returnType == null) {
- returnType = token;
- } else {
- if (!(!(".".equals(lastToken) || ".".equals(token) || "[]".equals(token))))
- return null;
- returnType += token;
- }
+}
+/**
+ * Field pattern are formed by [declaringType.]name[type]
+ * e.g. java.lang.Runnable.run() void
+ * main(*)
+ */
+private static SearchPattern createFieldPattern(String patternString, int limitTo, int matchMode, boolean isCaseSensitive) {
+
+ StringTokenizer tokenizer = new StringTokenizer(patternString, " .(,)", true);
+ final int InsideDeclaringPart = 1;
+ final int InsideType = 2;
+ String lastToken = null;
+
+ String declaringType = null, fieldName = null, parameterType = null;
+ String type = null;
+ boolean foundClosingParenthesis = false;
+ int mode = InsideDeclaringPart;
+ while (tokenizer.hasMoreTokens()){
+ String token = tokenizer.nextToken();
+ switch(mode){
+
+ // read declaring type and fieldName
+ case InsideDeclaringPart :
+ if (token.equals(".")){
+ if (declaringType == null){
+ if (fieldName == null) return null;
+ declaringType = fieldName;
+ } else {
+ declaringType += token + fieldName;
}
- }
- lastToken = token;
- }
- // parenthesis mismatch
- if (parameterCount > 0 && !foundClosingParenthesis)
- return null;
- if (selector == null)
- return null;
-
- char[] selectorChars = selector.toCharArray();
- if (selectorChars.length == 1 && selectorChars[0] == '*')
- selectorChars = null;
-
- char[] declaringTypeQualification = null, declaringTypeSimpleName = null;
- char[] returnTypeQualification = null, returnTypeSimpleName = null;
- char[][] parameterTypeQualifications = null, parameterTypeSimpleNames = null;
-
- // extract declaring type infos
- if (declaringType != null) {
- char[] declaringTypePart = declaringType.toCharArray();
- int lastDotPosition = CharOperation.lastIndexOf('.', declaringTypePart);
- if (lastDotPosition >= 0) {
- declaringTypeQualification =
- CharOperation.subarray(declaringTypePart, 0, lastDotPosition);
- if (declaringTypeQualification.length == 1
- && declaringTypeQualification[0] == '*')
- declaringTypeQualification = null;
- declaringTypeSimpleName =
- CharOperation.subarray(
- declaringTypePart,
- lastDotPosition + 1,
- declaringTypePart.length);
- } else {
- declaringTypeQualification = null;
- declaringTypeSimpleName = declaringTypePart;
- }
- if (declaringTypeSimpleName.length == 1 && declaringTypeSimpleName[0] == '*')
- declaringTypeSimpleName = null;
- }
- // extract parameter types infos
- if (parameterCount >= 0) {
- parameterTypeQualifications = new char[parameterCount][];
- parameterTypeSimpleNames = new char[parameterCount][];
- for (int i = 0; i < parameterCount; i++) {
- char[] parameterTypePart = parameterTypes[i].toCharArray();
- int lastDotPosition = CharOperation.lastIndexOf('.', parameterTypePart);
- if (lastDotPosition >= 0) {
- parameterTypeQualifications[i] =
- CharOperation.subarray(parameterTypePart, 0, lastDotPosition);
- if (parameterTypeQualifications[i].length == 1
- && parameterTypeQualifications[i][0] == '*')
- parameterTypeQualifications[i] = null;
- parameterTypeSimpleNames[i] =
- CharOperation.subarray(
- parameterTypePart,
- lastDotPosition + 1,
- parameterTypePart.length);
- } else {
- parameterTypeQualifications[i] = null;
- parameterTypeSimpleNames[i] = parameterTypePart;
+ fieldName = null;
+ } else if (token.equals(" ")){
+ if (!(" ".equals(lastToken) || ".".equals(lastToken))){
+ mode = InsideType;
+ }
+ } else { // name
+ if (fieldName != null) return null;
+ fieldName = token;
}
- if (parameterTypeSimpleNames[i].length == 1
- && parameterTypeSimpleNames[i][0] == '*')
- parameterTypeSimpleNames[i] = null;
- }
- }
- // extract return type infos
- if (returnType != null) {
- char[] returnTypePart = returnType.toCharArray();
- int lastDotPosition = CharOperation.lastIndexOf('.', returnTypePart);
- if (lastDotPosition >= 0) {
- returnTypeQualification =
- CharOperation.subarray(returnTypePart, 0, lastDotPosition);
- if (returnTypeQualification.length == 1 && returnTypeQualification[0] == '*')
- returnTypeQualification = null;
- returnTypeSimpleName =
- CharOperation.subarray(
- returnTypePart,
- lastDotPosition + 1,
- returnTypePart.length);
- } else {
- returnTypeQualification = null;
- returnTypeSimpleName = returnTypePart;
- }
- if (returnTypeSimpleName.length == 1 && returnTypeSimpleName[0] == '*')
- returnTypeSimpleName = null;
- }
- SearchPattern searchPattern = null;
- switch (limitTo) {
- case IJavaSearchConstants.DECLARATIONS :
- searchPattern =
- new MethodDeclarationPattern(
- selectorChars,
- matchMode,
- isCaseSensitive,
- declaringTypeQualification,
- declaringTypeSimpleName,
- returnTypeQualification,
- returnTypeSimpleName,
- parameterTypeQualifications,
- parameterTypeSimpleNames);
- break;
- case IJavaSearchConstants.REFERENCES :
- searchPattern =
- new MethodReferencePattern(
- selectorChars,
- matchMode,
- isCaseSensitive,
- declaringTypeQualification,
- declaringTypeSimpleName,
- returnTypeQualification,
- returnTypeSimpleName,
- parameterTypeQualifications,
- parameterTypeSimpleNames);
- break;
- case IJavaSearchConstants.ALL_OCCURRENCES :
- searchPattern =
- new OrPattern(
- new MethodDeclarationPattern(
- selectorChars,
- matchMode,
- isCaseSensitive,
- declaringTypeQualification,
- declaringTypeSimpleName,
- returnTypeQualification,
- returnTypeSimpleName,
- parameterTypeQualifications,
- parameterTypeSimpleNames),
- new MethodReferencePattern(
- selectorChars,
- matchMode,
- isCaseSensitive,
- declaringTypeQualification,
- declaringTypeSimpleName,
- returnTypeQualification,
- returnTypeSimpleName,
- parameterTypeQualifications,
- parameterTypeSimpleNames));
break;
+ // read type
+ case InsideType:
+ if (!token.equals(" ")){
+ if (type == null){
+ type = token;
+ } else {
+ if (!(!(".".equals(lastToken) || ".".equals(token) || "[]".equals(token)))) return null;
+ type += token;
+ }
+ }
}
- return searchPattern;
-
+ lastToken = token;
}
-
- private static SearchPattern createPackagePattern(
- String patternString,
- int limitTo,
- int matchMode,
- boolean isCaseSensitive) {
- SearchPattern searchPattern = null;
- switch (limitTo) {
- case IJavaSearchConstants.DECLARATIONS :
- searchPattern =
- new PackageDeclarationPattern(
- patternString.toCharArray(),
- matchMode,
- isCaseSensitive);
- break;
- case IJavaSearchConstants.REFERENCES :
- searchPattern =
- new PackageReferencePattern(
- patternString.toCharArray(),
- matchMode,
- isCaseSensitive);
- break;
- case IJavaSearchConstants.ALL_OCCURRENCES :
- searchPattern =
- new OrPattern(
- new PackageDeclarationPattern(
- patternString.toCharArray(),
- matchMode,
- isCaseSensitive),
- new PackageReferencePattern(
- patternString.toCharArray(),
- matchMode,
- isCaseSensitive));
- break;
+ if (fieldName == null) return null;
+
+ char[] fieldNameChars = fieldName.toCharArray();
+ if (fieldNameChars.length == 1 && fieldNameChars[0] == '*') fieldNameChars = null;
+
+ char[] declaringTypeQualification = null, declaringTypeSimpleName = null;
+ char[] typeQualification = null, typeSimpleName = null;
+
+ // extract declaring type infos
+ if (declaringType != null){
+ char[] declaringTypePart = declaringType.toCharArray();
+ int lastDotPosition = CharOperation.lastIndexOf('.', declaringTypePart);
+ if (lastDotPosition >= 0){
+ declaringTypeQualification = CharOperation.subarray(declaringTypePart, 0, lastDotPosition);
+ if (declaringTypeQualification.length == 1 && declaringTypeQualification[0] == '*') declaringTypeQualification = null;
+ declaringTypeSimpleName = CharOperation.subarray(declaringTypePart, lastDotPosition+1, declaringTypePart.length);
+ } else {
+ declaringTypeQualification = null;
+ declaringTypeSimpleName = declaringTypePart;
}
- return searchPattern;
-
+ if (declaringTypeSimpleName.length == 1 && declaringTypeSimpleName[0] == '*') declaringTypeSimpleName = null;
}
-
- public static SearchPattern createPattern(
- String patternString,
- int searchFor,
- int limitTo,
- int matchMode,
- boolean isCaseSensitive) {
-
- if (patternString == null || patternString.length() == 0)
- return null;
-
- SearchPattern searchPattern = null;
- switch (searchFor) {
-
- case IJavaSearchConstants.TYPE :
- searchPattern =
- createTypePattern(patternString, limitTo, matchMode, isCaseSensitive);
- break;
- case IJavaSearchConstants.METHOD :
- searchPattern =
- createMethodPattern(patternString, limitTo, matchMode, isCaseSensitive);
- break;
- case IJavaSearchConstants.CONSTRUCTOR :
- searchPattern =
- createConstructorPattern(patternString, limitTo, matchMode, isCaseSensitive);
- break;
- case IJavaSearchConstants.FIELD :
- searchPattern =
- createFieldPattern(patternString, limitTo, matchMode, isCaseSensitive);
- break;
- case IJavaSearchConstants.PACKAGE :
- searchPattern =
- createPackagePattern(patternString, limitTo, matchMode, isCaseSensitive);
+ // extract type infos
+ if (type != null){
+ char[] typePart = type.toCharArray();
+ int lastDotPosition = CharOperation.lastIndexOf('.', typePart);
+ if (lastDotPosition >= 0){
+ typeQualification = CharOperation.subarray(typePart, 0, lastDotPosition);
+ if (typeQualification.length == 1 && typeQualification[0] == '*') typeQualification = null;
+ typeSimpleName = CharOperation.subarray(typePart, lastDotPosition+1, typePart.length);
+ } else {
+ typeQualification = null;
+ typeSimpleName = typePart;
}
- return searchPattern;
+ if (typeSimpleName.length == 1 && typeSimpleName[0] == '*') typeSimpleName = null;
+ }
+ SearchPattern searchPattern = null;
+ switch (limitTo){
+ case IJavaSearchConstants.DECLARATIONS :
+ searchPattern = new FieldDeclarationPattern(fieldNameChars, matchMode, isCaseSensitive, declaringTypeQualification, declaringTypeSimpleName, typeQualification, typeSimpleName);
+ break;
+ case IJavaSearchConstants.REFERENCES :
+ searchPattern = new FieldReferencePattern(fieldNameChars, matchMode, isCaseSensitive, declaringTypeQualification, declaringTypeSimpleName, typeQualification, typeSimpleName);
+ break;
+ case IJavaSearchConstants.ALL_OCCURRENCES :
+ searchPattern = new OrPattern(
+ new FieldDeclarationPattern(fieldNameChars, matchMode, isCaseSensitive, declaringTypeQualification, declaringTypeSimpleName, typeQualification, typeSimpleName),
+ new FieldReferencePattern(fieldNameChars, matchMode, isCaseSensitive, declaringTypeQualification, declaringTypeSimpleName, typeQualification, typeSimpleName));
+ break;
}
+ return searchPattern;
- public static SearchPattern createPattern(IJavaElement element, int limitTo) {
- SearchPattern searchPattern = null;
- int lastDot;
- switch (element.getElementType()) {
- case IJavaElement.FIELD :
- IField field = (IField) element;
- String fullDeclaringName =
- field.getDeclaringType().getFullyQualifiedName().replace('$', '.');
- ;
- lastDot = fullDeclaringName.lastIndexOf('.');
- char[] declaringSimpleName =
- (lastDot != -1 ? fullDeclaringName.substring(lastDot + 1) : fullDeclaringName)
- .toCharArray();
- char[] declaringQualification =
- lastDot != -1 ? fullDeclaringName.substring(0, lastDot).toCharArray() : null;
- char[] name = field.getElementName().toCharArray();
- char[] typeSimpleName;
- char[] typeQualification;
- try {
- String typeSignature =
- Signature.toString(field.getTypeSignature()).replace('$', '.');
- lastDot = typeSignature.lastIndexOf('.');
- typeSimpleName =
- (lastDot != -1 ? typeSignature.substring(lastDot + 1) : typeSignature)
- .toCharArray();
- typeQualification =
- lastDot != -1 ? typeSignature.substring(0, lastDot).toCharArray() : null;
- } catch (JavaModelException e) {
- return null;
- }
- switch (limitTo) {
- case IJavaSearchConstants.DECLARATIONS :
- searchPattern =
- new FieldDeclarationPattern(
- name,
- EXACT_MATCH,
- CASE_SENSITIVE,
- declaringQualification,
- declaringSimpleName,
- typeQualification,
- typeSimpleName);
- break;
- case IJavaSearchConstants.REFERENCES :
- searchPattern =
- new FieldReferencePattern(
- name,
- EXACT_MATCH,
- CASE_SENSITIVE,
- declaringQualification,
- declaringSimpleName,
- typeQualification,
- typeSimpleName);
- break;
- case IJavaSearchConstants.ALL_OCCURRENCES :
- searchPattern =
- new OrPattern(
- new FieldDeclarationPattern(
- name,
- EXACT_MATCH,
- CASE_SENSITIVE,
- declaringQualification,
- declaringSimpleName,
- typeQualification,
- typeSimpleName),
- new FieldReferencePattern(
- name,
- EXACT_MATCH,
- CASE_SENSITIVE,
- declaringQualification,
- declaringSimpleName,
- typeQualification,
- typeSimpleName));
- break;
+}
+/**
+ * Method pattern are formed by [declaringType.]selector[(parameterTypes)][returnType]
+ * e.g. java.lang.Runnable.run() void
+ * main(*)
+ */
+private static SearchPattern createMethodPattern(String patternString, int limitTo, int matchMode, boolean isCaseSensitive) {
+
+ StringTokenizer tokenizer = new StringTokenizer(patternString, " .(,)", true);
+ final int InsideSelector = 1;
+ final int InsideParameter = 2;
+ final int InsideReturnType = 3;
+ String lastToken = null;
+
+ String declaringType = null, selector = null, parameterType = null;
+ String[] parameterTypes = null;
+ int parameterCount = -1;
+ String returnType = null;
+ boolean foundClosingParenthesis = false;
+ int mode = InsideSelector;
+ while (tokenizer.hasMoreTokens()){
+ String token = tokenizer.nextToken();
+ switch(mode){
+
+ // read declaring type and selector
+ case InsideSelector :
+ if (token.equals(".")){
+ if (declaringType == null){
+ if (selector == null) return null;
+ declaringType = selector;
+ } else {
+ declaringType += token + selector;
+ }
+ selector = null;
+ } else if (token.equals("(")){
+ parameterTypes = new String[5];
+ parameterCount = 0;
+ mode = InsideParameter;
+ } else if (token.equals(" ")){
+ if (!(" ".equals(lastToken) || ".".equals(lastToken))){
+ mode = InsideReturnType;
+ }
+ } else { // name
+ if (selector != null) return null;
+ selector = token;
}
break;
- case IJavaElement.IMPORT_DECLARATION :
- String elementName = element.getElementName();
- IImportDeclaration importDecl = (IImportDeclaration) element;
- if (importDecl.isOnDemand()) {
- lastDot = elementName.lastIndexOf('.');
- if (lastDot == -1)
- return null; // invalid import declaration
- searchPattern =
- createPackagePattern(
- elementName.substring(0, lastDot),
- limitTo,
- EXACT_MATCH,
- CASE_SENSITIVE);
+ // read parameter types
+ case InsideParameter :
+ if (token.equals(" ")){
+ } else if (token.equals(",")){
+ if (parameterType == null) return null;
+ if (parameterTypes.length == parameterCount){
+ System.arraycopy(parameterTypes, 0, parameterTypes = new String[parameterCount*2], 0, parameterCount);
+ }
+ parameterTypes[parameterCount++] = parameterType;
+ parameterType = null;
+ } else if (token.equals (")")){
+ foundClosingParenthesis = true;
+ if (parameterType != null){
+ if (parameterTypes.length == parameterCount){
+ System.arraycopy(parameterTypes, 0, parameterTypes = new String[parameterCount*2], 0, parameterCount);
+ }
+ parameterTypes[parameterCount++] = parameterType;
+ }
+ mode = InsideReturnType;
} else {
- searchPattern = createTypePattern(elementName, limitTo);
+ if (parameterType == null){
+ parameterType = token;
+ } else {
+ if (!(".".equals(lastToken) || ".".equals(token) || "[]".equals(token))) return null;
+ parameterType += token;
+ }
}
break;
- case IJavaElement.METHOD :
- IMethod method = (IMethod) element;
- boolean isConstructor;
- try {
- isConstructor = method.isConstructor();
- } catch (JavaModelException e) {
- return null;
- }
- fullDeclaringName =
- method.getDeclaringType().getFullyQualifiedName().replace('$', '.');
- lastDot = fullDeclaringName.lastIndexOf('.');
- declaringSimpleName =
- (lastDot != -1 ? fullDeclaringName.substring(lastDot + 1) : fullDeclaringName)
- .toCharArray();
- declaringQualification =
- lastDot != -1 ? fullDeclaringName.substring(0, lastDot).toCharArray() : null;
- char[] selector = method.getElementName().toCharArray();
- char[] returnSimpleName;
- char[] returnQualification;
- try {
- String returnType =
- Signature.toString(method.getReturnType()).replace('$', '.');
- lastDot = returnType.lastIndexOf('.');
- returnSimpleName =
- (lastDot != -1 ? returnType.substring(lastDot + 1) : returnType).toCharArray();
- returnQualification =
- lastDot != -1 ? returnType.substring(0, lastDot).toCharArray() : null;
- } catch (JavaModelException e) {
- return null;
- }
- String[] parameterTypes = method.getParameterTypes();
- int paramCount = parameterTypes.length;
- char[][] parameterSimpleNames = new char[paramCount][];
- char[][] parameterQualifications = new char[paramCount][];
- for (int i = 0; i < paramCount; i++) {
- String signature = Signature.toString(parameterTypes[i]).replace('$', '.');
- lastDot = signature.lastIndexOf('.');
- parameterSimpleNames[i] =
- (lastDot != -1 ? signature.substring(lastDot + 1) : signature).toCharArray();
- parameterQualifications[i] =
- lastDot != -1 ? signature.substring(0, lastDot).toCharArray() : null;
- }
- switch (limitTo) {
- case IJavaSearchConstants.DECLARATIONS :
- if (isConstructor) {
- searchPattern =
- new ConstructorDeclarationPattern(
- declaringSimpleName,
- EXACT_MATCH,
- CASE_SENSITIVE,
- declaringQualification,
- parameterQualifications,
- parameterSimpleNames);
- } else {
- searchPattern =
- new MethodDeclarationPattern(
- selector,
- EXACT_MATCH,
- CASE_SENSITIVE,
- declaringQualification,
- declaringSimpleName,
- returnQualification,
- returnSimpleName,
- parameterQualifications,
- parameterSimpleNames);
- }
- break;
- case IJavaSearchConstants.REFERENCES :
- if (isConstructor) {
- searchPattern =
- new ConstructorReferencePattern(
- declaringSimpleName,
- EXACT_MATCH,
- CASE_SENSITIVE,
- declaringQualification,
- parameterQualifications,
- parameterSimpleNames);
- } else {
- searchPattern =
- new MethodReferencePattern(
- selector,
- EXACT_MATCH,
- CASE_SENSITIVE,
- declaringQualification,
- declaringSimpleName,
- returnQualification,
- returnSimpleName,
- parameterQualifications,
- parameterSimpleNames);
- }
- break;
- case IJavaSearchConstants.ALL_OCCURRENCES :
- if (isConstructor) {
- searchPattern =
- new OrPattern(
- new ConstructorDeclarationPattern(
- declaringSimpleName,
- EXACT_MATCH,
- CASE_SENSITIVE,
- declaringQualification,
- parameterQualifications,
- parameterSimpleNames),
- new ConstructorReferencePattern(
- declaringSimpleName,
- EXACT_MATCH,
- CASE_SENSITIVE,
- declaringQualification,
- parameterQualifications,
- parameterSimpleNames));
- } else {
- searchPattern =
- new OrPattern(
- new MethodDeclarationPattern(
- selector,
- EXACT_MATCH,
- CASE_SENSITIVE,
- declaringQualification,
- declaringSimpleName,
- returnQualification,
- returnSimpleName,
- parameterQualifications,
- parameterSimpleNames),
- new MethodReferencePattern(
- selector,
- EXACT_MATCH,
- CASE_SENSITIVE,
- declaringQualification,
- declaringSimpleName,
- returnQualification,
- returnSimpleName,
- parameterQualifications,
- parameterSimpleNames));
- }
- break;
+ // read return type
+ case InsideReturnType:
+ if (!token.equals(" ")){
+ if (returnType == null){
+ returnType = token;
+ } else {
+ if (!(!(".".equals(lastToken) || ".".equals(token) || "[]".equals(token)))) return null;
+ returnType += token;
+ }
}
- break;
- case IJavaElement.TYPE :
- IType type = (IType) element;
- searchPattern = createTypePattern(type.getFullyQualifiedName(), limitTo);
- break;
- case IJavaElement.PACKAGE_DECLARATION :
- case IJavaElement.PACKAGE_FRAGMENT :
- searchPattern =
- createPackagePattern(
- element.getElementName(),
- limitTo,
- EXACT_MATCH,
- CASE_SENSITIVE);
- break;
}
- return searchPattern;
+ lastToken = token;
}
-
- private static SearchPattern createTypePattern(
- String fullyQualifiedName,
- int limitTo) {
- SearchPattern searchPattern = null;
- int lastDot = fullyQualifiedName.lastIndexOf('.');
- int lastDollar = fullyQualifiedName.lastIndexOf('$');
- if (lastDollar < lastDot)
- lastDollar = -1; // must be in last segment
- char[] enclosingTypeName, simpleName;
- if (lastDollar >= 0) {
- enclosingTypeName =
- fullyQualifiedName.substring(lastDot + 1, lastDollar).toCharArray();
- simpleName =
- fullyQualifiedName
- .substring(lastDollar + 1, fullyQualifiedName.length())
- .toCharArray();
+ // parenthesis mismatch
+ if (parameterCount>0 && !foundClosingParenthesis) return null;
+ if (selector == null) return null;
+
+ char[] selectorChars = selector.toCharArray();
+ if (selectorChars.length == 1 && selectorChars[0] == '*') selectorChars = null;
+
+ char[] declaringTypeQualification = null, declaringTypeSimpleName = null;
+ char[] returnTypeQualification = null, returnTypeSimpleName = null;
+ char[][] parameterTypeQualifications = null, parameterTypeSimpleNames = null;
+
+ // extract declaring type infos
+ if (declaringType != null){
+ char[] declaringTypePart = declaringType.toCharArray();
+ int lastDotPosition = CharOperation.lastIndexOf('.', declaringTypePart);
+ if (lastDotPosition >= 0){
+ declaringTypeQualification = CharOperation.subarray(declaringTypePart, 0, lastDotPosition);
+ if (declaringTypeQualification.length == 1 && declaringTypeQualification[0] == '*') declaringTypeQualification = null;
+ declaringTypeSimpleName = CharOperation.subarray(declaringTypePart, lastDotPosition+1, declaringTypePart.length);
} else {
- enclosingTypeName = new char[0];
- simpleName =
- (lastDot != -1
- ? fullyQualifiedName.substring(lastDot + 1)
- : fullyQualifiedName)
- .toCharArray();
- }
- char[] qualification =
- lastDot != -1 ? fullyQualifiedName.substring(0, lastDot).toCharArray() : null;
-
- switch (limitTo) {
- case IJavaSearchConstants.DECLARATIONS :
- char[][] enclosingTypeNames = CharOperation.splitOn('$', enclosingTypeName);
- searchPattern =
- new TypeDeclarationPattern(
- qualification,
- enclosingTypeNames,
- simpleName,
- TYPE_SUFFIX,
- EXACT_MATCH,
- CASE_SENSITIVE);
- break;
- case IJavaSearchConstants.REFERENCES :
- if (enclosingTypeName.length > 0) {
- qualification = CharOperation.concat(qualification, enclosingTypeName, '.');
- }
- searchPattern =
- new TypeReferencePattern(
- qualification,
- simpleName,
- EXACT_MATCH,
- CASE_SENSITIVE);
- break;
- case IJavaSearchConstants.IMPLEMENTORS :
- searchPattern =
- new SuperInterfaceReferencePattern(
- qualification,
- simpleName,
- EXACT_MATCH,
- CASE_SENSITIVE);
- break;
- case IJavaSearchConstants.ALL_OCCURRENCES :
- enclosingTypeNames = CharOperation.splitOn('$', enclosingTypeName);
- searchPattern =
- new OrPattern(
- new TypeDeclarationPattern(
- qualification,
- enclosingTypeNames,
- simpleName,
- TYPE_SUFFIX,
- EXACT_MATCH,
- CASE_SENSITIVE),
- new TypeReferencePattern(
- qualification,
- simpleName,
- EXACT_MATCH,
- CASE_SENSITIVE));
- break;
+ declaringTypeQualification = null;
+ declaringTypeSimpleName = declaringTypePart;
}
- return searchPattern;
+ if (declaringTypeSimpleName.length == 1 && declaringTypeSimpleName[0] == '*') declaringTypeSimpleName = null;
}
-
- /**
- * Type pattern are formed by [package.]type
- * e.g. java.lang.Object
- * Runnable
- *
- */
- private static SearchPattern createTypePattern(
- String patternString,
- int limitTo,
- int matchMode,
- boolean isCaseSensitive) {
-
- StringTokenizer tokenizer = new StringTokenizer(patternString, " .", true);
- String type = null;
- String lastToken = null;
- while (tokenizer.hasMoreTokens()) {
- String token = tokenizer.nextToken();
- if (!token.equals(" ")) {
- if (type == null) {
- type = token;
- } else {
- if (!(".".equals(lastToken) || ".".equals(token) || "[]".equals(token)))
- return null;
- type += token;
- }
- }
- lastToken = token;
- }
- if (type == null)
- return null;
-
- char[] packageChars = null, typeChars = null;
-
- // extract declaring type infos
- if (type != null) {
- char[] typePart = type.toCharArray();
- int lastDotPosition = CharOperation.lastIndexOf('.', typePart);
- if (lastDotPosition >= 0) {
- packageChars = CharOperation.subarray(typePart, 0, lastDotPosition);
- if (packageChars.length == 1 && packageChars[0] == '*')
- packageChars = null;
- typeChars =
- CharOperation.subarray(typePart, lastDotPosition + 1, typePart.length);
+ // extract parameter types infos
+ if (parameterCount >= 0){
+ parameterTypeQualifications = new char[parameterCount][];
+ parameterTypeSimpleNames = new char[parameterCount][];
+ for (int i = 0; i < parameterCount; i++){
+ char[] parameterTypePart = parameterTypes[i].toCharArray();
+ int lastDotPosition = CharOperation.lastIndexOf('.', parameterTypePart);
+ if (lastDotPosition >= 0){
+ parameterTypeQualifications[i] = CharOperation.subarray(parameterTypePart, 0, lastDotPosition);
+ if (parameterTypeQualifications[i].length == 1 && parameterTypeQualifications[i][0] == '*') parameterTypeQualifications[i] = null;
+ parameterTypeSimpleNames[i] = CharOperation.subarray(parameterTypePart, lastDotPosition+1, parameterTypePart.length);
} else {
- packageChars = null;
- typeChars = typePart;
+ parameterTypeQualifications[i] = null;
+ parameterTypeSimpleNames[i] = parameterTypePart;
}
- if (typeChars.length == 1 && typeChars[0] == '*')
- typeChars = null;
+ if (parameterTypeSimpleNames[i].length == 1 && parameterTypeSimpleNames[i][0] == '*') parameterTypeSimpleNames[i] = null;
}
- SearchPattern searchPattern = null;
- switch (limitTo) {
- case IJavaSearchConstants.DECLARATIONS :
- // cannot search for explicit member types
- searchPattern =
- new TypeDeclarationPattern(
- packageChars,
- null,
- typeChars,
- TYPE_SUFFIX,
- matchMode,
- isCaseSensitive);
- break;
- case IJavaSearchConstants.REFERENCES :
- searchPattern =
- new TypeReferencePattern(packageChars, typeChars, matchMode, isCaseSensitive);
- break;
- case IJavaSearchConstants.IMPLEMENTORS :
- searchPattern =
- new SuperInterfaceReferencePattern(
- packageChars,
- typeChars,
- matchMode,
- isCaseSensitive);
- break;
- case IJavaSearchConstants.ALL_OCCURRENCES :
- searchPattern =
- new OrPattern(
- new TypeDeclarationPattern(
- packageChars,
- null,
- typeChars,
- TYPE_SUFFIX,
- matchMode,
- isCaseSensitive),
- // cannot search for explicit member types
- new TypeReferencePattern(packageChars, typeChars, matchMode, isCaseSensitive));
- break;
+ }
+ // extract return type infos
+ if (returnType != null){
+ char[] returnTypePart = returnType.toCharArray();
+ int lastDotPosition = CharOperation.lastIndexOf('.', returnTypePart);
+ if (lastDotPosition >= 0){
+ returnTypeQualification = CharOperation.subarray(returnTypePart, 0, lastDotPosition);
+ if (returnTypeQualification.length == 1 && returnTypeQualification[0] == '*') returnTypeQualification = null;
+ returnTypeSimpleName = CharOperation.subarray(returnTypePart, lastDotPosition+1, returnTypePart.length);
+ } else {
+ returnTypeQualification = null;
+ returnTypeSimpleName = returnTypePart;
}
- return searchPattern;
-
+ if (returnTypeSimpleName.length == 1 && returnTypeSimpleName[0] == '*') returnTypeSimpleName = null;
}
-
- protected abstract void decodeIndexEntry(IEntryResult entryResult);
- /**
- * Feed the requestor according to the current search pattern
- */
- public abstract void feedIndexRequestor(
- IIndexSearchRequestor requestor,
- int detailLevel,
- int[] references,
- IndexInput input,
- IJavaSearchScope scope)
- throws IOException;
- /**
- * Query a given index for matching entries.
- */
- public void findIndexMatches(
- IIndex index,
- IIndexSearchRequestor requestor,
- int detailLevel,
- IProgressMonitor progressMonitor,
- IJavaSearchScope scope)
- throws IOException {
-
- if (progressMonitor != null && progressMonitor.isCanceled())
- throw new OperationCanceledException();
-
- IndexInput input = new BlocksIndexInput(index.getIndexFile());
- try {
- input.open();
- findIndexMatches(input, requestor, detailLevel, progressMonitor, scope);
- } finally {
- input.close();
- }
+ SearchPattern searchPattern = null;
+ switch (limitTo){
+ case IJavaSearchConstants.DECLARATIONS :
+ searchPattern = new MethodDeclarationPattern(selectorChars, matchMode, isCaseSensitive, declaringTypeQualification, declaringTypeSimpleName, returnTypeQualification, returnTypeSimpleName, parameterTypeQualifications, parameterTypeSimpleNames);
+ break;
+ case IJavaSearchConstants.REFERENCES :
+ searchPattern = new MethodReferencePattern(selectorChars, matchMode, isCaseSensitive, declaringTypeQualification, declaringTypeSimpleName, returnTypeQualification, returnTypeSimpleName, parameterTypeQualifications, parameterTypeSimpleNames);
+ break;
+ case IJavaSearchConstants.ALL_OCCURRENCES :
+ searchPattern = new OrPattern(
+ new MethodDeclarationPattern(selectorChars, matchMode, isCaseSensitive, declaringTypeQualification, declaringTypeSimpleName, returnTypeQualification, returnTypeSimpleName, parameterTypeQualifications, parameterTypeSimpleNames),
+ new MethodReferencePattern(selectorChars, matchMode, isCaseSensitive, declaringTypeQualification, declaringTypeSimpleName, returnTypeQualification, returnTypeSimpleName, parameterTypeQualifications, parameterTypeSimpleNames));
+ break;
}
+ return searchPattern;
- /**
- * Query a given index for matching entries.
- */
- public void findIndexMatches(
- IndexInput input,
- IIndexSearchRequestor requestor,
- int detailLevel,
- IProgressMonitor progressMonitor,
- IJavaSearchScope scope)
- throws IOException {
-
- if (progressMonitor != null && progressMonitor.isCanceled())
- throw new OperationCanceledException();
-
- /* narrow down a set of entries using prefix criteria */
- IEntryResult[] entries = input.queryEntriesPrefixedBy(indexEntryPrefix());
- if (entries == null)
- return;
-
- /* only select entries which actually match the entire search pattern */
- for (int i = 0, max = entries.length; i < max; i++) {
-
- if (progressMonitor != null && progressMonitor.isCanceled())
- throw new OperationCanceledException();
-
- /* retrieve and decode entry */
- IEntryResult entry = entries[i];
- decodeIndexEntry(entry);
- if (matchIndexEntry()) {
- feedIndexRequestor(
- requestor,
- detailLevel,
- entry.getFileReferences(),
- input,
- scope);
- }
- }
+}
+private static SearchPattern createPackagePattern(String patternString, int limitTo, int matchMode, boolean isCaseSensitive) {
+ SearchPattern searchPattern = null;
+ switch (limitTo){
+ case IJavaSearchConstants.DECLARATIONS :
+ searchPattern = new PackageDeclarationPattern(patternString.toCharArray(), matchMode, isCaseSensitive);
+ break;
+ case IJavaSearchConstants.REFERENCES :
+ searchPattern = new PackageReferencePattern(patternString.toCharArray(), matchMode, isCaseSensitive);
+ break;
+ case IJavaSearchConstants.ALL_OCCURRENCES :
+ searchPattern = new OrPattern(
+ new PackageDeclarationPattern(patternString.toCharArray(), matchMode, isCaseSensitive),
+ new PackageReferencePattern(patternString.toCharArray(), matchMode, isCaseSensitive)
+ );
+ break;
}
+ return searchPattern;
- /**
- * Answers the suitable prefix that should be used in order
- * to query indexes for the corresponding item.
- * The more accurate the prefix and the less false hits will have
- * to be eliminated later on.
- */
- public abstract char[] indexEntryPrefix();
- /**
- * Returns the type of container of this pattern, i.e. is it in compilation unit,
- * in class declarations, field declarations, or in method declarations.
- */
- protected abstract int matchContainer();
- /**
- * Finds out whether the given resolved ast node matches this search pattern.
- */
- public boolean matches(AstNode node) {
- return this.matches(node, true);
+}
+public static SearchPattern createPattern(String patternString, int searchFor, int limitTo, int matchMode, boolean isCaseSensitive) {
+
+ if (patternString == null || patternString.length() == 0)
+ return null;
+
+ SearchPattern searchPattern = null;
+ switch (searchFor) {
+
+ case IJavaSearchConstants.TYPE:
+ searchPattern = createTypePattern(patternString, limitTo, matchMode, isCaseSensitive);
+ break;
+ case IJavaSearchConstants.METHOD:
+ searchPattern = createMethodPattern(patternString, limitTo, matchMode, isCaseSensitive);
+ break;
+ case IJavaSearchConstants.CONSTRUCTOR:
+ searchPattern = createConstructorPattern(patternString, limitTo, matchMode, isCaseSensitive);
+ break;
+ case IJavaSearchConstants.FIELD:
+ searchPattern = createFieldPattern(patternString, limitTo, matchMode, isCaseSensitive);
+ break;
+ case IJavaSearchConstants.PACKAGE:
+ searchPattern = createPackagePattern(patternString, limitTo, matchMode, isCaseSensitive);
}
-
- /**
- * Returns whether this pattern matches the given node.
- * Look at resolved information only if specified.
- */
- protected abstract boolean matches(AstNode node, boolean resolve);
- /**
- * Finds out whether the given binding matches this search pattern.
- * Default is to return false.
- */
- public boolean matches(Binding binding) {
- return false;
+ return searchPattern;
+}
+public static SearchPattern createPattern(IJavaElement element, int limitTo) {
+ SearchPattern searchPattern = null;
+ int lastDot;
+ switch (element.getElementType()) {
+ case IJavaElement.FIELD :
+ IField field = (IField) element;
+ String fullDeclaringName = field.getDeclaringType().getFullyQualifiedName().replace('$', '.');;
+ lastDot = fullDeclaringName.lastIndexOf('.');
+ char[] declaringSimpleName = (lastDot != -1 ? fullDeclaringName.substring(lastDot + 1) : fullDeclaringName).toCharArray();
+ char[] declaringQualification = lastDot != -1 ? fullDeclaringName.substring(0, lastDot).toCharArray() : NO_CHAR;
+ char[] name = field.getElementName().toCharArray();
+ char[] typeSimpleName;
+ char[] typeQualification;
+ try {
+ String typeSignature = Signature.toString(field.getTypeSignature()).replace('$', '.');
+ lastDot = typeSignature.lastIndexOf('.');
+ typeSimpleName = (lastDot != -1 ? typeSignature.substring(lastDot + 1) : typeSignature).toCharArray();
+ typeQualification = lastDot != -1 ? typeSignature.substring(0, lastDot).toCharArray() : null;
+ } catch (JavaModelException e) {
+ return null;
+ }
+ switch (limitTo) {
+ case IJavaSearchConstants.DECLARATIONS :
+ searchPattern = new FieldDeclarationPattern(name, EXACT_MATCH, CASE_SENSITIVE, declaringQualification, declaringSimpleName, typeQualification, typeSimpleName);
+ break;
+ case IJavaSearchConstants.REFERENCES :
+ searchPattern = new FieldReferencePattern(name, EXACT_MATCH, CASE_SENSITIVE, declaringQualification, declaringSimpleName, typeQualification, typeSimpleName);
+ break;
+ case IJavaSearchConstants.ALL_OCCURRENCES :
+ searchPattern = new OrPattern(
+ new FieldDeclarationPattern(name, EXACT_MATCH, CASE_SENSITIVE, declaringQualification, declaringSimpleName, typeQualification, typeSimpleName),
+ new FieldReferencePattern(name, EXACT_MATCH, CASE_SENSITIVE, declaringQualification, declaringSimpleName, typeQualification, typeSimpleName));
+ break;
+ }
+ break;
+ case IJavaElement.IMPORT_DECLARATION :
+ String elementName = element.getElementName();
+ IImportDeclaration importDecl = (IImportDeclaration)element;
+ if (importDecl.isOnDemand()) {
+ lastDot = elementName.lastIndexOf('.');
+ if (lastDot == -1) return null; // invalid import declaration
+ searchPattern = createPackagePattern(elementName.substring(0, lastDot), limitTo, EXACT_MATCH, CASE_SENSITIVE);
+ } else {
+ searchPattern = createTypePattern(elementName, limitTo);
+ }
+ break;
+ case IJavaElement.METHOD :
+ IMethod method = (IMethod) element;
+ boolean isConstructor;
+ try {
+ isConstructor = method.isConstructor();
+ } catch (JavaModelException e) {
+ return null;
+ }
+ fullDeclaringName = method.getDeclaringType().getFullyQualifiedName().replace('$', '.');
+ lastDot = fullDeclaringName.lastIndexOf('.');
+ declaringSimpleName = (lastDot != -1 ? fullDeclaringName.substring(lastDot + 1) : fullDeclaringName).toCharArray();
+ declaringQualification = lastDot != -1 ? fullDeclaringName.substring(0, lastDot).toCharArray() : NO_CHAR;
+ char[] selector = method.getElementName().toCharArray();
+ char[] returnSimpleName;
+ char[] returnQualification;
+ try {
+ String returnType = Signature.toString(method.getReturnType()).replace('$', '.');
+ lastDot = returnType.lastIndexOf('.');
+ returnSimpleName = (lastDot != -1 ? returnType.substring(lastDot + 1) : returnType).toCharArray();
+ returnQualification = lastDot != -1 ? returnType.substring(0, lastDot).toCharArray() : null;
+ } catch (JavaModelException e) {
+ return null;
+ }
+ String[] parameterTypes = method.getParameterTypes();
+ int paramCount = parameterTypes.length;
+ char[][] parameterSimpleNames = new char[paramCount][];
+ char[][] parameterQualifications = new char[paramCount][];
+ for (int i = 0; i < paramCount; i++) {
+ String signature = Signature.toString(parameterTypes[i]).replace('$', '.');
+ lastDot = signature.lastIndexOf('.');
+ parameterSimpleNames[i] = (lastDot != -1 ? signature.substring(lastDot + 1) : signature).toCharArray();
+ parameterQualifications[i] = lastDot != -1 ? signature.substring(0, lastDot).toCharArray() : null;
+ }
+ switch (limitTo) {
+ case IJavaSearchConstants.DECLARATIONS :
+ if (isConstructor) {
+ searchPattern = new ConstructorDeclarationPattern(declaringSimpleName, EXACT_MATCH, CASE_SENSITIVE, declaringQualification, parameterQualifications, parameterSimpleNames);
+ } else {
+ searchPattern = new MethodDeclarationPattern(selector, EXACT_MATCH, CASE_SENSITIVE, declaringQualification, declaringSimpleName, returnQualification, returnSimpleName, parameterQualifications, parameterSimpleNames);
+ }
+ break;
+ case IJavaSearchConstants.REFERENCES :
+ if (isConstructor) {
+ searchPattern = new ConstructorReferencePattern(declaringSimpleName, EXACT_MATCH, CASE_SENSITIVE, declaringQualification, parameterQualifications, parameterSimpleNames);
+ } else {
+ searchPattern = new MethodReferencePattern(selector, EXACT_MATCH, CASE_SENSITIVE, declaringQualification, declaringSimpleName, returnQualification, returnSimpleName, parameterQualifications, parameterSimpleNames);
+ }
+ break;
+ case IJavaSearchConstants.ALL_OCCURRENCES :
+ if (isConstructor) {
+ searchPattern = new OrPattern(
+ new ConstructorDeclarationPattern(declaringSimpleName, EXACT_MATCH, CASE_SENSITIVE, declaringQualification, parameterQualifications, parameterSimpleNames),
+ new ConstructorReferencePattern(declaringSimpleName, EXACT_MATCH, CASE_SENSITIVE, declaringQualification, parameterQualifications, parameterSimpleNames));
+ } else {
+ searchPattern = new OrPattern(
+ new MethodDeclarationPattern(selector, EXACT_MATCH, CASE_SENSITIVE, declaringQualification, declaringSimpleName, returnQualification, returnSimpleName, parameterQualifications, parameterSimpleNames),
+ new MethodReferencePattern(selector, EXACT_MATCH, CASE_SENSITIVE, declaringQualification, declaringSimpleName, returnQualification, returnSimpleName, parameterQualifications, parameterSimpleNames));
+ }
+ break;
+ }
+ break;
+ case IJavaElement.TYPE :
+ IType type = (IType) element;
+ searchPattern = createTypePattern(type.getFullyQualifiedName(), limitTo);
+ break;
+ case IJavaElement.PACKAGE_DECLARATION :
+ case IJavaElement.PACKAGE_FRAGMENT :
+ searchPattern = createPackagePattern(element.getElementName(), limitTo, EXACT_MATCH, CASE_SENSITIVE);
+ break;
}
-
- /**
- * Finds out whether the given binary info matches this search pattern.
- * Default is to return false.
- */
- public boolean matchesBinary(Object binaryInfo, Object enclosingBinaryInfo) {
- return false;
+ return searchPattern;
+}
+private static SearchPattern createTypePattern(String fullyQualifiedName, int limitTo) {
+ SearchPattern searchPattern = null;
+ int lastDot = fullyQualifiedName.lastIndexOf('.');
+ int lastDollar = fullyQualifiedName.lastIndexOf('$');
+ if (lastDollar < lastDot) lastDollar = -1; // must be in last segment
+ char[] enclosingTypeName, simpleName;
+ if (lastDollar >= 0){
+ enclosingTypeName = fullyQualifiedName.substring(lastDot+1, lastDollar).toCharArray();
+ simpleName = fullyQualifiedName.substring(lastDollar+1, fullyQualifiedName.length()).toCharArray();
+ } else {
+ enclosingTypeName = new char[0];
+ simpleName = (lastDot != -1 ? fullyQualifiedName.substring(lastDot + 1) : fullyQualifiedName).toCharArray();
}
-
- /**
- * Returns whether the given name matches the given pattern.
- */
- protected boolean matchesName(char[] pattern, char[] name) {
- if (name != null) {
- switch (this.matchMode) {
- case EXACT_MATCH :
- return CharOperation.equals(pattern, name, this.isCaseSensitive);
- case PREFIX_MATCH :
- return CharOperation.prefixEquals(pattern, name, this.isCaseSensitive);
- case PATTERN_MATCH :
- return CharOperation.match(pattern, name, this.isCaseSensitive);
+ char[] qualification = lastDot != -1 ? fullyQualifiedName.substring(0, lastDot).toCharArray() : null;
+
+ switch (limitTo) {
+ case IJavaSearchConstants.DECLARATIONS :
+ char[][] enclosingTypeNames = CharOperation.splitOn('$', enclosingTypeName);
+ searchPattern = new TypeDeclarationPattern(qualification, enclosingTypeNames, simpleName, TYPE_SUFFIX, EXACT_MATCH, CASE_SENSITIVE);
+ break;
+ case IJavaSearchConstants.REFERENCES :
+ if (enclosingTypeName.length > 0) {
+ qualification = CharOperation.concat(qualification, enclosingTypeName, '.');
}
- }
- return false;
+ searchPattern = new TypeReferencePattern(qualification, simpleName, EXACT_MATCH, CASE_SENSITIVE);
+ break;
+ case IJavaSearchConstants.IMPLEMENTORS :
+ searchPattern = new SuperInterfaceReferencePattern(qualification, simpleName, EXACT_MATCH, CASE_SENSITIVE);
+ break;
+ case IJavaSearchConstants.ALL_OCCURRENCES :
+ enclosingTypeNames = CharOperation.splitOn('$', enclosingTypeName);
+ searchPattern = new OrPattern(
+ new TypeDeclarationPattern(qualification, enclosingTypeNames, simpleName, TYPE_SUFFIX, EXACT_MATCH, CASE_SENSITIVE),
+ new TypeReferencePattern(qualification, simpleName, EXACT_MATCH, CASE_SENSITIVE));
+ break;
}
-
- /**
- * Returns whether the given type binding matches the given simple name pattern
- * and qualification pattern.
- */
- protected boolean matchesType(
- char[] simpleNamePattern,
- char[] qualificationPattern,
- char[] fullyQualifiedTypeName) {
- char[] pattern;
- if (simpleNamePattern == null) {
- if (qualificationPattern == null) {
- pattern = ONE_STAR;
+ return searchPattern;
+}
+/**
+ * Type pattern are formed by [package.]type
+ * e.g. java.lang.Object
+ * Runnable
+ *
+ */
+private static SearchPattern createTypePattern(String patternString, int limitTo, int matchMode, boolean isCaseSensitive) {
+
+ StringTokenizer tokenizer = new StringTokenizer(patternString, " .", true);
+ String type = null;
+ String lastToken = null;
+ while (tokenizer.hasMoreTokens()){
+ String token = tokenizer.nextToken();
+ if (!token.equals(" ")){
+ if (type == null){
+ type = token;
} else {
- pattern = CharOperation.concat(qualificationPattern, ONE_STAR, '.');
+ if (!(".".equals(lastToken) || ".".equals(token) || "[]".equals(token))) return null;
+ type += token;
}
+ }
+ lastToken = token;
+ }
+ if (type == null) return null;
+
+ char[] packageChars = null, typeChars = null;
+
+ // extract declaring type infos
+ if (type != null){
+ char[] typePart = type.toCharArray();
+ int lastDotPosition = CharOperation.lastIndexOf('.', typePart);
+ if (lastDotPosition >= 0){
+ packageChars = CharOperation.subarray(typePart, 0, lastDotPosition);
+ if (packageChars.length == 1 && packageChars[0] == '*') packageChars = null;
+ typeChars = CharOperation.subarray(typePart, lastDotPosition+1, typePart.length);
} else {
- if (qualificationPattern == null) {
- pattern = CharOperation.concat(ONE_STAR, simpleNamePattern);
- } else {
- pattern = CharOperation.concat(qualificationPattern, simpleNamePattern, '.');
- }
+ packageChars = null;
+ typeChars = typePart;
}
- return CharOperation.match(
- pattern,
- fullyQualifiedTypeName,
- this.isCaseSensitive);
+ if (typeChars.length == 1 && typeChars[0] == '*') typeChars = null;
}
-
- /**
- * Returns whether the given type binding matches the given simple name pattern
- * and qualification pattern.
- */
- protected boolean matchesType(
- char[] simpleNamePattern,
- char[] qualificationPattern,
- TypeBinding type) {
- if (type == null)
- return false;
- return this.matchesType(
- simpleNamePattern,
- qualificationPattern,
- type.qualifiedPackageName().length == 0
- ? type.qualifiedSourceName()
- : CharOperation.concat(
- type.qualifiedPackageName(),
- type.qualifiedSourceName(),
- '.'));
+ SearchPattern searchPattern = null;
+ switch (limitTo){
+ case IJavaSearchConstants.DECLARATIONS : // cannot search for explicit member types
+ searchPattern = new TypeDeclarationPattern(packageChars, null, typeChars, TYPE_SUFFIX, matchMode, isCaseSensitive);
+ break;
+ case IJavaSearchConstants.REFERENCES :
+ searchPattern = new TypeReferencePattern(packageChars, typeChars, matchMode, isCaseSensitive);
+ break;
+ case IJavaSearchConstants.IMPLEMENTORS :
+ searchPattern = new SuperInterfaceReferencePattern(packageChars, typeChars, matchMode, isCaseSensitive);
+ break;
+ case IJavaSearchConstants.ALL_OCCURRENCES :
+ searchPattern = new OrPattern(
+ new TypeDeclarationPattern(packageChars, null, typeChars, TYPE_SUFFIX, matchMode, isCaseSensitive),// cannot search for explicit member types
+ new TypeReferencePattern(packageChars, typeChars, matchMode, isCaseSensitive));
+ break;
}
+ return searchPattern;
- /**
- * Checks whether an entry matches the current search pattern
- */
- protected abstract boolean matchIndexEntry();
- /**
- * Finds out whether the given ast node matches this search pattern.
- * Returns IMPOSSIBLE_MATCH if it doesn't.
- * Returns TRUSTED_MATCH if it matches exactly this search pattern (ie.
- * it doesn't need to be resolved or it has already been resolved.)
- * Returns POSSIBLE_MATCH if it potentially matches
- * this search pattern and it needs to be resolved to get more information.
- */
- public int matchLevel(AstNode node) {
- if (this.matches(node, false)) {
- if (this.needsResolve) {
- return POSSIBLE_MATCH;
- } else {
- return TRUSTED_MATCH;
- }
+}
+protected abstract void decodeIndexEntry(IEntryResult entryResult);
+/**
+ * Feed the requestor according to the current search pattern
+ */
+public abstract void feedIndexRequestor(IIndexSearchRequestor requestor, int detailLevel, int[] references, IndexInput input, IJavaSearchScope scope) throws IOException ;
+/**
+ * Query a given index for matching entries.
+ */
+public void findIndexMatches(IIndex index, IIndexSearchRequestor requestor, int detailLevel, IProgressMonitor progressMonitor, IJavaSearchScope scope) throws IOException {
+
+ if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException();
+
+ IndexInput input = new BlocksIndexInput(index.getIndexFile());
+ try {
+ input.open();
+ findIndexMatches(input, requestor, detailLevel, progressMonitor,scope);
+ } finally {
+ input.close();
+ }
+}
+/**
+ * Query a given index for matching entries.
+ */
+public void findIndexMatches(IndexInput input, IIndexSearchRequestor requestor, int detailLevel, IProgressMonitor progressMonitor, IJavaSearchScope scope) throws IOException {
+
+ if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException();
+
+ /* narrow down a set of entries using prefix criteria */
+ IEntryResult[] entries = input.queryEntriesPrefixedBy(indexEntryPrefix());
+ if (entries == null) return;
+
+ /* only select entries which actually match the entire search pattern */
+ for (int i = 0, max = entries.length; i < max; i++){
+
+ if (progressMonitor != null && progressMonitor.isCanceled()) throw new OperationCanceledException();
+
+ /* retrieve and decode entry */
+ IEntryResult entry = entries[i];
+ decodeIndexEntry(entry);
+ if (matchIndexEntry()){
+ feedIndexRequestor(requestor, detailLevel, entry.getFileReferences(), input, scope);
}
- return IMPOSSIBLE_MATCH;
}
-
- /**
- * Reports the match of the given reference.
- */
- protected void matchReportReference(
- AstNode reference,
- IJavaElement element,
- int accuracy,
- MatchLocator locator)
- throws CoreException {
- // default is to report a match on the whole node.
- locator.report(reference.sourceStart, reference.sourceEnd, element, accuracy);
+}
+/**
+ * Answers the suitable prefix that should be used in order
+ * to query indexes for the corresponding item.
+ * The more accurate the prefix and the less false hits will have
+ * to be eliminated later on.
+ */
+public abstract char[] indexEntryPrefix();
+/**
+ * Returns the type of container of this pattern, i.e. is it in compilation unit,
+ * in class declarations, field declarations, or in method declarations.
+ */
+protected abstract int matchContainer();
+/**
+ * Finds out whether the given resolved ast node matches this search pattern.
+ */
+public boolean matches(AstNode node) {
+ return this.matches(node, true);
+}
+/**
+ * Returns whether this pattern matches the given node.
+ * Look at resolved information only if specified.
+ */
+protected abstract boolean matches(AstNode node, boolean resolve);
+/**
+ * Finds out whether the given binding matches this search pattern.
+ * Default is to return false.
+ */
+public boolean matches(Binding binding) {
+ return false;
+}
+/**
+ * Finds out whether the given binary info matches this search pattern.
+ * Default is to return false.
+ */
+public boolean matchesBinary(Object binaryInfo, Object enclosingBinaryInfo) {
+ return false;
+}
+/**
+ * Returns whether the given name matches the given pattern.
+ */
+protected boolean matchesName(char[] pattern, char[] name) {
+ if (name != null){
+ switch (this.matchMode) {
+ case EXACT_MATCH :
+ return CharOperation.equals(pattern, name, this.isCaseSensitive);
+ case PREFIX_MATCH :
+ return CharOperation.prefixEquals(pattern, name, this.isCaseSensitive);
+ case PATTERN_MATCH :
+ return CharOperation.match(pattern, name, this.isCaseSensitive);
+ }
}
-
- /**
- * Add square brackets to the given simple name
- */
- protected char[] toArrayName(char[] simpleName, int dimensions) {
- if (dimensions == 0)
- return simpleName;
- char[] result = new char[simpleName.length + dimensions * 2];
- for (int i = 0; i < dimensions; i++) {
- result[simpleName.length + i * 2] = '[';
- result[simpleName.length + i * 2 + 1] = ']';
+ return false;
+}
+/**
+ * Returns whether the given type binding matches the given simple name pattern
+ * and qualification pattern.
+ */
+protected boolean matchesType(char[] simpleNamePattern, char[] qualificationPattern, char[] fullyQualifiedTypeName) {
+ char[] pattern;
+ if (simpleNamePattern == null) {
+ if (qualificationPattern == null) {
+ pattern = ONE_STAR;
+ } else {
+ pattern = CharOperation.concat(qualificationPattern, ONE_STAR, '.');
+ }
+ } else {
+ if (qualificationPattern == null) {
+ pattern = CharOperation.concat(ONE_STAR, simpleNamePattern);
+ } else {
+ pattern = CharOperation.concat(qualificationPattern, simpleNamePattern, '.');
}
- return result;
}
-
- public String toString() {
- return "SearchPattern";
+ return
+ CharOperation.match(
+ pattern,
+ fullyQualifiedTypeName,
+ this.isCaseSensitive
+ );
+}
+/**
+ * Returns whether the given type binding matches the given simple name pattern
+ * and qualification pattern.
+ */
+protected boolean matchesType(char[] simpleNamePattern, char[] qualificationPattern, TypeBinding type) {
+ if (type == null) return false;
+ return
+ this.matchesType(
+ simpleNamePattern,
+ qualificationPattern,
+ type.qualifiedPackageName().length == 0 ?
+ type.qualifiedSourceName() :
+ CharOperation.concat(type.qualifiedPackageName(), type.qualifiedSourceName(), '.')
+ );
+}
+/**
+ * Checks whether an entry matches the current search pattern
+ */
+protected abstract boolean matchIndexEntry();
+/**
+ * Finds out whether the given ast node matches this search pattern.
+ * Returns IMPOSSIBLE_MATCH if it doesn't.
+ * Returns TRUSTED_MATCH if it matches exactly this search pattern (ie.
+ * it doesn't need to be resolved or it has already been resolved.)
+ * Returns POSSIBLE_MATCH if it potentially matches
+ * this search pattern and it needs to be resolved to get more information.
+ */
+public int matchLevel(AstNode node) {
+ if (this.matches(node, false)) {
+ if (this.needsResolve) {
+ return POSSIBLE_MATCH;
+ } else {
+ return TRUSTED_MATCH;
+ }
}
-
- /**
- * Initializes this search pattern from the given lookup environment.
- * Returns whether it could be initialized.
- */
- public boolean initializeFromLookupEnvironment(LookupEnvironment env) {
- return true;
+ return IMPOSSIBLE_MATCH;
+}
+/**
+ * Reports the match of the given reference.
+ */
+protected void matchReportReference(AstNode reference, IJavaElement element, int accuracy, MatchLocator locator) throws CoreException {
+ // default is to report a match on the whole node.
+ locator.report(reference.sourceStart, reference.sourceEnd, element, accuracy);
+}
+/**
+ * Add square brackets to the given simple name
+ */
+protected char[] toArrayName(char[] simpleName, int dimensions) {
+ if (dimensions == 0) return simpleName;
+ char[] result = new char[simpleName.length + dimensions * 2];
+ for (int i = 0; i < dimensions; i++) {
+ result[simpleName.length + i*2] = '[';
+ result[simpleName.length + i*2 + 1] = ']';
}
+ return result;
+}
+public String toString(){
+ return "SearchPattern";
+}
- /**
- * Returns whether one of the given declaring types is a sub type of the given super type.
- */
- protected boolean matchesAsSubtype(
- ReferenceBinding declaringTypes[],
- ReferenceBinding superType) {
- if (declaringTypes == null) {
- return true;
- // we were not able to compute the declaring types, default to true
- } else {
- for (int i = 0, max = declaringTypes.length; i < max; i++) {
- if (this.matchesAsSubtype(declaringTypes[i], superType)) {
- return true;
- }
+/**
+ * Collects the super type names of the given declaring type.
+ * Returns NOT_FOUND_DECLARING_TYPE if the declaring type was not found.
+ * Returns null if the declaring type pattern doesn't require an exact match.
+ */
+protected char[][][] collectSuperTypeNames(char[] declaringQualification, char[] declaringSimpleName, int matchMode, LookupEnvironment env) {
+
+ char[][] declaringTypeName = null;
+ if (declaringQualification != null
+ && declaringSimpleName != null
+ && matchMode == EXACT_MATCH) {
+ char[][] qualification = CharOperation.splitOn('.', declaringQualification);
+ declaringTypeName = CharOperation.arrayConcat(qualification, declaringSimpleName);
+ }
+ if (declaringTypeName != null) {
+ for (int i = 0, max = declaringTypeName.length; i < max; i++) {
+ ReferenceBinding matchingDeclaringType = env.askForType(declaringTypeName);
+ if (matchingDeclaringType != null
+ && (matchingDeclaringType.isValidBinding()
+ || matchingDeclaringType.problemId() != ProblemReasons.NotFound)) {
+ return this.collectSuperTypeNames(matchingDeclaringType);
}
- return false;
+ // if nothing is in the cache, it could have been a member type (A.B.C.D --> A.B.C$D)
+ int last = declaringTypeName.length - 1;
+ if (last == 0) break;
+ declaringTypeName[last-1] = CharOperation.concat(declaringTypeName[last-1], declaringTypeName[last], '$'); // try nested type
+ declaringTypeName = CharOperation.subarray(declaringTypeName, 0, last);
}
+ return NOT_FOUND_DECLARING_TYPE; // the declaring type was not found
+ } else {
+ // non exact match: use the null value so that matches is more tolerant
+ return null;
}
+}
- /**
- * Returns whether the given reference type binding matches or is a subtype of a type
- * that matches the given simple name pattern and qualification pattern.
- */
- protected boolean matchesAsSubtype(
- ReferenceBinding type,
- char[] simpleNamePattern,
- char[] qualificationPattern) {
- // matches type
- if (this.matchesType(simpleNamePattern, qualificationPattern, type))
- return true;
+/**
+ * Collects the names of all the supertypes of the given type.
+ */
+private char[][][] collectSuperTypeNames(ReferenceBinding type) {
- // matches superclass
- ReferenceBinding superclass = type.superclass();
- if (superclass != null) {
- if (this.matchesAsSubtype(superclass, simpleNamePattern, qualificationPattern))
- return true;
- }
+ // superclass
+ char[][][] superClassNames = null;
+ ReferenceBinding superclass = type.superclass();
+ if (superclass != null) {
+ superClassNames = this.collectSuperTypeNames(superclass);
+ }
- // matches interfaces
- ReferenceBinding[] interfaces = type.superInterfaces();
+ // interfaces
+ char[][][][] superInterfaceNames = null;
+ int superInterfaceNamesLength = 0;
+ ReferenceBinding[] interfaces = type.superInterfaces();
+ if (interfaces != null) {
+ superInterfaceNames = new char[interfaces.length][][][];
for (int i = 0; i < interfaces.length; i++) {
- if (this
- .matchesAsSubtype(interfaces[i], simpleNamePattern, qualificationPattern))
- return true;
+ superInterfaceNames[i] = this.collectSuperTypeNames(interfaces[i]);
+ superInterfaceNamesLength += superInterfaceNames[i].length;
}
+ }
- return false;
+ int length =
+ (superclass == null ? 0 : 1)
+ + (superClassNames == null ? 0 : superClassNames.length)
+ + (interfaces == null ? 0 : interfaces.length)
+ + superInterfaceNamesLength;
+ char[][][] result = new char[length][][];
+ int index = 0;
+ if (superclass != null) {
+ result[index++] = superclass.compoundName;
+ if (superClassNames != null) {
+ System.arraycopy(superClassNames, 0, result, index, superClassNames.length);
+ index += superClassNames.length;
+ }
+ }
+ if (interfaces != null) {
+ for (int i = 0, max = interfaces.length; i < max; i++) {
+ result[index++] = interfaces[i].compoundName;
+ if (superInterfaceNames != null) {
+ System.arraycopy(superInterfaceNames[i], 0, result, index, superInterfaceNames[i].length);
+ index += superInterfaceNames[i].length;
+ }
+ }
}
+
+ return result;
+}
+
+/**
+ * Initializes this search pattern from the given lookup environment.
+ * Returns whether it could be initialized.
+ */
+public boolean initializeFromLookupEnvironment(LookupEnvironment env) {
+ return true;
+}
- /**
- * Returns whether the given reference type binding is a subtype of the given super type.
- */
- protected boolean matchesAsSubtype(
- ReferenceBinding type,
- ReferenceBinding superType) {
+/**
+ * Returns whether the given reference type binding matches or is a subtype of a type
+ * that matches the given simple name pattern and qualification pattern.
+ */
+protected boolean matchesAsSubtype(ReferenceBinding type, char[] simpleNamePattern, char[] qualificationPattern) {
+ // matches type
+ if (this.matchesType(simpleNamePattern, qualificationPattern, type))
+ return true;
+
+ // matches superclass
+ ReferenceBinding superclass = type.superclass();
+ if (superclass != null) {
+ if (this.matchesAsSubtype(superclass, simpleNamePattern, qualificationPattern))
+ return true;
+ }
- // matches superclass
- ReferenceBinding superclass = type.superclass();
- if (superType == superclass)
+ // matches interfaces
+ ReferenceBinding[] interfaces = type.superInterfaces();
+ for (int i = 0; i < interfaces.length; i++) {
+ if (this.matchesAsSubtype(interfaces[i], simpleNamePattern, qualificationPattern))
return true;
- if (superclass != null) {
- if (this.matchesAsSubtype(superclass, superType))
- return true;
- }
+ }
- // matches interfaces
- ReferenceBinding[] interfaces = type.superInterfaces();
- for (int i = 0; i < interfaces.length; i++) {
- ReferenceBinding interf = interfaces[i];
- if (superType == interf)
- return true;
- if (this.matchesAsSubtype(interf, superType))
+ return false;
+}
+
+/**
+ * Returns whether one of the given declaring types is the given receiver type.
+ */
+protected boolean matchesType(char[][][] declaringTypes, ReferenceBinding receiverType) {
+ if (declaringTypes == null) {
+ return true; // we were not able to compute the declaring types, default to true
+ } else {
+ for (int i = 0, max = declaringTypes.length; i < max; i++) {
+ if (CharOperation.equals(declaringTypes[i], receiverType.compoundName)) {
return true;
+ }
}
-
return false;
}
-
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/SuperInterfaceReferencePattern.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/SuperInterfaceReferencePattern.java
index 81cdc26384..cbc51f3fe5 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/SuperInterfaceReferencePattern.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/SuperInterfaceReferencePattern.java
@@ -7,66 +7,75 @@ package org.eclipse.jdt.internal.core.search.matching;
import org.eclipse.jdt.internal.compiler.lookup.*;
import org.eclipse.jdt.internal.core.search.indexing.*;
+import org.eclipse.jdt.internal.compiler.util.CharOperation;
+import org.eclipse.jdt.internal.compiler.env.IBinaryType;
+
public class SuperInterfaceReferencePattern extends SuperTypeReferencePattern {
- public SuperInterfaceReferencePattern(
- char[] superQualification,
- char[] superSimpleName,
- int matchMode,
- boolean isCaseSensitive) {
- super(superQualification, superSimpleName, matchMode, isCaseSensitive);
+public SuperInterfaceReferencePattern(char[] superQualification, char[] superSimpleName, int matchMode, boolean isCaseSensitive) {
+ super(superQualification, superSimpleName, matchMode, isCaseSensitive);
+}
+/**
+ * @see SearchPattern#matches(Binding)
+ */
+public boolean matches(Binding binding) {
+ if (!(binding instanceof ReferenceBinding)) return false;
+
+ ReferenceBinding[] superInterfaces = ((ReferenceBinding)binding).superInterfaces();
+ for (int i = 0, max = superInterfaces.length; i < max; i++){
+ if (this.matchesType(this.superSimpleName, this.superQualification, superInterfaces[i])){
+ return true;
+ }
+ }
+ return false;
+}
+/**
+ * @see SearchPattern#matchIndexEntry
+ */
+protected boolean matchIndexEntry() {
+ return
+ this.decodedSuperClassOrInterface == IIndexConstants.INTERFACE_SUFFIX
+ && super.matchIndexEntry();
+}
+public String toString(){
+ StringBuffer buffer = new StringBuffer(20);
+ buffer.append("SuperInterfaceReferencePattern: <");
+ if (superSimpleName != null) buffer.append(superSimpleName);
+ buffer.append(">, ");
+ switch(matchMode){
+ case EXACT_MATCH :
+ buffer.append("exact match, ");
+ break;
+ case PREFIX_MATCH :
+ buffer.append("prefix match, ");
+ break;
+ case PATTERN_MATCH :
+ buffer.append("pattern match, ");
+ break;
}
+ if (isCaseSensitive)
+ buffer.append("case sensitive");
+ else
+ buffer.append("case insensitive");
+ return buffer.toString();
+}
- /**
- * @see SearchPattern#matches(Binding)
- */
- public boolean matches(Binding binding) {
- if (!(binding instanceof ReferenceBinding))
- return false;
+/**
+ * @see SearchPattern#matchesBinary
+ */
+public boolean matchesBinary(Object binaryInfo, Object enclosingBinaryInfo) {
+ if (!(binaryInfo instanceof IBinaryType)) return false;
+ IBinaryType type = (IBinaryType)binaryInfo;
- ReferenceBinding[] superInterfaces =
- ((ReferenceBinding) binding).superInterfaces();
+ char[][] superInterfaces = type.getInterfaceNames();
+ if (superInterfaces != null) {
for (int i = 0, max = superInterfaces.length; i < max; i++) {
- if (this
- .matchesType(
- this.superSimpleName,
- this.superQualification,
- superInterfaces[i])) {
+ char[] superInterfaceName = (char[])superInterfaces[i].clone();
+ CharOperation.replace(superInterfaceName, '/', '.');
+ if (this.matchesType(this.superSimpleName, this.superQualification, superInterfaceName)){
return true;
}
}
- return false;
}
-
- /**
- * @see SearchPattern#matchIndexEntry
- */
- protected boolean matchIndexEntry() {
- return this.decodedSuperClassOrInterface == IIndexConstants.INTERFACE_SUFFIX
- && super.matchIndexEntry();
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer(20);
- buffer.append("SuperInterfaceReferencePattern: <");
- if (superSimpleName != null)
- buffer.append(superSimpleName);
- buffer.append(">, ");
- switch (matchMode) {
- case EXACT_MATCH :
- buffer.append("exact match, ");
- break;
- case PREFIX_MATCH :
- buffer.append("prefix match, ");
- break;
- case PATTERN_MATCH :
- buffer.append("pattern match, ");
- break;
- }
- if (isCaseSensitive)
- buffer.append("case sensitive");
- else
- buffer.append("case insensitive");
- return buffer.toString();
- }
-
+ return false;
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/SuperTypeReferencePattern.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/SuperTypeReferencePattern.java
index f02e880845..144edab8b3 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/SuperTypeReferencePattern.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/SuperTypeReferencePattern.java
@@ -16,6 +16,8 @@ import org.eclipse.jdt.internal.core.search.*;
import java.io.*;
+import org.eclipse.jdt.internal.compiler.env.IBinaryType;
+
public class SuperTypeReferencePattern extends SearchPattern {
public char[] superQualification;
@@ -29,226 +31,203 @@ public class SuperTypeReferencePattern extends SearchPattern {
protected char[] decodedEnclosingTypeName;
protected char decodedClassOrInterface;
protected int decodedModifiers;
- public SuperTypeReferencePattern(
- char[] superQualification,
- char[] superSimpleName,
- int matchMode,
- boolean isCaseSensitive) {
-
- super(matchMode, isCaseSensitive);
-
- this.superQualification =
- isCaseSensitive
- ? superQualification
- : CharOperation.toLowerCase(superQualification);
- this.superSimpleName =
- isCaseSensitive ? superSimpleName : CharOperation.toLowerCase(superSimpleName);
-
- this.needsResolve = superQualification != null;
+public SuperTypeReferencePattern(
+ char[] superQualification,
+ char[] superSimpleName,
+ int matchMode,
+ boolean isCaseSensitive) {
+
+ super(matchMode, isCaseSensitive);
+
+ this.superQualification = isCaseSensitive ? superQualification : CharOperation.toLowerCase(superQualification);
+ this.superSimpleName = isCaseSensitive ? superSimpleName : CharOperation.toLowerCase(superSimpleName);
+
+ this.needsResolve = superQualification != null;
+}
+/*
+ * superRef/Object/java.lang/X/p (i.e. class p.X extends java.lang.Object)
+ * superRef/Exception//X/p (i.e. class p.X extends Exception)
+ */
+public void decodeIndexEntry(IEntryResult entryResult){
+
+ char[] word = entryResult.getWord();
+ int slash = SUPER_REF.length - 1;
+ int size = word.length;
+ decodedSuperSimpleName = CharOperation.subarray(word, slash+1, slash = CharOperation.indexOf(SEPARATOR, word, slash+1));
+ int oldSlash = slash;
+ slash = CharOperation.indexOf(SEPARATOR, word, slash+1);
+ if (slash == oldSlash+1){ // could not have been known at index time
+ decodedSuperQualification = null;
+ } else {
+ decodedSuperQualification = CharOperation.subarray(word, oldSlash+1, slash);
}
-
- /*
- * superRef/Object/java.lang/X/p (i.e. class p.X extends java.lang.Object)
- * superRef/Exception//X/p (i.e. class p.X extends Exception)
- */
- public void decodeIndexEntry(IEntryResult entryResult) {
-
- char[] word = entryResult.getWord();
- int slash = SUPER_REF.length - 1;
- int size = word.length;
- decodedSuperSimpleName =
- CharOperation.subarray(
- word,
- slash + 1,
- slash = CharOperation.indexOf(SEPARATOR, word, slash + 1));
- int oldSlash = slash;
- slash = CharOperation.indexOf(SEPARATOR, word, slash + 1);
- if (slash == oldSlash + 1) { // could not have been known at index time
- decodedSuperQualification = null;
- } else {
- decodedSuperQualification = CharOperation.subarray(word, oldSlash + 1, slash);
- }
- decodedSuperClassOrInterface = word[slash + 1];
- slash += 2;
- decodedSimpleName =
- CharOperation.subarray(
- word,
- slash + 1,
- slash = CharOperation.indexOf(SEPARATOR, word, slash + 1));
- oldSlash = slash;
- slash = CharOperation.indexOf(SEPARATOR, word, slash + 1);
- if (slash == oldSlash + 1) { // could not have been known at index time
- decodedEnclosingTypeName = null;
- } else {
- decodedEnclosingTypeName = CharOperation.subarray(word, oldSlash + 1, slash);
- }
- oldSlash = slash;
- slash = CharOperation.indexOf(SEPARATOR, word, slash + 1);
- if (slash == oldSlash + 1) { // could not have been known at index time
- decodedQualification = null;
- } else {
- decodedQualification = CharOperation.subarray(word, oldSlash + 1, slash);
- }
-
- decodedClassOrInterface = word[slash + 1];
- decodedModifiers = (int) word[slash + 2];
+ decodedSuperClassOrInterface = word[slash+1];
+ slash += 2;
+ decodedSimpleName = CharOperation.subarray(word, slash+1, slash = CharOperation.indexOf(SEPARATOR, word, slash+1));
+ oldSlash = slash;
+ slash = CharOperation.indexOf(SEPARATOR, word, slash+1);
+ if (slash == oldSlash+1){ // could not have been known at index time
+ decodedEnclosingTypeName = null;
+ } else {
+ decodedEnclosingTypeName = CharOperation.subarray(word, oldSlash+1, slash);
}
-
- public void feedIndexRequestor(
- IIndexSearchRequestor requestor,
- int detailLevel,
- int[] references,
- IndexInput input,
- IJavaSearchScope scope)
- throws IOException {
- for (int i = 0, max = references.length; i < max; i++) {
- IndexedFile file = input.getIndexedFile(references[i]);
- String path;
- if (file != null
- && scope.encloses(path = IndexedFile.convertPath(file.getPath()))) {
- requestor.acceptSuperTypeReference(
- path,
- decodedQualification,
- decodedSimpleName,
- decodedEnclosingTypeName,
- decodedClassOrInterface,
- decodedSuperQualification,
- decodedSuperSimpleName,
- decodedSuperClassOrInterface,
- decodedModifiers);
- }
+ oldSlash = slash;
+ slash = CharOperation.indexOf(SEPARATOR, word, slash+1);
+ if (slash == oldSlash+1){ // could not have been known at index time
+ decodedQualification = null;
+ } else {
+ decodedQualification = CharOperation.subarray(word, oldSlash+1, slash);
+ }
+
+ decodedClassOrInterface = word[slash+1];
+ decodedModifiers = (int)word[slash+2];
+}
+public void feedIndexRequestor(IIndexSearchRequestor requestor, int detailLevel, int[] references, IndexInput input, IJavaSearchScope scope) throws IOException {
+ for (int i = 0, max = references.length; i < max; i++) {
+ IndexedFile file = input.getIndexedFile(references[i]);
+ String path;
+ if (file != null && scope.encloses(path = IndexedFile.convertPath(file.getPath()))) {
+ requestor.acceptSuperTypeReference(path, decodedQualification, decodedSimpleName, decodedEnclosingTypeName, decodedClassOrInterface, decodedSuperQualification, decodedSuperSimpleName, decodedSuperClassOrInterface, decodedModifiers);
}
}
+}
+/**
+ * see SearchPattern.indexEntryPrefix()
+ */
+public char[] indexEntryPrefix(){
- /**
- * see SearchPattern.indexEntryPrefix()
- */
- public char[] indexEntryPrefix() {
-
- return AbstractIndexer.bestReferencePrefix(
+ return AbstractIndexer.bestReferencePrefix(
SUPER_REF,
- superSimpleName,
- matchMode,
+ superSimpleName,
+ matchMode,
isCaseSensitive);
- }
-
- /**
- * @see SearchPattern#matchContainer()
- */
- protected int matchContainer() {
- return CLASS;
- }
-
- /**
- * @see SearchPattern#matches(AstNode, boolean)
- */
- protected boolean matches(AstNode node, boolean resolve) {
- if (!(node instanceof TypeReference))
- return false;
-
- TypeReference typeRef = (TypeReference) node;
- if (!resolve) {
- if (this.superSimpleName != null) {
- char[] typeRefSimpleName = null;
- if (typeRef instanceof SingleTypeReference) {
- typeRefSimpleName = ((SingleTypeReference) typeRef).token;
- } else { // QualifiedTypeReference
- char[][] tokens = ((QualifiedTypeReference) typeRef).tokens;
- typeRefSimpleName = tokens[tokens.length - 1];
- }
- if (!this.matchesName(this.superSimpleName, typeRefSimpleName))
- return false;
- }
- } else {
- TypeBinding binding = typeRef.binding;
- if (binding != null
- && !this.matchesType(this.superSimpleName, this.superQualification, binding))
+}
+/**
+ * @see SearchPattern#matchContainer()
+ */
+protected int matchContainer() {
+ return CLASS;
+}
+/**
+ * @see SearchPattern#matches(AstNode, boolean)
+ */
+protected boolean matches(AstNode node, boolean resolve) {
+ if (!(node instanceof TypeReference)) return false;
+
+ TypeReference typeRef = (TypeReference)node;
+ if (!resolve) {
+ if (this.superSimpleName != null) {
+ char[] typeRefSimpleName = null;
+ if (typeRef instanceof SingleTypeReference) {
+ typeRefSimpleName = ((SingleTypeReference)typeRef).token;
+ } else { // QualifiedTypeReference
+ char[][] tokens = ((QualifiedTypeReference)typeRef).tokens;
+ typeRefSimpleName = tokens[tokens.length-1];
+ }
+ if (!this.matchesName(this.superSimpleName, typeRefSimpleName))
return false;
}
- return true;
- }
-
- /**
- * @see SearchPattern#matches(Binding)
- */
- public boolean matches(Binding binding) {
- if (!(binding instanceof ReferenceBinding))
+ } else {
+ TypeBinding binding = typeRef.binding;
+ if (binding != null && !this.matchesType(this.superSimpleName, this.superQualification, binding))
return false;
-
- ReferenceBinding type = (ReferenceBinding) binding;
- if (this
- .matchesType(
- this.superSimpleName,
- this.superQualification,
- type.superclass())) {
- return true;
- }
-
- ReferenceBinding[] superInterfaces = type.superInterfaces();
- for (int i = 0, max = superInterfaces.length; i < max; i++) {
- if (this
- .matchesType(
- this.superSimpleName,
- this.superQualification,
- superInterfaces[i])) {
- return true;
- }
- }
- return false;
}
+ return true;
+}
+/**
+ * @see SearchPattern#matches(Binding)
+ */
+public boolean matches(Binding binding) {
+ if (!(binding instanceof ReferenceBinding)) return false;
- /**
- * @see SearchPattern#matchIndexEntry
- */
- protected boolean matchIndexEntry() {
-
- /* check type name matches */
- if (superSimpleName != null) {
- switch (matchMode) {
- case EXACT_MATCH :
- if (!CharOperation
- .equals(superSimpleName, decodedSuperSimpleName, isCaseSensitive)) {
- return false;
- }
- break;
- case PREFIX_MATCH :
- if (!CharOperation
- .prefixEquals(superSimpleName, decodedSuperSimpleName, isCaseSensitive)) {
- return false;
- }
- break;
- case PATTERN_MATCH :
- if (!CharOperation
- .match(superSimpleName, decodedSuperSimpleName, isCaseSensitive)) {
- return false;
- }
- }
- }
+ ReferenceBinding type = (ReferenceBinding) binding;
+ if (this.matchesType(this.superSimpleName, this.superQualification, type.superclass())){
return true;
}
+
+ ReferenceBinding[] superInterfaces = type.superInterfaces();
+ for (int i = 0, max = superInterfaces.length; i < max; i++){
+ if (this.matchesType(this.superSimpleName, this.superQualification, superInterfaces[i])){
+ return true;
+ }
+ }
+ return false;
+}
+/**
+ * @see SearchPattern#matchIndexEntry
+ */
+protected boolean matchIndexEntry() {
- public String toString() {
- StringBuffer buffer = new StringBuffer(20);
- buffer.append("SuperTypeReferencePattern: <");
- if (superSimpleName != null)
- buffer.append(superSimpleName);
- buffer.append(">, ");
- switch (matchMode) {
+ /* check type name matches */
+ if (superSimpleName != null){
+ switch(matchMode){
case EXACT_MATCH :
- buffer.append("exact match, ");
+ if (!CharOperation.equals(superSimpleName, decodedSuperSimpleName, isCaseSensitive)){
+ return false;
+ }
break;
case PREFIX_MATCH :
- buffer.append("prefix match, ");
+ if (!CharOperation.prefixEquals(superSimpleName, decodedSuperSimpleName, isCaseSensitive)){
+ return false;
+ }
break;
case PATTERN_MATCH :
- buffer.append("pattern match, ");
- break;
+ if (!CharOperation.match(superSimpleName, decodedSuperSimpleName, isCaseSensitive)){
+ return false;
+ }
}
- if (isCaseSensitive)
- buffer.append("case sensitive");
- else
- buffer.append("case insensitive");
- return buffer.toString();
}
+ return true;
+}
+public String toString(){
+ StringBuffer buffer = new StringBuffer(20);
+ buffer.append("SuperTypeReferencePattern: <");
+ if (superSimpleName != null) buffer.append(superSimpleName);
+ buffer.append(">, ");
+ switch(matchMode){
+ case EXACT_MATCH :
+ buffer.append("exact match, ");
+ break;
+ case PREFIX_MATCH :
+ buffer.append("prefix match, ");
+ break;
+ case PATTERN_MATCH :
+ buffer.append("pattern match, ");
+ break;
+ }
+ if (isCaseSensitive)
+ buffer.append("case sensitive");
+ else
+ buffer.append("case insensitive");
+ return buffer.toString();
+}
+/**
+ * @see SearchPattern#matchesBinary
+ */
+public boolean matchesBinary(Object binaryInfo, Object enclosingBinaryInfo) {
+ if (!(binaryInfo instanceof IBinaryType)) return false;
+ IBinaryType type = (IBinaryType)binaryInfo;
+
+ char[] vmName = type.getSuperclassName();
+ if (vmName != null) {
+ char[] superclassName = (char[])vmName.clone();
+ CharOperation.replace(vmName, '/', '.');
+ if (this.matchesType(this.superSimpleName, this.superQualification, superclassName)){
+ return true;
+ }
+ }
+
+ char[][] superInterfaces = type.getInterfaceNames();
+ if (superInterfaces != null) {
+ for (int i = 0, max = superInterfaces.length; i < max; i++) {
+ char[] superInterfaceName = (char[])superInterfaces[i].clone();
+ CharOperation.replace(superInterfaceName, '/', '.');
+ if (this.matchesType(this.superSimpleName, this.superQualification, superInterfaceName)){
+ return true;
+ }
+ }
+ }
+ return false;
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/TypeDeclarationPattern.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/TypeDeclarationPattern.java
index 3c9f2f5140..7970913d3a 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/TypeDeclarationPattern.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/TypeDeclarationPattern.java
@@ -28,366 +28,296 @@ public class TypeDeclarationPattern extends SearchPattern {
// set to CLASS_SUFFIX for only matching classes
// set to INTERFACE_SUFFIX for only matching interfaces
// set to TYPE_SUFFIX for matching both classes and interfaces
- private char classOrInterface;
+ private char classOrInterface;
private char[] decodedQualification;
private char[] decodedSimpleName;
private char[][] decodedEnclosingTypeNames;
private char decodedClassOrInterface;
- public TypeDeclarationPattern(
- char[] qualification,
- char[][] enclosingTypeNames,
- char[] simpleName,
- char classOrInterface,
- int matchMode,
- boolean isCaseSensitive) {
-
- super(matchMode, isCaseSensitive);
-
- this.qualification =
- isCaseSensitive ? qualification : CharOperation.toLowerCase(qualification);
- if (isCaseSensitive || enclosingTypeNames == null) {
- this.enclosingTypeNames = enclosingTypeNames;
- } else {
- int length = enclosingTypeNames.length;
- this.enclosingTypeNames = new char[length][];
- for (int i = 0; i < length; i++) {
- this.enclosingTypeNames[i] = CharOperation.toLowerCase(enclosingTypeNames[i]);
- }
+public TypeDeclarationPattern(
+ char[] qualification,
+ char[][] enclosingTypeNames,
+ char[] simpleName,
+ char classOrInterface,
+ int matchMode,
+ boolean isCaseSensitive) {
+
+ super(matchMode, isCaseSensitive);
+
+ this.qualification = isCaseSensitive ? qualification : CharOperation.toLowerCase(qualification);
+ if (isCaseSensitive || enclosingTypeNames == null) {
+ this.enclosingTypeNames = enclosingTypeNames;
+ } else {
+ int length = enclosingTypeNames.length;
+ this.enclosingTypeNames = new char[length][];
+ for (int i = 0; i < length; i++){
+ this.enclosingTypeNames[i] = CharOperation.toLowerCase(enclosingTypeNames[i]);
}
- this.simpleName =
- isCaseSensitive ? simpleName : CharOperation.toLowerCase(simpleName);
- this.classOrInterface = classOrInterface;
-
- this.needsResolve = qualification != null;
}
-
- public void decodeIndexEntry(IEntryResult entryResult) {
-
- char[] word = entryResult.getWord();
- int size = word.length;
-
- decodedClassOrInterface = word[TYPE_DECL_LENGTH];
- int oldSlash = TYPE_DECL_LENGTH + 1;
- int slash = CharOperation.indexOf(SEPARATOR, word, oldSlash + 1);
- if (slash == oldSlash + 1) {
- decodedQualification = NO_CHAR;
- } else {
- decodedQualification = CharOperation.subarray(word, oldSlash + 1, slash);
- }
- decodedSimpleName =
- CharOperation.subarray(
- word,
- slash + 1,
- slash = CharOperation.indexOf(SEPARATOR, word, slash + 1));
-
- if (slash + 1 < size) {
- decodedEnclosingTypeNames =
- CharOperation.splitOn('/', CharOperation.subarray(word, slash + 1, size - 1));
- } else {
- decodedEnclosingTypeNames = NO_CHAR_CHAR;
- }
+ this.simpleName = isCaseSensitive ? simpleName : CharOperation.toLowerCase(simpleName);
+ this.classOrInterface = classOrInterface;
+
+ this.needsResolve = qualification != null;
+}
+public void decodeIndexEntry(IEntryResult entryResult){
+
+ char[] word = entryResult.getWord();
+ int size = word.length;
+
+ decodedClassOrInterface = word[TYPE_DECL_LENGTH];
+ int oldSlash = TYPE_DECL_LENGTH+1;
+ int slash = CharOperation.indexOf(SEPARATOR, word, oldSlash+1);
+ if (slash == oldSlash+1){
+ decodedQualification = NO_CHAR;
+ } else {
+ decodedQualification = CharOperation.subarray(word, oldSlash+1, slash);
}
+ decodedSimpleName = CharOperation.subarray(word, slash+1, slash = CharOperation.indexOf(SEPARATOR, word, slash+1));
- /**
- * see SearchPattern.feedIndexRequestor
- */
- public void feedIndexRequestor(
- IIndexSearchRequestor requestor,
- int detailLevel,
- int[] references,
- IndexInput input,
- IJavaSearchScope scope)
- throws IOException {
- boolean isClass = decodedClassOrInterface == CLASS_SUFFIX;
- for (int i = 0, max = references.length; i < max; i++) {
- IndexedFile file = input.getIndexedFile(references[i]);
- String path;
- if (file != null
- && scope.encloses(path = IndexedFile.convertPath(file.getPath()))) {
- if (isClass) {
- requestor.acceptClassDeclaration(
- path,
- decodedSimpleName,
- decodedEnclosingTypeNames,
- decodedQualification);
- } else {
- requestor.acceptInterfaceDeclaration(
- path,
- decodedSimpleName,
- decodedEnclosingTypeNames,
- decodedQualification);
- }
+ if (slash+1 < size){
+ decodedEnclosingTypeNames = CharOperation.splitOn('/', CharOperation.subarray(word, slash+1, size-1));
+ } else {
+ decodedEnclosingTypeNames = NO_CHAR_CHAR;
+ }
+}
+/**
+ * see SearchPattern.feedIndexRequestor
+ */
+public void feedIndexRequestor(IIndexSearchRequestor requestor, int detailLevel, int[] references, IndexInput input, IJavaSearchScope scope) throws IOException {
+ boolean isClass = decodedClassOrInterface == CLASS_SUFFIX;
+ for (int i = 0, max = references.length; i < max; i++) {
+ IndexedFile file = input.getIndexedFile(references[i]);
+ String path;
+ if (file != null && scope.encloses(path =IndexedFile.convertPath(file.getPath()))) {
+ if (isClass) {
+ requestor.acceptClassDeclaration(path, decodedSimpleName, decodedEnclosingTypeNames, decodedQualification);
+ } else {
+ requestor.acceptInterfaceDeclaration(path, decodedSimpleName, decodedEnclosingTypeNames, decodedQualification);
}
}
}
+}
+/**
+ * see SearchPattern.indexEntryPrefix()
+ */
+public char[] indexEntryPrefix(){
- /**
- * see SearchPattern.indexEntryPrefix()
- */
- public char[] indexEntryPrefix() {
-
- return AbstractIndexer.bestTypeDeclarationPrefix(
+ return AbstractIndexer.bestTypeDeclarationPrefix(
qualification,
simpleName,
classOrInterface,
- matchMode,
+ matchMode,
isCaseSensitive);
- }
-
- /**
- * @see SearchPattern#matchContainer()
- */
- protected int matchContainer() {
- return COMPILATION_UNIT | CLASS;
- }
-
- /**
- * @see SearchPattern#matches(AstNode, boolean)
- */
- protected boolean matches(AstNode node, boolean resolve) {
- if (!(node instanceof TypeDeclaration))
- return false;
-
- TypeDeclaration type = (TypeDeclaration) node;
-
- // type name
- if (this.simpleName != null && !this.matchesName(this.simpleName, type.name))
- return false;
-
- if (resolve) {
- // fully qualified name
- TypeBinding binding = type.binding;
- if (binding != null && !this.matches(binding)) {
- return false;
- }
- }
-
- return true;
- }
+}
+/**
+ * @see SearchPattern#matchContainer()
+ */
+protected int matchContainer() {
+ return COMPILATION_UNIT | CLASS;
+}
+/**
+ * @see SearchPattern#matches(AstNode, boolean)
+ */
+protected boolean matches(AstNode node, boolean resolve) {
+ if (!(node instanceof TypeDeclaration)) return false;
- /**
- * @see SearchPattern#matches(Binding)
- */
- public boolean matches(Binding binding) {
- if (!(binding instanceof TypeBinding))
- return false;
+ TypeDeclaration type = (TypeDeclaration)node;
- TypeBinding type = (TypeBinding) binding;
+ // type name
+ if (this.simpleName != null && !this.matchesName(this.simpleName, type.name))
+ return false;
+ if (resolve) {
// fully qualified name
- char[] enclosingTypeName =
- this.enclosingTypeNames == null
- ? null
- : CharOperation.concatWith(this.enclosingTypeNames, '.');
- if (!this
- .matchesType(this.simpleName, this.qualification, enclosingTypeName, type)) {
+ TypeBinding binding = type.binding;
+ if (binding != null && !this.matches(binding)) {
return false;
}
-
- // class or interface
- switch (this.classOrInterface) {
- case CLASS_SUFFIX :
- if (type.isInterface())
- return false;
- break;
- case INTERFACE_SUFFIX :
- if (!type.isInterface())
- return false;
- break;
- }
-
- return true;
}
+
+ return true;
+}
+/**
+ * @see SearchPattern#matches(Binding)
+ */
+public boolean matches(Binding binding) {
+ if (!(binding instanceof TypeBinding)) return false;
- /**
- * @see SearchPattern#matchesBinary(Object, Object)
- */
- public boolean matchesBinary(Object binaryInfo, Object enclosingBinaryInfo) {
- if (!(binaryInfo instanceof IBinaryType))
- return false;
+ TypeBinding type = (TypeBinding)binding;
- IBinaryType type = (IBinaryType) binaryInfo;
+ // fully qualified name
+ char[] enclosingTypeName = this.enclosingTypeNames == null ? null : CharOperation.concatWith(this.enclosingTypeNames, '.');
+ if (!this.matchesType(this.simpleName, this.qualification, enclosingTypeName, type)) {
+ return false;
+ }
- // fully qualified name
- char[] typeName = (char[]) type.getName().clone();
- CharOperation.replace(typeName, '/', '.');
- char[] enclosingTypeName =
- this.enclosingTypeNames == null
- ? null
- : CharOperation.concatWith(this.enclosingTypeNames, '.');
- if (!this
- .matchesType(
- this.simpleName,
- this.qualification,
- enclosingTypeName,
- typeName)) {
- return false;
- }
+ // class or interface
+ switch (this.classOrInterface) {
+ case CLASS_SUFFIX:
+ if (type.isInterface())
+ return false;
+ break;
+ case INTERFACE_SUFFIX:
+ if (!type.isInterface())
+ return false;
+ break;
+ }
+
+ return true;
+}
+/**
+ * @see SearchPattern#matchesBinary(Object, Object)
+ */
+public boolean matchesBinary(Object binaryInfo, Object enclosingBinaryInfo) {
+ if (!(binaryInfo instanceof IBinaryType)) return false;
- // class or interface
- switch (this.classOrInterface) {
- case CLASS_SUFFIX :
- if (type.isInterface())
- return false;
- break;
- case INTERFACE_SUFFIX :
- if (!type.isInterface())
- return false;
- break;
- }
+ IBinaryType type = (IBinaryType)binaryInfo;
- return true;
+ // fully qualified name
+ char[] typeName = (char[])type.getName().clone();
+ CharOperation.replace(typeName, '/', '.');
+ char[] enclosingTypeName = this.enclosingTypeNames == null ? null : CharOperation.concatWith(this.enclosingTypeNames, '.');
+ if (!this.matchesType(this.simpleName, this.qualification, enclosingTypeName, typeName)) {
+ return false;
}
- /**
- * Returns whether the given type binding matches the given simple name pattern
- * qualification pattern and enclosing name pattern.
- */
- protected boolean matchesType(
- char[] simpleNamePattern,
- char[] qualificationPattern,
- char[] enclosingNamePattern,
- char[] fullyQualifiedTypeName) {
- if (enclosingNamePattern == null) {
- return this.matchesType(
- simpleNamePattern,
- qualificationPattern,
- fullyQualifiedTypeName);
+ // class or interface
+ switch (this.classOrInterface) {
+ case CLASS_SUFFIX:
+ if (type.isInterface())
+ return false;
+ break;
+ case INTERFACE_SUFFIX:
+ if (!type.isInterface())
+ return false;
+ break;
+ }
+
+ return true;
+}
+/**
+ * Returns whether the given type binding matches the given simple name pattern
+ * qualification pattern and enclosing name pattern.
+ */
+protected boolean matchesType(char[] simpleNamePattern, char[] qualificationPattern, char[] enclosingNamePattern, char[] fullyQualifiedTypeName) {
+ if (enclosingNamePattern == null) {
+ return this.matchesType(simpleNamePattern, qualificationPattern, fullyQualifiedTypeName);
+ } else {
+ char[] pattern;
+ if (qualificationPattern == null) {
+ pattern = enclosingNamePattern;
} else {
- char[] pattern;
- if (qualificationPattern == null) {
- pattern = enclosingNamePattern;
- } else {
- pattern = CharOperation.concat(qualificationPattern, enclosingNamePattern, '.');
- }
- return this.matchesType(simpleNamePattern, pattern, fullyQualifiedTypeName);
+ pattern = CharOperation.concat(qualificationPattern, enclosingNamePattern, '.');
}
+ return this.matchesType(simpleNamePattern, pattern, fullyQualifiedTypeName);
}
-
- /**
- * Returns whether the given type binding matches the given simple name pattern
- * qualification pattern and enclosing type name pattern.
- */
- protected boolean matchesType(
- char[] simpleNamePattern,
- char[] qualificationPattern,
- char[] enclosingNamePattern,
- TypeBinding type) {
- if (enclosingNamePattern == null) {
- return this.matchesType(simpleNamePattern, qualificationPattern, type);
+}
+/**
+ * Returns whether the given type binding matches the given simple name pattern
+ * qualification pattern and enclosing type name pattern.
+ */
+protected boolean matchesType(char[] simpleNamePattern, char[] qualificationPattern, char[] enclosingNamePattern, TypeBinding type) {
+ if (enclosingNamePattern == null) {
+ return this.matchesType(simpleNamePattern, qualificationPattern, type);
+ } else {
+ char[] pattern;
+ if (qualificationPattern == null) {
+ return matchesType(simpleNamePattern, enclosingNamePattern, type);
} else {
- char[] pattern;
- if (qualificationPattern == null) {
- return matchesType(simpleNamePattern, enclosingNamePattern, type);
- } else {
- // pattern was created from a Java element: qualification is the package name.
- char[] fullQualificationPattern =
- CharOperation.concat(qualificationPattern, enclosingNamePattern, '.');
- return this.matchesType(simpleNamePattern, fullQualificationPattern, type)
- && CharOperation.equals(
- qualification,
- CharOperation.concatWith(type.getPackage().compoundName, '.'));
- }
+ // pattern was created from a Java element: qualification is the package name.
+ char[] fullQualificationPattern = CharOperation.concat(qualificationPattern, enclosingNamePattern, '.');
+ return
+ this.matchesType(simpleNamePattern, fullQualificationPattern, type)
+ && CharOperation.equals(qualification, CharOperation.concatWith(type.getPackage().compoundName, '.'));
}
}
-
- /**
- * see SearchPattern.matchIndexEntry
- */
- protected boolean matchIndexEntry() {
-
- /* check class/interface nature */
- switch (classOrInterface) {
- case CLASS_SUFFIX :
- case INTERFACE_SUFFIX :
- if (classOrInterface != decodedClassOrInterface)
- return false;
- default :
- }
- /* check qualification - exact match only */
- if (qualification != null
- && !CharOperation.equals(qualification, decodedQualification, isCaseSensitive))
- return false;
- /* check enclosingTypeName - exact match only */
- if (enclosingTypeNames != null) {
- // empty char[][] means no enclosing type, i.e. the decoded one is the empty char array
- if (enclosingTypeNames.length == 0) {
- if (decodedEnclosingTypeNames != NO_CHAR_CHAR)
- return false;
- } else {
- if (!CharOperation
- .equals(enclosingTypeNames, decodedEnclosingTypeNames, isCaseSensitive))
- return false;
- }
- }
-
- /* check simple name matches */
- if (simpleName != null) {
- switch (matchMode) {
- case EXACT_MATCH :
- if (!CharOperation.equals(simpleName, decodedSimpleName, isCaseSensitive)) {
- return false;
- }
- break;
- case PREFIX_MATCH :
- if (!CharOperation
- .prefixEquals(simpleName, decodedSimpleName, isCaseSensitive)) {
- return false;
- }
- break;
- case PATTERN_MATCH :
- if (!CharOperation.match(simpleName, decodedSimpleName, isCaseSensitive)) {
- return false;
- }
- }
+}
+/**
+ * see SearchPattern.matchIndexEntry
+ */
+protected boolean matchIndexEntry(){
+
+ /* check class/interface nature */
+ switch(classOrInterface){
+ case CLASS_SUFFIX :
+ case INTERFACE_SUFFIX :
+ if (classOrInterface != decodedClassOrInterface) return false;
+ default :
+ }
+ /* check qualification - exact match only */
+ if (qualification != null && !CharOperation.equals(qualification, decodedQualification, isCaseSensitive))
+ return false;
+ /* check enclosingTypeName - exact match only */
+ if (enclosingTypeNames != null){
+ // empty char[][] means no enclosing type, i.e. the decoded one is the empty char array
+ if (enclosingTypeNames.length == 0){
+ if (decodedEnclosingTypeNames != NO_CHAR_CHAR) return false;
+ } else {
+ if (!CharOperation.equals(enclosingTypeNames, decodedEnclosingTypeNames, isCaseSensitive)) return false;
}
- return true;
}
- public String toString() {
- StringBuffer buffer = new StringBuffer(20);
- switch (classOrInterface) {
- case CLASS_SUFFIX :
- buffer.append("ClassDeclarationPattern: pkg<");
- break;
- case INTERFACE_SUFFIX :
- buffer.append("InterfaceDeclarationPattern: pkg<");
- break;
- default :
- buffer.append("TypeDeclarationPattern: pkg<");
- break;
- }
- if (qualification != null)
- buffer.append(qualification);
- buffer.append(">, enclosing<");
- if (enclosingTypeNames != null) {
- for (int i = 0; i < enclosingTypeNames.length; i++) {
- buffer.append(enclosingTypeNames[i]);
- if (i < enclosingTypeNames.length - 1)
- buffer.append('.');
- }
- }
- buffer.append(">, type<");
- if (simpleName != null)
- buffer.append(simpleName);
- buffer.append(">, ");
- switch (matchMode) {
+ /* check simple name matches */
+ if (simpleName != null){
+ switch(matchMode){
case EXACT_MATCH :
- buffer.append("exact match, ");
+ if (!CharOperation.equals(simpleName, decodedSimpleName, isCaseSensitive)){
+ return false;
+ }
break;
case PREFIX_MATCH :
- buffer.append("prefix match, ");
+ if (!CharOperation.prefixEquals(simpleName, decodedSimpleName, isCaseSensitive)){
+ return false;
+ }
break;
case PATTERN_MATCH :
- buffer.append("pattern match, ");
- break;
+ if (!CharOperation.match(simpleName, decodedSimpleName, isCaseSensitive)){
+ return false;
+ }
}
- if (isCaseSensitive)
- buffer.append("case sensitive");
- else
- buffer.append("case insensitive");
- return buffer.toString();
}
-
+ return true;
+}
+public String toString(){
+ StringBuffer buffer = new StringBuffer(20);
+ switch (classOrInterface){
+ case CLASS_SUFFIX :
+ buffer.append("ClassDeclarationPattern: pkg<");
+ break;
+ case INTERFACE_SUFFIX :
+ buffer.append("InterfaceDeclarationPattern: pkg<");
+ break;
+ default :
+ buffer.append("TypeDeclarationPattern: pkg<");
+ break;
+ }
+ if (qualification != null) buffer.append(qualification);
+ buffer.append(">, enclosing<");
+ if (enclosingTypeNames != null) {
+ for (int i = 0; i < enclosingTypeNames.length; i++){
+ buffer.append(enclosingTypeNames[i]);
+ if (i < enclosingTypeNames.length - 1)
+ buffer.append('.');
+ }
+ }
+ buffer.append(">, type<");
+ if (simpleName != null) buffer.append(simpleName);
+ buffer.append(">, ");
+ switch(matchMode){
+ case EXACT_MATCH :
+ buffer.append("exact match, ");
+ break;
+ case PREFIX_MATCH :
+ buffer.append("prefix match, ");
+ break;
+ case PATTERN_MATCH :
+ buffer.append("pattern match, ");
+ break;
+ }
+ if (isCaseSensitive)
+ buffer.append("case sensitive");
+ else
+ buffer.append("case insensitive");
+ return buffer.toString();
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/TypeReferencePattern.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/TypeReferencePattern.java
index 7d1263549b..d77743e201 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/TypeReferencePattern.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/matching/TypeReferencePattern.java
@@ -35,504 +35,406 @@ public class TypeReferencePattern extends MultipleSearchPattern {
private char[][] segments;
private int currentSegment;
private char[] decodedSegment;
- public TypeReferencePattern(
- char[] qualification,
- char[] simpleName,
- int matchMode,
- boolean isCaseSensitive) {
+public TypeReferencePattern(
+ char[] qualification,
+ char[] simpleName,
+ int matchMode,
+ boolean isCaseSensitive) {
- super(matchMode, isCaseSensitive);
+ super(matchMode, isCaseSensitive);
- this.qualification =
- isCaseSensitive ? qualification : CharOperation.toLowerCase(qualification);
- this.simpleName =
- isCaseSensitive ? simpleName : CharOperation.toLowerCase(simpleName);
+ this.qualification = isCaseSensitive ? qualification : CharOperation.toLowerCase(qualification);
+ this.simpleName = isCaseSensitive ? simpleName : CharOperation.toLowerCase(simpleName);
- if (simpleName == null) {
- this.segments = CharOperation.splitOn('.', qualification);
- }
-
- this.needsResolve = qualification != null;
+ if (simpleName == null) {
+ this.segments = CharOperation.splitOn('.', qualification);
}
-
- /**
- * Either decode ref/name, typeRef/name or superRef/superName/name
- */
- public void decodeIndexEntry(IEntryResult entryResult) {
-
- char[] word = entryResult.getWord();
- int size = word.length;
- int tagLength = currentTag.length;
- int nameLength = CharOperation.indexOf(SEPARATOR, word, tagLength);
- if (nameLength < 0)
- nameLength = size;
- if (this.simpleName == null) {
- // Optimization, eg. type reference is 'org.eclipse.jdt.core.*'
- this.decodedSegment = CharOperation.subarray(word, tagLength, nameLength);
- } else {
- this.decodedSimpleName = CharOperation.subarray(word, tagLength, nameLength);
- }
+
+ this.needsResolve = qualification != null;
+}
+/**
+ * Either decode ref/name, typeRef/name or superRef/superName/name
+ */
+public void decodeIndexEntry(IEntryResult entryResult){
+
+ char[] word = entryResult.getWord();
+ int size = word.length;
+ int tagLength = currentTag.length;
+ int nameLength = CharOperation.indexOf(SEPARATOR, word, tagLength);
+ if (nameLength < 0) nameLength = size;
+ if (this.simpleName == null) {
+ // Optimization, eg. type reference is 'org.eclipse.jdt.core.*'
+ this.decodedSegment = CharOperation.subarray(word, tagLength, nameLength);
+ } else {
+ this.decodedSimpleName = CharOperation.subarray(word, tagLength, nameLength);
}
-
- public void feedIndexRequestor(
- IIndexSearchRequestor requestor,
- int detailLevel,
- int[] references,
- IndexInput input,
- IJavaSearchScope scope)
- throws IOException {
- if (currentTag == REF) {
- foundAmbiguousIndexMatches = true;
- }
- for (int i = 0, max = references.length; i < max; i++) {
- int reference = references[i];
- if (reference != -1) { // if the reference has not been eliminated
- IndexedFile file = input.getIndexedFile(reference);
- String path;
- if (file != null
- && scope.encloses(path = IndexedFile.convertPath(file.getPath()))) {
- requestor.acceptTypeReference(path, decodedSimpleName);
- }
+}
+public void feedIndexRequestor(IIndexSearchRequestor requestor, int detailLevel, int[] references, IndexInput input, IJavaSearchScope scope) throws IOException {
+ if (currentTag == REF) {
+ foundAmbiguousIndexMatches = true;
+ }
+ for (int i = 0, max = references.length; i < max; i++) {
+ int reference = references[i];
+ if (reference != -1) { // if the reference has not been eliminated
+ IndexedFile file = input.getIndexedFile(reference);
+ String path;
+ if (file != null && scope.encloses(path = IndexedFile.convertPath(file.getPath()))) {
+ requestor.acceptTypeReference(path, decodedSimpleName);
}
}
}
-
- protected char[][] getPossibleTags() {
- if (this.simpleName == null) {
- return REF_TAGS;
+}
+protected char[][] getPossibleTags(){
+ if (this.simpleName == null) {
+ return REF_TAGS;
+ } else {
+ return TAGS;
+ }
+}
+/**
+ * @see AndPattern#hasNextQuery
+ */
+protected boolean hasNextQuery() {
+ if (this.simpleName == null) {
+ // Optimization, eg. type reference is 'org.eclipse.jdt.core.*'
+ if (this.segments.length > 2) {
+ // if package has more than 2 segments, don't look at the first 2 since they are mostly
+ // redundant (eg. in 'org.eclipse.jdt.core.*', 'com.ibm' is used all the time)
+ return --this.currentSegment >= 2;
} else {
- return TAGS;
+ return --this.currentSegment >= 0;
}
+ } else {
+ return false;
}
-
- /**
- * @see AndPattern#hasNextQuery
- */
- protected boolean hasNextQuery() {
- if (this.simpleName == null) {
- // Optimization, eg. type reference is 'org.eclipse.jdt.core.*'
- if (this.segments.length > 2) {
- // if package has more than 2 segments, don't look at the first 2 since they are mostly
- // redundant (eg. in 'org.eclipse.jdt.core.*', 'com.ibm' is used all the time)
- return --this.currentSegment >= 2;
- } else {
- return --this.currentSegment >= 0;
+}
+/**
+ * see SearchPattern.indexEntryPrefix()
+ */
+public char[] indexEntryPrefix(){
+
+ if (this.simpleName == null) {
+ // Optimization, eg. type reference is 'org.eclipse.jdt.core.*'
+ return AbstractIndexer.bestReferencePrefix(
+ REF,
+ this.segments[this.currentSegment],
+ matchMode,
+ isCaseSensitive);
+ } else {
+ return AbstractIndexer.bestReferencePrefix(
+ currentTag,
+ simpleName,
+ matchMode,
+ isCaseSensitive);
+ }
+}
+/**
+ * @see SearchPattern#matchContainer()
+ */
+protected int matchContainer() {
+ return COMPILATION_UNIT | CLASS | METHOD | FIELD;
+}
+/**
+ * @see SearchPattern#matches(AstNode, boolean)
+ */
+protected boolean matches(AstNode node, boolean resolve) {
+ if (node instanceof TypeReference) {
+ return this.matches((TypeReference)node, resolve);
+ } else if (node instanceof NameReference) {
+ return this.matches((NameReference)node, resolve);
+ } else if (node instanceof ImportReference) {
+ return this.matches((ImportReference)node, resolve);
+ }
+ return false;
+}
+/**
+ * Returns whether this type pattern matches the given import reference.
+ * Look at resolved information only if specified.
+ */
+private boolean matches(ImportReference importRef, boolean resolve) {
+
+ if (importRef.onDemand) return false;
+
+ char[][] tokens = importRef.tokens;
+ int importLength = tokens.length;
+
+ if (this.qualification != null){
+ char[][] qualificationTokens = CharOperation.splitOn('.', this.qualification);
+ int qualificationLength = qualificationTokens.length;
+ if (qualificationLength+1 > importLength) return false;
+ for (int i = 0; i < qualificationLength; i++){
+ if (!this.matchesName(qualificationTokens[i], tokens[i])) {
+ return false;
}
- } else {
+ }
+ if (this.simpleName != null
+ && !this.matchesName(this.simpleName, tokens[qualificationLength])) {
return false;
}
- }
-
- /**
- * see SearchPattern.indexEntryPrefix()
- */
- public char[] indexEntryPrefix() {
-
- if (this.simpleName == null) {
- // Optimization, eg. type reference is 'org.eclipse.jdt.core.*'
- return AbstractIndexer.bestReferencePrefix(
- REF,
- this.segments[this.currentSegment],
- matchMode,
- isCaseSensitive);
- } else {
- return AbstractIndexer.bestReferencePrefix(
- currentTag,
- simpleName,
- matchMode,
- isCaseSensitive);
+ } else {
+ if (this.simpleName != null) {
+ for (int i = 0; i < importLength; i++){
+ if (this.matchesName(this.simpleName, tokens[i])){
+ return true;
+ }
+ }
+ return false;
}
}
-
- /**
- * @see SearchPattern#matchContainer()
- */
- protected int matchContainer() {
- return COMPILATION_UNIT | CLASS | METHOD | FIELD;
- }
-
- /**
- * @see SearchPattern#matches(AstNode, boolean)
- */
- protected boolean matches(AstNode node, boolean resolve) {
- if (node instanceof TypeReference) {
- return this.matches((TypeReference) node, resolve);
- } else
- if (node instanceof NameReference) {
- return this.matches((NameReference) node, resolve);
- } else
- if (node instanceof ImportReference) {
- return this.matches((ImportReference) node, resolve);
+ return true;
+}
+/**
+ * Returns whether this type pattern matches the given name reference.
+ * Look at resolved information only if specified.
+ */
+private boolean matches(NameReference nameRef, boolean resolve) {
+ Binding binding = nameRef.binding;
+ if (!resolve || binding == null || !binding.isValidBinding()) {
+ if (this.simpleName != null) {
+ if (nameRef instanceof SingleNameReference) {
+ return this.matchesName(this.simpleName, ((SingleNameReference)nameRef).token);
+ } else { // QualifiedNameReference
+ char[][] tokens = ((QualifiedNameReference)nameRef).tokens;
+ for (int i = 0, max = tokens.length; i < max; i++){
+ if (this.matchesName(this.simpleName, tokens[i])) return true;
}
- return false;
- }
-
- /**
- * Returns whether this type pattern matches the given import reference.
- * Look at resolved information only if specified.
- */
- private boolean matches(ImportReference importRef, boolean resolve) {
-
- if (importRef.onDemand)
- return false;
-
- char[][] tokens = importRef.tokens;
- int importLength = tokens.length;
-
- if (this.qualification != null) {
- char[][] qualificationTokens = CharOperation.splitOn('.', this.qualification);
- int qualificationLength = qualificationTokens.length;
- if (qualificationLength + 1 > importLength)
return false;
- for (int i = 0; i < qualificationLength; i++) {
- if (!this.matchesName(qualificationTokens[i], tokens[i])) {
+ }
+ }
+ } else {
+ if (nameRef instanceof SingleNameReference){
+ if (binding instanceof TypeBinding){
+ if (!this.matchesType(this.simpleName, this.qualification, (TypeBinding) binding)){
return false;
}
+ } else {
+ return false; // must be a type binding
}
- if (this.simpleName != null
- && !this.matchesName(this.simpleName, tokens[qualificationLength])) {
- return false;
+ } else { // QualifiedNameReference
+ TypeBinding typeBinding = null;
+ QualifiedNameReference qNameRef = (QualifiedNameReference)nameRef;
+ char[][] tokens = qNameRef.tokens;
+ int lastIndex = tokens.length-1;
+ switch (qNameRef.bits & Statement.RestrictiveFlagMASK) {
+ case BindingIds.FIELD : // reading a field
+ typeBinding = ((FieldBinding)binding).declaringClass;
+ // no valid match amongst fields
+ int otherBindingsCount = qNameRef.otherBindings == null ? 0 : qNameRef.otherBindings.length;
+ lastIndex -= otherBindingsCount + 1;
+ if (lastIndex < 0) return false;
+ break;
+ case BindingIds.LOCAL : // reading a local variable
+ return false; // no type match in it
+ case BindingIds.TYPE : //=============only type ==============
+ typeBinding = (TypeBinding)binding;
}
- } else {
- if (this.simpleName != null) {
- for (int i = 0; i < importLength; i++) {
- if (this.matchesName(this.simpleName, tokens[i])) {
- return true;
- }
+ // try to match all enclosing types for which the token matches as well.
+ while (typeBinding != null && lastIndex >= 0){
+ if (matchesName(this.simpleName, tokens[lastIndex--])
+ && matchesType(this.simpleName, this.qualification, typeBinding)) return true;
+ //&& matchesAsSubtype(this.simpleName, this.qualification, typeBinding)) return true;
+ if (typeBinding instanceof ReferenceBinding){
+ typeBinding = ((ReferenceBinding)typeBinding).enclosingType();
+ } else {
+ typeBinding = null;
}
- return false;
}
- }
- return true;
+ return false;
+ }
}
+ return true;
+}
+/**
+ * Returns whether this type pattern matches the given type reference.
+ * Look at resolved information only if specified.
+ */
+private boolean matches(TypeReference typeRef, boolean resolve) {
+ if (!resolve) {
+ if (this.simpleName != null) {
+ if (typeRef instanceof SingleTypeReference) {
+ return this.matchesName(this.simpleName, ((SingleTypeReference)typeRef).token);
+ } else { // QualifiedTypeReference
+ char[][] tokens = ((QualifiedTypeReference)typeRef).tokens;
+ for (int i = 0, max = tokens.length; i < max; i++){
+ if (this.matchesName(this.simpleName, tokens[i])) return true;
+ }
+ return false;
+ }
+ }
+ } else {
- /**
- * Returns whether this type pattern matches the given name reference.
- * Look at resolved information only if specified.
- */
- private boolean matches(NameReference nameRef, boolean resolve) {
- Binding binding = nameRef.binding;
- if (!resolve || binding == null || !binding.isValidBinding()) {
- if (this.simpleName != null) {
- if (nameRef instanceof SingleNameReference) {
- return this.matchesName(this.simpleName, ((SingleNameReference) nameRef).token);
- } else { // QualifiedNameReference
- char[][] tokens = ((QualifiedNameReference) nameRef).tokens;
- for (int i = 0, max = tokens.length; i < max; i++) {
- if (this.matchesName(this.simpleName, tokens[i]))
- return true;
- }
+ TypeBinding typeBinding = typeRef.binding;
+ if (typeBinding != null){
+ if (typeBinding instanceof ArrayBinding) typeBinding = ((ArrayBinding)typeBinding).leafComponentType;
+ if (typeRef instanceof SingleTypeReference){
+ if (!this.matchesType(this.simpleName, this.qualification, typeBinding)){
return false;
}
- }
- } else {
- if (nameRef instanceof SingleNameReference) {
- if (binding instanceof TypeBinding) {
- if (!this
- .matchesType(this.simpleName, this.qualification, (TypeBinding) binding)) {
- return false;
- }
- } else {
- return false; // must be a type binding
- }
- } else { // QualifiedNameReference
- TypeBinding typeBinding = null;
- QualifiedNameReference qNameRef = (QualifiedNameReference) nameRef;
+ } else { // QualifiedTypeReference
+ QualifiedTypeReference qNameRef = (QualifiedTypeReference)typeRef;
char[][] tokens = qNameRef.tokens;
- int lastIndex = tokens.length - 1;
- switch (qNameRef.bits & Statement.RestrictiveFlagMASK) {
- case BindingIds.FIELD : // reading a field
- typeBinding = ((FieldBinding) binding).declaringClass;
- // no valid match amongst fields
- int otherBindingsCount =
- qNameRef.otherBindings == null ? 0 : qNameRef.otherBindings.length;
- lastIndex -= otherBindingsCount + 1;
- if (lastIndex < 0)
- return false;
- break;
- case BindingIds.LOCAL : // reading a local variable
- return false; // no type match in it
- case BindingIds.TYPE : //=============only type ==============
- typeBinding = (TypeBinding) binding;
- }
+ int lastIndex = tokens.length-1;
// try to match all enclosing types for which the token matches as well.
- while (typeBinding != null && lastIndex >= 0) {
+ while (typeBinding != null && lastIndex >= 0){
if (matchesName(this.simpleName, tokens[lastIndex--])
- && matchesType(this.simpleName, this.qualification, typeBinding))
- return true;
- //&& matchesAsSubtype(this.simpleName, this.qualification, typeBinding)) return true;
- if (typeBinding instanceof ReferenceBinding) {
- typeBinding = ((ReferenceBinding) typeBinding).enclosingType();
+ && matchesType(this.simpleName, this.qualification, typeBinding)) return true;
+ //&& matchesAsSubtype(this.simpleName, this.qualification, typeBinding)) return true;
+ if (typeBinding instanceof ReferenceBinding){
+ typeBinding = ((ReferenceBinding)typeBinding).enclosingType();
} else {
typeBinding = null;
}
}
return false;
- }
+ }
}
- return true;
+
}
+ return true;
+}
+/**
+ * @see SearchPattern#matches(Binding)
+ */
+public boolean matches(Binding binding) {
+ if (!(binding instanceof ReferenceBinding)) return false;
- /**
- * Returns whether this type pattern matches the given type reference.
- * Look at resolved information only if specified.
- */
- private boolean matches(TypeReference typeRef, boolean resolve) {
- if (!resolve) {
- if (this.simpleName != null) {
- if (typeRef instanceof SingleTypeReference) {
- return this.matchesName(this.simpleName, ((SingleTypeReference) typeRef).token);
- } else { // QualifiedTypeReference
- char[][] tokens = ((QualifiedTypeReference) typeRef).tokens;
- for (int i = 0, max = tokens.length; i < max; i++) {
- if (this.matchesName(this.simpleName, tokens[i]))
- return true;
- }
- return false;
- }
- }
- } else {
-
- TypeBinding typeBinding = typeRef.binding;
- if (typeBinding != null) {
- if (typeBinding instanceof ArrayBinding)
- typeBinding = ((ArrayBinding) typeBinding).leafComponentType;
- if (typeRef instanceof SingleTypeReference) {
- if (!this.matchesType(this.simpleName, this.qualification, typeBinding)) {
- return false;
- }
- } else { // QualifiedTypeReference
- QualifiedTypeReference qNameRef = (QualifiedTypeReference) typeRef;
- char[][] tokens = qNameRef.tokens;
- int lastIndex = tokens.length - 1;
- // try to match all enclosing types for which the token matches as well.
- while (typeBinding != null && lastIndex >= 0) {
- if (matchesName(this.simpleName, tokens[lastIndex--])
- && matchesType(this.simpleName, this.qualification, typeBinding))
- return true;
- //&& matchesAsSubtype(this.simpleName, this.qualification, typeBinding)) return true;
- if (typeBinding instanceof ReferenceBinding) {
- typeBinding = ((ReferenceBinding) typeBinding).enclosingType();
- } else {
- typeBinding = null;
- }
- }
- return false;
- }
- }
-
- }
+ ReferenceBinding type = (ReferenceBinding) binding;
+ if (this.matchesType(this.simpleName, this.qualification, type.superclass())){
return true;
}
-
- /**
- * @see SearchPattern#matches(Binding)
- */
- public boolean matches(Binding binding) {
- if (!(binding instanceof ReferenceBinding))
- return false;
-
- ReferenceBinding type = (ReferenceBinding) binding;
- if (this.matchesType(this.simpleName, this.qualification, type.superclass())) {
+
+ ReferenceBinding[] superInterfaces = type.superInterfaces();
+ for (int i = 0, max = superInterfaces.length; i < max; i++){
+ if (this.matchesType(this.simpleName, this.qualification, superInterfaces[i])){
return true;
}
-
- ReferenceBinding[] superInterfaces = type.superInterfaces();
- for (int i = 0, max = superInterfaces.length; i < max; i++) {
- if (this
- .matchesType(this.simpleName, this.qualification, superInterfaces[i])) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * @see SearchPattern#matchIndexEntry
- */
- protected boolean matchIndexEntry() {
-
- /* check type name matches */
- if (simpleName == null) {
- // Optimization, eg. type reference is 'org.eclipse.jdt.core.*'
- switch (matchMode) {
- case EXACT_MATCH :
- if (!CharOperation
- .equals(
- this.segments[this.currentSegment],
- this.decodedSegment,
- isCaseSensitive)) {
- return false;
- }
- break;
- case PREFIX_MATCH :
- if (!CharOperation
- .prefixEquals(
- this.segments[this.currentSegment],
- this.decodedSegment,
- isCaseSensitive)) {
- return false;
- }
- break;
- case PATTERN_MATCH :
- if (!CharOperation
- .match(
- this.segments[this.currentSegment],
- this.decodedSegment,
- isCaseSensitive)) {
- return false;
- }
- }
- } else {
- switch (matchMode) {
- case EXACT_MATCH :
- if (!CharOperation.equals(simpleName, decodedSimpleName, isCaseSensitive)) {
- return false;
- }
- break;
- case PREFIX_MATCH :
- if (!CharOperation
- .prefixEquals(simpleName, decodedSimpleName, isCaseSensitive)) {
- return false;
- }
- break;
- case PATTERN_MATCH :
- if (!CharOperation.match(simpleName, decodedSimpleName, isCaseSensitive)) {
- return false;
- }
- }
- }
- return true;
}
+ return false;
+}
+/**
+ * @see SearchPattern#matchIndexEntry
+ */
+protected boolean matchIndexEntry() {
- /**
- * @see SearchPattern#matchLevel
- */
- public int matchLevel(AstNode node) {
- if (node instanceof NameReference) {
- if (this.matches((NameReference) node, false)) {
- return POSSIBLE_MATCH; // always need to resolve name reference
- } else {
- return IMPOSSIBLE_MATCH;
- }
- } else
- if (node instanceof ImportReference) {
- if (this.matches((ImportReference) node, false)) {
- return POSSIBLE_MATCH;
- } else {
- return IMPOSSIBLE_MATCH;
+ /* check type name matches */
+ if (simpleName == null) {
+ // Optimization, eg. type reference is 'org.eclipse.jdt.core.*'
+ switch(matchMode){
+ case EXACT_MATCH :
+ if (!CharOperation.equals(this.segments[this.currentSegment], this.decodedSegment, isCaseSensitive)){
+ return false;
+ }
+ break;
+ case PREFIX_MATCH :
+ if (!CharOperation.prefixEquals(this.segments[this.currentSegment], this.decodedSegment, isCaseSensitive)){
+ return false;
+ }
+ break;
+ case PATTERN_MATCH :
+ if (!CharOperation.match(this.segments[this.currentSegment], this.decodedSegment, isCaseSensitive)){
+ return false;
}
- } else {
- return super.matchLevel(node);
- }
- }
-
- /**
- * @see SearchPattern#matchReportReference
- */
- protected void matchReportReference(
- AstNode reference,
- IJavaElement element,
- int accuracy,
- MatchLocator locator)
- throws CoreException {
- if (reference instanceof QualifiedNameReference) {
- this.matchReportReference(
- (QualifiedNameReference) reference,
- element,
- accuracy,
- locator);
- } else
- if (reference instanceof QualifiedTypeReference) {
- this.matchReportReference(
- (QualifiedTypeReference) reference,
- element,
- accuracy,
- locator);
- } else {
- super.matchReportReference(reference, element, accuracy, locator);
- }
- }
-
- /**
- * Reports the match of the given qualified name reference.
- */
- private void matchReportReference(
- QualifiedNameReference nameRef,
- IJavaElement element,
- int accuracy,
- MatchLocator locator)
- throws CoreException {
- char[][] qualifiedName =
- CharOperation.splitOn(
- '.',
- this.qualification == null
- ? this.simpleName
- : CharOperation.concat(this.qualification, this.simpleName, '.'));
- locator.reportQualifiedReference(
- nameRef.sourceStart,
- nameRef.sourceEnd,
- qualifiedName,
- element,
- accuracy);
- }
-
- /**
- * Reports the match of the given qualified type reference.
- */
- private void matchReportReference(
- QualifiedTypeReference typeRef,
- IJavaElement element,
- int accuracy,
- MatchLocator locator)
- throws CoreException {
- char[][] qualifiedName =
- CharOperation.splitOn(
- '.',
- CharOperation.concat(this.qualification, this.simpleName, '.'));
- locator.reportQualifiedReference(
- typeRef.sourceStart,
- typeRef.sourceEnd,
- qualifiedName,
- element,
- accuracy);
- }
-
- /**
- * @see AndPattern#resetQuery
- */
- protected void resetQuery() {
- if (this.simpleName == null) {
- /* walk the segments from end to start as it will find less potential references using 'lang' than 'java' */
- this.currentSegment = this.segments.length - 1;
}
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer(20);
- buffer.append("TypeReferencePattern: pkg<");
- if (qualification != null)
- buffer.append(qualification);
- buffer.append(">, type<");
- if (simpleName != null)
- buffer.append(simpleName);
- buffer.append(">, ");
- switch (matchMode) {
+ } else {
+ switch(matchMode){
case EXACT_MATCH :
- buffer.append("exact match, ");
+ if (!CharOperation.equals(simpleName, decodedSimpleName, isCaseSensitive)){
+ return false;
+ }
break;
case PREFIX_MATCH :
- buffer.append("prefix match, ");
+ if (!CharOperation.prefixEquals(simpleName, decodedSimpleName, isCaseSensitive)){
+ return false;
+ }
break;
case PATTERN_MATCH :
- buffer.append("pattern match, ");
- break;
+ if (!CharOperation.match(simpleName, decodedSimpleName, isCaseSensitive)){
+ return false;
+ }
}
- if (isCaseSensitive)
- buffer.append("case sensitive");
- else
- buffer.append("case insensitive");
- return buffer.toString();
}
-
+ return true;
+}
+/**
+ * @see SearchPattern#matchLevel
+ */
+public int matchLevel(AstNode node) {
+ if (node instanceof NameReference) {
+ if (this.matches((NameReference)node, false)) {
+ return POSSIBLE_MATCH; // always need to resolve name reference
+ } else {
+ return IMPOSSIBLE_MATCH;
+ }
+ } else if (node instanceof ImportReference) {
+ if (this.matches((ImportReference)node, false)) {
+ return POSSIBLE_MATCH;
+ } else {
+ return IMPOSSIBLE_MATCH;
+ }
+ } else {
+ return super.matchLevel(node);
+ }
+}
+/**
+ * @see SearchPattern#matchReportReference
+ */
+protected void matchReportReference(AstNode reference, IJavaElement element, int accuracy, MatchLocator locator) throws CoreException {
+ if (reference instanceof QualifiedNameReference) {
+ this.matchReportReference((QualifiedNameReference)reference, element, accuracy, locator);
+ } else if (reference instanceof QualifiedTypeReference) {
+ this.matchReportReference((QualifiedTypeReference)reference, element, accuracy, locator);
+ } else {
+ super.matchReportReference(reference, element, accuracy, locator);
+ }
+}
+/**
+ * Reports the match of the given qualified name reference.
+ */
+private void matchReportReference(QualifiedNameReference nameRef, IJavaElement element, int accuracy, MatchLocator locator) throws CoreException {
+ char[][] qualifiedName = CharOperation.splitOn('.',
+ this.qualification == null ?
+ this.simpleName :
+ CharOperation.concat(this.qualification, this.simpleName, '.'));
+ locator.reportQualifiedReference(nameRef.sourceStart, nameRef.sourceEnd, qualifiedName, element, accuracy);
+}
+/**
+ * Reports the match of the given qualified type reference.
+ */
+private void matchReportReference(QualifiedTypeReference typeRef, IJavaElement element, int accuracy, MatchLocator locator) throws CoreException {
+ char[][] qualifiedName = CharOperation.splitOn('.', CharOperation.concat(this.qualification, this.simpleName, '.'));
+ locator.reportQualifiedReference(typeRef.sourceStart, typeRef.sourceEnd, qualifiedName, element, accuracy);
+}
+/**
+ * @see AndPattern#resetQuery
+ */
+protected void resetQuery() {
+ if (this.simpleName == null) {
+ /* walk the segments from end to start as it will find less potential references using 'lang' than 'java' */
+ this.currentSegment = this.segments.length - 1;
+ }
+}
+public String toString(){
+ StringBuffer buffer = new StringBuffer(20);
+ buffer.append("TypeReferencePattern: pkg<");
+ if (qualification != null) buffer.append(qualification);
+ buffer.append(">, type<");
+ if (simpleName != null) buffer.append(simpleName);
+ buffer.append(">, ");
+ switch(matchMode){
+ case EXACT_MATCH :
+ buffer.append("exact match, ");
+ break;
+ case PREFIX_MATCH :
+ buffer.append("prefix match, ");
+ break;
+ case PATTERN_MATCH :
+ buffer.append("pattern match, ");
+ break;
+ }
+ if (isCaseSensitive)
+ buffer.append("case sensitive");
+ else
+ buffer.append("case insensitive");
+ return buffer.toString();
+}
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/processing/IJob.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/processing/IJob.java
index a068153fd5..4618beacc3 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/processing/IJob.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/processing/IJob.java
@@ -1,14 +1,14 @@
package org.eclipse.jdt.internal.core.search.processing;
public interface IJob {
- /**
- * Answer true if the job belongs to a given family (tag)
- */
- public boolean belongsTo(String jobFamily);
- /**
- * Execute the current job, answering:
- * RESCHEDULE if the job should be rescheduled later on
- * COMPLETE if the job is over
- */
- public boolean execute();
+/**
+ * Answer true if the job belongs to a given family (tag)
+ */
+public boolean belongsTo(String jobFamily);
+/**
+ * Execute the current job, answering:
+ * RESCHEDULE if the job should be rescheduled later on
+ * COMPLETE if the job is over
+ */
+public boolean execute();
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/processing/IJobConstants.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/processing/IJobConstants.java
index 794f089a98..27d8d59ca9 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/processing/IJobConstants.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/processing/IJobConstants.java
@@ -7,5 +7,5 @@ public interface IJobConstants {
int WaitUntilReady = 3;
boolean FAILED = false;
- boolean COMPLETE = true;
+ boolean COMPLETE = true;
}
diff --git a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/processing/JobManager.java b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
index 55b82d411a..9f098c0263 100644
--- a/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
+++ b/org.eclipse.jdt.core/search/org/eclipse/jdt/internal/core/search/processing/JobManager.java
@@ -16,270 +16,241 @@ public abstract class JobManager implements Runnable, IJobConstants {
protected int jobStart = 0;
protected int jobEnd = -1;
protected boolean executing = false;
-
+
/* background processing */
protected Thread thread;
/* flag indicating whether job execution is enabled or not */
private boolean enabled = true;
+
+ public static boolean VERBOSE = false;
+ /* flag indicating that the activation has completed */
+ public boolean activated = false;
- public static boolean VERBOSE = false;
- /**
- * Invoked exactly once, in background, before starting processing any job
- */
- public abstract void activateProcessing();
- /**
- * Answer the amount of awaiting jobs.
- */
- public synchronized int awaitingJobsCount() {
-
- return jobEnd - jobStart + 1;
- }
-
- /**
- * Answers the first job in the queue, or null if there is no job available
- * Until the job has completed, the job manager will keep answering the same job.
- */
- public synchronized IJob currentJob() {
+/**
+ * Invoked exactly once, in background, before starting processing any job
+ */
+public void activateProcessing(){
+ this.activated = true;
+}
+/**
+ * Answer the amount of awaiting jobs.
+ */
+public synchronized int awaitingJobsCount() {
- if (!enabled)
- return null;
+ // pretend busy in case concurrent job attempts performing before activated
+ if(!activated) return 1;
+
+ return jobEnd - jobStart + 1;
- if (jobStart <= jobEnd) {
- return awaitingJobs[jobStart];
- }
- return null;
- }
+}
+/**
+ * Answers the first job in the queue, or null if there is no job available
+ * Until the job has completed, the job manager will keep answering the same job.
+ */
+public synchronized IJob currentJob() {
- public synchronized void disable() {
- enabled = false;
+ if (!enabled) return null;
+
+ if (jobStart <= jobEnd){
+ return awaitingJobs[jobStart];
}
+ return null;
+}
+public synchronized void disable(){
+ enabled = false;
+}
+/**
+ * Remove the index from cache for a given project.
+ * Passing null as a job family discards them all.
+ */
+public void discardJobs(String jobFamily) {
+ boolean wasEnabled = isEnabled();
+ try {
+ disable();
- /**
- * Remove the index from cache for a given project.
- * Passing null as a job family discards them all.
- */
- public void discardJobs(String jobFamily) {
- boolean wasEnabled = isEnabled();
- try {
- disable();
-
- // wait until current job has completed
- while (thread != null && executing) {
- try {
- Thread.currentThread().sleep(50);
- } catch (InterruptedException e) {
- }
- }
-
- // flush and compact awaiting jobs
- int loc = -1;
- for (int i = jobStart; i <= jobEnd; i++) {
- IJob currentJob = awaitingJobs[i];
- awaitingJobs[i] = null;
- if (!(jobFamily == null
- || currentJob.belongsTo(jobFamily))) { // copy down, compacting
- awaitingJobs[++loc] = currentJob;
- }
+ // wait until current job has completed
+ while (thread != null && executing){
+ try {
+ Thread.currentThread().sleep(50);
+ } catch(InterruptedException e){
}
- jobStart = 0;
- jobEnd = loc;
- } finally {
- if (wasEnabled)
- enable();
}
- }
-
- public synchronized void enable() {
- enabled = true;
- }
-
- public synchronized boolean isEnabled() {
- return enabled;
- }
-
- /**
- * Advance to the next available job, once the current one has been completed.
- * Note: clients awaiting until the job count is zero are still waiting at this point.
- */
- protected synchronized void moveToNextJob() {
- //if (!enabled) return;
-
- if (jobStart <= jobEnd) {
- awaitingJobs[jobStart++] = null;
- if (jobStart > jobEnd) {
- jobStart = 0;
- jobEnd = -1;
+ // flush and compact awaiting jobs
+ int loc = -1;
+ for (int i = jobStart; i <= jobEnd; i++){
+ IJob currentJob = awaitingJobs[i];
+ awaitingJobs[i] = null;
+ if (!(jobFamily == null || currentJob.belongsTo(jobFamily))){// copy down, compacting
+ awaitingJobs[++loc] = currentJob;
}
}
+ jobStart = 0;
+ jobEnd = loc;
+ } finally {
+ if (wasEnabled) enable();
}
+}
+public synchronized void enable(){
+ enabled = true;
+}
+public synchronized boolean isEnabled(){
+ return enabled;
+}
+/**
+ * Advance to the next available job, once the current one has been completed.
+ * Note: clients awaiting until the job count is zero are still waiting at this point.
+ */
+protected synchronized void moveToNextJob() {
- /**
- * When idle, give chance to do something
- */
- protected void notifyIdle(long idlingTime) {
+ //if (!enabled) return;
+
+ if (jobStart <= jobEnd){
+ awaitingJobs[jobStart++] = null;
+ if (jobStart > jobEnd){
+ jobStart = 0;
+ jobEnd = -1;
+ }
}
+}
+/**
+ * When idle, give chance to do something
+ */
+protected void notifyIdle(long idlingTime){
+}
+/**
+ * This API is allowing to run one job in concurrence with background processing.
+ * Indeed since other jobs are performed in background, resource sharing might be
+ * an issue.Therefore, this functionality allows a given job to be run without
+ * colliding with background ones.
+ * Note: multiple thread might attempt to perform concurrent jobs at the same time,
+ * and shoud synchronize (it is deliberately left to clients to decide whether
+ * concurrent jobs might interfere or not, i.e. multiple read jobs are ok).
+ *
+ * Waiting policy can be:
+ * IJobConstants.ForceImmediateSearch
+ * IJobConstants.CancelIfNotReadyToSearch
+ * IJobConstants.WaitUntilReadyToSearch
+ *
+ */
+public boolean performConcurrentJob(IJob searchJob, int waitingPolicy, IProgressMonitor progress) {
+
+ if (VERBOSE) System.out.println("-> performing concurrent job : START - "+ searchJob);
+ boolean status = FAILED;
+ if (awaitingJobsCount() > 0){
+ switch(waitingPolicy){
+
+ case ForceImmediate :
+ if (VERBOSE) System.out.println("-> performing concurrent job : NOT READY - ForceImmediate - "+ searchJob);
+ boolean wasEnabled = isEnabled();
+ try {
+ disable(); // pause indexing
+ status = searchJob.execute();
+ if (VERBOSE) System.out.println("-> performing concurrent job : END - "+ searchJob);
+ } finally {
+ if (wasEnabled) enable();
+ }
+ return status;
+ case CancelIfNotReady :
+ if (VERBOSE) System.out.println("-> performing concurrent job : NOT READY - CancelIfNotReady - "+ searchJob);
+ progress.setCanceled(true);
+ break;
- /**
- * This API is allowing to run one job in concurrence with background processing.
- * Indeed since other jobs are performed in background, resource sharing might be
- * an issue.Therefore, this functionality allows a given job to be run without
- * colliding with background ones.
- * Note: multiple thread might attempt to perform concurrent jobs at the same time,
- * and shoud synchronize (it is deliberately left to clients to decide whether
- * concurrent jobs might interfere or not, i.e. multiple read jobs are ok).
- *
- * Waiting policy can be:
- * IJobConstants.ForceImmediateSearch
- * IJobConstants.CancelIfNotReadyToSearch
- * IJobConstants.WaitUntilReadyToSearch
- *
- */
- public boolean performConcurrentJob(
- IJob searchJob,
- int waitingPolicy,
- IProgressMonitor progress) {
-
- if (VERBOSE)
- System.out.println("-> performing concurrent job : START - " + searchJob);
- boolean status = FAILED;
- if (awaitingJobsCount() > 0) {
- switch (waitingPolicy) {
-
- case ForceImmediate :
- if (VERBOSE)
- System.out.println(
- "-> performing concurrent job : NOT READY - ForceImmediate - " + searchJob);
- boolean wasEnabled = isEnabled();
- try {
- disable(); // pause indexing
- status = searchJob.execute();
- if (VERBOSE)
- System.out.println("-> performing concurrent job : END - " + searchJob);
- } finally {
- if (wasEnabled)
- enable();
- }
- return status;
- case CancelIfNotReady :
- if (VERBOSE)
- System.out.println(
- "-> performing concurrent job : NOT READY - CancelIfNotReady - " + searchJob);
- progress.setCanceled(true);
- break;
-
- case WaitUntilReady :
+ case WaitUntilReady :
int awaitingWork;
IJob previousJob = null;
IJob currentJob;
while ((awaitingWork = awaitingJobsCount()) > 0) {
- if (progress != null && progress.isCanceled())
- throw new OperationCanceledException();
- currentJob = currentJob();
- // currentJob can be null when jobs have been added to the queue but job manager is not enabled
- if (currentJob != null && currentJob != previousJob) {
- if (VERBOSE)
- System.out.println(
- "-> performing concurrent job : NOT READY - WaitUntilReady - " + searchJob);
- if (progress != null) {
- progress.subTask(awaitingWork + " files to index");
+ if (progress != null && progress.isCanceled()) throw new OperationCanceledException();
+ currentJob = currentJob(); // currentJob can be null when jobs have been added to the queue but job manager is not enabled
+ if (currentJob != null && currentJob != previousJob){
+ if (VERBOSE) System.out.println("-> performing concurrent job : NOT READY - WaitUntilReady - "+ searchJob);
+ if (progress != null){
+ progress.subTask(awaitingWork+" files to index");
}
previousJob = currentJob;
}
try {
Thread.currentThread().sleep(50);
- } catch (InterruptedException e) {
+ } catch(InterruptedException e){
}
}
- }
- }
- status = searchJob.execute();
- if (VERBOSE)
- System.out.println("-> performing concurrent job : END - " + searchJob);
- return status;
- }
-
- public abstract String processName();
- public synchronized void request(IJob job) {
-
- // append the job to the list of ones to process later on
- int size = awaitingJobs.length;
- if (++jobEnd == size) { // when growing, relocate jobs starting at position 0
- jobEnd -= jobStart;
- System.arraycopy(
- awaitingJobs,
- jobStart,
- (awaitingJobs = new IJob[size * 2]),
- 0,
- jobEnd);
- jobStart = 0;
}
- awaitingJobs[jobEnd] = job;
- if (VERBOSE)
- System.out.println("-> requesting job: " + job);
-
}
-
- /**
- * Flush current state
- */
- public void reset() {
-
- if (thread != null) {
- discardJobs(null); // discard all jobs
- } else {
- /* initiate background processing */
- thread = new Thread(this, this.processName());
- thread.setDaemon(true);
- thread.start();
- }
+ status = searchJob.execute();
+ if (VERBOSE) System.out.println("-> performing concurrent job : END - "+ searchJob);
+ return status;
+}
+public abstract String processName();
+public synchronized void request(IJob job) {
+
+ // append the job to the list of ones to process later on
+ int size = awaitingJobs.length;
+ if (++jobEnd == size){ // when growing, relocate jobs starting at position 0
+ jobEnd -= jobStart;
+ System.arraycopy(awaitingJobs, jobStart, (awaitingJobs = new IJob[size * 2]), 0, jobEnd);
+ jobStart = 0;
}
+ awaitingJobs[jobEnd] = job;
+ if (VERBOSE) System.out.println("-> requesting job: "+job);
+
+}
+/**
+ * Flush current state
+ */
+public void reset(){
+
+ if (thread != null){
+ discardJobs(null); // discard all jobs
+ } else {
+ /* initiate background processing */
+ thread = new Thread(this, this.processName());
+ thread.setDaemon(true);
+ thread.start();
+ }
+}
+/**
+ * Infinite loop performing resource indexing
+ */
+public void run(){
- /**
- * Infinite loop performing resource indexing
- */
- public void run() {
-
- long idlingStart = -1;
- activateProcessing();
- while (true) {
+ long idlingStart = -1;
+ activateProcessing();
+ while (true){
+ try {
+ IJob job;
+ if ((job = currentJob()) == null){
+ if (idlingStart < 0) idlingStart = System.currentTimeMillis();
+ notifyIdle(System.currentTimeMillis() - idlingStart);
+ Thread.currentThread().sleep(500);
+ continue;
+ } else {
+ idlingStart = -1;
+ }
+ if (VERBOSE){
+ System.out.println("-> executing: "+job);
+ System.out.println("\t"+awaitingJobsCount()+" awaiting jobs.");
+ }
try {
- IJob job;
- if ((job = currentJob()) == null) {
- if (idlingStart < 0)
- idlingStart = System.currentTimeMillis();
- notifyIdle(System.currentTimeMillis() - idlingStart);
- Thread.currentThread().sleep(500);
- continue;
- } else {
- idlingStart = -1;
- }
- if (VERBOSE) {
- System.out.println("-> executing: " + job);
- System.out.println("\t" + awaitingJobsCount() + " awaiting jobs.");
- }
- try {
- executing = true;
- boolean status = job.execute();
- //if (status == FAILED) request(job);
- moveToNextJob();
- } finally {
- executing = false;
- Thread.currentThread().sleep(50);
- }
- } catch (InterruptedException e) { // background indexing was interrupted
+ executing = true;
+ boolean status = job.execute();
+ //if (status == FAILED) request(job);
+ moveToNextJob();
+ } finally {
+ executing = false;
+ Thread.currentThread().sleep(50);
}
+ } catch(InterruptedException e){ // background indexing was interrupted
}
}
+}
+/**
+ * Stop background processing, and wait until the current job is completed before returning
+ */
+public void shutdown(){
- /**
- * Stop background processing, and wait until the current job is completed before returning
- */
- public void shutdown() {
-
- disable();
- discardJobs(null); // will wait until current executing job has completed
- }
-
+ disable();
+ discardJobs(null); // will wait until current executing job has completed
+}
}

Back to the top