Java Code Examples for org.eclipse.jdt.core.dom.NodeFinder#perform()

The following examples show how to use org.eclipse.jdt.core.dom.NodeFinder#perform() . 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: SelfEncapsulateFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
	if (fVisibility < 0)
		fVisibility= (fField.getFlags() & (Flags.AccPublic | Flags.AccProtected | Flags.AccPrivate));
	RefactoringStatus result=  new RefactoringStatus();
	result.merge(Checks.checkAvailability(fField));
	if (result.hasFatalError())
		return result;
	fRoot= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(fField.getCompilationUnit(), true, pm);
	ISourceRange sourceRange= fField.getNameRange();
	ASTNode node= NodeFinder.perform(fRoot, sourceRange.getOffset(), sourceRange.getLength());
	if (node == null) {
		return mappingErrorFound(result, node);
	}
	fFieldDeclaration= (VariableDeclarationFragment)ASTNodes.getParent(node, VariableDeclarationFragment.class);
	if (fFieldDeclaration == null) {
		return mappingErrorFound(result, node);
	}
	if (fFieldDeclaration.resolveBinding() == null) {
		if (!processCompilerError(result, node))
			result.addFatalError(RefactoringCoreMessages.SelfEncapsulateField_type_not_resolveable);
		return result;
	}
	computeUsedNames();
	return result;
}
 
Example 2
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static ASTNode getHoveredASTNode(ITypeRoot typeRoot, IRegion region) {
	if (typeRoot == null || region == null) {
		return null;
	}

	CompilationUnit unit = SharedASTProviderCore.getAST(typeRoot, SharedASTProviderCore.WAIT_ACTIVE_ONLY, null);
	if (unit == null) {
		return null;
	}

	return NodeFinder.perform(unit, region.getOffset(), region.getLength());
}
 
Example 3
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean isSideEffectFree(SimpleName simpleName, CompilationUnit completeRoot) {
	SimpleName nameNode= (SimpleName) NodeFinder.perform(completeRoot, simpleName.getStartPosition(), simpleName.getLength());
	SimpleName[] references= LinkedNodeFinder.findByBinding(completeRoot, nameNode.resolveBinding());
	for (int i= 0; i < references.length; i++) {
		if (hasSideEffect(references[i]))
			return false;
	}
	return true;
}
 
Example 4
Source File: ASTNodeSearchUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static ASTNode findNode(SearchMatch searchResult, CompilationUnit cuNode) {
	ASTNode selectedNode= NodeFinder.perform(cuNode, searchResult.getOffset(), searchResult.getLength());
	if (selectedNode == null) {
		return null;
	}
	if (selectedNode.getParent() == null) {
		return null;
	}
	return selectedNode;
}
 
Example 5
Source File: JavaHistoryActionImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
final ASTNode getBodyContainer(CompilationUnit root, IMember parent) throws JavaModelException {
	ISourceRange sourceRange= parent.getNameRange();
	ASTNode parentNode= NodeFinder.perform(root, sourceRange);
	do {
		if (parentNode instanceof TypeDeclaration || parentNode instanceof EnumDeclaration || parentNode instanceof AnnotationTypeDeclaration)
			return parentNode;
		parentNode= parentNode.getParent();
	} while (parentNode != null);
	return null;
}
 
Example 6
Source File: RenameLocalVariableProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void initAST() {
	if (!fIsComposite)
		fCompilationUnitNode= RefactoringASTParser.parseWithASTProvider(fCu, true, null);
	ISourceRange sourceRange= fLocalVariable.getNameRange();
	ASTNode name= NodeFinder.perform(fCompilationUnitNode, sourceRange);
	if (name == null)
		return;
	if (name.getParent() instanceof VariableDeclaration)
		fTempDeclarationNode= (VariableDeclaration) name.getParent();
}
 
Example 7
Source File: ChangeTypeRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ASTNode findDeclaration(CompilationUnit root, ConstraintVariable cv) throws JavaModelException {

		if (fFieldBinding != null){
			IField f= (IField) fFieldBinding.getJavaElement();
			return ASTNodeSearchUtil.getFieldDeclarationNode(f, root);
		}

		if (cv instanceof ExpressionVariable){
			for (Iterator<ITypeConstraint> iter= fAllConstraints.iterator(); iter.hasNext();) {
				ITypeConstraint constraint= iter.next();
				if (constraint.isSimpleTypeConstraint()){
					SimpleTypeConstraint stc= (SimpleTypeConstraint)constraint;
					if (stc.isDefinesConstraint() && stc.getLeft().equals(cv)){
						ConstraintVariable right= stc.getRight();
						if (right instanceof TypeVariable){
							TypeVariable typeVariable= (TypeVariable)right;
							return NodeFinder.perform(root, typeVariable.getCompilationUnitRange().getSourceRange());
						}
					}
				}
			}
		} else if (cv instanceof ReturnTypeVariable) {
			ReturnTypeVariable rtv= (ReturnTypeVariable) cv;
			IMethodBinding mb= rtv.getMethodBinding();
			IMethod im= (IMethod) mb.getJavaElement();
			return ASTNodeSearchUtil.getMethodDeclarationNode(im, root);
		}
		return null;
	}
 
Example 8
Source File: ExtractMethodAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(Assignment node) {
	boolean result = super.visit(node);
	Selection selection = getSelection();
	ASTNode selectedNode = NodeFinder.perform(node, selection.getOffset(), selection.getLength());
	if ((selectedNode != null && SnippetFinder.isLeftHandSideOfAssignment(selectedNode)) || (selection.covers(node.getLeftHandSide()) && !selection.covers(node.getRightHandSide()))) {
		invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_leftHandSideOfAssignment, JavaStatusContext.create(fCUnit, node));
		return false;
	}
	return result;
}
 
Example 9
Source File: SelfEncapsulateFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
	if (fVisibility < 0) {
		fVisibility = (fField.getFlags() & (Flags.AccPublic | Flags.AccProtected | Flags.AccPrivate));
	}
	RefactoringStatus result = new RefactoringStatus();
	result.merge(Checks.checkAvailability(fField));
	if (result.hasFatalError()) {
		return result;
	}
	fRoot = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(fField.getCompilationUnit(), true, pm);
	ISourceRange sourceRange = fField.getNameRange();
	ASTNode node = NodeFinder.perform(fRoot, sourceRange.getOffset(), sourceRange.getLength());
	if (node == null) {
		return mappingErrorFound(result, node);
	}
	fFieldDeclaration = ASTNodes.getParent(node, VariableDeclarationFragment.class);
	if (fFieldDeclaration == null) {
		return mappingErrorFound(result, node);
	}
	if (fFieldDeclaration.resolveBinding() == null) {
		if (!processCompilerError(result, node)) {
			result.addFatalError(RefactoringCoreMessages.SelfEncapsulateField_type_not_resolveable);
		}
		return result;
	}
	computeUsedNames();
	return result;
}
 
Example 10
Source File: NLSKeyHyperlinkDetector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
	ITextEditor textEditor= (ITextEditor)getAdapter(ITextEditor.class);
	if (region == null || textEditor == null)
		return null;

	IEditorSite site= textEditor.getEditorSite();
	if (site == null)
		return null;

	ITypeRoot javaElement= getInputJavaElement(textEditor);
	if (javaElement == null)
		return null;

	CompilationUnit ast= SharedASTProvider.getAST(javaElement, SharedASTProvider.WAIT_NO, null);
	if (ast == null)
		return null;

	ASTNode node= NodeFinder.perform(ast, region.getOffset(), 1);
	if (!(node instanceof StringLiteral)  && !(node instanceof SimpleName))
		return null;

	if (node.getLocationInParent() == QualifiedName.QUALIFIER_PROPERTY)
		return null;

	IRegion nlsKeyRegion= new Region(node.getStartPosition(), node.getLength());
	AccessorClassReference ref= NLSHintHelper.getAccessorClassReference(ast, nlsKeyRegion);
	if (ref == null)
		return null;
	String keyName= null;
	if (node instanceof StringLiteral) {
		keyName= ((StringLiteral)node).getLiteralValue();
	} else {
		keyName= ((SimpleName)node).getIdentifier();
	}
	if (keyName != null)
		return new IHyperlink[] {new NLSKeyHyperlink(nlsKeyRegion, keyName, ref, textEditor)};

	return null;
}
 
Example 11
Source File: IntroduceFactoryRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Look "in the vicinity" of the given range to find the <code>ClassInstanceCreation</code>
 * node that this search hit identified. Necessary because the <code>SearchEngine</code>
 * doesn't always cough up text extents that <code>NodeFinder.perform()</code> agrees with.
 * @param start
 * @param length
 * @param unitAST
 * @return return a {@link ClassInstanceCreation} or a {@link MethodRef} or <code>null</code> if this is really a constructor->constructor call (e.g. "this(...)")
 * @throws CoreException
 */
private ASTNode getCtorCallAt(int start, int length, CompilationUnit unitAST) throws CoreException {
	ICompilationUnit unitHandle= ASTCreator.getCu(unitAST);
	ASTNode node= NodeFinder.perform(unitAST, start, length);

	if (node == null)
		throw new CoreException(JavaUIStatus.createError(IStatus.ERROR,
				Messages.format(RefactoringCoreMessages.IntroduceFactory_noASTNodeForConstructorSearchHit,
						new Object[] { Integer.toString(start), Integer.toString(start + length),
						    BasicElementLabels.getJavaCodeString(unitHandle.getSource().substring(start, start + length)),
							BasicElementLabels.getFileName(unitHandle) }),
				null));

	if (node instanceof ClassInstanceCreation) {
		if (((ClassInstanceCreation)node).getAnonymousClassDeclaration() != null) {
			// Cannot replace anonymous inner class, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=250660
			fConstructorVisibility= Modifier.PROTECTED;
			return null;
		}
		return node;
	} else if (node instanceof VariableDeclaration) {
		Expression	init= ((VariableDeclaration) node).getInitializer();

		if (init instanceof ClassInstanceCreation) {
			return init;
		} else if (init != null)
			throw new CoreException(JavaUIStatus.createError(IStatus.ERROR,
					Messages.format(RefactoringCoreMessages.IntroduceFactory_unexpectedInitializerNodeType,
							new Object[] { BasicElementLabels.getJavaCodeString(init.toString()), BasicElementLabels.getFileName(unitHandle) }),
					null));
		else
			throw new CoreException(JavaUIStatus.createError(IStatus.ERROR,
					Messages.format(RefactoringCoreMessages.IntroduceFactory_noConstructorCallNodeInsideFoundVarbleDecl,
							BasicElementLabels.getJavaCodeString(node.toString())),
					null));
	} else if (node instanceof ConstructorInvocation) {
		// This is a call we can bypass; it's from one constructor flavor
		// to another flavor on the same class.
		return null;
	} else if (node instanceof SuperConstructorInvocation) {
		// This is a call we can bypass; it's from one constructor flavor
		// to another flavor on the same class.
		fConstructorVisibility= Modifier.PROTECTED;
		return null;
	} else if (node instanceof ExpressionStatement) {
		Expression	expr= ((ExpressionStatement) node).getExpression();

		if (expr instanceof ClassInstanceCreation)
			return expr;
		else
			throw new CoreException(JavaUIStatus.createError(IStatus.ERROR,
					Messages.format(RefactoringCoreMessages.IntroduceFactory_unexpectedASTNodeTypeForConstructorSearchHit,
							new Object[] { BasicElementLabels.getJavaCodeString(expr.toString()), BasicElementLabels.getFileName(unitHandle) }),
					null));
	} else if (node instanceof SimpleName && (node.getParent() instanceof MethodDeclaration || node.getParent() instanceof AbstractTypeDeclaration)) {
		// We seem to have been given a hit for an implicit call to the base-class constructor.
		// Do nothing with this (implicit) call, but have to make sure we make the derived class
		// doesn't lose access to the base-class constructor (so make it 'protected', not 'private').
		fConstructorVisibility= Modifier.PROTECTED;
		return null;
	} else if (node instanceof MethodRef) {
		return node;
	} else
		throw new CoreException(JavaUIStatus.createError(IStatus.ERROR,
				Messages.format(RefactoringCoreMessages.IntroduceFactory_unexpectedASTNodeTypeForConstructorSearchHit,
						new Object[] { BasicElementLabels.getJavaElementName(node.getClass().getName() + "('" + node.toString() + "')"), BasicElementLabels.getFileName(unitHandle) }), //$NON-NLS-1$ //$NON-NLS-2$
				null));
}
 
Example 12
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private FieldDeclaration performFieldRewrite(IType type, ParameterObjectFactory pof, RefactoringStatus status) throws CoreException {
	fBaseCURewrite= new CompilationUnitRewrite(type.getCompilationUnit());
	SimpleName name= (SimpleName) NodeFinder.perform(fBaseCURewrite.getRoot(), type.getNameRange());
	TypeDeclaration typeNode= (TypeDeclaration) ASTNodes.getParent(name, ASTNode.TYPE_DECLARATION);
	ASTRewrite rewrite= fBaseCURewrite.getASTRewrite();
	int modifier= Modifier.PRIVATE;
	TextEditGroup removeFieldGroup= fBaseCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractClassRefactoring_group_remove_field);
	FieldDeclaration lastField= null;
	initializeDeclaration(typeNode);
	for (Iterator<FieldInfo> iter= fVariables.values().iterator(); iter.hasNext();) {
		FieldInfo pi= iter.next();
		if (isCreateField(pi)) {
			VariableDeclarationFragment vdf= pi.declaration;
			FieldDeclaration parent= (FieldDeclaration) vdf.getParent();
			if (lastField == null)
				lastField= parent;
			else if (lastField.getStartPosition() < parent.getStartPosition())
				lastField= parent;

			ListRewrite listRewrite= rewrite.getListRewrite(parent, FieldDeclaration.FRAGMENTS_PROPERTY);
			removeNode(vdf, removeFieldGroup, fBaseCURewrite);
			if (listRewrite.getRewrittenList().size() == 0) {
				removeNode(parent, removeFieldGroup, fBaseCURewrite);
			}

			if (fDescriptor.isCreateTopLevel()) {
				IVariableBinding binding= vdf.resolveBinding();
				ITypeRoot typeRoot= fBaseCURewrite.getCu();
				if (binding == null || binding.getType() == null){
					status.addFatalError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_fatal_error_cannot_resolve_binding, BasicElementLabels.getJavaElementName(pi.name)), JavaStatusContext.create(typeRoot, vdf));
				} else {
					ITypeBinding typeBinding= binding.getType();
					if (Modifier.isPrivate(typeBinding.getModifiers())){
						status.addError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_error_referencing_private_class, BasicElementLabels.getJavaElementName(typeBinding.getName())), JavaStatusContext.create(typeRoot, vdf));
					} else if (Modifier.isProtected(typeBinding.getModifiers())){
						ITypeBinding declaringClass= typeBinding.getDeclaringClass();
						if (declaringClass != null) {
							IPackageBinding package1= declaringClass.getPackage();
							if (package1 != null && !fDescriptor.getPackage().equals(package1.getName())){
								status.addError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_error_referencing_protected_class, new String[] {BasicElementLabels.getJavaElementName(typeBinding.getName()), BasicElementLabels.getJavaElementName(fDescriptor.getPackage())}), JavaStatusContext.create(typeRoot, vdf));
							}
						}
					}
				}
			}
			Expression initializer= vdf.getInitializer();
			if (initializer != null)
				pi.initializer= initializer;
			int modifiers= parent.getModifiers();
			if (!MemberVisibilityAdjustor.hasLowerVisibility(modifiers, modifier)){
				modifier= modifiers;
			}
		}
	}
	FieldDeclaration fieldDeclaration= createParameterObjectField(pof, typeNode, modifier);
	ListRewrite bodyDeclList= rewrite.getListRewrite(typeNode, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
	if (lastField != null)
		bodyDeclList.insertAfter(fieldDeclaration, lastField, null);
	else
		bodyDeclList.insertFirst(fieldDeclaration, null);
	return fieldDeclaration;
}
 
Example 13
Source File: UseSuperTypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected final void rewriteTypeOccurrences(final TextEditBasedChangeManager manager, final ASTRequestor requestor, final CompilationUnitRewrite rewrite, final ICompilationUnit unit, final CompilationUnit node, final Set<String> replacements, final IProgressMonitor monitor) throws CoreException {
	try {
		monitor.beginTask("", 100); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.ExtractInterfaceProcessor_creating);
		final Collection<ITypeConstraintVariable> collection= fTypeOccurrences.get(unit);
		if (collection != null && !collection.isEmpty()) {
			final IProgressMonitor subMonitor= new SubProgressMonitor(monitor, 100);
			try {
				subMonitor.beginTask("", collection.size() * 10); //$NON-NLS-1$
				subMonitor.setTaskName(RefactoringCoreMessages.ExtractInterfaceProcessor_creating);
				TType estimate= null;
				ISourceConstraintVariable variable= null;
				CompilationUnitRewrite currentRewrite= null;
				final ICompilationUnit sourceUnit= rewrite.getCu();
				if (sourceUnit.equals(unit))
					currentRewrite= rewrite;
				else
					currentRewrite= new CompilationUnitRewrite(fOwner, unit, node);
				for (final Iterator<ITypeConstraintVariable> iterator= collection.iterator(); iterator.hasNext();) {
					variable= iterator.next();
					estimate= (TType) variable.getData(SuperTypeConstraintsSolver.DATA_TYPE_ESTIMATE);
					if (estimate != null && variable instanceof ITypeConstraintVariable) {
						final ASTNode result= NodeFinder.perform(node, ((ITypeConstraintVariable) variable).getRange().getSourceRange());
						if (result != null)
							rewriteTypeOccurrence(estimate, currentRewrite, result, currentRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.SuperTypeRefactoringProcessor_update_type_occurrence, SET_SUPER_TYPE));
					}
					subMonitor.worked(10);
				}
				if (!sourceUnit.equals(unit)) {
					final TextChange change= currentRewrite.createChange(true);
					if (change != null)
						manager.manage(unit, change);
				}
			} finally {
				subMonitor.done();
			}
		}
	} finally {
		monitor.done();
	}
}
 
Example 14
Source File: TypeContextChecker.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static ITypeBinding[] resolveSuperInterfaces(String[] interfaces, IType typeHandle, StubTypeContext superInterfaceContext) {
	ITypeBinding[] result= new ITypeBinding[interfaces.length];

	int[] interfaceOffsets= new int[interfaces.length];
	StringBuffer cuString= new StringBuffer();
	cuString.append(superInterfaceContext.getBeforeString());
	int last= interfaces.length - 1;
	for (int i= 0; i <= last; i++) {
		interfaceOffsets[i]= cuString.length();
		cuString.append(interfaces[i]);
		if (i != last)
			cuString.append(", "); //$NON-NLS-1$
	}
	cuString.append(superInterfaceContext.getAfterString());

	try {
		ICompilationUnit wc= typeHandle.getCompilationUnit().getWorkingCopy(new WorkingCopyOwner() {/*subclass*/}, new NullProgressMonitor());
		try {
			wc.getBuffer().setContents(cuString.toString());
			CompilationUnit compilationUnit= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(wc, true);
			for (int i= 0; i <= last; i++) {
				ASTNode type= NodeFinder.perform(compilationUnit, interfaceOffsets[i], interfaces[i].length());
				if (type instanceof Type) {
					result[i]= handleBug84585(((Type) type).resolveBinding());
				} else if (type instanceof Name) {
					ASTNode parent= type.getParent();
					if (parent instanceof Type) {
						result[i]= handleBug84585(((Type) parent).resolveBinding());
					} else {
						throw new IllegalStateException();
					}
				} else {
					throw new IllegalStateException();
				}
			}
		} finally {
			wc.discardWorkingCopy();
		}
	} catch (JavaModelException e) {
		// won't happen
	}
	return result;
}
 
Example 15
Source File: ASTInformation.java    From JDeodorant with MIT License 4 votes vote down vote up
public ASTNode recoverASTNode() {
       CompilationUnit compilationUnit = CompilationUnitCache.getInstance().getCompilationUnit(iTypeRoot);
       ASTNode astNode = NodeFinder.perform(compilationUnit, startPosition, length);
	return astNode;
}
 
Example 16
Source File: PullUpRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void rewriteTypeOccurrences(final TextEditBasedChangeManager manager, final ASTRequestor requestor, final CompilationUnitRewrite rewrite, final ICompilationUnit unit, final CompilationUnit node, final Set<String> replacements, final IProgressMonitor monitor) throws CoreException {
	try {
		monitor.beginTask("", 100); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.ExtractInterfaceProcessor_creating);
		CompilationUnitRewrite currentRewrite= null;
		final CompilationUnitRewrite existingRewrite= fCompilationUnitRewrites.get(unit.getPrimary());
		final boolean isTouched= existingRewrite != null;
		if (isTouched)
			currentRewrite= existingRewrite;
		else
			currentRewrite= new CompilationUnitRewrite(unit, node);
		final Collection<ITypeConstraintVariable> collection= fTypeOccurrences.get(unit);
		if (collection != null && !collection.isEmpty()) {
			final IProgressMonitor subMonitor= new SubProgressMonitor(monitor, 100);
			try {
				subMonitor.beginTask("", collection.size() * 10); //$NON-NLS-1$
				subMonitor.setTaskName(RefactoringCoreMessages.ExtractInterfaceProcessor_creating);
				TType estimate= null;
				ISourceConstraintVariable variable= null;
				ITypeConstraintVariable constraint= null;
				for (final Iterator<ITypeConstraintVariable> iterator= collection.iterator(); iterator.hasNext();) {
					variable= iterator.next();
					if (variable instanceof ITypeConstraintVariable) {
						constraint= (ITypeConstraintVariable) variable;
						estimate= (TType) constraint.getData(SuperTypeConstraintsSolver.DATA_TYPE_ESTIMATE);
						if (estimate != null) {
							final CompilationUnitRange range= constraint.getRange();
							if (isTouched)
								rewriteTypeOccurrence(range, estimate, requestor, currentRewrite, node, replacements, currentRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.SuperTypeRefactoringProcessor_update_type_occurrence, SET_SUPER_TYPE));
							else {
								final ASTNode result= NodeFinder.perform(node, range.getSourceRange());
								if (result != null)
									rewriteTypeOccurrence(estimate, currentRewrite, result, currentRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.SuperTypeRefactoringProcessor_update_type_occurrence, SET_SUPER_TYPE));
							}
							subMonitor.worked(10);
						}
					}
				}
			} finally {
				subMonitor.done();
			}
		}
		if (!isTouched) {
			final TextChange change= currentRewrite.createChange(true);
			if (change != null)
				manager.manage(unit, change);
		}
	} finally {
		monitor.done();
	}
}
 
Example 17
Source File: InlineConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private Name[] extractReferenceNodes(SearchMatch[] searchResults, CompilationUnit cuNode) {
	Name[] references= new Name[searchResults.length];
	for (int i= 0; i < searchResults.length; i++)
		references[i]= (Name) NodeFinder.perform(cuNode, searchResults[i].getOffset(), searchResults[i].getLength());
	return references;
}
 
Example 18
Source File: RefactoringAnalyzeUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static SimpleName findSimpleNameNode(IRegion range, CompilationUnit cuNode) {
	ASTNode node = NodeFinder.perform(cuNode, range.getOffset(), range.getLength());
	return getSimpleName(node);
}
 
Example 19
Source File: IntroduceFactoryRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Determines what kind of AST node was selected, and returns an error status
 * if the kind of node is inappropriate for this refactoring.
 * @param pm
 * @return a RefactoringStatus indicating whether the selection is valid
 * @throws JavaModelException
 */
private RefactoringStatus checkSelection(IProgressMonitor pm) throws JavaModelException {
	try {
		pm.beginTask(RefactoringCoreMessages.IntroduceFactory_examiningSelection, 2);

		fSelectedNode= getTargetNode(fCUHandle, fSelectionStart, fSelectionLength);

		if (fSelectedNode == null)
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceFactory_notAConstructorInvocation);

		// getTargetNode() must return either a ClassInstanceCreation or a
		// constructor MethodDeclaration; nothing else.
		if (fSelectedNode instanceof ClassInstanceCreation) {
			ClassInstanceCreation classInstanceCreation= (ClassInstanceCreation)fSelectedNode;
			fCtorBinding= classInstanceCreation.resolveConstructorBinding();
		} else if (fSelectedNode instanceof MethodDeclaration) {
			MethodDeclaration methodDeclaration= (MethodDeclaration)fSelectedNode;
			fCtorBinding= methodDeclaration.resolveBinding();
		}

		if (fCtorBinding == null)
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceFactory_unableToResolveConstructorBinding);

		// If this constructor is of a generic type, get the generic version,
		// not some instantiation thereof.
		fCtorBinding= fCtorBinding.getMethodDeclaration();

		pm.worked(1);

		// We don't handle constructors of nested types at the moment
		if (fCtorBinding.getDeclaringClass().isNested())
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceFactory_unsupportedNestedTypes);

		ITypeBinding	ctorType= fCtorBinding.getDeclaringClass();
		IType			ctorOwningType= (IType) ctorType.getJavaElement();

		if (ctorOwningType.isBinary())
			// Can't modify binary CU; don't know what CU to put factory method
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceFactory_constructorInBinaryClass);
		if (ctorOwningType.isEnum())
			// Doesn't make sense to encapsulate enum constructors
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.IntroduceFactory_constructorInEnum);

		// Put the generated factory method inside the type that owns the constructor
		fFactoryUnitHandle= ctorOwningType.getCompilationUnit();
		fFactoryCU= getASTFor(fFactoryUnitHandle);

		Name	ctorOwnerName= (Name) NodeFinder.perform(fFactoryCU, ctorOwningType.getNameRange());

		fCtorOwningClass= (AbstractTypeDeclaration) ASTNodes.getParent(ctorOwnerName, AbstractTypeDeclaration.class);
		fFactoryOwningClass= fCtorOwningClass;

		pm.worked(1);

		if (fNewMethodName == null)
			return setNewMethodName("create" + fCtorBinding.getName());//$NON-NLS-1$
		else
			return new RefactoringStatus();
	} finally {
		pm.done();
	}
}
 
Example 20
Source File: JavadocView.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Returns the constant value for a field that is referenced by the currently active type. This
 * method does may not run in the main UI thread.
 * 
 * @param activeType the type that is currently active
 * @param field the field that is being referenced (usually not declared in
 *            <code>activeType</code>)
 * @param selection the region in <code>activeType</code> that contains the field reference
 * @param monitor a progress monitor
 * 
 * @return the constant value for the given field or <code>null</code> if none
 * @since 3.4
 */
private static Object getConstantValueFromActiveEditor(ITypeRoot activeType, IField field, ITextSelection selection, IProgressMonitor monitor) {
	CompilationUnit unit= SharedASTProvider.getAST(activeType, SharedASTProvider.WAIT_ACTIVE_ONLY, monitor);
	if (unit == null)
		return null;

	ASTNode node= NodeFinder.perform(unit, selection.getOffset(), selection.getLength());
	return JavadocHover.getVariableBindingConstValue(node, field);
}