1 /*******************************************************************************
2 * Copyright (c) 2000, 2003 IBM Corporation and others.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Common Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/cpl-v10.html
9 * IBM Corporation - initial API and implementation
10 *******************************************************************************/
11 package net.sourceforge.phpdt.internal.core;
13 import java.util.ArrayList;
14 import java.util.HashMap;
17 import net.sourceforge.phpdt.core.IBuffer;
18 import net.sourceforge.phpdt.core.IBufferFactory;
19 import net.sourceforge.phpdt.core.ICompilationUnit;
20 import net.sourceforge.phpdt.core.IImportContainer;
21 import net.sourceforge.phpdt.core.IImportDeclaration;
22 import net.sourceforge.phpdt.core.IJavaElement;
23 import net.sourceforge.phpdt.core.IJavaModelStatusConstants;
24 import net.sourceforge.phpdt.core.IJavaProject;
25 import net.sourceforge.phpdt.core.IMember;
26 import net.sourceforge.phpdt.core.IMethod;
27 import net.sourceforge.phpdt.core.IOpenable;
28 import net.sourceforge.phpdt.core.IPackageDeclaration;
29 import net.sourceforge.phpdt.core.IPackageFragmentRoot;
30 import net.sourceforge.phpdt.core.IParent;
31 import net.sourceforge.phpdt.core.IProblemRequestor;
32 import net.sourceforge.phpdt.core.ISourceManipulation;
33 import net.sourceforge.phpdt.core.ISourceRange;
34 import net.sourceforge.phpdt.core.ISourceReference;
35 import net.sourceforge.phpdt.core.IType;
36 import net.sourceforge.phpdt.core.IWorkingCopy;
37 import net.sourceforge.phpdt.core.JavaModelException;
38 import net.sourceforge.phpdt.core.Signature;
39 import net.sourceforge.phpdt.core.WorkingCopyOwner;
40 import net.sourceforge.phpdt.core.compiler.CharOperation;
41 import net.sourceforge.phpdt.core.jdom.IDOMNode;
42 import net.sourceforge.phpdt.internal.compiler.IProblemFactory;
43 import net.sourceforge.phpdt.internal.compiler.SourceElementParser;
44 import net.sourceforge.phpdt.internal.compiler.impl.CompilerOptions;
45 import net.sourceforge.phpdt.internal.compiler.problem.DefaultProblemFactory;
46 import net.sourceforge.phpdt.internal.core.util.Util;
47 import net.sourceforge.phpeclipse.internal.compiler.ast.CompilationUnitDeclaration;
48 import net.sourceforge.phpdt.core.*;
49 import org.eclipse.core.resources.IContainer;
50 import org.eclipse.core.resources.IFile;
51 import org.eclipse.core.resources.IMarker;
52 import org.eclipse.core.resources.IResource;
53 import org.eclipse.core.runtime.IPath;
54 import org.eclipse.core.runtime.IProgressMonitor;
55 import org.eclipse.core.runtime.Path;
58 * @see ICompilationUnit
61 public class CompilationUnit extends Openable implements ICompilationUnit, net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit {
62 public WorkingCopyOwner owner;
65 * Constructs a handle to a compilation unit with the given name in the
66 * specified package for the specified owner
68 * @exception IllegalArgumentException if the name of the compilation unit
69 * does not end with ".java"
71 protected CompilationUnit(PackageFragment parent, String name, WorkingCopyOwner owner) {
76 * Accepts the given visitor onto the parsed tree of this compilation unit, after
77 * having runned the name resolution.
78 * The visitor's corresponding <code>visit</code> method is called with the
79 * corresponding parse tree. If the visitor returns <code>true</code>, this method
80 * visits this parse node's members.
82 * @param visitor the visitor
83 * @exception JavaModelException if this method fails. Reasons include:
85 * <li> This element does not exist.</li>
86 * <li> The visitor failed with this exception.</li>
89 //public void accept(IAbstractSyntaxTreeVisitor visitor) throws JavaModelException {
90 // CompilationUnitVisitor.visit(this, visitor);
93 * @see ICompilationUnit#becomeWorkingCopy(IProblemRequestor, IProgressMonitor)
95 public void becomeWorkingCopy(IProblemRequestor problemRequestor, IProgressMonitor monitor) throws JavaModelException {
96 JavaModelManager manager = JavaModelManager.getJavaModelManager();
97 JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = manager.getPerWorkingCopyInfo(this, false/*don't create*/, true /*record usage*/, null/*no problem requestor needed*/);
98 if (perWorkingCopyInfo == null) {
99 // close cu and its children
102 BecomeWorkingCopyOperation operation = new BecomeWorkingCopyOperation(this, problemRequestor);
103 operation.runOperation(monitor);
106 //protected void buildStructure(OpenableElementInfo info, IProgressMonitor monitor) throws JavaModelException {
108 // if (monitor != null && monitor.isCanceled()) return;
110 // // remove existing (old) infos
113 // HashMap newElements = new HashMap(11);
114 // info.setIsStructureKnown(generateInfos(info, monitor, newElements, getResource()));
115 // JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().remove(this);
116 // for (Iterator iter = newElements.keySet().iterator(); iter.hasNext();) {
117 // IJavaElement key = (IJavaElement) iter.next();
118 // Object value = newElements.get(key);
119 // JavaModelManager.getJavaModelManager().putInfo(key, value);
121 // // add the info for this at the end, to ensure that a getInfo cannot reply null in case the LRU cache needs
122 // // to be flushed. Might lead to performance issues.
123 // // see PR 1G2K5S7: ITPJCORE:ALL - NPE when accessing source for a binary type
124 // JavaModelManager.getJavaModelManager().putInfo(this, info);
126 protected boolean buildStructure(OpenableElementInfo info, final IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
128 // check if this compilation unit can be opened
129 if (!isWorkingCopy()) { // no check is done on root kind or exclusion pattern for working copies
130 if ( // ((IPackageFragment)getParent()).getKind() == IPackageFragmentRoot.K_BINARY||
131 !isValidCompilationUnit()
132 || !underlyingResource.isAccessible()) {
133 throw newNotPresentException();
137 // prevents reopening of non-primary working copies (they are closed when they are discarded and should not be reopened)
138 if (!isPrimary() && getPerWorkingCopyInfo() == null) {
139 throw newNotPresentException();
142 CompilationUnitElementInfo unitInfo = (CompilationUnitElementInfo) info;
144 // get buffer contents
145 IBuffer buffer = getBufferManager().getBuffer(CompilationUnit.this);
146 if (buffer == null) {
147 buffer = openBuffer(pm, unitInfo); // open buffer independently from the info, since we are building the info
149 final char[] contents = buffer == null ? null : buffer.getCharacters();
151 // generate structure and compute syntax problems if needed
152 CompilationUnitStructureRequestor requestor = new CompilationUnitStructureRequestor(this, unitInfo, newElements);
153 JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = getPerWorkingCopyInfo();
154 IJavaProject project = getJavaProject();
155 boolean computeProblems = JavaProject.hasJavaNature(project.getProject()) && perWorkingCopyInfo != null && perWorkingCopyInfo.isActive();
156 IProblemFactory problemFactory = new DefaultProblemFactory();
157 Map options = project.getOptions(true);
158 SourceElementParser parser = new SourceElementParser(
161 new CompilerOptions(options));
162 //, true/*report local declarations*/);
163 requestor.parser = parser;
164 CompilationUnitDeclaration unit = parser.parseCompilationUnit(new net.sourceforge.phpdt.internal.compiler.env.ICompilationUnit() {
165 public char[] getContents() {
168 public char[] getMainTypeName() {
169 return CompilationUnit.this.getMainTypeName();
171 public char[][] getPackageName() {
172 return CompilationUnit.this.getPackageName();
174 public char[] getFileName() {
175 return CompilationUnit.this.getFileName();
177 }, true /*full parse to find local elements*/);
179 // update timestamp (might be IResource.NULL_STAMP if original does not exist)
180 if (underlyingResource == null) {
181 underlyingResource = getResource();
183 unitInfo.timestamp = ((IFile)underlyingResource).getModificationStamp();
185 // compute other problems if needed
186 CompilationUnitDeclaration compilationUnitDeclaration = null;
188 if (computeProblems){
189 perWorkingCopyInfo.beginReporting();
190 compilationUnitDeclaration = CompilationUnitProblemFinder.process(unit, this, contents, parser, this.owner, perWorkingCopyInfo, problemFactory, false/*don't cleanup cu*/, pm);
191 perWorkingCopyInfo.endReporting();
194 // if (info instanceof ASTHolderCUInfo) {
195 // int astLevel = ((ASTHolderCUInfo) info).astLevel;
196 // org.eclipse.jdt.core.dom.CompilationUnit cu = AST.convertCompilationUnit(astLevel, unit, contents, options, pm);
197 // ((ASTHolderCUInfo) info).ast = cu;
200 if (compilationUnitDeclaration != null) {
201 compilationUnitDeclaration.cleanUp();
205 return unitInfo.isStructureKnown();
208 // * @see ICodeAssist#codeComplete(int, ICompletionRequestor)
210 //public void codeComplete(int offset, ICompletionRequestor requestor) throws JavaModelException {
211 // codeComplete(this, isWorkingCopy() ? (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) getOriginalElement() : this, offset, requestor);
214 * @see ICodeAssist#codeSelect(int, int)
216 //public IJavaElement[] codeSelect(int offset, int length) throws JavaModelException {
217 // return super.codeSelect(this, offset, length);
220 * @see IWorkingCopy#commit(boolean, IProgressMonitor)
222 public void commit(boolean force, IProgressMonitor monitor) throws JavaModelException {
223 throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, this));
226 * @see ICompilationUnit#commitWorkingCopy(boolean, IProgressMonitor)
228 public void commitWorkingCopy(boolean force, IProgressMonitor monitor) throws JavaModelException {
229 CommitWorkingCopyOperation op= new CommitWorkingCopyOperation(this, force);
230 op.runOperation(monitor);
233 * @see ISourceManipulation#copy(IJavaElement, IJavaElement, String, boolean, IProgressMonitor)
235 public void copy(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
236 if (container == null) {
237 throw new IllegalArgumentException(Util.bind("operation.nullContainer")); //$NON-NLS-1$
239 IJavaElement[] elements = new IJavaElement[] {this};
240 IJavaElement[] containers = new IJavaElement[] {container};
241 String[] renamings = null;
242 if (rename != null) {
243 renamings = new String[] {rename};
245 getJavaModel().copy(elements, containers, null, renamings, force, monitor);
249 * Returns a new element info for this element.
251 protected Object createElementInfo() {
252 return new CompilationUnitElementInfo();
255 // * @see ICompilationUnit#createImport(String, IJavaElement, IProgressMonitor)
257 //public IImportDeclaration createImport(String name, IJavaElement sibling, IProgressMonitor monitor) throws JavaModelException {
258 // CreateImportOperation op = new CreateImportOperation(name, this);
259 // if (sibling != null) {
260 // op.createBefore(sibling);
262 // runOperation(op, monitor);
263 // return getImport(name);
266 * @see ICompilationUnit#createPackageDeclaration(String, IProgressMonitor)
268 public IPackageDeclaration createPackageDeclaration(String name, IProgressMonitor monitor) throws JavaModelException {
270 CreatePackageDeclarationOperation op= new CreatePackageDeclarationOperation(name, this);
271 runOperation(op, monitor);
272 return getPackageDeclaration(name);
275 // * @see ICompilationUnit#createType(String, IJavaElement, boolean, IProgressMonitor)
277 //public IType createType(String content, IJavaElement sibling, boolean force, IProgressMonitor monitor) throws JavaModelException {
279 // //autogenerate this compilation unit
280 // IPackageFragment pkg = (IPackageFragment) getParent();
281 // String source = ""; //$NON-NLS-1$
282 // if (pkg.getElementName().length() > 0) {
283 // //not the default package...add the package declaration
284 // source = "package " + pkg.getElementName() + ";" + org.eclipse.jdt.internal.compiler.util.Util.LINE_SEPARATOR + org.eclipse.jdt.internal.compiler.util.Util.LINE_SEPARATOR; //$NON-NLS-1$ //$NON-NLS-2$
286 // CreateCompilationUnitOperation op = new CreateCompilationUnitOperation(pkg, fName, source, force);
287 // runOperation(op, monitor);
289 // CreateTypeOperation op = new CreateTypeOperation(this, content, force);
290 // if (sibling != null) {
291 // op.createBefore(sibling);
293 // runOperation(op, monitor);
294 // return (IType) op.getResultElements()[0];
297 * @see ISourceManipulation#delete(boolean, IProgressMonitor)
299 public void delete(boolean force, IProgressMonitor monitor) throws JavaModelException {
300 IJavaElement[] elements= new IJavaElement[] {this};
301 getJavaModel().delete(elements, force, monitor);
304 * @see IWorkingCopy#destroy()
307 public void destroy() {
309 discardWorkingCopy();
310 } catch (JavaModelException e) {
315 * @see ICompilationUnit#discardWorkingCopy
317 public void discardWorkingCopy() throws JavaModelException {
318 // discard working copy and its children
319 DiscardWorkingCopyOperation op = new DiscardWorkingCopyOperation(this);
320 op.runOperation(null);
324 * Returns true if this handle represents the same Java element
325 * as the given handle.
327 * @see Object#equals(java.lang.Object)
329 public boolean equals(Object obj) {
330 if (!(obj instanceof CompilationUnit)) return false;
331 CompilationUnit other = (CompilationUnit)obj;
332 return this.owner.equals(other.owner) && super.equals(obj);
335 * @see JavaElement#equalsDOMNode(IDOMNode)
337 protected boolean equalsDOMNode(IDOMNode node) throws JavaModelException {
338 String name = getElementName();
339 if (node.getNodeType() == IDOMNode.COMPILATION_UNIT && name != null ) {
340 String nodeName = node.getName();
341 if (nodeName == null) return false;
342 if (name.equals(nodeName)) {
345 // iterate through all the types inside the receiver and see if one of them can fit
346 IType[] types = getTypes();
347 String typeNodeName = nodeName.substring(0, nodeName.indexOf(".java")); //$NON-NLS-1$
348 for (int i = 0, max = types.length; i < max; i++) {
349 if (types[i].getElementName().equals(typeNodeName)) {
358 * @see IWorkingCopy#findElements(IJavaElement)
360 public IJavaElement[] findElements(IJavaElement element) {
361 ArrayList children = new ArrayList();
362 while (element != null && element.getElementType() != IJavaElement.COMPILATION_UNIT) {
363 children.add(element);
364 element = element.getParent();
366 if (element == null) return null;
367 IJavaElement currentElement = this;
368 for (int i = children.size()-1; i >= 0; i--) {
369 IJavaElement child = (IJavaElement)children.get(i);
370 switch (child.getElementType()) {
371 // case IJavaElement.PACKAGE_DECLARATION:
372 // currentElement = ((ICompilationUnit)currentElement).getPackageDeclaration(child.getElementName());
374 // case IJavaElement.IMPORT_CONTAINER:
375 // currentElement = ((ICompilationUnit)currentElement).getImportContainer();
377 // case IJavaElement.IMPORT_DECLARATION:
378 // currentElement = ((IImportContainer)currentElement).getImport(child.getElementName());
380 case IJavaElement.TYPE:
381 if (currentElement.getElementType() == IJavaElement.COMPILATION_UNIT) {
382 currentElement = ((ICompilationUnit)currentElement).getType(child.getElementName());
384 currentElement = ((IType)currentElement).getType(child.getElementName());
387 // case IJavaElement.INITIALIZER:
388 // currentElement = ((IType)currentElement).getInitializer(((JavaElement)child).getOccurrenceCount());
390 case IJavaElement.FIELD:
391 currentElement = ((IType)currentElement).getField(child.getElementName());
393 case IJavaElement.METHOD:
394 return ((IType)currentElement).findMethods((IMethod)child);
398 if (currentElement != null && currentElement.exists()) {
399 return new IJavaElement[] {currentElement};
405 * @see IWorkingCopy#findPrimaryType()
407 public IType findPrimaryType() {
408 String typeName = Signature.getQualifier(this.getElementName());
409 IType primaryType= this.getType(typeName);
410 if (primaryType.exists()) {
416 * @see IWorkingCopy#findSharedWorkingCopy(IBufferFactory)
419 public IJavaElement findSharedWorkingCopy(IBufferFactory factory) {
421 // if factory is null, default factory must be used
422 if (factory == null) factory = this.getBufferManager().getDefaultBufferFactory();
424 return findWorkingCopy(BufferFactoryWrapper.create(factory));
428 * @see ICompilationUnit#findWorkingCopy(WorkingCopyOwner)
430 public ICompilationUnit findWorkingCopy(WorkingCopyOwner workingCopyOwner) {
431 CompilationUnit cu = new CompilationUnit((PackageFragment)this.parent, getElementName(), workingCopyOwner);
432 if (workingCopyOwner == DefaultWorkingCopyOwner.PRIMARY) {
435 // must be a working copy
436 JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = cu.getPerWorkingCopyInfo();
437 if (perWorkingCopyInfo != null) {
438 return perWorkingCopyInfo.getWorkingCopy();
444 protected boolean generateInfos(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
446 // if (getParent() instanceof JarPackageFragment) {
447 // // ignore .java files in jar
448 // throw newNotPresentException();
450 // put the info now, because getting the contents requires it
451 JavaModelManager.getJavaModelManager().putInfo(this, info);
452 CompilationUnitElementInfo unitInfo = (CompilationUnitElementInfo) info;
454 // generate structure
455 CompilationUnitStructureRequestor requestor = new CompilationUnitStructureRequestor(this, unitInfo, newElements);
456 IProblemFactory factory = new DefaultProblemFactory();
457 SourceElementParser parser = new SourceElementParser(requestor, factory, new CompilerOptions(getJavaProject().getOptions(true)));
458 // SourceElementParser parser = new SourceElementParser(requestor, factory);
459 requestor.parser = parser;
460 parser.parseCompilationUnit(this, false);
461 if (isWorkingCopy()) {
462 CompilationUnit original = (CompilationUnit) getOriginalElement();
463 // might be IResource.NULL_STAMP if original does not exist
464 unitInfo.timestamp = ((IFile) original.getResource()).getModificationStamp();
466 return unitInfo.isStructureKnown();
470 * @see ICompilationUnit#getAllTypes()
472 public IType[] getAllTypes() throws JavaModelException {
473 IJavaElement[] types = getTypes();
475 ArrayList allTypes = new ArrayList(types.length);
476 ArrayList typesToTraverse = new ArrayList(types.length);
477 for (i = 0; i < types.length; i++) {
478 typesToTraverse.add(types[i]);
480 while (!typesToTraverse.isEmpty()) {
481 IType type = (IType) typesToTraverse.get(0);
482 typesToTraverse.remove(type);
484 types = type.getTypes();
485 for (i = 0; i < types.length; i++) {
486 typesToTraverse.add(types[i]);
489 IType[] arrayOfAllTypes = new IType[allTypes.size()];
490 allTypes.toArray(arrayOfAllTypes);
491 return arrayOfAllTypes;
494 * @see IMember#getCompilationUnit()
496 public ICompilationUnit getCompilationUnit() {
500 * @see org.eclipse.jdt.internal.compiler.env.ICompilationUnit#getContents()
502 public char[] getContents() {
504 IBuffer buffer = this.getBuffer();
505 return buffer == null ? null : buffer.getCharacters();
506 } catch (JavaModelException e) {
507 return CharOperation.NO_CHAR;
511 * A compilation unit has a corresponding resource unless it is contained
514 * @see IJavaElement#getCorrespondingResource()
516 public IResource getCorrespondingResource() throws JavaModelException {
517 IPackageFragmentRoot root= (IPackageFragmentRoot)getParent().getParent();
518 if (root.isArchive()) {
521 return getUnderlyingResource();
525 * @see ICompilationUnit#getElementAt(int)
527 public IJavaElement getElementAt(int position) throws JavaModelException {
529 IJavaElement e= getSourceElementAt(position);
539 public int getElementType() {
540 return COMPILATION_UNIT;
542 public char[] getFileName(){
543 return getElementName().toCharArray();
546 * @see JavaElement#getHandleMementoDelimiter()
548 protected char getHandleMementoDelimiter() {
549 return JavaElement.JEM_COMPILATIONUNIT;
552 * @see ICompilationUnit#getImport(String)
554 public IImportDeclaration getImport(String importName) {
555 return new ImportDeclaration((ImportContainer)getImportContainer(), importName);
559 * @see ICompilationUnit#getImportContainer()
561 public IImportContainer getImportContainer() {
562 return new ImportContainer(this);
567 * @see ICompilationUnit#getImports()
569 //public IImportDeclaration[] getImports() throws JavaModelException {
570 // IImportContainer container= getImportContainer();
571 // if (container.exists()) {
572 // IJavaElement[] elements= container.getChildren();
573 // IImportDeclaration[] imprts= new IImportDeclaration[elements.length];
574 // System.arraycopy(elements, 0, imprts, 0, elements.length);
576 // } else if (!exists()) {
577 // throw newNotPresentException();
579 // return new IImportDeclaration[0];
584 * @see org.eclipse.jdt.internal.compiler.env.ICompilationUnit#getMainTypeName()
586 public char[] getMainTypeName(){
587 String name= getElementName();
589 name= name.substring(0, name.length() - 5);
590 return name.toCharArray();
594 * @see IWorkingCopy#getOriginal(IJavaElement)
597 public IJavaElement getOriginal(IJavaElement workingCopyElement) {
598 // backward compatibility
599 if (!isWorkingCopy()) return null;
600 CompilationUnit cu = (CompilationUnit)workingCopyElement.getAncestor(COMPILATION_UNIT);
601 if (cu == null || !this.owner.equals(cu.owner)) {
605 return workingCopyElement.getPrimaryElement();
608 * @see IWorkingCopy#getOriginalElement()
611 public IJavaElement getOriginalElement() {
612 // backward compatibility
613 if (!isWorkingCopy()) return null;
615 return getPrimaryElement();
618 * @see ICompilationUnit#getOwner()
620 public WorkingCopyOwner getOwner() {
621 return isPrimary() || !isWorkingCopy() ? null : this.owner;
624 * @see ICompilationUnit#getPackageDeclaration(String)
626 public IPackageDeclaration getPackageDeclaration(String name) {
627 return new PackageDeclaration(this, name);
630 * @see ICompilationUnit#getPackageDeclarations()
632 public IPackageDeclaration[] getPackageDeclarations() throws JavaModelException {
633 ArrayList list = getChildrenOfType(PACKAGE_DECLARATION);
634 IPackageDeclaration[] array= new IPackageDeclaration[list.size()];
639 * @see org.eclipse.jdt.internal.compiler.env.ICompilationUnit#getPackageName()
641 public char[][] getPackageName() {
645 * @see IJavaElement#getPath()
647 public IPath getPath() {
648 PackageFragmentRoot root = this.getPackageFragmentRoot();
649 if (root.isArchive()) {
650 return root.getPath();
652 return this.getParent().getPath().append(this.getElementName());
656 * Returns the per working copy info for the receiver, or null if none exist.
657 * Note: the use count of the per working copy info is NOT incremented.
659 public JavaModelManager.PerWorkingCopyInfo getPerWorkingCopyInfo() {
660 return JavaModelManager.getJavaModelManager().getPerWorkingCopyInfo(this, false/*don't create*/, false/*don't record usage*/, null/*no problem requestor needed*/);
663 * @see ICompilationUnit#getPrimary()
665 public ICompilationUnit getPrimary() {
666 return (ICompilationUnit)getPrimaryElement(true);
669 * @see JavaElement#getPrimaryElement(boolean)
671 public IJavaElement getPrimaryElement(boolean checkOwner) {
672 if (checkOwner && isPrimary()) return this;
673 return new CompilationUnit((PackageFragment)getParent(), getElementName(), DefaultWorkingCopyOwner.PRIMARY);
677 * @see IJavaElement#getResource()
679 public IResource getResource() {
680 PackageFragmentRoot root = this.getPackageFragmentRoot();
681 if (root.isArchive()) {
682 return root.getResource();
684 return ((IContainer)this.getParent().getResource()).getFile(new Path(this.getElementName()));
689 * @see ISourceReference#getSource()
691 public String getSource() throws JavaModelException {
692 IBuffer buffer = getBuffer();
693 if (buffer == null) return ""; //$NON-NLS-1$
694 return buffer.getContents();
697 * @see ISourceReference#getSourceRange()
699 public ISourceRange getSourceRange() throws JavaModelException {
700 return ((CompilationUnitElementInfo) getElementInfo()).getSourceRange();
703 * @see ICompilationUnit#getType(String)
705 public IType getType(String name) {
706 return new SourceType(this, name);
709 * @see ICompilationUnit#getTypes()
711 public IType[] getTypes() throws JavaModelException {
712 ArrayList list = getChildrenOfType(TYPE);
713 IType[] array= new IType[list.size()];
720 public IResource getUnderlyingResource() throws JavaModelException {
721 if (isWorkingCopy() && !isPrimary()) return null;
722 return super.getUnderlyingResource();
725 // * @see IWorkingCopy#getSharedWorkingCopy(IProgressMonitor, IBufferFactory, IProblemRequestor)
727 //public IJavaElement getSharedWorkingCopy(IProgressMonitor pm, IBufferFactory factory, IProblemRequestor problemRequestor) throws JavaModelException {
729 // // if factory is null, default factory must be used
730 // if (factory == null) factory = this.getBufferManager().getDefaultBufferFactory();
732 // JavaModelManager manager = JavaModelManager.getJavaModelManager();
734 // // In order to be shared, working copies have to denote the same compilation unit
735 // // AND use the same buffer factory.
736 // // Assuming there is a little set of buffer factories, then use a 2 level Map cache.
737 // Map sharedWorkingCopies = manager.sharedWorkingCopies;
739 // Map perFactoryWorkingCopies = (Map) sharedWorkingCopies.get(factory);
740 // if (perFactoryWorkingCopies == null){
741 // perFactoryWorkingCopies = new HashMap();
742 // sharedWorkingCopies.put(factory, perFactoryWorkingCopies);
744 // WorkingCopy workingCopy = (WorkingCopy)perFactoryWorkingCopies.get(this);
745 // if (workingCopy != null) {
746 // workingCopy.useCount++;
748 // if (SHARED_WC_VERBOSE) {
749 // System.out.println("Incrementing use count of shared working copy " + workingCopy.toStringWithAncestors()); //$NON-NLS-1$
752 // return workingCopy;
754 // CreateWorkingCopyOperation op = new CreateWorkingCopyOperation(this, perFactoryWorkingCopies, factory, problemRequestor);
755 // runOperation(op, pm);
756 // return op.getResultElements()[0];
760 // * @see IWorkingCopy#getWorkingCopy()
762 //public IJavaElement getWorkingCopy() throws JavaModelException {
763 // return this.getWorkingCopy(null, null, null);
767 // * @see IWorkingCopy#getWorkingCopy(IProgressMonitor, IBufferFactory, IProblemRequestor)
769 //public IJavaElement getWorkingCopy(IProgressMonitor pm, IBufferFactory factory, IProblemRequestor problemRequestor) throws JavaModelException {
770 // CreateWorkingCopyOperation op = new CreateWorkingCopyOperation(this, null, factory, problemRequestor);
771 // runOperation(op, pm);
772 // return op.getResultElements()[0];
775 * @see IWorkingCopy#getSharedWorkingCopy(IProgressMonitor, IBufferFactory, IProblemRequestor)
778 public IJavaElement getSharedWorkingCopy(IProgressMonitor pm, IBufferFactory factory, IProblemRequestor problemRequestor) throws JavaModelException {
780 // if factory is null, default factory must be used
781 if (factory == null) factory = this.getBufferManager().getDefaultBufferFactory();
783 return getWorkingCopy(BufferFactoryWrapper.create(factory), problemRequestor, pm);
786 * @see IWorkingCopy#getWorkingCopy()
789 public IJavaElement getWorkingCopy() throws JavaModelException {
790 return getWorkingCopy(null);
793 * @see ICompilationUnit#getWorkingCopy(IProgressMonitor)
795 public ICompilationUnit getWorkingCopy(IProgressMonitor monitor) throws JavaModelException {
796 return getWorkingCopy(new WorkingCopyOwner() {/*non shared working copy*/}, null/*no problem requestor*/, monitor);
799 * @see IWorkingCopy#getWorkingCopy(IProgressMonitor, IBufferFactory, IProblemRequestor)
802 public IJavaElement getWorkingCopy(IProgressMonitor monitor, IBufferFactory factory, IProblemRequestor problemRequestor) throws JavaModelException {
803 return getWorkingCopy(BufferFactoryWrapper.create(factory), problemRequestor, monitor);
806 * @see ICompilationUnit#getWorkingCopy(WorkingCopyOwner, IProblemRequestor, IProgressMonitor)
808 public ICompilationUnit getWorkingCopy(WorkingCopyOwner workingCopyOwner, IProblemRequestor problemRequestor, IProgressMonitor monitor) throws JavaModelException {
809 if (!isPrimary()) return this;
811 JavaModelManager manager = JavaModelManager.getJavaModelManager();
813 CompilationUnit workingCopy = new CompilationUnit((PackageFragment)getParent(), getElementName(), workingCopyOwner);
814 JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo =
815 manager.getPerWorkingCopyInfo(workingCopy, false/*don't create*/, true/*record usage*/, null/*not used since don't create*/);
816 if (perWorkingCopyInfo != null) {
817 return perWorkingCopyInfo.getWorkingCopy(); // return existing handle instead of the one created above
819 BecomeWorkingCopyOperation op = new BecomeWorkingCopyOperation(workingCopy, problemRequestor);
820 op.runOperation(monitor);
825 * If I am not open, return true to avoid parsing.
827 * @see IParent#hasChildren()
829 public boolean hasChildren() throws JavaModelException {
831 // return getChildren().length > 0;
838 * @see Openable#hasBuffer()
840 protected boolean hasBuffer() {
844 * @see ICompilationUnit#hasResourceChanged()
846 public boolean hasResourceChanged() {
847 if (!isWorkingCopy()) return false;
849 // if resource got deleted, then #getModificationStamp() will answer IResource.NULL_STAMP, which is always different from the cached
851 Object info = JavaModelManager.getJavaModelManager().getInfo(this);
852 if (info == null) return false;
853 return ((CompilationUnitElementInfo)info).timestamp != getResource().getModificationStamp();
856 * @see IWorkingCopy#isBasedOn(IResource)
859 public boolean isBasedOn(IResource resource) {
860 if (!isWorkingCopy()) return false;
861 if (!getResource().equals(resource)) return false;
862 return !hasResourceChanged();
865 * @see IOpenable#isConsistent()
867 public boolean isConsistent() {
868 return JavaModelManager.getJavaModelManager().getElementsOutOfSynchWithBuffers().get(this) == null;
875 public boolean isOpen() {
876 Object info = JavaModelManager.getJavaModelManager().getInfo(this);
877 return info != null && ((CompilationUnitElementInfo)info).isOpen();
879 public boolean isPrimary() {
880 return this.owner == DefaultWorkingCopyOwner.PRIMARY;
883 * @see Openable#isSourceElement()
885 protected boolean isSourceElement() {
888 protected boolean isValidCompilationUnit() {
889 IPackageFragmentRoot root = getPackageFragmentRoot();
891 if (root.getKind() != IPackageFragmentRoot.K_SOURCE) return false;
892 } catch (JavaModelException e) {
895 // IResource resource = getResource();
896 // if (resource != null) {
897 // char[][] inclusionPatterns = ((PackageFragmentRoot)root).fullInclusionPatternChars();
898 // char[][] exclusionPatterns = ((PackageFragmentRoot)root).fullExclusionPatternChars();
899 // if (Util.isExcluded(resource, inclusionPatterns, exclusionPatterns)) return false;
901 if (!Util.isValidCompilationUnitName(getElementName())) return false;
905 * @see ICompilationUnit#isWorkingCopy()
907 public boolean isWorkingCopy() {
908 // For backward compatibility, non primary working copies are always returning true; in removal
909 // delta, clients can still check that element was a working copy before being discarded.
910 return !isPrimary() || getPerWorkingCopyInfo() != null;
913 * @see IOpenable#makeConsistent(IProgressMonitor)
915 public void makeConsistent(IProgressMonitor monitor) throws JavaModelException {
916 makeConsistent(false/*don't create AST*/, 0, monitor);
918 public Object makeConsistent(boolean createAST, int astLevel, IProgressMonitor monitor) throws JavaModelException {
919 if (isConsistent()) return null;
921 // create a new info and make it the current info
922 // (this will remove the info and its children just before storing the new infos)
924 // ASTHolderCUInfo info = new ASTHolderCUInfo();
925 // info.astLevel = astLevel;
926 // openWhenClosed(info, monitor);
927 // org.eclipse.jdt.core.dom.CompilationUnit result = info.ast;
931 openWhenClosed(createElementInfo(), monitor);
935 //public net.sourceforge.phpdt.core.dom.CompilationUnit makeConsistent(boolean createAST, int astLevel, IProgressMonitor monitor) throws JavaModelException {
936 // if (isConsistent()) return null;
938 // // create a new info and make it the current info
939 // // (this will remove the info and its children just before storing the new infos)
941 // ASTHolderCUInfo info = new ASTHolderCUInfo();
942 // info.astLevel = astLevel;
943 // openWhenClosed(info, monitor);
944 // net.sourceforge.phpdt.core.dom.CompilationUnit result = info.ast;
948 // openWhenClosed(createElementInfo(), monitor);
954 * @see ISourceManipulation#move(IJavaElement, IJavaElement, String, boolean, IProgressMonitor)
956 public void move(IJavaElement container, IJavaElement sibling, String rename, boolean force, IProgressMonitor monitor) throws JavaModelException {
957 if (container == null) {
958 throw new IllegalArgumentException(Util.bind("operation.nullContainer")); //$NON-NLS-1$
960 IJavaElement[] elements= new IJavaElement[] {this};
961 IJavaElement[] containers= new IJavaElement[] {container};
963 String[] renamings= null;
964 if (rename != null) {
965 renamings= new String[] {rename};
967 getJavaModel().move(elements, containers, null, renamings, force, monitor);
971 // * @see Openable#openBuffer(IProgressMonitor)
973 //protected IBuffer openBuffer(IProgressMonitor pm) throws JavaModelException {
975 // // create buffer - compilation units only use default buffer factory
976 // BufferManager bufManager = getBufferManager();
977 // IBuffer buffer = getBufferFactory().createBuffer(this);
978 // if (buffer == null) return null;
980 // // set the buffer source
981 // if (buffer.getCharacters() == null){
982 // IFile file = (IFile)this.getResource();
983 // if (file == null || !file.exists()) throw newNotPresentException();
984 // buffer.setContents(Util.getResourceContentsAsCharArray(file));
987 // // add buffer to buffer cache
988 // bufManager.addBuffer(buffer);
990 // // listen to buffer changes
991 // buffer.addBufferChangedListener(this);
996 * @see Openable#openBuffer(IProgressMonitor, Object)
998 protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaModelException {
1001 boolean isWorkingCopy = isWorkingCopy();
1004 ? this.owner.createBuffer(this)
1005 : BufferManager.getDefaultBufferManager().createBuffer(this);
1006 if (buffer == null) return null;
1008 // set the buffer source
1009 if (buffer.getCharacters() == null) {
1010 if (isWorkingCopy) {
1011 ICompilationUnit original;
1013 && (original = new CompilationUnit((PackageFragment)getParent(), getElementName(), DefaultWorkingCopyOwner.PRIMARY)).isOpen()) {
1014 buffer.setContents(original.getSource());
1016 IFile file = (IFile)getResource();
1017 if (file == null || !file.exists()) {
1018 // initialize buffer with empty contents
1019 buffer.setContents(CharOperation.NO_CHAR);
1021 buffer.setContents(Util.getResourceContentsAsCharArray(file));
1025 IFile file = (IFile)this.getResource();
1026 if (file == null || !file.exists()) throw newNotPresentException();
1027 buffer.setContents(Util.getResourceContentsAsCharArray(file));
1031 // add buffer to buffer cache
1032 BufferManager bufManager = getBufferManager();
1033 bufManager.addBuffer(buffer);
1035 // listen to buffer changes
1036 buffer.addBufferChangedListener(this);
1041 * @see Openable#openParent
1043 protected void openParent(Object childInfo, HashMap newElements, IProgressMonitor pm) throws JavaModelException {
1045 super.openParent(childInfo, newElements, pm);
1046 } catch(JavaModelException e){
1047 // allow parent to not exist for working copies defined outside classpath
1048 if (!isWorkingCopy() && !e.isDoesNotExist()){
1055 * @see ICompilationUnit#reconcile()
1058 public IMarker[] reconcile() throws JavaModelException {
1059 reconcile(NO_AST, false/*don't force problem detection*/, null/*use primary owner*/, null/*no progress monitor*/);
1063 * @see ICompilationUnit#reconcile(int, boolean, WorkingCopyOwner, IProgressMonitor)
1065 public void reconcile(boolean forceProblemDetection, IProgressMonitor monitor) throws JavaModelException {
1066 reconcile(NO_AST, forceProblemDetection, null/*use primary owner*/, monitor);
1070 * @see ICompilationUnit#reconcile(int, boolean, WorkingCopyOwner, IProgressMonitor)
1073 //public org.eclipse.jdt.core.dom.CompilationUnit reconcile(
1074 public Object reconcile(
1076 boolean forceProblemDetection,
1077 WorkingCopyOwner workingCopyOwner,
1078 IProgressMonitor monitor)
1079 throws JavaModelException {
1081 if (!isWorkingCopy()) return null; // Reconciling is not supported on non working copies
1082 if (workingCopyOwner == null) workingCopyOwner = DefaultWorkingCopyOwner.PRIMARY;
1084 boolean createAST = false;
1085 // if (astLevel == AST.JLS2) {
1086 // // client asking for level 2 AST; these are supported
1087 // createAST = true;
1088 // } else if (astLevel == AST.JLS3) {
1089 // // client asking for level 3 ASTs; these are not supported
1090 // // TODO (jerome) - these should also be supported in 1.5 stream
1091 // createAST = false;
1093 // // client asking for no AST (0) or unknown ast level
1094 // // either way, request denied
1095 // createAST = false;
1097 ReconcileWorkingCopyOperation op = new ReconcileWorkingCopyOperation(this, createAST, astLevel, forceProblemDetection, workingCopyOwner);
1098 op.runOperation(monitor);
1104 * @see ISourceManipulation#rename(String, boolean, IProgressMonitor)
1106 public void rename(String name, boolean force, IProgressMonitor monitor) throws JavaModelException {
1108 throw new IllegalArgumentException(Util.bind("operation.nullName")); //$NON-NLS-1$
1110 IJavaElement[] elements= new IJavaElement[] {this};
1111 IJavaElement[] dests= new IJavaElement[] {this.getParent()};
1112 String[] renamings= new String[] {name};
1113 getJavaModel().rename(elements, dests, renamings, force, monitor);
1116 * Does nothing - this is not a working copy.
1118 * @see IWorkingCopy#restore()
1120 public void restore () throws JavaModelException {
1123 * @see ICodeAssist#codeComplete(int, ICodeCompletionRequestor)
1124 * @deprecated - use codeComplete(int, ICompletionRequestor)
1126 //public void codeComplete(int offset, final ICodeCompletionRequestor requestor) throws JavaModelException {
1128 // if (requestor == null){
1129 // codeComplete(offset, (ICompletionRequestor)null);
1134 // new ICompletionRequestor(){
1135 // public void acceptAnonymousType(char[] superTypePackageName,char[] superTypeName,char[][] parameterPackageNames,char[][] parameterTypeNames,char[][] parameterNames,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance){
1137 // public void acceptClass(char[] packageName, char[] className, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) {
1138 // requestor.acceptClass(packageName, className, completionName, modifiers, completionStart, completionEnd);
1140 // public void acceptError(IProblem error) {
1141 // if (true) return; // was disabled in 1.0
1144 // IMarker marker = ResourcesPlugin.getWorkspace().getRoot().createMarker(IJavaModelMarker.TRANSIENT_PROBLEM);
1145 // marker.setAttribute(IJavaModelMarker.ID, error.getID());
1146 // marker.setAttribute(IMarker.CHAR_START, error.getSourceStart());
1147 // marker.setAttribute(IMarker.CHAR_END, error.getSourceEnd() + 1);
1148 // marker.setAttribute(IMarker.LINE_NUMBER, error.getSourceLineNumber());
1149 // marker.setAttribute(IMarker.MESSAGE, error.getMessage());
1150 // marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
1151 // requestor.acceptError(marker);
1152 // } catch(CoreException e){
1155 // public void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[] typePackageName, char[] typeName, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) {
1156 // requestor.acceptField(declaringTypePackageName, declaringTypeName, name, typePackageName, typeName, completionName, modifiers, completionStart, completionEnd);
1158 // public void acceptInterface(char[] packageName,char[] interfaceName,char[] completionName,int modifiers,int completionStart,int completionEnd, int relevance) {
1159 // requestor.acceptInterface(packageName, interfaceName, completionName, modifiers, completionStart, completionEnd);
1161 // public void acceptKeyword(char[] keywordName,int completionStart,int completionEnd, int relevance){
1162 // requestor.acceptKeyword(keywordName, completionStart, completionEnd);
1164 // public void acceptLabel(char[] labelName,int completionStart,int completionEnd, int relevance){
1165 // requestor.acceptLabel(labelName, completionStart, completionEnd);
1167 // public void acceptLocalVariable(char[] name,char[] typePackageName,char[] typeName,int modifiers,int completionStart,int completionEnd, int relevance){
1170 // 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){
1171 // // skip parameter names
1172 // requestor.acceptMethod(declaringTypePackageName, declaringTypeName, selector, parameterPackageNames, parameterTypeNames, returnTypePackageName, returnTypeName, completionName, modifiers, completionStart, completionEnd);
1174 // 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){
1177 // public void acceptModifier(char[] modifierName,int completionStart,int completionEnd, int relevance){
1178 // requestor.acceptModifier(modifierName, completionStart, completionEnd);
1180 // public void acceptPackage(char[] packageName,char[] completionName,int completionStart,int completionEnd, int relevance){
1181 // requestor.acceptPackage(packageName, completionName, completionStart, completionEnd);
1183 // public void acceptType(char[] packageName,char[] typeName,char[] completionName,int completionStart,int completionEnd, int relevance){
1184 // requestor.acceptType(packageName, typeName, completionName, completionStart, completionEnd);
1186 // public void acceptVariableName(char[] typePackageName,char[] typeName,char[] name,char[] completionName,int completionStart,int completionEnd, int relevance){
1192 // * @see JavaElement#rootedAt(IJavaProject)
1194 //public IJavaElement rootedAt(IJavaProject project) {
1196 // new CompilationUnit(
1197 // (IPackageFragment)((JavaElement)parent).rootedAt(project),
1201 * Assume that this is a working copy
1203 protected void updateTimeStamp(CompilationUnit original) throws JavaModelException {
1205 ((IFile) original.getResource()).getModificationStamp();
1206 if (timeStamp == IResource.NULL_STAMP) {
1207 throw new JavaModelException(
1208 new JavaModelStatus(IJavaModelStatusConstants.INVALID_RESOURCE));
1210 ((CompilationUnitElementInfo) getElementInfo()).timestamp = timeStamp;