Java Code Examples for org.eclipse.jdt.core.dom.CompilationUnit#getTypeRoot()

The following examples show how to use org.eclipse.jdt.core.dom.CompilationUnit#getTypeRoot() . 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: ExtractTempRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public ExtractTempRefactoring(CompilationUnit astRoot, int selectionStart, int selectionLength, Map formatterOptions) {
	Assert.isTrue(selectionStart >= 0);
	Assert.isTrue(selectionLength >= 0);
	Assert.isTrue(astRoot.getTypeRoot() instanceof ICompilationUnit);

	fSelectionStart = selectionStart;
	fSelectionLength = selectionLength;
	fCu = (ICompilationUnit) astRoot.getTypeRoot();
	fCompilationUnitNode = astRoot;

	fReplaceAllOccurrences = true; // default
	fDeclareFinal = false; // default
	fTempName = ""; //$NON-NLS-1$

	fLinkedProposalModel = null;
	fCheckResultForCompileProblems = true;
	fFormatterOptions = formatterOptions;
}
 
Example 2
Source File: ExtractFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public ExtractFieldRefactoring(CompilationUnit astRoot, int selectionStart, int selectionLength) {
	Assert.isTrue(selectionStart >= 0);
	Assert.isTrue(selectionLength >= 0);
	Assert.isTrue(astRoot.getTypeRoot() instanceof ICompilationUnit);

	fSelectionStart = selectionStart;
	fSelectionLength = selectionLength;
	fCu = (ICompilationUnit) astRoot.getTypeRoot();
	fCompilationUnitNode = astRoot;

	fDeclareFinal = false;
	fDeclareStatic = false;
	fFieldName = ""; //$NON-NLS-1$

	fLinkedProposalModel = null;
	fVisibility = Modifier.PRIVATE;
	fInitializeIn = INITIALIZE_IN_METHOD;
}
 
Example 3
Source File: ExtractTempRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public ExtractTempRefactoring(CompilationUnit astRoot, int selectionStart, int selectionLength) {
	Assert.isTrue(selectionStart >= 0);
	Assert.isTrue(selectionLength >= 0);
	Assert.isTrue(astRoot.getTypeRoot() instanceof ICompilationUnit);

	fSelectionStart= selectionStart;
	fSelectionLength= selectionLength;
	fCu= (ICompilationUnit) astRoot.getTypeRoot();
	fCompilationUnitNode= astRoot;

	fReplaceAllOccurrences= true; // default
	fDeclareFinal= false; // default
	fTempName= ""; //$NON-NLS-1$

	fLinkedProposalModel= null;
	fCheckResultForCompileProblems= true;
}
 
Example 4
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the source of the given node from the location where it was parsed.
 * @param node the node to get the source from
 * @param extendedRange if set, the extended ranges of the nodes should ne used
 * @param removeIndent if set, the indentation is removed.
 * @return return the source for the given node or null if accessing the source failed.
 */
public static String getNodeSource(ASTNode node, boolean extendedRange, boolean removeIndent) {
	ASTNode root= node.getRoot();
	if (root instanceof CompilationUnit) {
		CompilationUnit astRoot= (CompilationUnit) root;
		ITypeRoot typeRoot= astRoot.getTypeRoot();
		try {
			if (typeRoot != null && typeRoot.getBuffer() != null) {
				IBuffer buffer= typeRoot.getBuffer();
				int offset= extendedRange ? astRoot.getExtendedStartPosition(node) : node.getStartPosition();
				int length= extendedRange ? astRoot.getExtendedLength(node) : node.getLength();
				String str= buffer.getText(offset, length);
				if (removeIndent) {
					IJavaProject project= typeRoot.getJavaProject();
					int indent= StubUtility.getIndentUsed(buffer, node.getStartPosition(), project);
					str= Strings.changeIndent(str, indent, project, new String(), typeRoot.findRecommendedLineSeparator());
				}
				return str;
			}
		} catch (JavaModelException e) {
			// ignore
		}
	}
	return null;
}
 
Example 5
Source File: OccurrencesSearchQuery.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private JavaElementLine getLineElement(CompilationUnit astRoot, OccurrenceLocation location, HashMap<Integer, JavaElementLine> lineToGroup) {
	int lineNumber= astRoot.getLineNumber(location.getOffset());
	if (lineNumber <= 0) {
		return null;
	}
	JavaElementLine lineElement= null;
	try {
		Integer key= new Integer(lineNumber);
		lineElement= lineToGroup.get(key);
		if (lineElement == null) {
			int lineStartOffset= astRoot.getPosition(lineNumber, 0);
			if (lineStartOffset >= 0) {
				lineElement= new JavaElementLine(astRoot.getTypeRoot(), lineNumber - 1, lineStartOffset);
				lineToGroup.put(key, lineElement);
			}
		}
	} catch (CoreException e) {
		//nothing
	}
	return lineElement;
}
 
Example 6
Source File: BreakContinueTargetFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public String initialize(CompilationUnit root, ASTNode node) {
	ASTNode controlNode= getBreakOrContinueNode(node);
	if (controlNode != null) {
		fASTRoot= root;

		try {
			if (root.getTypeRoot() == null || root.getTypeRoot().getBuffer() == null)
				return SearchMessages.BreakContinueTargetFinder_cannot_highlight;
		} catch (JavaModelException e) {
			return SearchMessages.BreakContinueTargetFinder_cannot_highlight;
		}
		fSelected= controlNode;
		fIsBreak= fSelected instanceof BreakStatement;
		fLabel= getLabel();
		fDescription= Messages.format(SearchMessages.BreakContinueTargetFinder_occurrence_description, BasicElementLabels.getJavaElementName(ASTNodes.asString(fSelected)));
		return null;
	} else {
		return SearchMessages.BreakContinueTargetFinder_no_break_or_continue_selected;
	}
}
 
Example 7
Source File: ExtractConstantRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public ExtractConstantRefactoring(CompilationUnit astRoot, int selectionStart, int selectionLength, Map formatterOptions) {
	Assert.isTrue(selectionStart >= 0);
	Assert.isTrue(selectionLength >= 0);
	Assert.isTrue(astRoot.getTypeRoot() instanceof ICompilationUnit);

	fSelectionStart = selectionStart;
	fSelectionLength = selectionLength;
	fCu = (ICompilationUnit) astRoot.getTypeRoot();
	fCuRewrite = new CompilationUnitRewrite(null, fCu, astRoot, formatterOptions);
	fLinkedProposalModel = null;
	fConstantName = ""; //$NON-NLS-1$
	fCheckResultForCompileProblems = true;
	fFormatterOptions = formatterOptions;
}
 
Example 8
Source File: BaseDocumentLifeCycleHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private IStatus publishDiagnostics(IProgressMonitor monitor) throws JavaModelException {
	long start = System.currentTimeMillis();
	if (monitor.isCanceled()) {
		return Status.CANCEL_STATUS;
	}
	this.sharedASTProvider.disposeAST();
	List<ICompilationUnit> toValidate = Arrays.asList(JavaCore.getWorkingCopies(null));
	if (toValidate.isEmpty()) {
		return Status.OK_STATUS;
	}
	SubMonitor progress = SubMonitor.convert(monitor, toValidate.size() + 1);
	if (monitor.isCanceled()) {
		return Status.CANCEL_STATUS;
	}
	for (ICompilationUnit rootToValidate : toValidate) {
		if (monitor.isCanceled()) {
			return Status.CANCEL_STATUS;
		}
		CompilationUnit astRoot = this.sharedASTProvider.getAST(rootToValidate, CoreASTProvider.WAIT_YES, monitor);
		if (monitor.isCanceled()) {
			return Status.CANCEL_STATUS;
		}
		if (astRoot != null) {
			// report errors, even if there are no problems in the file: The client need to know that they got fixed.
			ICompilationUnit unit = (ICompilationUnit) astRoot.getTypeRoot();
			publishDiagnostics(unit, progress.newChild(1));
		}
	}
	JavaLanguageServerPlugin.logInfo("Validated " + toValidate.size() + ". Took " + (System.currentTimeMillis() - start) + " ms");
	return Status.OK_STATUS;
}
 
Example 9
Source File: InlineMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static SourceProvider resolveSourceProvider(RefactoringStatus status, ITypeRoot typeRoot, ASTNode invocation) {
	CompilationUnit root= (CompilationUnit)invocation.getRoot();
	IMethodBinding methodBinding= Invocations.resolveBinding(invocation);
	if (methodBinding == null) {
		status.addFatalError(RefactoringCoreMessages.InlineMethodRefactoring_error_noMethodDeclaration);
		return null;
	}
	MethodDeclaration declaration= (MethodDeclaration)root.findDeclaringNode(methodBinding);
	if (declaration != null) {
		return new SourceProvider(typeRoot, declaration);
	}
	IMethod method= (IMethod)methodBinding.getJavaElement();
	if (method != null) {
		CompilationUnit methodDeclarationAstRoot;
		ICompilationUnit methodCu= method.getCompilationUnit();
		if (methodCu != null) {
			methodDeclarationAstRoot= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(methodCu, true);
		} else {
			IClassFile classFile= method.getClassFile();
			if (! JavaElementUtil.isSourceAvailable(classFile)) {
				String methodLabel= JavaElementLabels.getTextLabel(method, JavaElementLabels.M_FULLY_QUALIFIED | JavaElementLabels.M_PARAMETER_TYPES);
				status.addFatalError(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_error_classFile, methodLabel));
				return null;
			}
			methodDeclarationAstRoot= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(classFile, true);
		}
		ASTNode node= methodDeclarationAstRoot.findDeclaringNode(methodBinding.getMethodDeclaration().getKey());
		if (node instanceof MethodDeclaration) {
			return new SourceProvider(methodDeclarationAstRoot.getTypeRoot(), (MethodDeclaration) node);
		}
	}
	status.addFatalError(RefactoringCoreMessages.InlineMethodRefactoring_error_noMethodDeclaration);
	return null;
}
 
Example 10
Source File: ExtractConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ExtractConstantRefactoring(CompilationUnit astRoot, int selectionStart, int selectionLength) {
	Assert.isTrue(selectionStart >= 0);
	Assert.isTrue(selectionLength >= 0);
	Assert.isTrue(astRoot.getTypeRoot() instanceof ICompilationUnit);

	fSelectionStart= selectionStart;
	fSelectionLength= selectionLength;
	fCu= (ICompilationUnit) astRoot.getTypeRoot();
	fCuRewrite= new CompilationUnitRewrite(fCu, astRoot);
	fLinkedProposalModel= null;
	fConstantName= ""; //$NON-NLS-1$
	fCheckResultForCompileProblems= true;
}
 
Example 11
Source File: ImportReferencesCollector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean processJavadocComments(CompilationUnit astRoot) {
	 // don't visit Javadoc for 'package-info' (bug 216432)
	if (astRoot != null && astRoot.getTypeRoot() != null) {
		return !JavaModelUtil.PACKAGE_INFO_JAVA.equals(astRoot.getTypeRoot().getElementName());
	}
	return true;
}
 
Example 12
Source File: OccurrencesSearchResultPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void preformEditorSelectionChanged(ITextSelection selection, CompilationUnit astRoot) {
	if (!isLinkingEnabled()) {
		return;
	}
	IOccurrencesFinder finder;

	AbstractTextSearchResult input= getInput();
	if (input == null) {
		finder= new OccurrencesFinder();
	} else {
		String id= ((OccurrencesSearchQuery) input.getQuery()).getFinderId();
		if (id == OccurrencesFinder.ID) {
			finder= new OccurrencesFinder();
		} else if (id == ExceptionOccurrencesFinder.ID) {
			finder= new ExceptionOccurrencesFinder();
		} else {
			finder= new ImplementOccurrencesFinder();
		}
	}

	int offset= selection.getOffset();
	int length= selection.getLength();
	if (finder.initialize(astRoot, offset, length) == null) {
		final OccurrencesSearchQuery query= new OccurrencesSearchQuery(finder, astRoot.getTypeRoot());
		query.run(null);
		OccurrencesSearchResult result= (OccurrencesSearchResult) query.getSearchResult();
		final JavaElementLine line= getMatchingLine(result, offset, length);

		getSite().getShell().getDisplay().asyncExec(new Runnable() {
			public void run() {
				setInput(query.getSearchResult(), line == null ? null : new StructuredSelection(line));
			}
		});
	}
}
 
Example 13
Source File: ExtractMethodRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public ExtractMethodRefactoring(CompilationUnit astRoot, int selectionStart, int selectionLength, Map formatterOptions) {
	this((ICompilationUnit) astRoot.getTypeRoot(), selectionStart, selectionLength, formatterOptions);
	fRoot = astRoot;
}
 
Example 14
Source File: ASTRewrite.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Converts all modifications recorded by this rewriter into an object representing the the corresponding text
 * edits to the source of a {@link ITypeRoot} from which the AST was created from.
 * The type root's source itself is not modified by this method call.
 * <p>
 * Important: This API can only be used if the modified AST has been created from a
 * {@link ITypeRoot} with source. That means {@link ASTParser#setSource(ICompilationUnit)},
 * {@link ASTParser#setSource(IClassFile)} or {@link ASTParser#setSource(ITypeRoot)}
 * has been used when initializing the {@link ASTParser}. A {@link IllegalArgumentException} is thrown
 * otherwise. An {@link IllegalArgumentException} is also thrown when the type roots buffer does not correspond
 * anymore to the AST. Use {@link #rewriteAST(IDocument, Map)} for all ASTs created from other content.
 * </p>
 * <p>
 * For nodes in the original that are being replaced or deleted,
 * this rewriter computes the adjusted source ranges
 * by calling {@link TargetSourceRangeComputer#computeSourceRange(ASTNode) getExtendedSourceRangeComputer().computeSourceRange(node)}.
 * </p>
 * <p>
 * Calling this methods does not discard the modifications
 * on record. Subsequence modifications are added to the ones
 * already on record. If this method is called again later,
 * the resulting text edit object will accurately reflect
 * the net cumulative effect of all those changes.
 * </p>
 *
 * @return text edit object describing the changes to the
 * document corresponding to the changes recorded by this rewriter
 * @throws JavaModelException A {@link JavaModelException} is thrown when
 * the underlying compilation units buffer could not be accessed.
 * @throws IllegalArgumentException An {@link IllegalArgumentException}
 * is thrown if the document passed does not correspond to the AST that is rewritten.
 *
 * @since 3.2
 */
public TextEdit rewriteAST() throws JavaModelException, IllegalArgumentException {
	ASTNode rootNode= getRootNode();
	if (rootNode == null) {
		return new MultiTextEdit(); // no changes
	}

	ASTNode root= rootNode.getRoot();
	if (!(root instanceof CompilationUnit)) {
		throw new IllegalArgumentException("This API can only be used if the AST is created from a compilation unit or class file"); //$NON-NLS-1$
	}
	CompilationUnit astRoot= (CompilationUnit) root;
	ITypeRoot typeRoot = astRoot.getTypeRoot();
	if (typeRoot == null || typeRoot.getBuffer() == null) {
		throw new IllegalArgumentException("This API can only be used if the AST is created from a compilation unit or class file"); //$NON-NLS-1$
	}

	char[] content= typeRoot.getBuffer().getCharacters();
	LineInformation lineInfo= LineInformation.create(astRoot);
	String lineDelim= typeRoot.findRecommendedLineSeparator();
	Map options= typeRoot.getJavaProject().getOptions(true);

	return internalRewriteAST(content, lineInfo, lineDelim, astRoot.getCommentList(), options, rootNode, (RecoveryScannerData)astRoot.getStatementsRecoveryData());
}
 
Example 15
Source File: GenerateToStringOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Creates new <code>GenerateToStringOperation</code>, using <code>settings.toStringStyle</code>
 * field to choose the right subclass.
 * 
 * @param typeBinding binding for the type for which the toString() method will be created
 * @param selectedBindings bindings for the typetype's members to be used in created method
 * @param unit a compilation unit containing the type
 * @param elementPosition at this position in the compilation unit created method will be added
 * @param settings the settings for toString() generator
 * @return a ready to use <code>GenerateToStringOperation</code> object
 */
public static GenerateToStringOperation createOperation(ITypeBinding typeBinding, Object[] selectedBindings, CompilationUnit unit, IJavaElement elementPosition,
		ToStringGenerationSettings settings) {
	AbstractToStringGenerator generator= createToStringGenerator(settings.toStringStyle);
	ToStringTemplateParser parser= createTemplateParser(settings.toStringStyle);
	parser.parseTemplate(settings.stringFormatTemplate);
	CompilationUnitRewrite rewrite= new CompilationUnitRewrite((ICompilationUnit)unit.getTypeRoot(), unit);
	ToStringGenerationContext context= new ToStringGenerationContext(parser, selectedBindings, settings, typeBinding, rewrite);
	generator.setContext(context);
	return new GenerateToStringOperation(elementPosition, context, generator, unit, rewrite);
}
 
Example 16
Source File: ExtractMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Creates a new extract method refactoring
 * @param astRoot the AST root of an AST created from a compilation unit
 * @param selectionStart start
 * @param selectionLength length
 */
public ExtractMethodRefactoring(CompilationUnit astRoot, int selectionStart, int selectionLength) {
	this((ICompilationUnit) astRoot.getTypeRoot(), selectionStart, selectionLength);
	fRoot= astRoot;
}