类org.eclipse.jdt.core.dom.CompilationUnit源码实例Demo

下面列出了怎么用org.eclipse.jdt.core.dom.CompilationUnit的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: api-mining   文件: JavaMethodClassCounter.java
public static void countMethodsClasses(final File projectDir)
		throws IOException {

	System.out.println("\n===== Project " + projectDir);
	final MethodClassCountVisitor mccv = new MethodClassCountVisitor();
	final JavaASTExtractor astExtractor = new JavaASTExtractor(false);

	final List<File> files = (List<File>) FileUtils.listFiles(projectDir,
			new String[] { "java" }, true);

	int count = 0;
	for (final File file : files) {

		final CompilationUnit cu = astExtractor.getAST(file);
		cu.accept(mccv);

		if (count % 1000 == 0)
			System.out.println("At file " + count + " of " + files.size());
		count++;
	}

	System.out.println("Project " + projectDir);
	System.out.println("No. *.java files " + files.size());
	System.out.println("No. Methods: " + mccv.noMethods);
	System.out.println("No. Classes: " + mccv.noClasses);
}
 
protected void installOccurrencesFinder(boolean forceUpdate) {
	fMarkOccurrenceAnnotations= true;

	fPostSelectionListenerWithAST= new ISelectionListenerWithAST() {
		public void selectionChanged(IEditorPart part, ITextSelection selection, CompilationUnit astRoot) {
			updateOccurrenceAnnotations(selection, astRoot);
		}
	};
	SelectionListenerWithASTManager.getDefault().addListener(this, fPostSelectionListenerWithAST);
	if (forceUpdate && getSelectionProvider() != null) {
		fForcedMarkOccurrencesSelection= getSelectionProvider().getSelection();
		ITypeRoot inputJavaElement= getInputJavaElement();
		if (inputJavaElement != null)
			updateOccurrenceAnnotations((ITextSelection)fForcedMarkOccurrencesSelection, SharedASTProvider.getAST(inputJavaElement, SharedASTProvider.WAIT_NO, getProgressMonitor()));
	}

	if (fOccurrencesFinderJobCanceler == null) {
		fOccurrencesFinderJobCanceler= new OccurrencesFinderJobCanceler();
		fOccurrencesFinderJobCanceler.install();
	}
}
 
源代码3 项目: compiler   文件: Java7BaseTest.java
protected static void dumpJava(final String content) {
	final ASTParser parser = ASTParser.newParser(astLevel);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setSource(content.toCharArray());

	final Map<?, ?> options = JavaCore.getOptions();
	JavaCore.setComplianceOptions(javaVersion, options);
	parser.setCompilerOptions(options);

	final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

	try {
		final UglyMathCommentsExtractor cex = new UglyMathCommentsExtractor(cu, content);
		final ASTDumper dumper = new ASTDumper(cex);
		dumper.dump(cu);
		cex.close();
	} catch (final Exception e) {}
}
 
public static void addMethodRetunsVoidProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws JavaModelException {
	CompilationUnit astRoot= context.getASTRoot();
	ASTNode selectedNode= problem.getCoveringNode(astRoot);
	if (!(selectedNode instanceof ReturnStatement)) {
		return;
	}
	ReturnStatement returnStatement= (ReturnStatement) selectedNode;
	Expression expression= returnStatement.getExpression();
	if (expression == null) {
		return;
	}
	BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
	if (decl instanceof MethodDeclaration) {
		MethodDeclaration methDecl= (MethodDeclaration) decl;
		Type retType= methDecl.getReturnType2();
		if (retType == null || retType.resolveBinding() == null) {
			return;
		}
		TypeMismatchSubProcessor.addChangeSenderTypeProposals(context, expression, retType.resolveBinding(), false, IProposalRelevance.METHOD_RETURNS_VOID, proposals);
	}
}
 
源代码5 项目: RefactoringMiner   文件: UMLModelASTReader.java
private UMLModelASTReader(File rootFolder, ASTParser parser, List<String> javaFiles, Set<String> repositoryDirectories) {
	this.umlModel = new UMLModel(repositoryDirectories);
	this.projectRoot = rootFolder.getPath();
	this.parser = parser;
	final String[] emptyArray = new String[0];
	
	String[] filesArray = new String[javaFiles.size()];
	for (int i = 0; i < filesArray.length; i++) {
		filesArray[i] = rootFolder + File.separator + javaFiles.get(i).replaceAll("/", systemFileSeparator);
	}

	FileASTRequestor fileASTRequestor = new FileASTRequestor() { 
		@Override
		public void acceptAST(String sourceFilePath, CompilationUnit ast) {
			String relativePath = sourceFilePath.substring(projectRoot.length() + 1).replaceAll(systemFileSeparator, "/");
			processCompilationUnit(relativePath, ast);
		}
	};
	this.parser.createASTs((String[]) filesArray, null, emptyArray, fileASTRequestor, null);
}
 
/**
 * Creates a new add unimplemented constructors operation.
 *
 * @param astRoot the compilation unit AST node
 * @param type the type to add the methods to
 * @param constructorsToImplement the method binding keys to implement
 * @param insertPos the insertion point, or <code>-1</code>
 * @param imports <code>true</code> if the import edits should be applied, <code>false</code> otherwise
 * @param apply <code>true</code> if the resulting edit should be applied, <code>false</code> otherwise
 * @param save <code>true</code> if the changed compilation unit should be saved, <code>false</code> otherwise
 */
public AddUnimplementedConstructorsOperation(CompilationUnit astRoot, ITypeBinding type, IMethodBinding[] constructorsToImplement, int insertPos, final boolean imports, final boolean apply, final boolean save) {
	if (astRoot == null || !(astRoot.getJavaElement() instanceof ICompilationUnit)) {
		throw new IllegalArgumentException("AST must not be null and has to be created from a ICompilationUnit"); //$NON-NLS-1$
	}
	if (type == null) {
		throw new IllegalArgumentException("The type must not be null"); //$NON-NLS-1$
	}
	ASTNode node= astRoot.findDeclaringNode(type);
	if (!(node instanceof AnonymousClassDeclaration || node instanceof AbstractTypeDeclaration)) {
		throw new IllegalArgumentException("type has to map to a type declaration in the AST"); //$NON-NLS-1$
	}

	fType= type;
	fInsertPos= insertPos;
	fASTRoot= astRoot;
	fConstructorsToImplement= constructorsToImplement;
	fSave= save;
	fApply= apply;
	fImports= imports;

	fCreateComments= StubUtility.doAddComments(astRoot.getJavaElement().getJavaProject());
	fVisibility= Modifier.PUBLIC;
	fOmitSuper= false;
}
 
public static CompilationUnitRewriteOperationsFix[] createNonStaticAccessFixes(CompilationUnit compilationUnit, IProblemLocation problem) {
	if (!isNonStaticAccess(problem))
		return null;

	ToStaticAccessOperation operations[]= createToStaticAccessOperations(compilationUnit, new HashMap<ASTNode, Block>(), problem, false);
	if (operations == null)
		return null;

	String label1= Messages.format(FixMessages.CodeStyleFix_ChangeAccessToStatic_description, operations[0].getAccessorName());
	CompilationUnitRewriteOperationsFix fix1= new CompilationUnitRewriteOperationsFix(label1, compilationUnit, operations[0]);

	if (operations.length > 1) {
		String label2= Messages.format(FixMessages.CodeStyleFix_ChangeAccessToStaticUsingInstanceType_description, operations[1].getAccessorName());
		CompilationUnitRewriteOperationsFix fix2= new CompilationUnitRewriteOperationsFix(label2, compilationUnit, operations[1]);
		return new CompilationUnitRewriteOperationsFix[] {fix1, fix2};
	}
	return new CompilationUnitRewriteOperationsFix[] {fix1};
}
 
源代码8 项目: sarl   文件: SarlClassPathDetector.java
/** Visit the given Java compilation unit.
 *
 * @param jfile the compilation unit.
 */
protected void visitJavaCompilationUnit(IFile jfile) {
	final ICompilationUnit cu = JavaCore.createCompilationUnitFrom(jfile);
	if (cu != null) {
		final ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
		parser.setSource(cu);
		parser.setFocalPosition(0);
		final CompilationUnit root = (CompilationUnit) parser.createAST(null);
		final PackageDeclaration packDecl = root.getPackage();

		final IPath packPath = jfile.getParent().getFullPath();
		final String cuName = jfile.getName();
		if (packDecl == null) {
			addToMap(this.sourceFolders, packPath, new Path(cuName));
		} else {
			final IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/'));
			final IPath folderPath = getFolderPath(packPath, relPath);
			if (folderPath != null) {
				addToMap(this.sourceFolders, folderPath, relPath.append(cuName));
			}
		}
	}
}
 
private static String getExpressionBaseName(Expression expr) {
	IBinding argBinding= Bindings.resolveExpressionBinding(expr, true);
	if (argBinding instanceof IVariableBinding) {
		IJavaProject project= null;
		ASTNode root= expr.getRoot();
		if (root instanceof CompilationUnit) {
			ITypeRoot typeRoot= ((CompilationUnit) root).getTypeRoot();
			if (typeRoot != null) {
				project= typeRoot.getJavaProject();
			}
		}
		return StubUtility.getBaseName((IVariableBinding)argBinding, project);
	}
	if (expr instanceof SimpleName) {
		return ((SimpleName) expr).getIdentifier();
	}
	return null;
}
 
/**
 * Uses the New Java file template from the code template page to generate a
 * compilation unit with the given type content.
 * 
 * @param cu The new created compilation unit
 * @param typeContent The content of the type, including signature and type
 * body.
 * @param lineDelimiter The line delimiter to be used.
 * @return String Returns the result of evaluating the new file template
 * with the given type content.
 * @throws CoreException when fetching the file comment fails or fetching the content for the
 *             new compilation unit fails
 * @since 2.1
 */
protected String constructCUContent(ICompilationUnit cu, String typeContent, String lineDelimiter) throws CoreException {
	String fileComment= getFileComment(cu, lineDelimiter);
	String typeComment= getTypeComment(cu, lineDelimiter);
	IPackageFragment pack= (IPackageFragment) cu.getParent();
	String content= CodeGeneration.getCompilationUnitContent(cu, fileComment, typeComment, typeContent, lineDelimiter);
	if (content != null) {
		ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setProject(cu.getJavaProject());
		parser.setSource(content.toCharArray());
		CompilationUnit unit= (CompilationUnit) parser.createAST(null);
		if ((pack.isDefaultPackage() || unit.getPackage() != null) && !unit.types().isEmpty()) {
			return content;
		}
	}
	StringBuffer buf= new StringBuffer();
	if (!pack.isDefaultPackage()) {
		buf.append("package ").append(pack.getElementName()).append(';'); //$NON-NLS-1$
	}
	buf.append(lineDelimiter).append(lineDelimiter);
	if (typeComment != null) {
		buf.append(typeComment).append(lineDelimiter);
	}
	buf.append(typeContent);
	return buf.toString();
}
 
private SearchResultGroup[] removeUnrealReferences(SearchResultGroup[] groups) {
	List<SearchResultGroup> result= new ArrayList<SearchResultGroup>(groups.length);
	for (int i= 0; i < groups.length; i++) {
		SearchResultGroup group= groups[i];
		ICompilationUnit cu= group.getCompilationUnit();
		if (cu == null)
			continue;
		CompilationUnit cuNode= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(cu, false);
		SearchMatch[] allSearchResults= group.getSearchResults();
		List<SearchMatch> realConstructorReferences= new ArrayList<SearchMatch>(Arrays.asList(allSearchResults));
		for (int j= 0; j < allSearchResults.length; j++) {
			SearchMatch searchResult= allSearchResults[j];
			if (! isRealConstructorReferenceNode(ASTNodeSearchUtil.getAstNode(searchResult, cuNode)))
				realConstructorReferences.remove(searchResult);
		}
		if (! realConstructorReferences.isEmpty())
			result.add(new SearchResultGroup(group.getResource(), realConstructorReferences.toArray(new SearchMatch[realConstructorReferences.size()])));
	}
	return result.toArray(new SearchResultGroup[result.size()]);
}
 
@Override
protected boolean shouldReport(IProblem problem, CompilationUnit cu) {
	if (!super.shouldReport(problem, cu))
		return false;
	ASTNode node= ASTNodeSearchUtil.getAstNode(cu, problem.getSourceStart(), problem.getSourceEnd() - problem.getSourceStart() + 1);
	if (node instanceof Type) {
		Type type= (Type) node;
		if (problem.getID() == IProblem.UndefinedType && getClassName().equals(ASTNodes.getTypeName(type))) {
			return false;
		}
	}
	if (node instanceof Name) {
		Name name= (Name) node;
		if (problem.getID() == IProblem.ImportNotFound && getPackage().indexOf(name.getFullyQualifiedName()) != -1)
			return false;
		if (problem.getID() == IProblem.MissingTypeInMethod) {
			StructuralPropertyDescriptor locationInParent= name.getLocationInParent();
			String[] arguments= problem.getArguments();
			if ((locationInParent == MethodInvocation.NAME_PROPERTY || locationInParent == SuperMethodInvocation.NAME_PROPERTY)
					&& arguments.length > 3
					&& arguments[3].endsWith(getClassName()))
				return false;
		}
	}
	return true;
}
 
private Expression evaluateArgumentExpressions(AST ast, ITypeBinding requiredType, String key) {
	CompilationUnit root= (CompilationUnit) fCallerNode.getRoot();

	int offset= fCallerNode.getStartPosition();
	Expression best= null;
	ITypeBinding bestType= null;

	ScopeAnalyzer analyzer= new ScopeAnalyzer(root);
	IBinding[] bindings= analyzer.getDeclarationsInScope(offset, ScopeAnalyzer.VARIABLES);
	for (int i= 0; i < bindings.length; i++) {
		IVariableBinding curr= (IVariableBinding) bindings[i];
		ITypeBinding type= curr.getType();
		if (type != null && canAssign(type, requiredType) && testModifier(curr)) {
			if (best == null || isMoreSpecific(bestType, type)) {
				best= ast.newSimpleName(curr.getName());
				bestType= type;
			}
		}
	}
	Expression defaultExpression= ASTNodeFactory.newDefaultExpression(ast, requiredType);
	if (best == null) {
		best= defaultExpression;
	}
	return best;
}
 
private IRegion evaluateReplaceRange(CompilationUnit root) {
	List imports= root.imports();
	if (!imports.isEmpty()) {
		ImportDeclaration first= (ImportDeclaration) imports.get(0);
		ImportDeclaration last= (ImportDeclaration) imports.get(imports.size() - 1);

		int startPos= first.getStartPosition(); // no extended range for first: bug 121428
		int endPos= root.getExtendedStartPosition(last) + root.getExtendedLength(last);
		int endLine= root.getLineNumber(endPos);
		if (endLine > 0) {
			int nextLinePos= root.getPosition(endLine + 1, 0);
			if (nextLinePos >= 0) {
				int firstTypePos= getFirstTypeBeginPos(root);
				if (firstTypePos != -1 && firstTypePos < nextLinePos) {
					endPos= firstTypePos;
				} else {
					endPos= nextLinePos;
				}
			}
		}
		return new Region(startPos, endPos - startPos);
	} else {
		int start= getPackageStatementEndPos(root);
		return new Region(start, 0);
	}
}
 
@Override
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
	if (!(getEditor() instanceof JavaEditor))
		return null;

	ITypeRoot je= getEditorInputJavaElement();
	if (je == null)
		return null;

	// Never wait for an AST in UI thread.
	CompilationUnit ast= SharedASTProvider.getAST(je, SharedASTProvider.WAIT_NO, null);
	if (ast == null)
		return null;

	ASTNode node= NodeFinder.perform(ast, offset, 1);
	if (node instanceof StringLiteral) {
		StringLiteral stringLiteral= (StringLiteral)node;
		return new Region(stringLiteral.getStartPosition(), stringLiteral.getLength());
	} else if (node instanceof SimpleName) {
		SimpleName simpleName= (SimpleName)node;
		return new Region(simpleName.getStartPosition(), simpleName.getLength());
	}

	return null;
}
 
private int findInHierarchyWithAST(CompilationUnit astRoot, IMethod method) throws JavaModelException {
	ASTNode node= NodeFinder.perform(astRoot, method.getNameRange());
	if (node instanceof SimpleName && node.getParent() instanceof MethodDeclaration) {
		IMethodBinding binding= ((MethodDeclaration) node.getParent()).resolveBinding();
		if (binding != null) {
			IMethodBinding defining= Bindings.findOverriddenMethod(binding, true);
			if (defining != null) {
				if (JdtFlags.isAbstract(defining)) {
					return JavaElementImageDescriptor.IMPLEMENTS;
				} else {
					return JavaElementImageDescriptor.OVERRIDES;
				}
			}
			return 0;
		}
	}
	return -1;
}
 
public JavaDebugElementCodeMiningASTVisitor(IJavaStackFrame frame, CompilationUnit cu, ITextViewer viewer,
		List<ICodeMining> minings, AbstractDebugVariableCodeMiningProvider provider) {
	this.cu = cu;
	this.minings = minings;
	this.provider = provider;
	this.viewer = viewer;
	this.fFrame = frame;
}
 
/**
	 * {@inheritDoc}
	 */
	@Override
	public int computeNumberOfFixes(CompilationUnit compilationUnit) {
		int result= 0;
		IProblem[] problems= compilationUnit.getProblems();
		for (int i= 0; i < problems.length; i++) {
			int id= problems[i].getID();
			if (id == this.handledProblemID) {
				// FIXME search specifically: return param (which??)
//				if (!QuickFixes.hasExplicitNullnessAnnotation(compilationUnit, problems[i].getSourceStart()))
				result++;
			}
		}
		return result;
	}
 
private void checkCUCompleteConditions(final RefactoringStatus status, CompilationUnit currentResolvedCU, ICompilationUnit currentCU, List<RefactoringProcessor> processors) throws CoreException {

		// check local variable conditions
		List<RefactoringProcessor> locals= getProcessorsOfType(processors, RenameLocalVariableProcessor.class);
		if (!locals.isEmpty()) {
			RenameAnalyzeUtil.LocalAnalyzePackage[] analyzePackages= new RenameAnalyzeUtil.LocalAnalyzePackage[locals.size()];
			TextChangeManager manager= new TextChangeManager();
			int current= 0;
			TextChange textChange= manager.get(currentCU);
			textChange.setKeepPreviewEdits(true);
			for (Iterator<RefactoringProcessor> iterator= locals.iterator(); iterator.hasNext();) {
				RenameLocalVariableProcessor localProcessor= (RenameLocalVariableProcessor) iterator.next();
				RenameAnalyzeUtil.LocalAnalyzePackage analyzePackage= localProcessor.getLocalAnalyzePackage();
				analyzePackages[current]= analyzePackage;
				for (int i= 0; i < analyzePackage.fOccurenceEdits.length; i++) {
					TextChangeCompatibility.addTextEdit(textChange, "", analyzePackage.fOccurenceEdits[i], GroupCategorySet.NONE); //$NON-NLS-1$
				}
				current++;
			}
			status.merge(RenameAnalyzeUtil.analyzeLocalRenames(analyzePackages, textChange, currentResolvedCU, false));
		}

		/*
		 * There is room for performance improvement here: One could move
		 * shadowing analyzes out of the field and method processors and perform
		 * it here, thus saving on working copy creation. Drawback is increased
		 * heap consumption.
		 */
	}
 
protected StructuralPropertyDescriptor getChildPropertyDescriptor(ASTNode parent) {
	switch (parent.getNodeType()) {
		case ASTNode.COMPILATION_UNIT:
			return CompilationUnit.TYPES_PROPERTY;
		case ASTNode.ENUM_DECLARATION:
			return EnumDeclaration.BODY_DECLARATIONS_PROPERTY;
		case ASTNode.ANNOTATION_TYPE_DECLARATION:
			return AnnotationTypeDeclaration.BODY_DECLARATIONS_PROPERTY;
		default:
			return TypeDeclaration.BODY_DECLARATIONS_PROPERTY;
	}
}
 
private static Change createDeleteChange(ICompilationUnit cu, List<IJavaElement> javaElements, TextChangeManager manager) throws CoreException {
	CompilationUnit cuNode= RefactoringASTParser.parseWithASTProvider(cu, false, null);
	CompilationUnitRewrite rewriter= new CompilationUnitRewrite(cu, cuNode);
	IJavaElement[] elements= javaElements.toArray(new IJavaElement[javaElements.size()]);
	ASTNodeDeleteUtil.markAsDeleted(elements, rewriter, null);
	return addTextEditFromRewrite(manager, cu, rewriter.getASTRewrite());
}
 
源代码22 项目: eclipse.jdt.ls   文件: JavadocContentAccess.java
private static CompilationUnit createAST(IJavaElement element, String cuSource) {
	ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);

	IJavaProject javaProject= element.getJavaProject();
	parser.setProject(javaProject);
	Map<String, String> options= javaProject.getOptions(true);
	options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED); // workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=212207
	parser.setCompilerOptions(options);

	parser.setSource(cuSource.toCharArray());
	return (CompilationUnit) parser.createAST(null);
}
 
public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit, IProblemLocation[] problems, boolean insertInferredTypeArguments, boolean removeRedundantTypeArguments) {

		if (insertInferredTypeArguments) {
			final ArrayList<ASTNode> changedNodes= new ArrayList<ASTNode>();
			compilationUnit.accept(new InsertTypeArgumentsVisitor(changedNodes));

			if (changedNodes.isEmpty())
				return null;

			CompilationUnitRewriteOperation op= new InsertTypeArgumentsOperation(changedNodes.toArray(new ParameterizedType[changedNodes.size()]));
			return new TypeParametersFix(FixMessages.TypeParametersFix_insert_inferred_type_arguments_name, compilationUnit, new CompilationUnitRewriteOperation[] { op });

		} else if (removeRedundantTypeArguments) {
			List<CompilationUnitRewriteOperation> result= new ArrayList<CompilationUnitRewriteOperation>();
			for (int i= 0; i < problems.length; i++) {
				IProblemLocation problem= problems[i];
				int id= problem.getProblemId();

				if (id == IProblem.RedundantSpecificationOfTypeArguments) {
					ParameterizedType parameterizedType= getParameterizedType(compilationUnit, problem);
					if (parameterizedType == null)
						return null;
					result.add(new RemoveTypeArgumentsOperation(parameterizedType));
				}
			}
			if (!result.isEmpty()) {
				return new TypeParametersFix(FixMessages.TypeParametersFix_remove_redundant_type_arguments_name, compilationUnit, result.toArray(new CompilationUnitRewriteOperation[result.size()]));
			}
		}
		return null;
	}
 
源代码24 项目: txtUML   文件: ModelTest.java
@Test
public void testTransitionMethodNotCorrect() throws Exception {
	CompilationUnit compilationUnit = prepareAST("TransitionMethodNotCorrect.java");

	compilationUnit.accept(new ModelVisitor(mockCollector));

	verify(mockCollector).report(is(UNKNOWN_TRANSITION_METHOD));
	verify(mockCollector).report(is(TRANSITION_METHOD_PARAMETERS));

	checkNoOtherErrorRaised();
}
 
public static CompilationUnit createQuickFixAST(ICompilationUnit compilationUnit, IProgressMonitor monitor) {
	ASTParser astParser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	astParser.setSource(compilationUnit);
	astParser.setResolveBindings(true);
	astParser.setStatementsRecovery(ASTProvider.SHARED_AST_STATEMENT_RECOVERY);
	astParser.setBindingsRecovery(ASTProvider.SHARED_BINDING_RECOVERY);
	return (CompilationUnit) astParser.createAST(monitor);
}
 
@Override
public Change createChange(IProgressMonitor pm) throws CoreException {
	ASTParser p= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	p.setSource(getDestinationCu());
	CompilationUnit cuNode= (CompilationUnit) p.createAST(pm);
	ASTRewrite rewrite= ASTRewrite.create(cuNode.getAST());
	TypedSource source= null;
	for (int i= fSources.length - 1; i >= 0; i--) {
		source= fSources[i];
		final ASTNode destination= getDestinationNodeForSourceElement(fDestination, source.getType(), cuNode);
		if (destination != null) {
			if (destination instanceof CompilationUnit)
				insertToCu(rewrite, createNewNodeToInsertToCu(source, rewrite), (CompilationUnit) destination);
			else if (destination instanceof AbstractTypeDeclaration)
				insertToType(rewrite, createNewNodeToInsertToType(source, rewrite), (AbstractTypeDeclaration) destination);
		}
	}
	final CompilationUnitChange result= new CompilationUnitChange(ReorgMessages.PasteAction_change_name, getDestinationCu());
	try {
		ITextFileBuffer buffer= RefactoringFileBuffers.acquire(getDestinationCu());
		TextEdit rootEdit= rewrite.rewriteAST(buffer.getDocument(), fDestination.getJavaProject().getOptions(true));
		if (getDestinationCu().isWorkingCopy())
			result.setSaveMode(TextFileChange.LEAVE_DIRTY);
		TextChangeCompatibility.addTextEdit(result, ReorgMessages.PasteAction_edit_name, rootEdit);
	} finally {
		RefactoringFileBuffers.release(getDestinationCu());
	}
	return result;
}
 
源代码27 项目: eclipse.jdt.ls   文件: ChangeUtil.java
private static void convertPackageUpdateEdit(ICompilationUnit cu, String newPkgName, WorkspaceEdit rootEdit) throws JavaModelException {
	CompilationUnit unit = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(cu, true);		
	ASTRewrite rewrite = ASTRewrite.create(unit.getAST());
	if (updatePackageStatement(unit, newPkgName, rewrite, cu)) {
		TextEdit textEdit = rewrite.rewriteAST();
		convertTextEdit(rootEdit, cu, textEdit);
	}
}
 
源代码28 项目: buck   文件: JavaFileParser.java
public Optional<String> getPackageNameFromSource(String code) {
  CompilationUnit compilationUnit = makeCompilationUnitFromSource(code);

  // A Java file might not have a package. Hopefully all of ours do though...
  PackageDeclaration packageDecl = compilationUnit.getPackage();
  if (packageDecl != null) {
    return Optional.of(packageDecl.getName().toString());
  }
  return Optional.empty();
}
 
源代码29 项目: eclipse.jdt.ls   文件: OverrideMethodsOperation.java
private static TextEdit createTextEditForOverridableMethods(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding typeBinding, IMethodBinding[] methodBindings) throws CoreException {
	ASTRewrite astRewrite = ASTRewrite.create(astRoot.getAST());
	ImportRewrite importRewrite = StubUtility.createImportRewrite(astRoot, true);
	ListRewrite listRewrite = null;
	ASTNode typeNode = astRoot.findDeclaringNode(typeBinding);
	if (typeNode instanceof AnonymousClassDeclaration) {
		listRewrite = astRewrite.getListRewrite(typeNode, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY);
	} else if (typeNode instanceof AbstractTypeDeclaration) {
		listRewrite = astRewrite.getListRewrite(typeNode, ((AbstractTypeDeclaration) typeNode).getBodyDeclarationsProperty());
	} else {
		return null;
	}

	CodeGenerationSettings settings = PreferenceManager.getCodeGenerationSettings(cu.getResource());
	ImportRewriteContext context = new ContextSensitiveImportRewriteContext(astRoot, typeNode.getStartPosition(), importRewrite);
	for (IMethodBinding methodBinding : methodBindings) {
		MethodDeclaration stub = StubUtility2Core.createImplementationStubCore(cu, astRewrite, importRewrite, context, methodBinding, typeBinding, settings, typeBinding.isInterface(), typeNode, false);
		if (stub != null) {
			listRewrite.insertLast(stub, null);
		}
	}

	MultiTextEdit edit = new MultiTextEdit();
	edit.addChild(importRewrite.rewriteImports(null));
	edit.addChild(astRewrite.rewriteAST());
	return edit;
}
 
源代码30 项目: gwt-eclipse-plugin   文件: JavaASTUtils.java
public static MethodDeclaration findMethodDeclaration(
    CompilationUnit astRoot, String methodBindingKey) {
  ASTNode bindingDecl = astRoot.findDeclaringNode(methodBindingKey);
  if (bindingDecl == null
      || bindingDecl.getNodeType() != ASTNode.METHOD_DECLARATION) {
    return null;
  }
  return (MethodDeclaration) bindingDecl;
}
 
 类所在包
 同包方法