org.eclipse.jdt.internal.core.CompilationUnit Java Examples

The following examples show how to use org.eclipse.jdt.internal.core.CompilationUnit. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ModelBasedCompletionEngine.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static void codeComplete(ICompilationUnit cu, int position, CompletionRequestor requestor, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException {
	if (!(cu instanceof CompilationUnit)) {
		return;
	}

	if (requestor == null) {
		throw new IllegalArgumentException("Completion requestor cannot be null"); //$NON-NLS-1$
	}

	IBuffer buffer = cu.getBuffer();
	if (buffer == null) {
		return;
	}

	if (position < -1 || position > buffer.getLength()) {
		throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS));
	}

	JavaProject project = (JavaProject) cu.getJavaProject();
	ModelBasedSearchableEnvironment environment = new ModelBasedSearchableEnvironment(project, owner, requestor.isTestCodeExcluded());
	environment.setUnitToSkip((CompilationUnit) cu);

	// code complete
	CompletionEngine engine = new CompletionEngine(environment, requestor, project.getOptions(true), project, owner, monitor);
	engine.complete((CompilationUnit) cu, position, 0, cu);
}
 
Example #2
Source File: Utils.java    From CogniCrypt with Eclipse Public License 2.0 6 votes vote down vote up
public static IResource findClassByName(final String className, final IProject currentProject) throws ClassNotFoundException {
	try {
		for (final IPackageFragment l : JavaCore.create(currentProject).getPackageFragments()) {
			for (final ICompilationUnit cu : l.getCompilationUnits()) {
				final IJavaElement cuResource = JavaCore.create(cu.getCorrespondingResource());
				for (IJavaElement a : (ArrayList<IJavaElement>)((CompilationUnit) cuResource).getChildrenOfType(7)) {
					String name = cuResource.getParent().getElementName() + "." + a.getElementName();

					if (name.startsWith(".")) {
						name = name.substring(1);
					}
					if (name.startsWith(className)) {
						return cu.getCorrespondingResource();
					}
				}
			}
		}
	}
	catch (final JavaModelException e) {
		throw new ClassNotFoundException("Class " + className + " not found.", e);
	}
	throw new ClassNotFoundException("Class " + className + " not found.");
}
 
Example #3
Source File: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates an IType from the given simple top level type name.
 */
protected IType createTypeHandle(String simpleTypeName) {
	Openable openable = this.currentPossibleMatch.openable;
	if (openable instanceof CompilationUnit)
		return ((CompilationUnit) openable).getType(simpleTypeName);

	IType binaryType = ((ClassFile) openable).getType();
	String binaryTypeQualifiedName = binaryType.getTypeQualifiedName();
	if (simpleTypeName.equals(binaryTypeQualifiedName))
		return binaryType; // answer only top-level types, sometimes the classFile is for a member/local type

	// type name may be null for anonymous (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=164791)
	String classFileName = simpleTypeName.length() == 0 ? binaryTypeQualifiedName : simpleTypeName;
	IClassFile classFile = binaryType.getPackageFragment().getClassFile(classFileName + SuffixConstants.SUFFIX_STRING_class);
	return classFile.getType();
}
 
Example #4
Source File: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates an IImportDeclaration from the given import statement
 */
protected IJavaElement createImportHandle(ImportReference importRef) {
	char[] importName = CharOperation.concatWith(importRef.getImportName(), '.');
	if ((importRef.bits & ASTNode.OnDemand) != 0)
		importName = CharOperation.concat(importName, ".*" .toCharArray()); //$NON-NLS-1$
	Openable openable = this.currentPossibleMatch.openable;
	if (openable instanceof CompilationUnit)
		return ((CompilationUnit) openable).getImport(new String(importName));

	// binary types do not contain import statements so just answer the top-level type as the element
	IType binaryType = ((ClassFile) openable).getType();
	String typeName = binaryType.getElementName();
	int lastDollar = typeName.lastIndexOf('$');
	if (lastDollar == -1) return binaryType;
	return createTypeHandle(typeName.substring(0, lastDollar));
}
 
Example #5
Source File: CustomGroovyLanguageSupport.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
public CompilationUnit newCompilationUnit(PackageFragment parent, String name, WorkingCopyOwner owner) {
    if (ContentTypeUtils.isGroovyLikeFileName(name)) {
        return new BonitaScriptGroovyCompilationUnit(parent, name, owner) ;
    } else {
        return new CompilationUnit(parent, name, owner);
    }
}
 
Example #6
Source File: RegionBasedTypeHierarchy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected boolean isAffectedByOpenable(IJavaElementDelta delta, IJavaElement element, int eventType) {
	// change to working copy
	if (element instanceof CompilationUnit && ((CompilationUnit)element).isWorkingCopy()) {
		return super.isAffectedByOpenable(delta, element, eventType);
	}

	// if no focus, hierarchy is affected if the element is part of the region
	if (this.focusType == null) {
		return this.region.contains(element);
	} else {
		return super.isAffectedByOpenable(delta, element, eventType);
	}
}
 
Example #7
Source File: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates an IImportDeclaration from the given import statement
 */
protected IJavaElement createPackageDeclarationHandle(CompilationUnitDeclaration unit) {
	if (unit.isPackageInfo()) {
		char[] packName = CharOperation.concatWith(unit.currentPackage.getImportName(), '.');
		Openable openable = this.currentPossibleMatch.openable;
		if (openable instanceof CompilationUnit) {
			return ((CompilationUnit) openable).getPackageDeclaration(new String(packName));
		}
	}
	return createTypeHandle(new String(unit.getMainTypeName()));
}
 
Example #8
Source File: MarkerUtil.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@SuppressWarnings("restriction")
private static char[] getContent(IType source) throws JavaModelException {
    char[] charContent = null;
    IOpenable op = source.getOpenable();
    if (op instanceof CompilationUnit) {
        charContent = ((CompilationUnit) (op)).getContents();
    }
    if (charContent == null) {
        String content = source.getSource();
        if (content != null) {
            charContent = content.toCharArray();
        }
    }
    return charContent;
}
 
Example #9
Source File: AssistImportContainer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public AssistImportContainer(CompilationUnit parent, Map infoCache) {
	super(parent);
	this.infoCache = infoCache;
}
 
Example #10
Source File: AssistPackageDeclaration.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public AssistPackageDeclaration(CompilationUnit parent, String name, Map infoCache) {
	super(parent, name);
	this.infoCache = infoCache;
}
 
Example #11
Source File: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
WorkingCopyDocument(org.eclipse.jdt.core.ICompilationUnit workingCopy, SearchParticipant participant) {
	super(workingCopy.getPath().toString(), participant);
	this.charContents = ((CompilationUnit)workingCopy).getContents();
	this.workingCopy = workingCopy;
}
 
Example #12
Source File: CompletionUnitStructureRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected PackageDeclaration createPackageDeclaration(JavaElement parent, String name) {
	return new AssistPackageDeclaration((CompilationUnit) parent, name, this.newElements);
}
 
Example #13
Source File: CompletionUnitStructureRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected ImportContainer createImportContainer(ICompilationUnit parent) {
	return new AssistImportContainer((CompilationUnit)parent, this.newElements);
}
 
Example #14
Source File: UiBinderImportReferenceType.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public boolean matches(Object javaElement) {
  
  if (javaElement instanceof IType) {      
    
    return super.matches(javaElement);
    
  } else if (javaElement instanceof CompilationUnit) {
    // When a java file that is changed is referenced from a ui.xml file,
    // eclipse gives a CompilationUnit instead of an IType, so this
    // logic is needed for this case.

    String enclosingClassName = getFullyQualifiedName();
    
    // if this LogicalType represents an inner class, we want only the outermost
    // enclosing class, because the given CompilationUnit represents a 
    // java file, and hence an outermost class
    int dollarIndex = enclosingClassName.indexOf('$');
    if (dollarIndex != -1) {
      enclosingClassName = enclosingClassName.substring(0, dollarIndex); 
    }
    
    CompilationUnit cu = ((CompilationUnit) javaElement);
    
    // CompilationUnit class doesn't just give us the full qualified name
    // of the top-most class... so we must assemble it ourselves...
    IPackageDeclaration[] pkgs;
    try {
      pkgs = cu.getPackageDeclarations();
    } catch (JavaModelException e) {
      return false;
    }
    
    if (pkgs.length > 0) {
      // cu.getElementName() returns a filename, so lop off the extension to get the class name
      String className = cu.getElementName().substring(0, cu.getElementName().indexOf('.'));
      String cuName = pkgs[0].getElementName() + "." + className;
      if (enclosingClassName.equals(cuName)) {
        return true;
      }
    }
  }

  return false;
}
 
Example #15
Source File: AbstractNewXtendElementWizardPage.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
private ICompilationUnit getCompilationUnitStub() {
	String compilationUnitName = getCompilationUnitName(getTypeName());
	return new CompilationUnit((PackageFragment) getPackageFragment(), compilationUnitName, DefaultWorkingCopyOwner.PRIMARY);
}
 
Example #16
Source File: ReconcileContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns a resolved AST with {@link AST#JLS3 JLS3} level.
 * It is created from the current state of the working copy.
 * Creates one if none exists yet.
 * Returns <code>null</code> if the current state of the working copy
 * doesn't allow the AST to be created (e.g. if the working copy's content
 * cannot be parsed).
 * <p>
 * If the AST level requested during reconciling is not {@link AST#JLS3}
 * or if binding resolutions was not requested, then a different AST is created.
 * Note that this AST does not become the current AST and it is only valid for
 * the requestor.
 * </p>
 *
 * @return the AST created from the current state of the working copy,
 *   or <code>null</code> if none could be created
 * @exception JavaModelException  if the contents of the working copy
 *		cannot be accessed. Reasons include:
 * <ul>
 * <li> The working copy does not exist (ELEMENT_DOES_NOT_EXIST)</li>
 * </ul>
 * @deprecated JLS3 has been deprecated. This method has been replaced by {@link #getAST4()} which returns an AST
 * with JLS4 level.
 */
public org.eclipse.jdt.core.dom.CompilationUnit getAST3() throws JavaModelException {
	if (this.operation.astLevel != AST.JLS3 || !this.operation.resolveBindings) {
		// create AST (optionally resolving bindings)
		ASTParser parser = ASTParser.newParser(AST.JLS3);
		parser.setCompilerOptions(this.workingCopy.getJavaProject().getOptions(true));
		if (JavaProject.hasJavaNature(this.workingCopy.getJavaProject().getProject()))
			parser.setResolveBindings(true);
		parser.setStatementsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);
		parser.setBindingsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_BINDINGS_RECOVERY) != 0);
		parser.setSource(this.workingCopy);
		parser.setIgnoreMethodBodies((this.operation.reconcileFlags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0);
		return (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(this.operation.progressMonitor);
	}
	return this.operation.makeConsistent(this.workingCopy);
}
 
Example #17
Source File: ReconcileContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns a resolved AST with {@link AST#JLS4 JLS4} level.
 * It is created from the current state of the working copy.
 * Creates one if none exists yet.
 * Returns <code>null</code> if the current state of the working copy
 * doesn't allow the AST to be created (e.g. if the working copy's content
 * cannot be parsed).
 * <p>
 * If the AST level requested during reconciling is not {@link AST#JLS4}
 * or if binding resolutions was not requested, then a different AST is created.
 * Note that this AST does not become the current AST and it is only valid for
 * the requestor.
 * </p>
 *
 * @return the AST created from the current state of the working copy,
 *   or <code>null</code> if none could be created
 * @exception JavaModelException  if the contents of the working copy
 *		cannot be accessed. Reasons include:
 * <ul>
 * <li> The working copy does not exist (ELEMENT_DOES_NOT_EXIST)</li>
 * </ul>
 * @deprecated JLS4 has been deprecated. This method has been replaced by {@link #getAST8()} which returns an AST
 * with JLS8 level.
 * @since 3.7.1
 */
public org.eclipse.jdt.core.dom.CompilationUnit getAST4() throws JavaModelException {
	if (this.operation.astLevel != AST.JLS4 || !this.operation.resolveBindings) {
		// create AST (optionally resolving bindings)
		ASTParser parser = ASTParser.newParser(AST.JLS4);
		parser.setCompilerOptions(this.workingCopy.getJavaProject().getOptions(true));
		if (JavaProject.hasJavaNature(this.workingCopy.getJavaProject().getProject()))
			parser.setResolveBindings(true);
		parser.setStatementsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);
		parser.setBindingsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_BINDINGS_RECOVERY) != 0);
		parser.setSource(this.workingCopy);
		parser.setIgnoreMethodBodies((this.operation.reconcileFlags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0);
		return (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(this.operation.progressMonitor);
	}
	return this.operation.makeConsistent(this.workingCopy);
}
 
Example #18
Source File: ReconcileContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns a resolved AST with {@link AST#JLS8 JLS8} level.
 * It is created from the current state of the working copy.
 * Creates one if none exists yet.
 * Returns <code>null</code> if the current state of the working copy
 * doesn't allow the AST to be created (e.g. if the working copy's content
 * cannot be parsed).
 * <p>
 * If the AST level requested during reconciling is not {@link AST#JLS8}
 * or if binding resolutions was not requested, then a different AST is created.
 * Note that this AST does not become the current AST and it is only valid for
 * the requestor.
 * </p>
 *
 * @return the AST created from the current state of the working copy,
 *   or <code>null</code> if none could be created
 * @exception JavaModelException  if the contents of the working copy
 *		cannot be accessed. Reasons include:
 * <ul>
 * <li> The working copy does not exist (ELEMENT_DOES_NOT_EXIST)</li>
 * </ul>
 * @since 3.10
 */
public org.eclipse.jdt.core.dom.CompilationUnit getAST8() throws JavaModelException {
	if (this.operation.astLevel != AST.JLS8 || !this.operation.resolveBindings) {
		// create AST (optionally resolving bindings)
		ASTParser parser = ASTParser.newParser(AST.JLS8);
		parser.setCompilerOptions(this.workingCopy.getJavaProject().getOptions(true));
		if (JavaProject.hasJavaNature(this.workingCopy.getJavaProject().getProject()))
			parser.setResolveBindings(true);
		parser.setStatementsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);
		parser.setBindingsRecovery((this.operation.reconcileFlags & ICompilationUnit.ENABLE_BINDINGS_RECOVERY) != 0);
		parser.setSource(this.workingCopy);
		parser.setIgnoreMethodBodies((this.operation.reconcileFlags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0);
		return (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(this.operation.progressMonitor);
	}
	return this.operation.makeConsistent(this.workingCopy);
}
 
Example #19
Source File: AbstractNewSarlElementWizardPage.java    From sarl with Apache License 2.0 4 votes vote down vote up
private ICompilationUnit getCompilationUnitStub() {
	final String compilationUnitName = getCompilationUnitName(getTypeName());
	return new CompilationUnit((PackageFragment) getPackageFragment(), compilationUnitName, DefaultWorkingCopyOwner.PRIMARY);
}
 
Example #20
Source File: WorkingCopyOwner.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Returns a new working copy with the given name using this working copy owner to
 * create its buffer.
 * <p>
 * This working copy always belongs to the default package in a package
 * fragment root that corresponds to its Java project, and this Java project never exists.
 * However this Java project has the given classpath that is used when resolving names
 * in this working copy.
 * </p><p>
 * A DOM AST created using this working copy will have bindings resolved using the given
 * classpath, and problem are reported to the given problem requestor.
 * <p></p>
 * <code>JavaCore#getOptions()</code> is used to create the DOM AST as it is not
 * possible to set the options on the non-existing Java project.
 * </p><p>
 * When the working copy instance is created, an {@link IJavaElementDelta#ADDED added delta} is
 * reported on this working copy.
 * </p><p>
 * Once done with the working copy, users of this method must discard it using
 * {@link ICompilationUnit#discardWorkingCopy()}.
 * </p><p>
 * Note that when such working copy is committed, only its buffer is saved (see
 * {@link IBuffer#save(IProgressMonitor, boolean)}) but no resource is created.
 * </p><p>
 * This method is not intended to be overriden by clients.
 * </p>
 *
 * @param name the name of the working copy (e.g. "X.java")
 * @param classpath the classpath used to resolve names in this working copy
 * @param problemRequestor a requestor which will get notified of problems detected during
 * 	reconciling as they are discovered. The requestor can be set to <code>null</code> indicating
 * 	that the client is not interested in problems.
 * @param monitor a progress monitor used to report progress while opening the working copy
 * 	or <code>null</code> if no progress should be reported
 * @throws JavaModelException if the contents of this working copy can
 *   not be determined.
 * @return a new working copy
 * @see ICompilationUnit#becomeWorkingCopy(IProblemRequestor, IProgressMonitor)
 * @since 3.2
 *
 * @deprecated Use {@link #newWorkingCopy(String, IClasspathEntry[], IProgressMonitor)} instead.
 * 	Note that if this deprecated method is used, problems may be reported twice
 * 	if the given requestor is not the same as the current working copy owner one.
 */
public final ICompilationUnit newWorkingCopy(String name, IClasspathEntry[] classpath, IProblemRequestor problemRequestor, IProgressMonitor monitor) throws JavaModelException {
	ExternalJavaProject project = new ExternalJavaProject(classpath);
	IPackageFragment parent = ((PackageFragmentRoot) project.getPackageFragmentRoot(project.getProject())).getPackageFragment(CharOperation.NO_STRINGS);
	CompilationUnit result = new CompilationUnit((PackageFragment) parent, name, this);
	result.becomeWorkingCopy(problemRequestor, monitor);
	return result;
}
 
Example #21
Source File: WorkingCopyOwner.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Returns a new working copy with the given name using this working copy owner to
 * create its buffer.
 * <p>
 * This working copy always belongs to the default package in a package
 * fragment root that corresponds to its Java project, and this Java project never exists.
 * However this Java project has the given classpath that is used when resolving names
 * in this working copy.
 * </p><p>
 * If a DOM AST is created using this working copy, then given classpath will be used
 *  if bindings need to be resolved. Problems will be reported to the problem requestor
 * of the current working copy owner problem if it is not <code>null</code>.
 * <p></p>
 * Options used to create the DOM AST are got from {@link JavaCore#getOptions()}
 * as it is not possible to set the options on a non-existing Java project.
 * </p><p>
 * When the working copy instance is created, an {@link IJavaElementDelta#ADDED added delta} is
 * reported on this working copy.
 * </p><p>
 * Once done with the working copy, users of this method must discard it using
 * {@link ICompilationUnit#discardWorkingCopy()}.
 * </p><p>
 * Note that when such working copy is committed, only its buffer is saved (see
 * {@link IBuffer#save(IProgressMonitor, boolean)}) but no resource is created.
 * </p><p>
 * This method is not intended to be overriden by clients.
 * </p>
 *
 * @param name the name of the working copy (e.g. "X.java")
 * @param classpath the classpath used to resolve names in this working copy
 * @param monitor a progress monitor used to report progress while opening the working copy
 * 	or <code>null</code> if no progress should be reported
 * @throws JavaModelException if the contents of this working copy can
 *   not be determined.
 * @return a new working copy
 * @see ICompilationUnit#becomeWorkingCopy(IProgressMonitor)
 *
 * @since 3.3
 */
public final ICompilationUnit newWorkingCopy(String name, IClasspathEntry[] classpath, IProgressMonitor monitor) throws JavaModelException {
	ExternalJavaProject project = new ExternalJavaProject(classpath);
	IPackageFragment parent = ((PackageFragmentRoot) project.getPackageFragmentRoot(project.getProject())).getPackageFragment(CharOperation.NO_STRINGS);
	CompilationUnit result = new CompilationUnit((PackageFragment) parent, name, this);
	result.becomeWorkingCopy(getProblemRequestor(result), monitor);
	return result;
}
 
Example #22
Source File: ReconcileContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Creates a reconcile context for the given reconcile operation.
 *
 * @param operation the reconcile operation
 * @noreference This constructor is not intended to be called by clients.
 */
public ReconcileContext(ReconcileWorkingCopyOperation operation, CompilationUnit workingCopy) {
	this.operation = operation;
	this.workingCopy = workingCopy;
}