Java Code Examples for org.eclipse.jdt.core.dom.ASTNode#getRoot()

The following examples show how to use org.eclipse.jdt.core.dom.ASTNode#getRoot() . 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: TypeAnnotationRewrite.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Removes all {@link Annotation} whose only {@link Target} is {@link ElementType#TYPE_USE} from
 * <code>node</code>'s <code>childListProperty</code>.
 * <p>
 * In a combination of {@link ElementType#TYPE_USE} and {@link ElementType#TYPE_PARAMETER}
 * the latter is ignored, because this is implied by the former and creates no ambiguity.</p>
 *
 * @param node ASTNode
 * @param childListProperty child list property
 * @param rewrite rewrite that removes the nodes
 * @param editGroup the edit group in which to collect the corresponding text edits, or null if
 *            ungrouped
 */
public static void removePureTypeAnnotations(ASTNode node, ChildListPropertyDescriptor childListProperty, ASTRewrite rewrite, TextEditGroup editGroup) {
	CompilationUnit root= (CompilationUnit) node.getRoot();
	if (!JavaModelUtil.is18OrHigher(root.getJavaElement().getJavaProject())) {
		return;
	}
	ListRewrite listRewrite= rewrite.getListRewrite(node, childListProperty);
	@SuppressWarnings("unchecked")
	List<? extends ASTNode> children= (List<? extends ASTNode>) node.getStructuralProperty(childListProperty);
	for (ASTNode child : children) {
		if (child instanceof Annotation) {
			Annotation annotation= (Annotation) child;
			if (isPureTypeAnnotation(annotation)) {
				listRewrite.remove(child, editGroup);
			}
		}
	}
}
 
Example 2
Source File: RedundantNullnessTypeAnnotationsFilter.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static /* @Nullable */ RedundantNullnessTypeAnnotationsFilter createIfConfigured(/* @Nullable */ ASTNode node) {
	if (node == null) {
		return null;
	}
	final ASTNode root= node.getRoot();
	if (root instanceof CompilationUnit) {
		CompilationUnit compilationUnit= (CompilationUnit) root;
		IJavaElement javaElement= compilationUnit.getJavaElement();
		IJavaProject javaProject= javaElement == null ? null : javaElement.getJavaProject();
		if (javaProject != null) {
			if (JavaCore.ENABLED.equals(javaProject.getOption(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, true))) {
				String nonNullAnnotationName= javaProject.getOption(JavaCore.COMPILER_NONNULL_ANNOTATION_NAME, true);
				String nullableAnnotationName= javaProject.getOption(JavaCore.COMPILER_NULLABLE_ANNOTATION_NAME, true);
				String nonNullByDefaultName= javaProject.getOption(JavaCore.COMPILER_NONNULL_BY_DEFAULT_ANNOTATION_NAME, true);
				if (nonNullAnnotationName == null || nullableAnnotationName == null || nonNullByDefaultName == null) {
					return null;
				}
				EnumSet<TypeLocation> nonNullByDefaultLocations= determineNonNullByDefaultLocations(node, nonNullByDefaultName);
				return new RedundantNullnessTypeAnnotationsFilter(nonNullAnnotationName, nullableAnnotationName, nonNullByDefaultLocations);
			}
		}
	}
	return null;
}
 
Example 3
Source File: RemoteServiceValidatorTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
public void testMissingAsyncInterface() throws JavaModelException {
  ICompilationUnit syncInterface = JavaProjectUtilities.createCompilationUnit(
      javaProject,
      "com.google.TestService",
      "package com.google;\npublic interface TestService extends com.google.gwt.user.client.rpc.RemoteService {}\n");
  ASTNode node = newAST(syncInterface);
  CompilationUnit compilationUnit = (CompilationUnit) node.getRoot();
  TypeDeclaration typeDeclaration = JavaASTUtils.findTypeDeclaration(
      compilationUnit, "com.google.TestService");
  assertTrue(compilationUnit.getProblems().length == 0);

  RemoteServiceValidator rsv = new RemoteServiceValidator();
  ValidationResult validationResults = rsv.validate(node);

  List<RemoteServiceProblem> expected = Arrays.asList(RemoteServiceProblemFactory.newMissingAsyncType(typeDeclaration));
  assertProblemsEqual(expected, validationResults.getProblems());
  assertEquals(
      Arrays.asList(RemoteServiceUtilities.computeAsyncTypeName("com.google.TestService")),
      validationResults.getTypeDependencies());
}
 
Example 4
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static Message[] getMessages(ASTNode node, int flags) {
	ASTNode root= node.getRoot();
	if (!(root instanceof CompilationUnit))
		return EMPTY_MESSAGES;
	Message[] messages= ((CompilationUnit)root).getMessages();
	if (root == node)
		return messages;
	final int iterations= computeIterations(flags);
	List<Message> result= new ArrayList<Message>(5);
	for (int i= 0; i < messages.length; i++) {
		Message message= messages[i];
		ASTNode temp= node;
		int count= iterations;
		do {
			int nodeOffset= temp.getStartPosition();
			int messageOffset= message.getStartPosition();
			if (nodeOffset <= messageOffset && messageOffset < nodeOffset + temp.getLength()) {
				result.add(message);
				count= 0;
			} else {
				count--;
			}
		} while ((temp= temp.getParent()) != null && count > 0);
	}
	return result.toArray(new Message[result.size()]);
}
 
Example 5
Source File: GdtJavaProblem.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
protected GdtJavaProblem(ASTNode node, int offset, int length, T problemType,
    GdtProblemSeverity severity, String[] messageArguments,
    String[] problemArguments) {
  this.id = problemType.getProblemId();

  this.filename = getFileNameFromASTNode(node);
  this.startPosition = offset;
  this.endPosition = offset + length - 1;
  CompilationUnit cu = (CompilationUnit) node.getRoot();
  this.line = cu.getLineNumber(node.getStartPosition());
  this.column = cu.getColumnNumber(node.getStartPosition());

  this.problemType = problemType;
  this.severity = severity;
  this.message = MessageFormat.format(problemType.getMessage(),
      (Object[]) messageArguments);
  this.problemArguments = problemArguments;
}
 
Example 6
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 7
Source File: RefactoringASTParser.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ICompilationUnit getCompilationUnit(ASTNode node) {
	ASTNode root= node.getRoot();
	if (root instanceof CompilationUnit) {
		IJavaElement cu= ((CompilationUnit) root).getJavaElement();
		if (cu instanceof ICompilationUnit)
			return (ICompilationUnit) cu;
	}
	return null;
}
 
Example 8
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a list of local variable names which are visible at the given node.
 *
 * @param node the AST node
 * @return a list of local variable names visible at the given node
 * @see ScopeAnalyzer#getDeclarationsInScope(int, int)
 * @since 3.10
 */
public static List<String> getVisibleLocalVariablesInScope(ASTNode node) {
	List<String> variableNames= new ArrayList<String>();
	CompilationUnit root= (CompilationUnit) node.getRoot();
	IBinding[] bindings= new ScopeAnalyzer(root).
			getDeclarationsInScope(node.getStartPosition(), ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY);
	for (IBinding binding : bindings) {
		if (binding instanceof IVariableBinding && !((IVariableBinding) binding).isField()) {
			variableNames.add(binding.getName());
		}
	}
	return variableNames;
}
 
Example 9
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static IProblem[] getProblems(ASTNode node, int scope, int severity) {
	ASTNode root= node.getRoot();
	if (!(root instanceof CompilationUnit))
		return EMPTY_PROBLEMS;
	IProblem[] problems= ((CompilationUnit)root).getProblems();
	if (root == node)
		return problems;
	final int iterations= computeIterations(scope);
	List<IProblem> result= new ArrayList<IProblem>(5);
	for (int i= 0; i < problems.length; i++) {
		IProblem problem= problems[i];
		boolean consider= false;
		if ((severity & PROBLEMS) == PROBLEMS)
			consider= true;
		else if ((severity & WARNING) != 0)
			consider= problem.isWarning();
		else if ((severity & ERROR) != 0)
			consider= problem.isError();
		if (consider) {
			ASTNode temp= node;
			int count= iterations;
			do {
				int nodeOffset= temp.getStartPosition();
				int problemOffset= problem.getSourceStart();
				if (nodeOffset <= problemOffset && problemOffset < nodeOffset + temp.getLength()) {
					result.add(problem);
					count= 0;
				} else {
					count--;
				}
			} while ((temp= temp.getParent()) != null && count > 0);
		}
	}
	return result.toArray(new IProblem[result.size()]);
}
 
Example 10
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ASTNode findDeclaration(IBinding binding, ASTNode root) {
	root= root.getRoot();
	if (root instanceof CompilationUnit) {
		return ((CompilationUnit)root).findDeclaringNode(binding);
	}
	return null;
}
 
Example 11
Source File: JavadocLineBreakPreparator.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private List<Comment> getComments(ASTNode astRoot) {
	if (astRoot.getRoot() instanceof CompilationUnit) {
		CompilationUnit compilationUnit = (CompilationUnit) astRoot.getRoot();
		return compilationUnit.getCommentList();
	}
	return Collections.emptyList();
}
 
Example 12
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 13
Source File: RenamingDatasetExtractor.java    From naturalize with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean matchRenaming(final Renaming renaming, final ASTNode n) {
	if (!n.toString().equals(renaming.nameAfter)) {
		return false;
	}
	final CompilationUnit cu = (CompilationUnit) n.getRoot();
	return renaming.linesAfter.contains(cu.getLineNumber(n
			.getStartPosition()));
}
 
Example 14
Source File: VarargsWarningsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void addAddSafeVarargsToDeclarationProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	if (!JavaModelUtil.is17OrHigher(context.getCompilationUnit().getJavaProject()))
		return;

	ASTNode coveringNode= problem.getCoveringNode(context.getASTRoot());
	IMethodBinding methodBinding;
	if (coveringNode instanceof MethodInvocation) {
		methodBinding= ((MethodInvocation) coveringNode).resolveMethodBinding();
	} else if (coveringNode instanceof ClassInstanceCreation) {
		methodBinding= ((ClassInstanceCreation) coveringNode).resolveConstructorBinding();
	} else {
		return;
	}
	if (methodBinding == null)
		return;
	
	String label= Messages.format(CorrectionMessages.VarargsWarningsSubProcessor_add_safevarargs_to_method_label, methodBinding.getName());

	ITypeBinding declaringType= methodBinding.getDeclaringClass();
	CompilationUnit astRoot= (CompilationUnit) coveringNode.getRoot();
	if (declaringType != null && declaringType.isFromSource()) {
		try {
			ICompilationUnit targetCu= ASTResolving.findCompilationUnitForBinding(context.getCompilationUnit(), astRoot, declaringType);
			if (targetCu != null) {
				AddSafeVarargsProposal proposal= new AddSafeVarargsProposal(label, targetCu, null, methodBinding.getMethodDeclaration(), IProposalRelevance.ADD_SAFEVARARGS);
				proposals.add(proposal);
			}
		} catch (JavaModelException e) {
			return;
		}
	}
}
 
Example 15
Source File: AbstractPairedInterfaceValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
protected CompilationUnit getCompilationUnit(ASTNode node) {
  ASTNode root = node.getRoot();
  assert (root.getNodeType() == ASTNode.COMPILATION_UNIT);
  return (CompilationUnit) root;
}
 
Example 16
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 17
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 corresponding text
 * edits to the given document containing the original source
 * code. The document itself is not modified.
 * <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>
 *
 * @param document original document containing source code
 * @param options the table of formatter options
 * (key type: <code>String</code>; value type: <code>String</code>);
 * or <code>null</code> to use the standard global options
 * {@link JavaCore#getOptions() JavaCore.getOptions()}
 * @return text edit object describing the changes to the
 * document corresponding to the changes recorded by this rewriter
 * @throws IllegalArgumentException An <code>IllegalArgumentException</code>
 * is thrown if the document passed does not correspond to the AST that is rewritten.
 */
public TextEdit rewriteAST(IDocument document, Map options) throws IllegalArgumentException {
	if (document == null) {
		throw new IllegalArgumentException();
	}

	ASTNode rootNode= getRootNode();
	if (rootNode == null) {
		return new MultiTextEdit(); // no changes
	}

	char[] content= document.get().toCharArray();
	LineInformation lineInfo= LineInformation.create(document);
	String lineDelim= TextUtilities.getDefaultLineDelimiter(document);

	ASTNode astRoot= rootNode.getRoot();
	List commentNodes= astRoot instanceof CompilationUnit ? ((CompilationUnit) astRoot).getCommentList() : null;
	Map currentOptions = options == null ? JavaCore.getOptions() : options;
	return internalRewriteAST(content, lineInfo, lineDelim, commentNodes, currentOptions, rootNode, (RecoveryScannerData)((CompilationUnit) astRoot).getStatementsRecoveryData());
}
 
Example 18
Source File: ImportReferencesCollector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void collect(ASTNode node, IJavaProject project, Region rangeLimit, boolean skipMethodBodies, Collection<SimpleName> resultingTypeImports, Collection<SimpleName> resultingStaticImports) {
	ASTNode root= node.getRoot();
	CompilationUnit astRoot= root instanceof CompilationUnit ? (CompilationUnit) root : null;
	node.accept(new ImportReferencesCollector(project, astRoot, rangeLimit, skipMethodBodies, resultingTypeImports, resultingStaticImports));
}
 
Example 19
Source File: TargetSourceRangeComputer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Returns the target source range of the given node. Unlike
 * {@link ASTNode#getStartPosition()} and {@link ASTNode#getLength()},
 * the extended source range may include comments and whitespace
 * immediately before or after the normal source range for the node.
 * <p>
 * The returned source ranges must satisfy the following conditions:
 * <dl>
 * <li>no two source ranges in an AST may be overlapping</li>
 * <li>a source range of a parent node must fully cover the source ranges of its children</li>
 * 	</dl>
 * 	</p>
 * <p>
 * The default implementation uses
 * {@link CompilationUnit#getExtendedStartPosition(ASTNode)}
 * and {@link CompilationUnit#getExtendedLength(ASTNode)}
 * to compute the target source range. Clients may override or
 * extend this method to expand or contract the source range of the
 * given node. The resulting source range must cover at least the
 * original source range of the node.
 * </p>
 *
 * @param node the node with a known source range in the compilation unit
 * being rewritten
 * @return the exact source range in the compilation unit being rewritten
 * that should be replaced (or deleted)
 */
public SourceRange computeSourceRange(ASTNode node) {
	ASTNode root= node.getRoot();
	if (root instanceof CompilationUnit) {
		CompilationUnit cu= (CompilationUnit) root;
		return new SourceRange(cu.getExtendedStartPosition(node), cu.getExtendedLength(node));
	}
	return new SourceRange(node.getStartPosition(), node.getLength());
}
 
Example 20
Source File: ContextSensitiveImportRewriteContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Creates an import rewrite context at the given node's start position.
 * 
 * @param node the node to use as context
 * @param importRewrite the import rewrite
 * 
 * @since 3.6
 */
public ContextSensitiveImportRewriteContext(ASTNode node, ImportRewrite importRewrite) {
	this((CompilationUnit)node.getRoot(), node.getStartPosition(), importRewrite);
}