Skip to main content
summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
Diffstat (limited to 'org.eclipse.jdt.core/search')
-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
90 files changed, 9160 insertions, 12008 deletions
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