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

The following examples show how to use org.eclipse.jdt.core.dom.ASTNode. 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: RefactorProcessor.java    From eclipse.jdt.ls with 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 #2
Source File: ExtractMethodAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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
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 #4
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@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 #5
Source File: JavaTypeDeclarationBindingExtractor.java    From codemining-core 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: NestedDefinitionLocation.java    From lapse-plus with GNU General Public License v3.0 6 votes vote down vote up
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 #7
Source File: SemanticHighlightings.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@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 #8
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 #9
Source File: ExtractTempRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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 #10
Source File: Invocations.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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 #11
Source File: ControlVariable.java    From JDeodorant with 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 #12
Source File: MethodRetriever.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Map<String, MethodDeclaration> getMethodNodes(
		final String file) throws Exception {
	final JavaASTExtractor astExtractor = new JavaASTExtractor(false);
	final MethodRetriever m = new MethodRetriever();
	final ASTNode cu = astExtractor.getBestEffortAstNode(file);
	cu.accept(m);
	return m.methods;
}
 
Example #13
Source File: JavaASTAnnotatedTokenizer.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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();
	}
}
 
Example #14
Source File: ExtendedCodeFormatter.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
@Override
protected void prepareWraps(int kind) {
	ASTNode astRoot = getField("astRoot", ASTNode.class);
	TokenManager tokenManager = getField("tokenManager", TokenManager.class);
	applyPreparators(Phase.PRE_WRAPPING, kind, astRoot, tokenManager);
	super.prepareWraps(kind);
	applyPreparators(Phase.POST_WRAPPING, kind, astRoot, tokenManager);
}
 
Example #15
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 #16
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static String getArgumentName(List<Expression> arguments, int index) {
	String def= String.valueOf(index + 1);

	ASTNode expr= arguments.get(index);
	if (expr.getLength() > 18) {
		return def;
	}
	ASTMatcher matcher= new ASTMatcher();
	for (int i= 0; i < arguments.size(); i++) {
		if (i != index && matcher.safeSubtreeMatch(expr, arguments.get(i))) {
			return def;
		}
	}
	return '\'' + BasicElementLabels.getJavaElementName(ASTNodes.asString(expr)) + '\'';
}
 
Example #17
Source File: JavaMethodDeclarationBindingExtractor.java    From api-mining with GNU General Public License v3.0 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 #18
Source File: NullAnnotationsCorrectionProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void addReturnAndArgumentTypeProposal(IInvocationContext context, IProblemLocation problem, ChangeKind changeKind, 
		Collection<ICommandAccess> proposals) {
	CompilationUnit astRoot= context.getASTRoot();
	ASTNode selectedNode= problem.getCoveringNode(astRoot);

	boolean isArgumentProblem= NullAnnotationsFix.isComplainingAboutArgument(selectedNode);
	if (isArgumentProblem || NullAnnotationsFix.isComplainingAboutReturn(selectedNode))
		addNullAnnotationInSignatureProposal(context, problem, proposals, changeKind, isArgumentProblem);
}
 
Example #19
Source File: SelfEncapsulateFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private boolean processCompilerError(RefactoringStatus result, ASTNode node) {
	Message[] messages = ASTNodes.getMessages(node, ASTNodes.INCLUDE_ALL_PARENTS);
	if (messages.length == 0) {
		return false;
	}
	result.addFatalError(Messages.format(RefactoringCoreMessages.SelfEncapsulateField_compiler_errors_field, new String[] { BasicElementLabels.getJavaElementName(fField.getElementName()), messages[0].getMessage() }));
	return true;
}
 
Example #20
Source File: JavaASTUtils.java    From gwt-eclipse-plugin with 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 #21
Source File: TreedUtils.java    From compiler with 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 #22
Source File: AssignToVariableAssistProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
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 #23
Source File: SnippetFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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 #24
Source File: ASTNodeDeleteUtil.java    From eclipse.jdt.ls with 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 #25
Source File: ConvertAnonymousToNestedRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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 File: IdentifierPerType.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
public static final void addToMap(
		final Map<String, RangeSet<Integer>> identifiers,
		final ASTNode node, final String identifier) {
	final int startPosition = node.getStartPosition();
	final Range<Integer> nodeRange = Range.closedOpen(startPosition,
			startPosition + node.getLength());

	RangeSet<Integer> idRanges = identifiers.get(identifier);
	if (idRanges == null) {
		idRanges = TreeRangeSet.create();
		identifiers.put(identifier, idRanges);
	}

	idRanges.add(nodeRange);
}
 
Example #27
Source File: TreedMapper.java    From compiler with 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 #28
Source File: AddUnimplementedMethodsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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 #29
Source File: HierarchyProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected static BodyDeclaration createPlaceholderForProtectedTypeDeclaration(final BodyDeclaration bodyDeclaration, final CompilationUnit declaringCuNode, final ICompilationUnit declaringCu, final ASTRewrite rewrite, final boolean removeIndentation) throws JavaModelException {
	String text= null;
	try {
		final ASTRewrite rewriter= ASTRewrite.create(bodyDeclaration.getAST());
		ModifierRewrite.create(rewriter, bodyDeclaration).setVisibility(Modifier.PROTECTED, null);
		final ITrackedNodePosition position= rewriter.track(bodyDeclaration);
		final IDocument document= new Document(declaringCu.getBuffer().getText(declaringCuNode.getStartPosition(), declaringCuNode.getLength()));
		rewriter.rewriteAST(document, declaringCu.getJavaProject().getOptions(true)).apply(document, TextEdit.UPDATE_REGIONS);
		text= document.get(position.getStartPosition(), position.getLength());
	} catch (BadLocationException exception) {
		text= getNewText(bodyDeclaration, declaringCu, removeIndentation);
	}
	return (BodyDeclaration) rewrite.createStringPlaceholder(text, ASTNode.TYPE_DECLARATION);
}
 
Example #30
Source File: PromoteTempToFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@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;
}