Java Code Examples for org.eclipse.jdt.core.dom.CompilationUnit

The following examples show how to use org.eclipse.jdt.core.dom.CompilationUnit. These examples are extracted from open source projects. 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
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);
}
 
Example 2
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();
	}
}
 
Example 3
Source Project: compiler   Source File: Java7BaseTest.java    License: Apache License 2.0 6 votes vote down vote up
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) {}
}
 
Example 4
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);
	}
}
 
Example 5
Source Project: RefactoringMiner   Source File: UMLModelASTReader.java    License: MIT License 6 votes vote down vote up
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);
}
 
Example 6
/**
 * 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;
}
 
Example 7
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};
}
 
Example 8
Source Project: sarl   Source File: SarlClassPathDetector.java    License: Apache License 2.0 6 votes vote down vote up
/** 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));
			}
		}
	}
}
 
Example 9
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;
}
 
Example 10
/**
 * 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();
}
 
Example 11
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()]);
}
 
Example 12
@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;
}
 
Example 13
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;
}
 
Example 14
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);
	}
}
 
Example 15
@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;
}
 
Example 16
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;
}
 
Example 17
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;
}
 
Example 18
/**
	 * {@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;
	}
 
Example 19
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.
		 */
	}
 
Example 20
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;
	}
}
 
Example 21
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());
}
 
Example 22
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);
}
 
Example 23
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;
	}
 
Example 24
Source Project: txtUML   Source File: ModelTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@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();
}
 
Example 25
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);
}
 
Example 26
@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;
}
 
Example 27
Source Project: eclipse.jdt.ls   Source File: ChangeUtil.java    License: Eclipse Public License 2.0 5 votes vote down vote up
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);
	}
}
 
Example 28
Source Project: buck   Source File: JavaFileParser.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 29
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;
}
 
Example 30
Source Project: gwt-eclipse-plugin   Source File: JavaASTUtils.java    License: Eclipse Public License 1.0 5 votes vote down vote up
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;
}