org.eclipse.jdt.core.dom.CompilationUnit#getTypeRoot ( )源码实例Demo

下面列出了org.eclipse.jdt.core.dom.CompilationUnit#getTypeRoot ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: eclipse.jdt.ls   文件: ExtractTempRefactoring.java
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;
}
 
源代码2 项目: eclipse.jdt.ls   文件: ExtractFieldRefactoring.java
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;
}
 
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;
}
 
/**
 * 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;
}
 
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;
}
 
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;
	}
}
 
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;
}
 
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;
}
 
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;
}
 
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;
}
 
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;
}
 
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));
			}
		});
	}
}
 
源代码13 项目: eclipse.jdt.ls   文件: ExtractMethodRefactoring.java
public ExtractMethodRefactoring(CompilationUnit astRoot, int selectionStart, int selectionLength, Map formatterOptions) {
	this((ICompilationUnit) astRoot.getTypeRoot(), selectionStart, selectionLength, formatterOptions);
	fRoot = astRoot;
}
 
/**
 * 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());
}
 
/**
 * 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);
}
 
/**
 * 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;
}