a7795eba00956940977f2b7039abd476cffe5550
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpdt / internal / core / SearchableEnvironment.java
1 /*******************************************************************************
2  * Copyright (c) 2000, 2003 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials 
4  * are made available under the terms of the Common Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/cpl-v10.html
7  * 
8  * Contributors:
9  *     IBM Corporation - initial API and implementation
10  *******************************************************************************/
11 package net.sourceforge.phpdt.internal.core;
12
13 import net.sourceforge.phpdt.core.ICompilationUnit;
14 import net.sourceforge.phpdt.core.IJavaElement;
15 import net.sourceforge.phpdt.core.IJavaProject;
16 import net.sourceforge.phpdt.core.IPackageFragment;
17 import net.sourceforge.phpdt.core.IType;
18 import net.sourceforge.phpdt.core.JavaModelException;
19 import net.sourceforge.phpdt.core.WorkingCopyOwner;
20 import net.sourceforge.phpdt.core.compiler.CharOperation;
21 import net.sourceforge.phpdt.core.search.IJavaSearchConstants;
22 import net.sourceforge.phpdt.core.search.ITypeNameRequestor;
23 import net.sourceforge.phpdt.internal.codeassist.ISearchRequestor;
24 import net.sourceforge.phpdt.internal.codeassist.ISearchableNameEnvironment;
25 import net.sourceforge.phpdt.internal.compiler.env.IConstants;
26 import net.sourceforge.phpdt.internal.compiler.env.INameEnvironment;
27 import net.sourceforge.phpdt.internal.compiler.env.ISourceType;
28 import net.sourceforge.phpdt.internal.compiler.env.NameEnvironmentAnswer;
29
30 import org.eclipse.core.runtime.IProgressMonitor;
31
32 /**
33  *      This class provides a <code>SearchableBuilderEnvironment</code> for code assist which
34  *      uses the Java model as a search tool.  
35  */
36 public class SearchableEnvironment implements ISearchableNameEnvironment, IJavaSearchConstants {
37   protected NameLookup nameLookup;
38   protected ICompilationUnit unitToSkip;
39
40   protected IJavaProject project;
41   //protected IJavaSearchScope searchScope;
42
43         /**
44          * Creates a Sea
45   /**
46    * Creates a SearchableEnvironment on the given project
47    */
48   public SearchableEnvironment(IJavaProject project) throws JavaModelException {
49     this.project = project;
50     this.nameLookup = (NameLookup) ((JavaProject) project).getNameLookup();
51
52     // Create search scope with visible entry on the project's classpath
53     //          this.searchScope = SearchEngine.createJavaSearchScope(this.project.getAllPackageFragmentRoots());
54   }
55   
56         
57
58         /**
59          * Creates a SearchableEnvironment on the given project
60          */
61         public SearchableEnvironment(JavaProject project, WorkingCopyOwner owner) throws JavaModelException {
62                 this.project = project;
63                 this.nameLookup = project.newNameLookup(owner);
64
65                 // Create search scope with visible entry on the project's classpath
66 //              this.searchScope = SearchEngine.createJavaSearchScope(this.project.getAllPackageFragmentRoots());
67         }
68   /**
69    * Returns the given type in the the given package if it exists,
70    * otherwise <code>null</code>.
71    */
72   protected NameEnvironmentAnswer find(String typeName, String packageName) {
73     if (packageName == null)
74       packageName = IPackageFragment.DEFAULT_PACKAGE_NAME;
75    
76     IType type = this.nameLookup.findType(typeName, packageName, false, NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES);
77     if (type != null) {
78       //                        if (type instanceof BinaryType) {
79       //                                try {
80       //                                        return new NameEnvironmentAnswer(
81       //                                                (IBinaryType) ((BinaryType) type).getElementInfo());
82       //                                } catch (JavaModelException npe) {
83       //                                        return null;
84       //                                }
85       //                        } else { //SourceType
86       try {
87         // retrieve the requested type
88         SourceTypeElementInfo sourceType = (SourceTypeElementInfo) ((SourceType) type).getElementInfo();
89         ISourceType topLevelType = sourceType;
90         while (topLevelType.getEnclosingType() != null) {
91           topLevelType = topLevelType.getEnclosingType();
92         }
93         // find all siblings (other types declared in same unit, since may be used for name resolution)
94         IType[] types = sourceType.getHandle().getCompilationUnit().getTypes();
95         ISourceType[] sourceTypes = new ISourceType[types.length];
96
97         // in the resulting collection, ensure the requested type is the first one
98         sourceTypes[0] = sourceType;
99         for (int i = 0, index = 1; i < types.length; i++) {
100           ISourceType otherType = (ISourceType) ((JavaElement) types[i]).getElementInfo();
101           if (!otherType.equals(topLevelType))
102             sourceTypes[index++] = otherType;
103         }
104         return new NameEnvironmentAnswer(sourceTypes);
105       } catch (JavaModelException npe) {
106         return null;
107       }
108       //                        }
109     }
110     return null;
111   }
112
113   /**
114    * @see ISearchableNameEnvironment#findPackages(char[], ISearchRequestor)
115    */
116   public void findPackages(char[] prefix, ISearchRequestor requestor) {
117     //          this.nameLookup.seekPackageFragments(
118     //                  new String(prefix),
119     //                  true,
120     //                  new SearchableEnvironmentRequestor(requestor));
121   }
122
123   /**
124    * @see INameEnvironment#findType(char[][])
125    */
126   public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
127     if (compoundTypeName == null)
128       return null;
129
130     int length = compoundTypeName.length;
131     if (length <= 1) {
132       if (length == 0)
133         return null;
134       return find(new String(compoundTypeName[0]), null);
135     }
136
137     int lengthM1 = length - 1;
138     char[][] packageName = new char[lengthM1][];
139     System.arraycopy(compoundTypeName, 0, packageName, 0, lengthM1);
140
141     return find(new String(compoundTypeName[lengthM1]), CharOperation.toString(packageName));
142   }
143
144   /**
145    * @see INameEnvironment#findType(char[], char[][])
146    */
147   public NameEnvironmentAnswer findType(char[] name, char[][] packageName) {
148     if (name == null)
149       return null;
150
151     return find(new String(name), packageName == null || packageName.length == 0 ? null : CharOperation.toString(packageName));
152   }
153
154   /**
155    * @see ISearchableNameEnvironment#findTypes(char[], ISearchRequestor)
156    */
157   public void findTypes(char[] prefix, final ISearchRequestor storage) {
158
159     /*
160         if (true){
161                 findTypes(new String(prefix), storage, NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES);
162                 return;         
163         }
164     */
165     //          try {
166     final String excludePath;
167     if (this.unitToSkip != null) {
168       if (!(this.unitToSkip instanceof IJavaElement)) {
169         // revert to model investigation
170         findTypes(new String(prefix), storage, NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES);
171         return;
172       }
173       excludePath = ((IJavaElement) this.unitToSkip).getPath().toString();
174     } else {
175       excludePath = null;
176     }
177     int lastDotIndex = CharOperation.lastIndexOf('.', prefix);
178     char[] qualification, simpleName;
179     if (lastDotIndex < 0) {
180       qualification = null;
181       simpleName = CharOperation.toLowerCase(prefix);
182     } else {
183       qualification = CharOperation.subarray(prefix, 0, lastDotIndex);
184       simpleName = CharOperation.toLowerCase(CharOperation.subarray(prefix, lastDotIndex + 1, prefix.length));
185     }
186
187     IProgressMonitor progressMonitor = new IProgressMonitor() {
188       boolean isCanceled = false;
189       public void beginTask(String name, int totalWork) {
190       }
191       public void done() {
192       }
193       public void internalWorked(double work) {
194       }
195       public boolean isCanceled() {
196         return isCanceled;
197       }
198       public void setCanceled(boolean value) {
199         isCanceled = value;
200       }
201       public void setTaskName(String name) {
202       }
203       public void subTask(String name) {
204       }
205       public void worked(int work) {
206       }
207     };
208     ITypeNameRequestor nameRequestor = new ITypeNameRequestor() {
209       public void acceptClass(char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path) {
210         if (excludePath != null && excludePath.equals(path))
211           return;
212         if (enclosingTypeNames != null && enclosingTypeNames.length > 0)
213           return; // accept only top level types
214         storage.acceptClass(packageName, simpleTypeName, IConstants.AccPublic);
215       }
216       public void acceptInterface(char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path) {
217         if (excludePath != null && excludePath.equals(path))
218           return;
219         if (enclosingTypeNames != null && enclosingTypeNames.length > 0)
220           return; // accept only top level types
221         storage.acceptInterface(packageName, simpleTypeName, IConstants.AccPublic);
222       }
223     };
224     //                  try {
225     //                          new SearchEngine().searchAllTypeNames(
226     //                                  this.project.getProject().getWorkspace(),
227     //                                  qualification,
228     //                                  simpleName,
229     //                                  PREFIX_MATCH,
230     //                                  CASE_INSENSITIVE,
231     //                                  IJavaSearchConstants.TYPE,
232     //                                  this.searchScope,
233     //                                  nameRequestor,
234     //                                  CANCEL_IF_NOT_READY_TO_SEARCH,
235     //                                  progressMonitor);
236     //                  } catch (OperationCanceledException e) {
237     //                          findTypes(
238     //                                  new String(prefix),
239     //                                  storage,
240     //                                  NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES);
241     //                  }
242     //          } catch (JavaModelException e) {
243     //                  findTypes(
244     //                          new String(prefix),
245     //                          storage,
246     //                          NameLookup.ACCEPT_CLASSES | NameLookup.ACCEPT_INTERFACES);
247     //          }
248   }
249
250   /**
251    * Returns all types whose name starts with the given (qualified) <code>prefix</code>.
252    *
253    * If the <code>prefix</code> is unqualified, all types whose simple name matches
254    * the <code>prefix</code> are returned.
255    */
256   private void findTypes(String prefix, ISearchRequestor storage, int type) {
257     SearchableEnvironmentRequestor requestor = new SearchableEnvironmentRequestor(storage, this.unitToSkip);
258     int index = prefix.lastIndexOf('.');
259     if (index == -1) {
260       this.nameLookup.seekTypes(prefix, null, true, type, requestor);
261     } else {
262       String packageName = prefix.substring(0, index);
263       JavaElementRequestor elementRequestor = new JavaElementRequestor();
264       this.nameLookup.seekPackageFragments(packageName, false, elementRequestor);
265       IPackageFragment[] fragments = elementRequestor.getPackageFragments();
266       if (fragments != null) {
267         String className = prefix.substring(index + 1);
268         for (int i = 0, length = fragments.length; i < length; i++)
269           if (fragments[i] != null)
270             this.nameLookup.seekTypes(className, fragments[i], true, type, requestor);
271       }
272     }
273   }
274
275   /**
276    * @see INameEnvironment#isPackage(char[][], char[])
277    */
278   public boolean isPackage(char[][] parentPackageName, char[] subPackageName) {
279     if (subPackageName == null || CharOperation.contains('.', subPackageName))
280       return false;
281     if (parentPackageName == null || parentPackageName.length == 0)
282       return isTopLevelPackage(subPackageName);
283     for (int i = 0, length = parentPackageName.length; i < length; i++)
284       if (parentPackageName[i] == null || CharOperation.contains('.', parentPackageName[i]))
285         return false;
286
287     String packageName = new String(CharOperation.concatWith(parentPackageName, subPackageName, '.'));
288     return this.nameLookup.findPackageFragments(packageName, false) != null;
289   }
290
291   public boolean isTopLevelPackage(char[] packageName) {
292     return packageName != null
293       && !CharOperation.contains('.', packageName)
294       && this.nameLookup.findPackageFragments(new String(packageName), false) != null;
295   }
296
297   /**
298    * Returns a printable string for the array.
299    */
300   protected String toStringChar(char[] name) {
301     return "[" //$NON-NLS-1$
302     + new String(name) + "]"; //$NON-NLS-1$
303   }
304
305   /**
306    * Returns a printable string for the array.
307    */
308   protected String toStringCharChar(char[][] names) {
309     StringBuffer result = new StringBuffer();
310     for (int i = 0; i < names.length; i++) {
311       result.append(toStringChar(names[i]));
312     }
313     return result.toString();
314   }
315
316   public void cleanup() {
317   }
318 }