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

The following examples show how to use org.eclipse.jdt.core.dom.ASTNode#accept() . 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: MethodScopeExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static Multimap<Scope, String> getScopeSnippets(final ASTNode node,
		final boolean methodAsRoots) {
	final ScopeFinder scopeFinder = new ScopeFinder(methodAsRoots);
	node.accept(scopeFinder);

	final Multimap<Scope, String> scopes = TreeMultimap.create();
	for (final Entry<ASTNode, Method> method : scopeFinder.methods
			.entries()) {
		scopes.put(new Scope(method.getKey().toString(),
				method.getValue().type, METHOD_CALL, 0, 0), method
				.getValue().name);
	}

	return scopes;

}
 
Example 2
Source File: TypenameScopeExtractor.java    From api-mining with GNU General Public License v3.0 6 votes vote down vote up
private Multimap<Scope, String> getClassnames(final ASTNode node) {
	final ClassnameFinder cf = new ClassnameFinder(methodsAsRoots);
	node.accept(cf);

	final Multimap<Scope, String> classnames = TreeMultimap.create();

	for (final Entry<ASTNode, String> classname : cf.types.entries()) {
		final ASTNode parentNode = classname.getKey();
		final Scope sc = new Scope(
				classname.getKey().toString(),
				parentNode.getNodeType() == ASTNode.METHOD_DECLARATION ? ScopeType.SCOPE_METHOD
						: ScopeType.SCOPE_CLASS, TYPENAME,
				parentNode.getNodeType(), -1);
		classnames.put(sc, classname.getValue());
	}
	return classnames;
}
 
Example 3
Source File: BugResolution.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Nonnull
private String findLabelReplacement(ASTVisitor labelFixingVisitor) {
    IMarker marker = getMarker();
    try {
        ASTNode node = getNodeForMarker(marker);
        if (node != null) {
            node.accept(labelFixingVisitor);
            String retVal = ((CustomLabelVisitor) labelFixingVisitor).getLabelReplacement();
            return retVal == null ? DEFAULT_REPLACEMENT : retVal;
        }
        // Catch all exceptions (explicit) so that the label creation won't fail
        // FindBugs prefers this being explicit instead of just catching Exception
    } catch (JavaModelException | ASTNodeNotFoundException | RuntimeException e) {
        FindbugsPlugin.getDefault().logException(e, e.getLocalizedMessage());
        return DEFAULT_REPLACEMENT;
    }
    return DEFAULT_REPLACEMENT;
}
 
Example 4
Source File: AccessorClassModifier.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private ASTNode findField(ASTNode astRoot, final String name) {

		class STOP_VISITING extends RuntimeException {
			private static final long serialVersionUID= 1L;
		}

		final ASTNode[] result= new ASTNode[1];

		try {
			astRoot.accept(new ASTVisitor() {

				@Override
				public boolean visit(VariableDeclarationFragment node) {
					if (name.equals(node.getName().getFullyQualifiedName())) {
						result[0]= node.getParent();
						throw new STOP_VISITING();
					}
					return true;
				}
			});
		} catch (STOP_VISITING ex) {
			// stop visiting AST
		}

		return result[0];
	}
 
Example 5
Source File: JavaTypeDeclarationBindingExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Set<Set<ASTNode>> getNameBindings(final ASTNode node) {
	final ClassnameFinder finder = new ClassnameFinder();
	node.accept(finder);

	final Set<Set<ASTNode>> nameBindings = Sets.newHashSet();
	for (final String typeName : finder.classNamePostions.keySet()) {
		for (final ASTNode nameNode : finder.classNamePostions
				.get(typeName)) {
			final Set<ASTNode> boundNodes = Sets.newIdentityHashSet();
			boundNodes.add(nameNode);
			nameBindings.add(boundNodes);
		}
	}
	return nameBindings;
}
 
Example 6
Source File: RenameTypeParameterProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates the necessary changes for the renaming of the type parameter.
 *
 * @param monitor
 *            the progress monitor to display progress
 * @return the status of the operation
 * @throws CoreException
 *             if the change could not be generated
 */
private RefactoringStatus createRenameChanges(IProgressMonitor monitor) throws CoreException {
	Assert.isNotNull(monitor);
	RefactoringStatus status= new RefactoringStatus();
	try {
		monitor.beginTask(RefactoringCoreMessages.RenameTypeParameterRefactoring_searching, 2);
		ICompilationUnit cu= fTypeParameter.getDeclaringMember().getCompilationUnit();
		CompilationUnit root= RefactoringASTParser.parseWithASTProvider(cu, true, null);
		CompilationUnitRewrite rewrite= new CompilationUnitRewrite(cu, root);
		IMember member= fTypeParameter.getDeclaringMember();
		ASTNode declaration= null;
		if (member instanceof IMethod) {
			declaration= ASTNodeSearchUtil.getMethodDeclarationNode((IMethod) member, root);
		} else if (member instanceof IType) {
			declaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode((IType) member, root);
		} else {
			JavaLanguageServerPlugin.logError("Unexpected sub-type of IMember: " + member.getClass().getName()); //$NON-NLS-1$
			Assert.isTrue(false);
		}
		monitor.worked(1);
		RenameTypeParameterVisitor visitor= new RenameTypeParameterVisitor(rewrite, fTypeParameter.getNameRange(), status);
		if (declaration != null) {
			declaration.accept(visitor);
		}
		fChange= visitor.getResult();
	} finally {
		monitor.done();
	}
	return status;
}
 
Example 7
Source File: JavaApproximateVariableBindingExtractor.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Set<Set<ASTNode>> getNameBindings(final ASTNode node) {
	final VariableBindingFinder bindingFinder = new VariableBindingFinder();
	node.accept(bindingFinder);

	final Set<Set<ASTNode>> nameBindings = Sets.newHashSet();
	for (final Entry<Integer, List<ASTNode>> variableBindings : bindingFinder.variableBinding
			.entrySet()) {
		final Set<ASTNode> boundNodes = Sets.newIdentityHashSet();
		boundNodes.addAll(variableBindings.getValue());
		nameBindings.add(boundNodes);
	}
	return nameBindings;
}
 
Example 8
Source File: JavaMethodDeclarationBindingExtractor.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Set<Set<ASTNode>> getNameBindings(final ASTNode node) {
	final MethodBindings mb = new MethodBindings();
	node.accept(mb);

	final Set<Set<ASTNode>> nameBindings = Sets.newHashSet();
	for (final Entry<String, ASTNode> entry : mb.methodNamePostions
			.entries()) {
		final Set<ASTNode> boundNodes = Sets.newIdentityHashSet();
		boundNodes.add(entry.getValue());
		nameBindings.add(boundNodes);
	}
	return nameBindings;
}
 
Example 9
Source File: JavaApproximateVariableBindingExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Set<Set<ASTNode>> getNameBindings(final ASTNode node) {
	final VariableBindingFinder bindingFinder = new VariableBindingFinder();
	node.accept(bindingFinder);

	final Set<Set<ASTNode>> nameBindings = Sets.newHashSet();
	for (final Entry<Integer, List<ASTNode>> variableBindings : bindingFinder.variableBinding
			.entrySet()) {
		final Set<ASTNode> boundNodes = Sets.newIdentityHashSet();
		boundNodes.addAll(variableBindings.getValue());
		nameBindings.add(boundNodes);
	}
	return nameBindings;
}
 
Example 10
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(final TagElement node) {
  boolean _isNested = node.isNested();
  if (_isNested) {
    this.appendToBuffer("{");
  } else {
    this.appendLineWrapToBuffer();
    this.appendToBuffer(" * ");
  }
  boolean previousRequiresWhiteSpace = false;
  String _tagName = node.getTagName();
  boolean _tripleNotEquals = (_tagName != null);
  if (_tripleNotEquals) {
    this.appendToBuffer(node.getTagName());
    previousRequiresWhiteSpace = true;
  }
  boolean previousRequiresNewLine = false;
  for (Iterator<? extends ASTNode> it = node.fragments().iterator(); it.hasNext();) {
    {
      ASTNode e = it.next();
      boolean currentIncludesWhiteSpace = (e instanceof TextElement);
      if ((previousRequiresNewLine && currentIncludesWhiteSpace)) {
        this.appendLineWrapToBuffer();
        this.appendToBuffer(" * ");
      }
      previousRequiresNewLine = currentIncludesWhiteSpace;
      if ((previousRequiresWhiteSpace && (!currentIncludesWhiteSpace))) {
        this.appendSpaceToBuffer();
      }
      e.accept(this);
      previousRequiresWhiteSpace = ((!currentIncludesWhiteSpace) && (!(e instanceof TagElement)));
    }
  }
  boolean _isNested_1 = node.isNested();
  if (_isNested_1) {
    this.appendToBuffer("}");
  }
  return false;
}
 
Example 11
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(final ArrayType node) {
  boolean _java8orHigher = this.java8orHigher();
  boolean _not = (!_java8orHigher);
  if (_not) {
    node.getComponentType().accept(this);
    this.appendToBuffer("[]");
  } else {
    ASTNode _genericChildProperty = this._aSTFlattenerUtils.genericChildProperty(node, "elementType");
    if (_genericChildProperty!=null) {
      _genericChildProperty.accept(this);
    }
    List<ASTNode> dimensions = this._aSTFlattenerUtils.genericChildListProperty(node, "dimensions");
    boolean _isNullOrEmpty = IterableExtensions.isNullOrEmpty(dimensions);
    boolean _not_1 = (!_isNullOrEmpty);
    if (_not_1) {
      final Consumer<ASTNode> _function = (ASTNode dim) -> {
        List<ASTNode> _genericChildListProperty = this._aSTFlattenerUtils.genericChildListProperty(dim, "annotations");
        if (_genericChildListProperty!=null) {
          this.visitAll(_genericChildListProperty);
        }
        this.appendToBuffer("[]");
      };
      dimensions.forEach(_function);
    }
  }
  return false;
}
 
Example 12
Source File: RenameTypeParameterProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates the necessary changes for the renaming of the type parameter.
 *
 * @param monitor
 *            the progress monitor to display progress
 * @return the status of the operation
 * @throws CoreException
 *             if the change could not be generated
 */
private RefactoringStatus createRenameChanges(IProgressMonitor monitor) throws CoreException {
	Assert.isNotNull(monitor);
	RefactoringStatus status= new RefactoringStatus();
	try {
		monitor.beginTask(RefactoringCoreMessages.RenameTypeParameterRefactoring_searching, 2);
		ICompilationUnit cu= fTypeParameter.getDeclaringMember().getCompilationUnit();
		CompilationUnit root= RefactoringASTParser.parseWithASTProvider(cu, true, null);
		CompilationUnitRewrite rewrite= new CompilationUnitRewrite(cu, root);
		IMember member= fTypeParameter.getDeclaringMember();
		ASTNode declaration= null;
		if (member instanceof IMethod) {
			declaration= ASTNodeSearchUtil.getMethodDeclarationNode((IMethod) member, root);
		} else if (member instanceof IType) {
			declaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode((IType) member, root);
		} else {
			JavaPlugin.logErrorMessage("Unexpected sub-type of IMember: " + member.getClass().getName()); //$NON-NLS-1$
			Assert.isTrue(false);
		}
		monitor.worked(1);
		RenameTypeParameterVisitor visitor= new RenameTypeParameterVisitor(rewrite, fTypeParameter.getNameRange(), status);
		if (declaration != null)
			declaration.accept(visitor);
		fChange= visitor.getResult();
	} finally {
		monitor.done();
	}
	return status;
}
 
Example 13
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
public void handleAssignment(final Assignment node, final ASTNode leftSide, final Type type) {
  leftSide.accept(this);
  this.appendToBuffer(node.getOperator().toString());
  this.handleRightHandSide(node, type);
}
 
Example 14
Source File: MoveStaticMembersProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static List<IBinding> perform(ASTNode root) {
	TypeReferenceFinder visitor= new TypeReferenceFinder();
	root.accept(visitor);
	return visitor.fResult;
}
 
Example 15
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public CompareInBitWiseOpFinder(ASTNode selectedNode) {
	fSelectedNode= selectedNode;
	selectedNode.accept(this);
}
 
Example 16
Source File: JavaASTExtractor.java    From api-mining with GNU General Public License v3.0 4 votes vote down vote up
private final MethodDeclaration getFirstMethodDeclaration(final ASTNode node) {
	final TopMethodRetriever visitor = new TopMethodRetriever();
	node.accept(visitor);
	return visitor.topDcl;
}
 
Example 17
Source File: JavaASTExtractor.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private final MethodDeclaration getFirstMethodDeclaration(final ASTNode node) {
	final TopMethodRetriever visitor = new TopMethodRetriever();
	node.accept(visitor);
	return visitor.topDcl;
}
 
Example 18
Source File: NodeFinder.java    From lapse-plus with GNU General Public License v3.0 3 votes vote down vote up
/**
 * A visitor that maps a selection to a given ASTNode. The result node is
 * determined as follows:
 * <ul>
 *   <li>first the visitor tries to find a node with the exact start and length</li>
 *   <li>if no such node exists than the node that encloses the range defined by
 *       start and end is returned.</li>
 *   <li>if the length is zero than also nodes are considered where the node's
 *       start or end position matches <code>start</code>.</li>
 *   <li>otherwise <code>null</code> is returned.</li>
 * </ul>
 */
public static ASTNode perform(ASTNode root, int start, int length) {
  NodeFinder finder= new NodeFinder(start, length);
  root.accept(finder);
  ASTNode result= finder.getCoveredNode();
  if (result == null || result.getStartPosition() != start || result.getLength() != length) {
    return finder.getCoveringNode();
  }
  return result;
}
 
Example 19
Source File: VariableScopeExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Return the variable scopes of the given node.
 * 
 * @param node
 * @return
 */
public Multimap<ASTNode, Variable> getVariableScopes(final ASTNode node) {
	variableScopes.clear();
	node.accept(this);
	return ImmutableMultimap.copyOf(variableScopes);
}
 
Example 20
Source File: VariableScopeExtractor.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Return the variable scopes of the given node.
 * 
 * @param node
 * @return
 */
public Multimap<ASTNode, Variable> getVariableScopes(final ASTNode node) {
	variableScopes.clear();
	node.accept(this);
	return ImmutableMultimap.copyOf(variableScopes);
}