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

The following examples show how to use org.eclipse.jdt.core.dom.ASTNode. 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
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel linkedModel) throws CoreException {
	ASTRewrite rewrite= cuRewrite.getASTRewrite();
	IBinding binding= fUnusedName.resolveBinding();
	CompilationUnit root= (CompilationUnit) fUnusedName.getRoot();
	String displayString= FixMessages.UnusedCodeFix_RemoveUnusedTypeParameter_description;
	TextEditGroup group= createTextEditGroup(displayString, cuRewrite);

	if (binding.getKind() == IBinding.TYPE) {
		ITypeBinding decl= ((ITypeBinding) binding).getTypeDeclaration();
		ASTNode declaration= root.findDeclaringNode(decl);
		if (declaration.getParent() instanceof TypeDeclarationStatement) {
			declaration= declaration.getParent();
		}
		rewrite.remove(declaration, group);
	}
}
 
Example 2
private Statement getParentLoopBody(ASTNode node) {
	Statement stmt= null;
	ASTNode start= node;
	while (start != null
			&& !(start instanceof ForStatement)
			&& !(start instanceof DoStatement)
			&& !(start instanceof WhileStatement)
			&& !(start instanceof EnhancedForStatement)
			&& !(start instanceof SwitchStatement)) {
		start= start.getParent();
	}
	if (start instanceof ForStatement) {
		stmt= ((ForStatement)start).getBody();
	} else if (start instanceof DoStatement) {
		stmt= ((DoStatement)start).getBody();
	} else if (start instanceof WhileStatement) {
		stmt= ((WhileStatement)start).getBody();
	} else if (start instanceof EnhancedForStatement) {
		stmt= ((EnhancedForStatement)start).getBody();
	}
	if (start != null && start.getParent() instanceof LabeledStatement) {
		LabeledStatement labeledStatement= (LabeledStatement)start.getParent();
		fEnclosingLoopLabel= labeledStatement.getLabel();
	}
	return stmt;
}
 
Example 3
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 4
public boolean containsAncestor(ASTNode name) {
//		System.out.println(
//				"Checking " + getASTNode() + ", " + getASTNode().hashCode() + " vs " + 
//				name + ", " + name.hashCode());
		if(parent == null) {
			return false;	
		}
		
		if(same(parent.getASTNode(), name)) {
			logError(			
				getParent().getASTNode() + " at " + parent.getASTNode().getStartPosition() + " and " +
				name + " at " + name.getStartPosition() + 
				" matched."
				);
			return true;
		} else {
			return getParent().containsAncestor(name);
		}
	}
 
Example 5
@Override
public boolean consumes(SemanticToken token) {

	// 1: match types
	SimpleName name = token.getNode();
	ASTNode node = name.getParent();
	int nodeType = node.getNodeType();
	if (nodeType != ASTNode.SIMPLE_TYPE && nodeType != ASTNode.QUALIFIED_TYPE && nodeType != ASTNode.QUALIFIED_NAME && nodeType != ASTNode.TYPE_DECLARATION) {
		return false;
	}
	while (nodeType == ASTNode.QUALIFIED_NAME) {
		node = node.getParent();
		nodeType = node.getNodeType();
		if (nodeType == ASTNode.IMPORT_DECLARATION) {
			return false;
		}
	}

	// 2: match interfaces
	IBinding binding = token.getBinding();
	return binding instanceof ITypeBinding && ((ITypeBinding) binding).isInterface();
}
 
Example 6
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 7
Source Project: JDeodorant   Source File: ControlVariable.java    License: MIT License 6 votes vote down vote up
private static List<Expression> removeExpressionsInAConditionalExpression(List<Expression> expressions, Statement containingStatement)
{
	ListIterator<Expression> it = expressions.listIterator();
	while (it.hasNext())
	{
		Expression currentUpdater = it.next();
		ASTNode parent = currentUpdater.getParent();
		while (parent != null && !parent.equals(containingStatement))
		{
			if (parent instanceof ConditionalExpression)
			{
				it.remove();
				break;
			}
			parent = parent.getParent();
		}
	}
	return expressions;
}
 
Example 8
Source Project: eclipse.jdt.ls   Source File: RefactorProcessor.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private boolean getExtractMethodProposal(CodeActionParams params, IInvocationContext context, ASTNode coveringNode, boolean problemsAtLocation, Collection<ChangeCorrectionProposal> proposals) throws CoreException {
	if (proposals == null) {
		return false;
	}

	CUCorrectionProposal proposal = null;
	if (this.preferenceManager.getClientPreferences().isAdvancedExtractRefactoringSupported()) {
		proposal = RefactorProposalUtility.getExtractMethodCommandProposal(params, context, coveringNode, problemsAtLocation);
	} else {
		proposal = RefactorProposalUtility.getExtractMethodProposal(params, context, coveringNode, problemsAtLocation);
	}

	if (proposal == null) {
		return false;
	}

	proposals.add(proposal);
	return true;
}
 
Example 9
public static IMethodBinding resolveBinding(ASTNode invocation) {
	switch (invocation.getNodeType()) {
		case ASTNode.METHOD_INVOCATION:
			return ((MethodInvocation)invocation).resolveMethodBinding();
		case ASTNode.SUPER_METHOD_INVOCATION:
			return ((SuperMethodInvocation)invocation).resolveMethodBinding();
			
		case ASTNode.CONSTRUCTOR_INVOCATION:
			return ((ConstructorInvocation)invocation).resolveConstructorBinding();
		case ASTNode.SUPER_CONSTRUCTOR_INVOCATION:
			return ((SuperConstructorInvocation)invocation).resolveConstructorBinding();
			
		case ASTNode.CLASS_INSTANCE_CREATION:
			return ((ClassInstanceCreation)invocation).resolveConstructorBinding();
		case ASTNode.ENUM_CONSTANT_DECLARATION:
			return ((EnumConstantDeclaration)invocation).resolveConstructorBinding();
			
		default:
			throw new IllegalArgumentException(invocation.toString());
	}
}
 
Example 10
private void replaceSelectedExpressionWithTempDeclaration() throws CoreException {
	ASTRewrite rewrite= fCURewrite.getASTRewrite();
	Expression selectedExpression= getSelectedExpression().getAssociatedExpression(); // whole expression selected

	Expression initializer= (Expression) rewrite.createMoveTarget(selectedExpression);
	ASTNode replacement= createTempDeclaration(initializer); // creates a VariableDeclarationStatement

	ExpressionStatement parent= (ExpressionStatement) selectedExpression.getParent();
	if (ASTNodes.isControlStatementBody(parent.getLocationInParent())) {
		Block block= rewrite.getAST().newBlock();
		block.statements().add(replacement);
		replacement= block;

	}
	rewrite.replace(parent, replacement, fCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractTempRefactoring_declare_local_variable));
}
 
Example 11
@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 12
private VariableDeclarationFragment addFieldDeclaration(ASTRewrite rewrite, ASTNode newTypeDecl, int modifiers, Expression expression, ASTNode nodeToAssign, ITypeBinding typeBinding,
		int index) {
	if (fExistingFragment != null) {
		return fExistingFragment;
	}

	ChildListPropertyDescriptor property= ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
	List<BodyDeclaration> decls= ASTNodes.getBodyDeclarations(newTypeDecl);
	AST ast= newTypeDecl.getAST();
	String[] varNames= suggestFieldNames(typeBinding, expression, modifiers, nodeToAssign);
	for (int i= 0; i < varNames.length; i++) {
		addLinkedPositionProposal(KEY_NAME + index, varNames[i]);
	}
	String varName= varNames[0];

	VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment();
	newDeclFrag.setName(ast.newSimpleName(varName));

	FieldDeclaration newDecl= ast.newFieldDeclaration(newDeclFrag);

	Type type= evaluateType(ast, nodeToAssign, typeBinding, KEY_TYPE + index, TypeLocation.FIELD);
	newDecl.setType(type);
	newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers));

	ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(getLinkedProposalModel(), rewrite, newDecl.modifiers(), false, ModifierCorrectionSubProcessor.KEY_MODIFIER + index);

	int insertIndex= findFieldInsertIndex(decls, nodeToAssign.getStartPosition()) + index;
	rewrite.getListRewrite(newTypeDecl, property).insertAt(newDecl, insertIndex, null);

	return newDeclFrag;
}
 
Example 13
private ASTNode getNodeToInsertBefore(ListRewrite rewriter) {
	if (fInsertPos != -1) {
		List<?> members= rewriter.getOriginalList();
		for (int i= 0; i < members.size(); i++) {
			ASTNode curr= (ASTNode) members.get(i);
			if (curr.getStartPosition() >= fInsertPos) {
				return curr;
			}
		}
	}
	return null;
}
 
Example 14
public static void addFallThroughProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (selectedNode instanceof SwitchCase && selectedNode.getLocationInParent() == SwitchStatement.STATEMENTS_PROPERTY) {
		AST ast= selectedNode.getAST();
		ASTNode parent= selectedNode.getParent();

		// insert break:
		ASTRewrite rewrite= ASTRewrite.create(ast);
		ListRewrite listRewrite= rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY);
		listRewrite.insertBefore(ast.newBreakStatement(), selectedNode, null);

		String label= CorrectionMessages.LocalCorrectionsSubProcessor_insert_break_statement;
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_BREAK_STATEMENT, image);
		proposals.add(proposal);

		// insert //$FALL-THROUGH$:
		rewrite= ASTRewrite.create(ast);
		rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer());
		listRewrite= rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY);
		ASTNode fallThroughComment= rewrite.createStringPlaceholder("//$FALL-THROUGH$", ASTNode.EMPTY_STATEMENT); //$NON-NLS-1$
		listRewrite.insertBefore(fallThroughComment, selectedNode, null);

		label= CorrectionMessages.LocalCorrectionsSubProcessor_insert_fall_through;
		image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_FALL_THROUGH, image);
		proposals.add(proposal);
	}
}
 
Example 15
/**
 * Creates the type parameters of the new supertype.
 *
 * @param targetRewrite
 *            the target compilation unit rewrite
 * @param subType
 *            the subtype
 * @param sourceDeclaration
 *            the type declaration of the source type
 * @param targetDeclaration
 *            the type declaration of the target type
 */
protected final void createTypeParameters(final ASTRewrite targetRewrite, final IType subType, final AbstractTypeDeclaration sourceDeclaration, final AbstractTypeDeclaration targetDeclaration) {
	Assert.isNotNull(targetRewrite);
	Assert.isNotNull(sourceDeclaration);
	Assert.isNotNull(targetDeclaration);
	if (sourceDeclaration instanceof TypeDeclaration) {
		TypeParameter parameter= null;
		final ListRewrite rewrite= targetRewrite.getListRewrite(targetDeclaration, TypeDeclaration.TYPE_PARAMETERS_PROPERTY);
		for (final Iterator<TypeParameter> iterator= ((TypeDeclaration) sourceDeclaration).typeParameters().iterator(); iterator.hasNext();) {
			parameter= iterator.next();
			rewrite.insertLast(ASTNode.copySubtree(targetRewrite.getAST(), parameter), null);
			ImportRewriteUtil.collectImports(subType.getJavaProject(), sourceDeclaration, fTypeBindings, fStaticBindings, false);
		}
	}
}
 
Example 16
Source Project: eclipse.jdt.ls   Source File: SnippetFinder.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected boolean visitNode(ASTNode node) {
	if (matches(node)) {
		return false;
	} else if (!isResetted()) {
		reset();
		if (matches(node)) {
			return false;
		}
	}
	return true;
}
 
Example 17
private RefactoringStatus checkClashesInConstructors() {
	Assert.isTrue(fInitializeIn == INITIALIZE_IN_CONSTRUCTOR);
	Assert.isTrue(!isDeclaredInAnonymousClass());
	final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) getMethodDeclaration().getParent();
	if (declaration instanceof TypeDeclaration) {
		MethodDeclaration[] methods= ((TypeDeclaration) declaration).getMethods();
		for (int i= 0; i < methods.length; i++) {
			MethodDeclaration method= methods[i];
			if (!method.isConstructor())
				continue;
			NameCollector nameCollector= new NameCollector(method) {
				@Override
				protected boolean visitNode(ASTNode node) {
					return true;
				}
			};
			method.accept(nameCollector);
			List<String> names= nameCollector.getNames();
			if (names.contains(fFieldName)) {
				String[] keys= { BasicElementLabels.getJavaElementName(fFieldName), BindingLabelProvider.getBindingLabel(method.resolveBinding(), JavaElementLabels.ALL_FULLY_QUALIFIED)};
				String msg= Messages.format(RefactoringCoreMessages.PromoteTempToFieldRefactoring_Name_conflict, keys);
				return RefactoringStatus.createFatalErrorStatus(msg);
			}
		}
	}
	return null;
}
 
Example 18
public static JavaValidationResult validateCompilationUnit(ASTNode ast) {
  ICompilationUnit cu = JavaASTUtils.getCompilationUnit(ast);

  // If the compilation unit is not on the build classpath, return an empty
  // list of problems/JSNI Java references.
  if (!cu.getJavaProject().isOnClasspath(cu)) {
    return new JavaValidationResult();
  }

  // Walk the Java AST to find problems and Java references in JSNI blocks
  JavaValidationVisitor visitor = new JavaValidationVisitor();
  ast.accept(visitor);

  /*
   * Index the Java references in the compilation unit, but only if we're
   * doing a reconcile from the Java Editor or from our direct call from
   * JsniReferenceChange.perform method. There will be no working copy owner
   * in both of these cases. However, during the pre-refactoring checks, the
   * JDT will call reconcile on a working copy with a JavaRenameProcessor as
   * the working copy owner. If we index the Java refs during that reconcile,
   * which is based on a particular JDT refactoring, we may have inaccurate
   * offsets when we go to calculate the edits for our own refactoring.
   */
  if (cu.getOwner() == null) {
    List<JsniJavaRef> jsniJavaRefs = visitor.getValidationResult().getJavaRefs();
    indexJavaRefs(cu, jsniJavaRefs);
  }

  return visitor.getValidationResult();
}
 
Example 19
/**
 * Replaces the given node in this rewriter. The replacement node
 * must either be brand new (not part of the original AST) or a placeholder
 * node (for example, one created by {@link #createCopyTarget(ASTNode)}
 * or {@link #createStringPlaceholder(String, int)}). The AST itself
    * is not actually modified in any way; rather, the rewriter just records
    * a note that this node has been replaced.
 *
 * @param node the node being replaced. The node can either be an original node in the AST
 * or (since 3.4) a new node already inserted or used as replacement in this AST rewriter.
 * @param replacement the replacement node, or <code>null</code> if no
 * replacement
 * @param editGroup the edit group in which to collect the corresponding
 * text edits, or <code>null</code> if ungrouped
 * @throws IllegalArgumentException if the node is null, or if the node is not part
 * of this rewriter's AST, or if the replacement node is not a new node (or
    * placeholder), or if the described modification is otherwise invalid
 */
public final void replace(ASTNode node, ASTNode replacement, TextEditGroup editGroup) {
	if (node == null) {
		throw new IllegalArgumentException();
	}

	StructuralPropertyDescriptor property;
	ASTNode parent;
	if (RewriteEventStore.isNewNode(node)) { // replace a new node, bug 164862
		PropertyLocation location= this.eventStore.getPropertyLocation(node, RewriteEventStore.NEW);
		if (location != null) {
			property= location.getProperty();
			parent= location.getParent();
		} else {
			throw new IllegalArgumentException("Node is not part of the rewriter's AST"); //$NON-NLS-1$
		}
	} else {
		property= node.getLocationInParent();
		parent= node.getParent();
	}

	if (property.isChildListProperty()) {
		getListRewrite(parent, (ChildListPropertyDescriptor) property).replace(node, replacement, editGroup);
	} else {
		set(parent, property, replacement, editGroup);
	}
}
 
Example 20
@Override
public boolean consumes(SemanticToken token) {

	// 1: match types in type parameter lists
	SimpleName name = token.getNode();
	ASTNode node = name.getParent();
	if (node.getNodeType() != ASTNode.SIMPLE_TYPE && node.getNodeType() != ASTNode.TYPE_PARAMETER) {
		return false;
	}

	// 2: match generic type variable references
	IBinding binding = token.getBinding();
	return binding instanceof ITypeBinding && ((ITypeBinding) binding).isTypeVariable();
}
 
Example 21
Source Project: xtext-xtend   Source File: JavaASTFlattener.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(final ThrowStatement node) {
  this.appendToBuffer("throw ");
  node.getExpression().accept(this);
  ASTNode _parent = node.getParent();
  boolean _not = (!(_parent instanceof Block));
  if (_not) {
    this.appendToBuffer(";");
  }
  return false;
}
 
Example 22
/**
 * @return <code>null</code> if the selection is invalid or does not cover a temp
 * declaration or reference.
 */
public static VariableDeclaration findTempDeclaration(CompilationUnit cu, int selectionOffset, int selectionLength) {
	TempSelectionAnalyzer analyzer= new TempSelectionAnalyzer(selectionOffset, selectionLength);
	cu.accept(analyzer);

	ASTNode[] selected= analyzer.getSelectedNodes();
	if (selected == null || selected.length != 1)
		return null;

	ASTNode selectedNode= selected[0];
	if (selectedNode instanceof VariableDeclaration)
		return (VariableDeclaration)selectedNode;

	if (selectedNode instanceof Name){
		Name reference= (Name)selectedNode;
		IBinding binding= reference.resolveBinding();
		if (binding == null)
			return null;
		ASTNode declaringNode= cu.findDeclaringNode(binding);
		if (declaringNode instanceof VariableDeclaration)
			return (VariableDeclaration)declaringNode;
		else
			return null;
	} else if (selectedNode instanceof VariableDeclarationStatement){
		VariableDeclarationStatement vds= (VariableDeclarationStatement)selectedNode;
		if (vds.fragments().size() != 1)
			return null;
		return (VariableDeclaration)vds.fragments().get(0);
	}
	return null;
}
 
Example 23
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
	RefactoringStatus result= Checks.validateModifiesFiles(
		ResourceUtil.getFiles(new ICompilationUnit[]{fCu}),
		getValidationContext());
	if (result.hasFatalError())
		return result;

	initAST(pm);

	if (fTempDeclarationNode == null)
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_select_declaration);

	if (! Checks.isDeclaredIn(fTempDeclarationNode, MethodDeclaration.class))
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_only_declared_in_methods);

	if (isMethodParameter())
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_method_parameters);

	if (isTempAnExceptionInCatchBlock())
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_exceptions);

	ASTNode declaringType= ASTResolving.findParentType(fTempDeclarationNode);
	if (declaringType instanceof TypeDeclaration && ((TypeDeclaration) declaringType).isInterface())
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_interface_methods);
	
	result.merge(checkTempTypeForLocalTypeUsage());
	if (result.hasFatalError())
	    return result;

	checkTempInitializerForLocalTypeUsage();

	if (!fSelfInitializing)
		initializeDefaults();
	return result;
}
 
Example 24
Source Project: compiler   Source File: TreedMapper.java    License: Apache License 2.0 5 votes vote down vote up
private void getNotYetMappedAncestors(ASTNode node, ArrayList<ASTNode> ancestors) {
	ASTNode p = node.getParent();
	if (treeMap.get(p).isEmpty()) {
		ancestors.add(p);
		getNotYetMappedAncestors(p, ancestors);
	}
}
 
Example 25
private void setSuperType(TypeDeclaration declaration) {
      ClassInstanceCreation classInstanceCreation= (ClassInstanceCreation) fAnonymousInnerClassNode.getParent();
ITypeBinding binding= classInstanceCreation.resolveTypeBinding();
      if (binding == null)
          return;
Type newType= (Type) ASTNode.copySubtree(fAnonymousInnerClassNode.getAST(), classInstanceCreation.getType());
if (binding.getSuperclass().getQualifiedName().equals("java.lang.Object")) { //$NON-NLS-1$
          Assert.isTrue(binding.getInterfaces().length <= 1);
          if (binding.getInterfaces().length == 0)
              return;
          declaration.superInterfaceTypes().add(0, newType);
      } else {
          declaration.setSuperclassType(newType);
      }
  }
 
Example 26
Source Project: eclipse.jdt.ls   Source File: ASTNodeDeleteUtil.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private static ASTNode[] getNodesToDelete(IJavaElement element, CompilationUnit cuNode) throws JavaModelException {
	// fields are different because you don't delete the whole declaration but only a fragment of it
	if (element.getElementType() == IJavaElement.FIELD) {
		if (JdtFlags.isEnum((IField) element)) {
			return new ASTNode[] { ASTNodeSearchUtil.getEnumConstantDeclaration((IField) element, cuNode)};
		} else {
			return new ASTNode[] { ASTNodeSearchUtil.getFieldDeclarationFragmentNode((IField) element, cuNode)};
		}
	}
	if (element.getElementType() == IJavaElement.TYPE && ((IType) element).isLocal()) {
		IType type= (IType) element;
		if (type.isAnonymous()) {
			if (type.getParent().getElementType() == IJavaElement.FIELD) {
				EnumConstantDeclaration enumDecl= ASTNodeSearchUtil.getEnumConstantDeclaration((IField) element.getParent(), cuNode);
				if (enumDecl != null && enumDecl.getAnonymousClassDeclaration() != null)  {
					return new ASTNode[] { enumDecl.getAnonymousClassDeclaration() };
				}
			}
			ClassInstanceCreation creation= ASTNodeSearchUtil.getClassInstanceCreationNode(type, cuNode);
			if (creation != null) {
				if (creation.getLocationInParent() == ExpressionStatement.EXPRESSION_PROPERTY) {
					return new ASTNode[] { creation.getParent() };
				} else if (creation.getLocationInParent() == VariableDeclarationFragment.INITIALIZER_PROPERTY) {
					return new ASTNode[] { creation};
				}
				return new ASTNode[] { creation.getAnonymousClassDeclaration() };
			}
			return new ASTNode[0];
		} else {
			ASTNode[] nodes= ASTNodeSearchUtil.getDeclarationNodes(element, cuNode);
			// we have to delete the TypeDeclarationStatement
			nodes[0]= nodes[0].getParent();
			return nodes;
		}
	}
	return ASTNodeSearchUtil.getDeclarationNodes(element, cuNode);
}
 
Example 27
public boolean hasCorrectNesting(ASTNode node) {
	if (fNodes.size() == 0)
		return true;
	ASTNode parent= node.getParent();
	if(fNodes.get(0).getParent() != parent)
		return false;
	// Here we know that we have two elements. In this case the
	// parent must be a block or a switch statement. Otherwise a
	// snippet like "if (true) foo(); else foo();" would match
	// the pattern "foo(); foo();"
	int nodeType= parent.getNodeType();
	return nodeType == ASTNode.BLOCK || nodeType == ASTNode.SWITCH_STATEMENT;
}
 
Example 28
Source Project: compiler   Source File: TreedUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static char buildLabelForVector(ASTNode node) {
	char label = (char) node.getNodeType();
	if (node instanceof Expression) {
		if (node.getClass().getSimpleName().endsWith("Literal")) {
			return (char) (label | (node.toString().hashCode() << 7));
		}
		int type = node.getNodeType();
		switch (type) {
		case ASTNode.INFIX_EXPRESSION:
			return (char) (label | (((InfixExpression) node).getOperator().toString().hashCode() << 7));
		case ASTNode.SIMPLE_NAME:
			return (char) (label | (node.toString().hashCode() << 7));
		case ASTNode.POSTFIX_EXPRESSION:
			return (char) (label | (((PostfixExpression) node).getOperator().toString().hashCode() << 7));
		case ASTNode.PREFIX_EXPRESSION:
			return (char) (label | (((PrefixExpression) node).getOperator().toString().hashCode() << 7));
		default:
			break;
		}
	} else if (node instanceof Modifier) {
		return (char) (label | (node.toString().hashCode() << 7));
	} else if (node instanceof Type) {
		if (node instanceof PrimitiveType)
			return (char) (label | (node.toString().hashCode() << 7));
	} else if (node instanceof TextElement) {
		return (char) (label | (node.toString().hashCode() << 7));
	} else if (node instanceof TagElement) {
		String tag = ((TagElement) node).getTagName();
		if (tag != null)
			return (char) (label | (((TagElement) node).getTagName().hashCode() << 7));
	}
	return label;
}
 
Example 29
Source Project: gwt-eclipse-plugin   Source File: JavaASTUtils.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public static TypeDeclaration getEnclosingType(TypeDeclaration typeDecl) {
  ASTNode parent = typeDecl.getParent();
  if (parent instanceof TypeDeclaration) {
    return (TypeDeclaration) parent;
  }
  return null;
}
 
Example 30
/**
 * Convert the numeric id of a node to its textual representation.
 *
 * @param id
 * @return
 */
private final String nodeIdToString(final int id) {
	if (id == -1) {
		return "NONE";
	} else {
		return ASTNode.nodeClassForType(id).getSimpleName();
	}
}