KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > core > CompilationUnit


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  * Alex Smirnoff (alexsmr@sympatico.ca) - part of the changes to support Java-like extension
11  * (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=71460)
12  *******************************************************************************/

13 package org.eclipse.jdt.internal.core;
14
15 import java.util.*;
16
17 import org.eclipse.core.resources.*;
18 import org.eclipse.core.runtime.*;
19 import org.eclipse.jdt.core.*;
20 import org.eclipse.jdt.core.compiler.*;
21 import org.eclipse.jdt.core.dom.AST;
22 import org.eclipse.jdt.internal.compiler.IProblemFactory;
23 import org.eclipse.jdt.internal.compiler.SourceElementParser;
24 import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
25 import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
26 import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
27 import org.eclipse.jdt.internal.compiler.util.SuffixConstants;
28 import org.eclipse.jdt.internal.core.util.MementoTokenizer;
29 import org.eclipse.jdt.internal.core.util.Messages;
30 import org.eclipse.jdt.internal.core.util.Util;
31
32 /**
33  * @see ICompilationUnit
34  */

35 public class CompilationUnit extends Openable implements ICompilationUnit, org.eclipse.jdt.internal.compiler.env.ICompilationUnit, SuffixConstants {
36     /**
37      * Internal synonynm for deprecated constant AST.JSL2
38      * to alleviate deprecation warnings.
39      * @deprecated
40      */

41     /*package*/ static final int JLS2_INTERNAL = AST.JLS2;
42     
43     private static final IImportDeclaration[] NO_IMPORTS = new IImportDeclaration[0];
44     
45     protected String JavaDoc name;
46     public WorkingCopyOwner owner;
47
48 /**
49  * Constructs a handle to a compilation unit with the given name in the
50  * specified package for the specified owner
51  */

52 public CompilationUnit(PackageFragment parent, String JavaDoc name, WorkingCopyOwner owner) {
53     super(parent);
54     this.name = name;
55     this.owner = owner;
56 }
57 /*
58  * @see ICompilationUnit#becomeWorkingCopy(IProblemRequestor, IProgressMonitor)
59  */

60 public void becomeWorkingCopy(IProblemRequestor problemRequestor, IProgressMonitor monitor) throws JavaModelException {
61     JavaModelManager manager = JavaModelManager.getJavaModelManager();
62     JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = manager.getPerWorkingCopyInfo(this, false/*don't create*/, true /*record usage*/, null/*no problem requestor needed*/);
63     if (perWorkingCopyInfo == null) {
64         // close cu and its children
65
close();
66
67         BecomeWorkingCopyOperation operation = new BecomeWorkingCopyOperation(this, problemRequestor);
68         operation.runOperation(monitor);
69     }
70 }
71 /*
72  * @see ICompilationUnit#becomeWorkingCopy(IProgressMonitor)
73  */

74 public void becomeWorkingCopy(IProgressMonitor monitor) throws JavaModelException {
75     IProblemRequestor requestor = this.owner == null ? null : this.owner.getProblemRequestor(this);
76     becomeWorkingCopy(requestor, monitor);
77 }
78 protected boolean buildStructure(OpenableElementInfo info, final IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
79
80     // check if this compilation unit can be opened
81
if (!isWorkingCopy()) { // no check is done on root kind or exclusion pattern for working copies
82
IStatus status = validateCompilationUnit(underlyingResource);
83         if (!status.isOK()) throw newJavaModelException(status);
84     }
85     
86     // prevents reopening of non-primary working copies (they are closed when they are discarded and should not be reopened)
87
if (!isPrimary() && getPerWorkingCopyInfo() == null) {
88         throw newNotPresentException();
89     }
90
91     CompilationUnitElementInfo unitInfo = (CompilationUnitElementInfo) info;
92
93     // get buffer contents
94
IBuffer buffer = getBufferManager().getBuffer(CompilationUnit.this);
95     if (buffer == null) {
96         buffer = openBuffer(pm, unitInfo); // open buffer independently from the info, since we are building the info
97
}
98     final char[] contents;
99     if (buffer == null) {
100         contents = CharOperation.NO_CHAR ;
101     } else {
102         char[] characters = buffer.getCharacters();
103         contents = characters == null ? CharOperation.NO_CHAR : characters;
104     }
105
106     // generate structure and compute syntax problems if needed
107
CompilationUnitStructureRequestor requestor = new CompilationUnitStructureRequestor(this, unitInfo, newElements);
108     JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = getPerWorkingCopyInfo();
109     IJavaProject project = getJavaProject();
110
111     boolean createAST;
112     boolean resolveBindings;
113     int reconcileFlags;
114     HashMap problems;
115     if (info instanceof ASTHolderCUInfo) {
116         ASTHolderCUInfo astHolder = (ASTHolderCUInfo) info;
117         createAST = astHolder.astLevel != NO_AST;
118         resolveBindings = astHolder.resolveBindings;
119         reconcileFlags = astHolder.reconcileFlags;
120         problems = astHolder.problems;
121     } else {
122         createAST = false;
123         resolveBindings = false;
124         reconcileFlags = 0;
125         problems = null;
126     }
127     
128     boolean computeProblems = perWorkingCopyInfo != null && perWorkingCopyInfo.isActive() && project != null && JavaProject.hasJavaNature(project.getProject());
129     IProblemFactory problemFactory = new DefaultProblemFactory();
130     Map options = project == null ? JavaCore.getOptions() : project.getOptions(true);
131     if (!computeProblems) {
132         // disable task tags checking to speed up parsing
133
options.put(JavaCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$
134
}
135     SourceElementParser parser = new SourceElementParser(
136         requestor,
137         problemFactory,
138         new CompilerOptions(options),
139         true/*report local declarations*/,
140         !createAST /*optimize string literals only if not creating a DOM AST*/);
141     parser.reportOnlyOneSyntaxError = !computeProblems;
142     parser.setMethodsFullRecovery(true);
143     parser.setStatementsRecovery((reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);
144     
145     if (!computeProblems && !resolveBindings && !createAST) // disable javadoc parsing if not computing problems, not resolving and not creating ast
146
parser.javadocParser.checkDocComment = false;
147     requestor.parser = parser;
148     CompilationUnitDeclaration unit = parser.parseCompilationUnit(
149         new org.eclipse.jdt.internal.compiler.env.ICompilationUnit() {
150             public char[] getContents() {
151                 return contents;
152             }
153             public char[] getMainTypeName() {
154                 return CompilationUnit.this.getMainTypeName();
155             }
156             public char[][] getPackageName() {
157                 return CompilationUnit.this.getPackageName();
158             }
159             public char[] getFileName() {
160                 return CompilationUnit.this.getFileName();
161             }
162         },
163         true /*full parse to find local elements*/);
164     
165     // update timestamp (might be IResource.NULL_STAMP if original does not exist)
166
if (underlyingResource == null) {
167         underlyingResource = getResource();
168     }
169     // underlying resource is null in the case of a working copy on a class file in a jar
170
if (underlyingResource != null)
171         unitInfo.timestamp = ((IFile)underlyingResource).getModificationStamp();
172     
173     // compute other problems if needed
174
CompilationUnitDeclaration compilationUnitDeclaration = null;
175     try {
176         if (computeProblems) {
177             if (problems == null) {
178                 // report problems to the problem requestor
179
problems = new HashMap();
180                 compilationUnitDeclaration = CompilationUnitProblemFinder.process(unit, this, contents, parser, this.owner, problems, createAST, reconcileFlags, pm);
181                 try {
182                     perWorkingCopyInfo.beginReporting();
183                     for (Iterator iteraror = problems.values().iterator(); iteraror.hasNext();) {
184                         CategorizedProblem[] categorizedProblems = (CategorizedProblem[]) iteraror.next();
185                         if (categorizedProblems == null) continue;
186                         for (int i = 0, length = categorizedProblems.length; i < length; i++) {
187                             perWorkingCopyInfo.acceptProblem(categorizedProblems[i]);
188                         }
189                     }
190                 } finally {
191                     perWorkingCopyInfo.endReporting();
192                 }
193             } else {
194                 // collect problems
195
compilationUnitDeclaration = CompilationUnitProblemFinder.process(unit, this, contents, parser, this.owner, problems, createAST, reconcileFlags, pm);
196             }
197         }
198         
199         if (createAST) {
200             int astLevel = ((ASTHolderCUInfo) info).astLevel;
201             org.eclipse.jdt.core.dom.CompilationUnit cu = AST.convertCompilationUnit(astLevel, unit, contents, options, computeProblems, this, reconcileFlags, pm);
202             ((ASTHolderCUInfo) info).ast = cu;
203         }
204     } finally {
205         if (compilationUnitDeclaration != null) {
206             compilationUnitDeclaration.cleanUp();
207         }
208     }
209     
210     return unitInfo.isStructureKnown();
211 }
212 /*
213  * @see Openable#canBeRemovedFromCache
214  */

215 public boolean canBeRemovedFromCache() {
216     if (getPerWorkingCopyInfo() != null) return false; // working copies should remain in the cache until they are destroyed
217
return super.canBeRemovedFromCache();
218 }
219 /*
220  * @see Openable#canBufferBeRemovedFromCache
221  */

222 public boolean canBufferBeRemovedFromCache(IBuffer buffer) {
223     if (getPerWorkingCopyInfo() != null) return false; // working copy buffers should remain in the cache until working copy is destroyed
224
return super.canBufferBeRemovedFromCache(buffer);
225 }/*
226  * @see IOpenable#close
227  */

228 public void close() throws JavaModelException {
229     if (getPerWorkingCopyInfo() != null) return; // a working copy must remain opened until it is discarded
230
super.close();
231 }
232 /*
233  * @see Openable#closing
234  */

235 protected void closing(Object JavaDoc info) {
236     if (getPerWorkingCopyInfo() == null) {
237         super.closing(info);
238     } // else the buffer of a working copy must remain open for the lifetime of the working copy
239
}
240 /**
241  * @see ICodeAssist#codeComplete(int, ICompletionRequestor)
242  * @deprecated
243  */

244 public void codeComplete(int offset, ICompletionRequestor requestor) throws JavaModelException {
245     codeComplete(offset, requestor, DefaultWorkingCopyOwner.PRIMARY);
246 }
247 /**
248  * @see ICodeAssist#codeComplete(int, ICompletionRequestor, WorkingCopyOwner)
249  * @deprecated
250  */

251 public void codeComplete(int offset, ICompletionRequestor requestor, WorkingCopyOwner workingCopyOwner) throws JavaModelException {
252     if (requestor == null) {
253         throw new IllegalArgumentException JavaDoc("Completion requestor cannot be null"); //$NON-NLS-1$
254
}
255     codeComplete(offset, new org.eclipse.jdt.internal.codeassist.CompletionRequestorWrapper(requestor), workingCopyOwner);
256 }
257 /**
258  * @see ICodeAssist#codeComplete(int, ICodeCompletionRequestor)
259  * @deprecated - use codeComplete(int, ICompletionRequestor)
260  */

261 public void codeComplete(int offset, final ICodeCompletionRequestor requestor) throws JavaModelException {
262     
263     if (requestor == null){
264         codeComplete(offset, (ICompletionRequestor)null);
265         return;
266     }
267     codeComplete(
268         offset,
269         new ICompletionRequestor(){
270             public void acceptAnonymousType(char[] superTypePackageName,char[] superTypeName,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance){
271                 // ignore
272
}
273             public void acceptClass(char[] packageName, char[] className, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) {
274                 requestor.acceptClass(packageName, className, completionName, modifiers, completionStart, completionEnd);
275             }
276             public void acceptError(IProblem error) {
277                 // was disabled in 1.0
278
}
279             public void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, char[] fieldName, char[] typePackageName, char[] typeName, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) {
280                 requestor.acceptField(declaringTypePackageName, declaringTypeName, fieldName, typePackageName, typeName, completionName, modifiers, completionStart, completionEnd);
281             }
282             public void acceptInterface(char[] packageName,char[] interfaceName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) {
283                 requestor.acceptInterface(packageName, interfaceName, completionName, modifiers, completionStart, completionEnd);
284             }
285             public void acceptKeyword(char[] keywordName,int completionStart,int completionEnd, int relevance){
286                 requestor.acceptKeyword(keywordName, completionStart, completionEnd);
287             }
288             public void acceptLabel(char[] labelName,int completionStart,int completionEnd, int relevance){
289                 requestor.acceptLabel(labelName, completionStart, completionEnd);
290             }
291             public void acceptLocalVariable(char[] localVarName,char[] typePackageName,char[] typeName,int modifiers,int completionStart,int completionEnd, int relevance){
292                 // ignore
293
}
294             public void acceptMethod(char[] declaringTypePackageName,char[] declaringTypeName,char[] selector,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] returnTypePackageName,char[] returnTypeName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance){
295                 // skip parameter names
296
requestor.acceptMethod(declaringTypePackageName, declaringTypeName, selector, parameterPackageNames, parameterTypeNames, returnTypePackageName, returnTypeName, completionName, modifiers, completionStart, completionEnd);
297             }
298             public void acceptMethodDeclaration(char[] declaringTypePackageName,char[] declaringTypeName,char[] selector,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] returnTypePackageName,char[] returnTypeName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance){
299                 // ignore
300
}
301             public void acceptModifier(char[] modifierName,int completionStart,int completionEnd, int relevance){
302                 requestor.acceptModifier(modifierName, completionStart, completionEnd);
303             }
304             public void acceptPackage(char[] packageName,char[] completionName,int completionStart,int completionEnd, int relevance){
305                 requestor.acceptPackage(packageName, completionName, completionStart, completionEnd);
306             }
307             public void acceptType(char[] packageName,char[] typeName,char[] completionName,int completionStart,int completionEnd, int relevance){
308                 requestor.acceptType(packageName, typeName, completionName, completionStart, completionEnd);
309             }
310             public void acceptVariableName(char[] typePackageName,char[] typeName,char[] varName,char[] completionName,int completionStart,int completionEnd, int relevance){
311                 // ignore
312
}
313         });
314 }
315
316 /* (non-Javadoc)
317  * @see org.eclipse.jdt.core.ICodeAssist#codeComplete(int, org.eclipse.jdt.core.CompletionRequestor)
318  */

319 public void codeComplete(int offset, CompletionRequestor requestor) throws JavaModelException {
320     codeComplete(offset, requestor, DefaultWorkingCopyOwner.PRIMARY);
321 }
322
323 /* (non-Javadoc)
324  * @see org.eclipse.jdt.core.ICodeAssist#codeComplete(int, org.eclipse.jdt.core.CompletionRequestor, org.eclipse.jdt.core.WorkingCopyOwner)
325  */

326 public void codeComplete(int offset, CompletionRequestor requestor, WorkingCopyOwner workingCopyOwner) throws JavaModelException {
327     codeComplete(this, isWorkingCopy() ? (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) getOriginalElement() : this, offset, requestor, workingCopyOwner);
328 }
329
330 /**
331  * @see ICodeAssist#codeSelect(int, int)
332  */

333 public IJavaElement[] codeSelect(int offset, int length) throws JavaModelException {
334     return codeSelect(offset, length, DefaultWorkingCopyOwner.PRIMARY);
335 }
336 /**
337  * @see ICodeAssist#codeSelect(int, int, WorkingCopyOwner)
338  */

339 public IJavaElement[] codeSelect(int offset, int length, WorkingCopyOwner workingCopyOwner) throws JavaModelException {
340     return super.codeSelect(this, offset, length, workingCopyOwner);
341 }
342 /**
343  * @see IWorkingCopy#commit(boolean, IProgressMonitor)
344  * @deprecated
345  */

346 public void commit(boolean force, IProgressMonitor monitor) throws JavaModelException {
347     commitWorkingCopy(force, monitor);
348 }
349 /**
350  * @see ICompilationUnit#commitWorkingCopy(boolean, IProgressMonitor)
351  */

352 public void commitWorkingCopy(boolean force, IProgressMonitor monitor) throws JavaModelException {
353     CommitWorkingCopyOperation op= new CommitWorkingCopyOperation(this, force);
354     op.runOperation(monitor);
355 }
356 /**
357  * @see ISourceManipulation#copy(IJavaElement, IJavaElement, String, boolean, IProgressMonitor)
358  */

359 public void copy(IJavaElement container, IJavaElement sibling, String JavaDoc rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
360     if (container == null) {
361         throw new IllegalArgumentException JavaDoc(Messages.operation_nullContainer);
362     }
363     IJavaElement[] elements = new IJavaElement[] {this};
364     IJavaElement[] containers = new IJavaElement[] {container};
365     String JavaDoc[] renamings = null;
366     if (rename != null) {
367         renamings = new String JavaDoc[] {rename};
368     }
369     getJavaModel().copy(elements, containers, null, renamings, force, monitor);
370 }
371 /**
372  * Returns a new element info for this element.
373  */

374 protected Object JavaDoc createElementInfo() {
375     return new CompilationUnitElementInfo();
376 }
377 /**
378  * @see ICompilationUnit#createImport(String, IJavaElement, IProgressMonitor)
379  */

380 public IImportDeclaration createImport(String JavaDoc importName, IJavaElement sibling, IProgressMonitor monitor) throws JavaModelException {
381     return createImport(importName, sibling, Flags.AccDefault, monitor);
382 }
383
384 /**
385  * @see ICompilationUnit#createImport(String, IJavaElement, int, IProgressMonitor)
386  * @since 3.0
387  */

388 public IImportDeclaration createImport(String JavaDoc importName, IJavaElement sibling, int flags, IProgressMonitor monitor) throws JavaModelException {
389     CreateImportOperation op = new CreateImportOperation(importName, this, flags);
390     if (sibling != null) {
391         op.createBefore(sibling);
392     }
393     op.runOperation(monitor);
394     return getImport(importName);
395 }
396
397 /**
398  * @see ICompilationUnit#createPackageDeclaration(String, IProgressMonitor)
399  */

400 public IPackageDeclaration createPackageDeclaration(String JavaDoc pkg, IProgressMonitor monitor) throws JavaModelException {
401     
402     CreatePackageDeclarationOperation op= new CreatePackageDeclarationOperation(pkg, this);
403     op.runOperation(monitor);
404     return getPackageDeclaration(pkg);
405 }
406 /**
407  * @see ICompilationUnit#createType(String, IJavaElement, boolean, IProgressMonitor)
408  */

409 public IType createType(String JavaDoc content, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException {
410     if (!exists()) {
411         //autogenerate this compilation unit
412
IPackageFragment pkg = (IPackageFragment) getParent();
413         String JavaDoc source = ""; //$NON-NLS-1$
414
if (!pkg.isDefaultPackage()) {
415             //not the default package...add the package declaration
416
String JavaDoc lineSeparator = Util.getLineSeparator(null/*no existing source*/, getJavaProject());
417             source = "package " + pkg.getElementName() + ";" + lineSeparator + lineSeparator; //$NON-NLS-1$ //$NON-NLS-2$
418
}
419         CreateCompilationUnitOperation op = new CreateCompilationUnitOperation(pkg, this.name, source, force);
420         op.runOperation(monitor);
421     }
422     CreateTypeOperation op = new CreateTypeOperation(this, content, force);
423     if (sibling != null) {
424         op.createBefore(sibling);
425     }
426     op.runOperation(monitor);
427     return (IType) op.getResultElements()[0];
428 }
429 /**
430  * @see ISourceManipulation#delete(boolean, IProgressMonitor)
431  */

432 public void delete(boolean force, IProgressMonitor monitor) throws JavaModelException {
433     IJavaElement[] elements= new IJavaElement[] {this};
434     getJavaModel().delete(elements, force, monitor);
435 }
436 /**
437  * @see IWorkingCopy#destroy()
438  * @deprecated
439  */

440 public void destroy() {
441     try {
442         discardWorkingCopy();
443     } catch (JavaModelException e) {
444         if (JavaModelManager.VERBOSE)
445             e.printStackTrace();
446     }
447 }
448 /*
449  * @see ICompilationUnit#discardWorkingCopy
450  */

451 public void discardWorkingCopy() throws JavaModelException {
452     // discard working copy and its children
453
DiscardWorkingCopyOperation op = new DiscardWorkingCopyOperation(this);
454     op.runOperation(null);
455 }
456 /**
457  * Returns true if this handle represents the same Java element
458  * as the given handle.
459  *
460  * @see Object#equals(java.lang.Object)
461  */

462 public boolean equals(Object JavaDoc obj) {
463     if (!(obj instanceof CompilationUnit)) return false;
464     CompilationUnit other = (CompilationUnit)obj;
465     return this.owner.equals(other.owner) && super.equals(obj);
466 }
467 public boolean exists() {
468     // working copy always exists in the model until it is gotten rid of (even if not on classpath)
469
if (getPerWorkingCopyInfo() != null) return true;
470     
471     // if not a working copy, it exists only if it is a primary compilation unit
472
return isPrimary() && validateCompilationUnit(getResource()).isOK();
473 }
474 /**
475  * @see ICompilationUnit#findElements(IJavaElement)
476  */

477 public IJavaElement[] findElements(IJavaElement element) {
478     ArrayList children = new ArrayList();
479     while (element != null && element.getElementType() != IJavaElement.COMPILATION_UNIT) {
480         children.add(element);
481         element = element.getParent();
482     }
483     if (element == null) return null;
484     IJavaElement currentElement = this;
485     for (int i = children.size()-1; i >= 0; i--) {
486         SourceRefElement child = (SourceRefElement)children.get(i);
487         switch (child.getElementType()) {
488             case IJavaElement.PACKAGE_DECLARATION:
489                 currentElement = ((ICompilationUnit)currentElement).getPackageDeclaration(child.getElementName());
490                 break;
491             case IJavaElement.IMPORT_CONTAINER:
492                 currentElement = ((ICompilationUnit)currentElement).getImportContainer();
493                 break;
494             case IJavaElement.IMPORT_DECLARATION:
495                 currentElement = ((IImportContainer)currentElement).getImport(child.getElementName());
496                 break;
497             case IJavaElement.TYPE:
498                 switch (currentElement.getElementType()) {
499                     case IJavaElement.COMPILATION_UNIT:
500                         currentElement = ((ICompilationUnit)currentElement).getType(child.getElementName());
501                         break;
502                     case IJavaElement.TYPE:
503                         currentElement = ((IType)currentElement).getType(child.getElementName());
504                         break;
505                     case IJavaElement.FIELD:
506                     case IJavaElement.INITIALIZER:
507                     case IJavaElement.METHOD:
508                         currentElement = ((IMember)currentElement).getType(child.getElementName(), child.occurrenceCount);
509                         break;
510                 }
511                 break;
512             case IJavaElement.INITIALIZER:
513                 currentElement = ((IType)currentElement).getInitializer(child.occurrenceCount);
514                 break;
515             case IJavaElement.FIELD:
516                 currentElement = ((IType)currentElement).getField(child.getElementName());
517                 break;
518             case IJavaElement.METHOD:
519                 currentElement = ((IType)currentElement).getMethod(child.getElementName(), ((IMethod)child).getParameterTypes());
520                 break;
521         }
522         
523     }
524     if (currentElement != null && currentElement.exists()) {
525         return new IJavaElement[] {currentElement};
526     } else {
527         return null;
528     }
529 }
530 /**
531  * @see ICompilationUnit#findPrimaryType()
532  */

533 public IType findPrimaryType() {
534     String JavaDoc typeName = Util.getNameWithoutJavaLikeExtension(getElementName());
535     IType primaryType= getType(typeName);
536     if (primaryType.exists()) {
537         return primaryType;
538     }
539     return null;
540 }
541
542 /**
543  * @see IWorkingCopy#findSharedWorkingCopy(IBufferFactory)
544  * @deprecated
545  */

546 public IJavaElement findSharedWorkingCopy(IBufferFactory factory) {
547
548     // if factory is null, default factory must be used
549
if (factory == null) factory = this.getBufferManager().getDefaultBufferFactory();
550     
551     return findWorkingCopy(BufferFactoryWrapper.create(factory));
552 }
553
554 /**
555  * @see ICompilationUnit#findWorkingCopy(WorkingCopyOwner)
556  */

557 public ICompilationUnit findWorkingCopy(WorkingCopyOwner workingCopyOwner) {
558     CompilationUnit cu = new CompilationUnit((PackageFragment)this.parent, getElementName(), workingCopyOwner);
559     if (workingCopyOwner == DefaultWorkingCopyOwner.PRIMARY) {
560         return cu;
561     } else {
562         // must be a working copy
563
JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = cu.getPerWorkingCopyInfo();
564         if (perWorkingCopyInfo != null) {
565             return perWorkingCopyInfo.getWorkingCopy();
566         } else {
567             return null;
568         }
569     }
570 }
571 /**
572  * @see ICompilationUnit#getAllTypes()
573  */

574 public IType[] getAllTypes() throws JavaModelException {
575     IJavaElement[] types = getTypes();
576     int i;
577     ArrayList allTypes = new ArrayList(types.length);
578     ArrayList typesToTraverse = new ArrayList(types.length);
579     for (i = 0; i < types.length; i++) {
580         typesToTraverse.add(types[i]);
581     }
582     while (!typesToTraverse.isEmpty()) {
583         IType type = (IType) typesToTraverse.get(0);
584         typesToTraverse.remove(type);
585         allTypes.add(type);
586         types = type.getTypes();
587         for (i = 0; i < types.length; i++) {
588             typesToTraverse.add(types[i]);
589         }
590     }
591     IType[] arrayOfAllTypes = new IType[allTypes.size()];
592     allTypes.toArray(arrayOfAllTypes);
593     return arrayOfAllTypes;
594 }
595 /**
596  * @see IMember#getCompilationUnit()
597  */

598 public ICompilationUnit getCompilationUnit() {
599     return this;
600 }
601 /**
602  * @see org.eclipse.jdt.internal.compiler.env.ICompilationUnit#getContents()
603  */

604 public char[] getContents() {
605     IBuffer buffer = getBufferManager().getBuffer(this);
606     if (buffer == null) {
607         // no need to force opening of CU to get the content
608
// also this cannot be a working copy, as its buffer is never closed while the working copy is alive
609
try {
610             return Util.getResourceContentsAsCharArray((IFile) getResource());
611         } catch (JavaModelException e) {
612             return CharOperation.NO_CHAR;
613         }
614     }
615     char[] contents = buffer.getCharacters();
616     if (contents == null) // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=129814
617
return CharOperation.NO_CHAR;
618     return contents;
619 }
620 /**
621  * A compilation unit has a corresponding resource unless it is contained
622  * in a jar.
623  *
624  * @see IJavaElement#getCorrespondingResource()
625  */

626 public IResource getCorrespondingResource() throws JavaModelException {
627     PackageFragmentRoot root = getPackageFragmentRoot();
628     if (root == null || root.isArchive()) {
629         return null;
630     } else {
631         return getUnderlyingResource();
632     }
633 }
634 /**
635  * @see ICompilationUnit#getElementAt(int)
636  */

637 public IJavaElement getElementAt(int position) throws JavaModelException {
638
639     IJavaElement e= getSourceElementAt(position);
640     if (e == this) {
641         return null;
642     } else {
643         return e;
644     }
645 }
646 public String JavaDoc getElementName() {
647     return this.name;
648 }
649 /**
650  * @see IJavaElement
651  */

652 public int getElementType() {
653     return COMPILATION_UNIT;
654 }
655 /**
656  * @see org.eclipse.jdt.internal.compiler.env.IDependent#getFileName()
657  */

658 public char[] getFileName(){
659     return getPath().toString().toCharArray();
660 }
661
662 /*
663  * @see JavaElement
664  */

665 public IJavaElement getHandleFromMemento(String JavaDoc token, MementoTokenizer memento, WorkingCopyOwner workingCopyOwner) {
666     switch (token.charAt(0)) {
667         case JEM_IMPORTDECLARATION:
668             JavaElement container = (JavaElement)getImportContainer();
669             return container.getHandleFromMemento(token, memento, workingCopyOwner);
670         case JEM_PACKAGEDECLARATION:
671             if (!memento.hasMoreTokens()) return this;
672             String JavaDoc pkgName = memento.nextToken();
673             JavaElement pkgDecl = (JavaElement)getPackageDeclaration(pkgName);
674             return pkgDecl.getHandleFromMemento(memento, workingCopyOwner);
675         case JEM_TYPE:
676             if (!memento.hasMoreTokens()) return this;
677             String JavaDoc typeName = memento.nextToken();
678             JavaElement type = (JavaElement)getType(typeName);
679             return type.getHandleFromMemento(memento, workingCopyOwner);
680     }
681     return null;
682 }
683
684 /**
685  * @see JavaElement#getHandleMementoDelimiter()
686  */

687 protected char getHandleMementoDelimiter() {
688     return JavaElement.JEM_COMPILATIONUNIT;
689 }
690 /**
691  * @see ICompilationUnit#getImport(String)
692  */

693 public IImportDeclaration getImport(String JavaDoc importName) {
694     return getImportContainer().getImport(importName);
695 }
696 /**
697  * @see ICompilationUnit#getImportContainer()
698  */

699 public IImportContainer getImportContainer() {
700     return new ImportContainer(this);
701 }
702
703
704 /**
705  * @see ICompilationUnit#getImports()
706  */

707 public IImportDeclaration[] getImports() throws JavaModelException {
708     IImportContainer container= getImportContainer();
709     JavaModelManager manager = JavaModelManager.getJavaModelManager();
710     Object JavaDoc info = manager.getInfo(container);
711     if (info == null) {
712         if (manager.getInfo(this) != null)
713             // CU was opened, but no import container, then no imports
714
return NO_IMPORTS;
715         else {
716             open(null); // force opening of CU
717
info = manager.getInfo(container);
718             if (info == null)
719                 // after opening, if no import container, then no imports
720
return NO_IMPORTS;
721         }
722     }
723     IJavaElement[] elements = ((JavaElementInfo) info).children;
724     int length = elements.length;
725     IImportDeclaration[] imports = new IImportDeclaration[length];
726     System.arraycopy(elements, 0, imports, 0, length);
727     return imports;
728 }
729 /**
730  * @see IMember#getTypeRoot()
731  */

732 public ITypeRoot getTypeRoot() {
733     return this;
734 }
735 /**
736  * @see org.eclipse.jdt.internal.compiler.env.ICompilationUnit#getMainTypeName()
737  */

738 public char[] getMainTypeName(){
739     return Util.getNameWithoutJavaLikeExtension(getElementName()).toCharArray();
740 }
741 /**
742  * @see IWorkingCopy#getOriginal(IJavaElement)
743  * @deprecated
744  */

745 public IJavaElement getOriginal(IJavaElement workingCopyElement) {
746     // backward compatibility
747
if (!isWorkingCopy()) return null;
748     CompilationUnit cu = (CompilationUnit)workingCopyElement.getAncestor(COMPILATION_UNIT);
749     if (cu == null || !this.owner.equals(cu.owner)) {
750         return null;
751     }
752     
753     return workingCopyElement.getPrimaryElement();
754 }
755 /**
756  * @see IWorkingCopy#getOriginalElement()
757  * @deprecated
758  */

759 public IJavaElement getOriginalElement() {
760     // backward compatibility
761
if (!isWorkingCopy()) return null;
762     
763     return getPrimaryElement();
764 }
765 /*
766  * @see ICompilationUnit#getOwner()
767  */

768 public WorkingCopyOwner getOwner() {
769     return isPrimary() || !isWorkingCopy() ? null : this.owner;
770 }
771 /**
772  * @see ICompilationUnit#getPackageDeclaration(String)
773  */

774 public IPackageDeclaration getPackageDeclaration(String JavaDoc pkg) {
775     return new PackageDeclaration(this, pkg);
776 }
777 /**
778  * @see ICompilationUnit#getPackageDeclarations()
779  */

780 public IPackageDeclaration[] getPackageDeclarations() throws JavaModelException {
781     ArrayList list = getChildrenOfType(PACKAGE_DECLARATION);
782     IPackageDeclaration[] array= new IPackageDeclaration[list.size()];
783     list.toArray(array);
784     return array;
785 }
786 /**
787  * @see org.eclipse.jdt.internal.compiler.env.ICompilationUnit#getPackageName()
788  */

789 public char[][] getPackageName() {
790     PackageFragment packageFragment = (PackageFragment) getParent();
791     if (packageFragment == null) return CharOperation.NO_CHAR_CHAR;
792     return Util.toCharArrays(packageFragment.names);
793 }
794
795 /**
796  * @see IJavaElement#getPath()
797  */

798 public IPath getPath() {
799     PackageFragmentRoot root = getPackageFragmentRoot();
800     if (root == null) return new Path(getElementName()); // working copy not in workspace
801
if (root.isArchive()) {
802         return root.getPath();
803     } else {
804         return getParent().getPath().append(getElementName());
805     }
806 }
807 /*
808  * Returns the per working copy info for the receiver, or null if none exist.
809  * Note: the use count of the per working copy info is NOT incremented.
810  */

811 public JavaModelManager.PerWorkingCopyInfo getPerWorkingCopyInfo() {
812     return JavaModelManager.getJavaModelManager().getPerWorkingCopyInfo(this, false/*don't create*/, false/*don't record usage*/, null/*no problem requestor needed*/);
813 }
814 /*
815  * @see ICompilationUnit#getPrimary()
816  */

817 public ICompilationUnit getPrimary() {
818     return (ICompilationUnit)getPrimaryElement(true);
819 }
820 /*
821  * @see JavaElement#getPrimaryElement(boolean)
822  */

823 public IJavaElement getPrimaryElement(boolean checkOwner) {
824     if (checkOwner && isPrimary()) return this;
825     return new CompilationUnit((PackageFragment)getParent(), getElementName(), DefaultWorkingCopyOwner.PRIMARY);
826 }
827 /**
828  * @see IJavaElement#getResource()
829  */

830 public IResource getResource() {
831     PackageFragmentRoot root = getPackageFragmentRoot();
832     if (root == null) return null; // working copy not in workspace
833
if (root.isArchive()) {
834         return root.getResource();
835     } else {
836         return ((IContainer) getParent().getResource()).getFile(new Path(getElementName()));
837     }
838 }
839 /**
840  * @see ISourceReference#getSource()
841  */

842 public String JavaDoc getSource() throws JavaModelException {
843     IBuffer buffer = getBuffer();
844     if (buffer == null) return ""; //$NON-NLS-1$
845
return buffer.getContents();
846 }
847 /**
848  * @see ISourceReference#getSourceRange()
849  */

850 public ISourceRange getSourceRange() throws JavaModelException {
851     return ((CompilationUnitElementInfo) getElementInfo()).getSourceRange();
852 }
853 /**
854  * @see ICompilationUnit#getType(String)
855  */

856 public IType getType(String JavaDoc typeName) {
857     return new SourceType(this, typeName);
858 }
859 /**
860  * @see ICompilationUnit#getTypes()
861  */

862 public IType[] getTypes() throws JavaModelException {
863     ArrayList list = getChildrenOfType(TYPE);
864     IType[] array= new IType[list.size()];
865     list.toArray(array);
866     return array;
867 }
868 /**
869  * @see IJavaElement
870  */

871 public IResource getUnderlyingResource() throws JavaModelException {
872     if (isWorkingCopy() && !isPrimary()) return null;