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;
873     return super.getUnderlyingResource();
874 }
875 /**
876  * @see IWorkingCopy#getSharedWorkingCopy(IProgressMonitor, IBufferFactory, IProblemRequestor)
877  * @deprecated
878  */

879 public IJavaElement getSharedWorkingCopy(IProgressMonitor pm, IBufferFactory factory, IProblemRequestor problemRequestor) throws JavaModelException {
880     
881     // if factory is null, default factory must be used
882
if (factory == null) factory = this.getBufferManager().getDefaultBufferFactory();
883     
884     return getWorkingCopy(BufferFactoryWrapper.create(factory), problemRequestor, pm);
885 }
886 /**
887  * @see IWorkingCopy#getWorkingCopy()
888  * @deprecated
889  */

890 public IJavaElement getWorkingCopy() throws JavaModelException {
891     return getWorkingCopy(null);
892 }
893 /**
894  * @see ICompilationUnit#getWorkingCopy(IProgressMonitor)
895  */

896 public ICompilationUnit getWorkingCopy(IProgressMonitor monitor) throws JavaModelException {
897     return getWorkingCopy(new WorkingCopyOwner() {/*non shared working copy*/}, null/*no problem requestor*/, monitor);
898 }
899 /**
900  * @see ITypeRoot#getWorkingCopy(WorkingCopyOwner, IProgressMonitor)
901  */

902 public ICompilationUnit getWorkingCopy(WorkingCopyOwner workingCopyOwner, IProgressMonitor monitor) throws JavaModelException {
903     return getWorkingCopy(workingCopyOwner, null, monitor);
904 }
905 /**
906  * @see IWorkingCopy#getWorkingCopy(IProgressMonitor, IBufferFactory, IProblemRequestor)
907  * @deprecated
908  */

909 public IJavaElement getWorkingCopy(IProgressMonitor monitor, IBufferFactory factory, IProblemRequestor problemRequestor) throws JavaModelException {
910     return getWorkingCopy(BufferFactoryWrapper.create(factory), problemRequestor, monitor);
911 }
912 /**
913  * @see ICompilationUnit#getWorkingCopy(WorkingCopyOwner, IProblemRequestor, IProgressMonitor)
914  * @deprecated
915  */

916 public ICompilationUnit getWorkingCopy(WorkingCopyOwner workingCopyOwner, IProblemRequestor problemRequestor, IProgressMonitor monitor) throws JavaModelException {
917     if (!isPrimary()) return this;
918     
919     JavaModelManager manager = JavaModelManager.getJavaModelManager();
920     
921     CompilationUnit workingCopy = new CompilationUnit((PackageFragment)getParent(), getElementName(), workingCopyOwner);
922     JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo =
923         manager.getPerWorkingCopyInfo(workingCopy, false/*don't create*/, true/*record usage*/, null/*not used since don't create*/);
924     if (perWorkingCopyInfo != null) {
925         return perWorkingCopyInfo.getWorkingCopy(); // return existing handle instead of the one created above
926
}
927     BecomeWorkingCopyOperation op = new BecomeWorkingCopyOperation(workingCopy, problemRequestor);
928     op.runOperation(monitor);
929     return workingCopy;
930 }
931 /**
932  * @see Openable#hasBuffer()
933  */

934 protected boolean hasBuffer() {
935     return true;
936 }
937 /*
938  * @see ICompilationUnit#hasResourceChanged()
939  */

940 public boolean hasResourceChanged() {
941     if (!isWorkingCopy()) return false;
942     
943     // if resource got deleted, then #getModificationStamp() will answer IResource.NULL_STAMP, which is always different from the cached
944
// timestamp
945
Object JavaDoc info = JavaModelManager.getJavaModelManager().getInfo(this);
946     if (info == null) return false;
947     IResource resource = getResource();
948     if (resource == null) return false;
949     return ((CompilationUnitElementInfo)info).timestamp != resource.getModificationStamp();
950 }
951 /**
952  * @see IWorkingCopy#isBasedOn(IResource)
953  * @deprecated
954  */

955 public boolean isBasedOn(IResource resource) {
956     if (!isWorkingCopy()) return false;
957     if (!getResource().equals(resource)) return false;
958     return !hasResourceChanged();
959 }
960 /**
961  * @see IOpenable#isConsistent()
962  */

963 public boolean isConsistent() {
964     return !JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().contains(this);
965 }
966 public boolean isPrimary() {
967     return this.owner == DefaultWorkingCopyOwner.PRIMARY;
968 }
969 /**
970  * @see Openable#isSourceElement()
971  */

972 protected boolean isSourceElement() {
973     return true;
974 }
975 protected IStatus validateCompilationUnit(IResource resource) {
976     IPackageFragmentRoot root = getPackageFragmentRoot();
977     // root never null as validation is not done for working copies
978
try {
979         if (root.getKind() != IPackageFragmentRoot.K_SOURCE)
980             return new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, root);
981     } catch (JavaModelException e) {
982         return e.getJavaModelStatus();
983     }
984     if (resource != null) {
985         char[][] inclusionPatterns = ((PackageFragmentRoot)root).fullInclusionPatternChars();
986         char[][] exclusionPatterns = ((PackageFragmentRoot)root).fullExclusionPatternChars();
987         if (Util.isExcluded(resource, inclusionPatterns, exclusionPatterns))
988             return new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_NOT_ON_CLASSPATH, this);
989         if (!resource.isAccessible())
990             return new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, this);
991     }
992     IJavaProject project = getJavaProject();
993     return JavaConventions.validateCompilationUnitName(getElementName(),project.getOption(JavaCore.COMPILER_SOURCE, true), project.getOption(JavaCore.COMPILER_COMPLIANCE, true));
994 }
995 /*
996  * @see ICompilationUnit#isWorkingCopy()
997  */

998 public boolean isWorkingCopy() {
999     // For backward compatibility, non primary working copies are always returning true; in removal
1000
// delta, clients can still check that element was a working copy before being discarded.
1001
return !isPrimary() || getPerWorkingCopyInfo() != null;
1002}
1003/**
1004 * @see IOpenable#makeConsistent(IProgressMonitor)
1005 */

1006public void makeConsistent(IProgressMonitor monitor) throws JavaModelException {
1007    makeConsistent(NO_AST, false/*don't resolve bindings*/, 0 /* don't perform statements recovery */, null/*don't collect problems but report them*/, monitor);
1008}
1009public org.eclipse.jdt.core.dom.CompilationUnit makeConsistent(int astLevel, boolean resolveBindings, int reconcileFlags, HashMap problems, IProgressMonitor monitor) throws JavaModelException {
1010    if (isConsistent()) return null;
1011        
1012    // create a new info and make it the current info
1013
// (this will remove the info and its children just before storing the new infos)
1014
if (astLevel != NO_AST || problems != null) {
1015        ASTHolderCUInfo info = new ASTHolderCUInfo();
1016        info.astLevel = astLevel;
1017        info.resolveBindings = resolveBindings;
1018        info.reconcileFlags = reconcileFlags;
1019        info.problems = problems;
1020        openWhenClosed(info, monitor);
1021        org.eclipse.jdt.core.dom.CompilationUnit result = info.ast;
1022        info.ast = null;
1023        return result;
1024    } else {
1025        openWhenClosed(createElementInfo(), monitor);
1026        return null;
1027    }
1028}
1029/**
1030 * @see ISourceManipulation#move(IJavaElement, IJavaElement, String, boolean, IProgressMonitor)
1031 */

1032public void move(IJavaElement container, IJavaElement sibling, String JavaDoc rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
1033    if (container == null) {
1034        throw new IllegalArgumentException JavaDoc(Messages.operation_nullContainer);
1035    }
1036    IJavaElement[] elements= new IJavaElement[] {this};
1037    IJavaElement[] containers= new IJavaElement[] {container};
1038    
1039    String JavaDoc[] renamings= null;
1040    if (rename != null) {
1041        renamings= new String JavaDoc[] {rename};
1042    }
1043    getJavaModel().move(elements, containers, null, renamings, force, monitor);
1044}
1045
1046/**
1047 * @see Openable#openBuffer(IProgressMonitor, Object)
1048 */

1049protected IBuffer openBuffer(IProgressMonitor pm, Object JavaDoc info) throws JavaModelException {
1050
1051    // create buffer
1052
BufferManager bufManager = getBufferManager();
1053    boolean isWorkingCopy = isWorkingCopy();
1054    IBuffer buffer =
1055        isWorkingCopy
1056            ? this.owner.createBuffer(this)
1057            : BufferManager.createBuffer(this);
1058    if (buffer == null) return null;
1059    
1060    // synchronize to ensure that 2 threads are not putting 2 different buffers at the same time
1061
// see https://bugs.eclipse.org/bugs/show_bug.cgi?id=146331
1062
synchronized(bufManager) {
1063        IBuffer existingBuffer = bufManager.getBuffer(this);
1064        if (existingBuffer != null)
1065            return existingBuffer;
1066        
1067        // set the buffer source
1068
if (buffer.getCharacters() == null) {
1069            if (isWorkingCopy) {
1070                ICompilationUnit original;
1071                if (!isPrimary()
1072                        && (original = new CompilationUnit((PackageFragment)getParent(), getElementName(), DefaultWorkingCopyOwner.PRIMARY)).isOpen()) {
1073                    buffer.setContents(original.getSource());
1074                } else {
1075                    IFile file = (IFile)getResource();
1076                    if (file == null || !file.exists()) {
1077                        // initialize buffer with empty contents
1078
buffer.setContents(CharOperation.NO_CHAR);
1079                    } else {
1080                        buffer.setContents(Util.getResourceContentsAsCharArray(file));
1081                    }
1082                }
1083            } else {
1084                IFile file = (IFile)this.getResource();
1085                if (file == null || !file.exists()) throw newNotPresentException();
1086                buffer.setContents(Util.getResourceContentsAsCharArray(file));
1087            }
1088        }
1089    
1090        // add buffer to buffer cache
1091
// note this may cause existing buffers to be removed from the buffer cache, but only primary compilation unit's buffer
1092
// can be closed, thus no call to a client's IBuffer#close() can be done in this synchronized block.
1093
bufManager.addBuffer(buffer);
1094                
1095        // listen to buffer changes
1096
buffer.addBufferChangedListener(this);
1097    }
1098    return buffer;
1099}
1100protected void openParent(Object JavaDoc childInfo, HashMap newElements, IProgressMonitor pm) throws JavaModelException {
1101    if (!isWorkingCopy())
1102        super.openParent(childInfo, newElements, pm);
1103    // don't open parent for a working copy to speed up the first becomeWorkingCopy
1104
// (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=89411)
1105
}
1106/**
1107 * @see ICompilationUnit#reconcile()
1108 * @deprecated
1109 */

1110public IMarker[] reconcile() throws JavaModelException {
1111    reconcile(NO_AST, false/*don't force problem detection*/, false, null/*use primary owner*/, null/*no progress monitor*/);
1112    return null;
1113}
1114/**
1115 * @see ICompilationUnit#reconcile(int, boolean, WorkingCopyOwner, IProgressMonitor)
1116 */

1117public void reconcile(boolean forceProblemDetection, IProgressMonitor monitor) throws JavaModelException {
1118    reconcile(NO_AST, forceProblemDetection? ICompilationUnit.FORCE_PROBLEM_DETECTION : 0, null/*use primary owner*/, monitor);
1119}
1120
1121/**
1122 * @see ICompilationUnit#reconcile(int, boolean, WorkingCopyOwner, IProgressMonitor)
1123 * @since 3.0
1124 */

1125public org.eclipse.jdt.core.dom.CompilationUnit reconcile(
1126        int astLevel,
1127        boolean forceProblemDetection,
1128        WorkingCopyOwner workingCopyOwner,
1129        IProgressMonitor monitor) throws JavaModelException {
1130    return reconcile(astLevel, forceProblemDetection? ICompilationUnit.FORCE_PROBLEM_DETECTION : 0, workingCopyOwner, monitor);
1131}
1132
1133/**
1134 * @see ICompilationUnit#reconcile(int, boolean, WorkingCopyOwner, IProgressMonitor)
1135 * @since 3.0
1136 */

1137public org.eclipse.jdt.core.dom.CompilationUnit reconcile(
1138        int astLevel,
1139        boolean forceProblemDetection,
1140        boolean enableStatementsRecovery,
1141        WorkingCopyOwner workingCopyOwner,
1142        IProgressMonitor monitor) throws JavaModelException {
1143    int flags = 0;
1144    if (forceProblemDetection) flags |= ICompilationUnit.FORCE_PROBLEM_DETECTION;
1145    if (enableStatementsRecovery) flags |= ICompilationUnit.ENABLE_STATEMENTS_RECOVERY;
1146    return reconcile(astLevel, flags, workingCopyOwner, monitor);
1147}
1148
1149public org.eclipse.jdt.core.dom.CompilationUnit reconcile(
1150        int astLevel,
1151        int reconcileFlags,
1152        WorkingCopyOwner workingCopyOwner,
1153        IProgressMonitor monitor)
1154        throws JavaModelException {
1155    
1156    if (!isWorkingCopy()) return null; // Reconciling is not supported on non working copies
1157
if (workingCopyOwner == null) workingCopyOwner = DefaultWorkingCopyOwner.PRIMARY;
1158    
1159    
1160    PerformanceStats stats = null;
1161    if(ReconcileWorkingCopyOperation.PERF) {
1162        stats = PerformanceStats.getStats(JavaModelManager.RECONCILE_PERF, this);
1163        stats.startRun(new String JavaDoc(this.getFileName()));
1164    }
1165    ReconcileWorkingCopyOperation op = new ReconcileWorkingCopyOperation(this, astLevel, reconcileFlags, workingCopyOwner);
1166    JavaModelManager manager = JavaModelManager.getJavaModelManager();
1167    try {
1168        manager.cacheZipFiles(); // cache zip files for performance (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=134172)
1169
op.runOperation(monitor);
1170    } finally {
1171        manager.flushZipFiles();
1172    }
1173    if(ReconcileWorkingCopyOperation.PERF) {
1174        stats.endRun();
1175    }
1176    return op.ast;
1177}
1178
1179/**
1180 * @see ISourceManipulation#rename(String, boolean, IProgressMonitor)
1181 */

1182public void rename(String JavaDoc newName, boolean force, IProgressMonitor monitor) throws JavaModelException {
1183    if (newName == null) {
1184        throw new IllegalArgumentException JavaDoc(Messages.operation_nullName);
1185    }
1186    IJavaElement[] elements= new IJavaElement[] {this};
1187    IJavaElement[] dests= new IJavaElement[] {this.getParent()};
1188    String JavaDoc[] renamings= new String JavaDoc[] {newName};
1189    getJavaModel().rename(elements, dests, renamings, force, monitor);
1190}
1191/*
1192 * @see ICompilationUnit
1193 */

1194public void restore() throws JavaModelException {
1195
1196    if (!isWorkingCopy()) return;
1197
1198    CompilationUnit original = (CompilationUnit) getOriginalElement();
1199    IBuffer buffer = this.getBuffer();
1200    if (buffer == null) return;
1201    buffer.setContents(original.getContents());
1202    updateTimeStamp(original);
1203    makeConsistent(null);
1204}
1205/**
1206 * @see IOpenable
1207 */

1208public void save(IProgressMonitor pm, boolean force) throws JavaModelException {
1209    if (isWorkingCopy()) {
1210        // no need to save the buffer for a working copy (this is a noop)
1211
reconcile(); // not simply makeConsistent, also computes fine-grain deltas
1212
// in case the working copy is being reconciled already (if not it would miss
1213
// one iteration of deltas).
1214
} else {
1215        super.save(pm, force);
1216    }
1217}
1218/**
1219 * Debugging purposes
1220 */

1221protected void toStringInfo(int tab, StringBuffer JavaDoc buffer, Object JavaDoc info, boolean showResolvedInfo) {
1222    if (!isPrimary()) {
1223        buffer.append(this.tabString(tab));
1224        buffer.append("[Working copy] "); //$NON-NLS-1$
1225
toStringName(buffer);
1226    } else {
1227        if (isWorkingCopy()) {
1228            buffer.append(this.tabString(tab));
1229            buffer.append("[Working copy] "); //$NON-NLS-1$
1230
toStringName(buffer);
1231            if (info == null) {
1232                buffer.append(" (not open)"); //$NON-NLS-1$
1233
}
1234        } else {
1235            super.toStringInfo(tab, buffer, info, showResolvedInfo);
1236        }
1237    }
1238}
1239/*
1240 * Assume that this is a working copy
1241 */

1242protected void updateTimeStamp(CompilationUnit original) throws JavaModelException {
1243    long timeStamp =
1244        ((IFile) original.getResource()).getModificationStamp();
1245    if (timeStamp == IResource.NULL_STAMP) {
1246        throw new JavaModelException(
1247            new JavaModelStatus(IJavaModelStatusConstants.INVALID_RESOURCE));
1248    }
1249    ((CompilationUnitElementInfo) getElementInfo()).timestamp = timeStamp;
1250}
1251
1252}
1253
Popular Tags