org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser Java Examples

The following examples show how to use org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser. 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: SuperTypeConstraintsCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public final void endVisit(final QualifiedName node) {
	final ASTNode parent= node.getParent();
	final Name qualifier= node.getQualifier();
	IBinding binding= qualifier.resolveBinding();
	if (binding instanceof ITypeBinding) {
		final ConstraintVariable2 variable= fModel.createTypeVariable((ITypeBinding) binding, new CompilationUnitRange(RefactoringASTParser.getCompilationUnit(node), new SourceRange(qualifier.getStartPosition(), qualifier.getLength())));
		if (variable != null)
			qualifier.setProperty(PROPERTY_CONSTRAINT_VARIABLE, variable);
	}
	binding= node.getName().resolveBinding();
	if (binding instanceof IVariableBinding && !(parent instanceof ImportDeclaration))
		endVisit((IVariableBinding) binding, qualifier, node);
	else if (binding instanceof ITypeBinding && parent instanceof MethodDeclaration)
		endVisit((ITypeBinding) binding, node);
}
 
Example #2
Source File: ConvertAnonymousToNestedRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void initAST(IProgressMonitor pm) {
   	if (fCompilationUnitNode == null) {
   		fCompilationUnitNode= RefactoringASTParser.parseWithASTProvider(fCu, true, pm);
   	}
   	if (fAnonymousInnerClassNode == null) {
   		fAnonymousInnerClassNode= getAnonymousInnerClass(NodeFinder.perform(fCompilationUnitNode, fSelectionStart, fSelectionLength));
   	}
	if (fAnonymousInnerClassNode != null) {
		final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) ASTNodes.getParent(fAnonymousInnerClassNode, AbstractTypeDeclaration.class);
		if (declaration instanceof TypeDeclaration) {
			final AbstractTypeDeclaration[] nested= ((TypeDeclaration) declaration).getTypes();
			fClassNamesUsed= new HashSet<String>(nested.length);
			for (int index= 0; index < nested.length; index++)
				fClassNamesUsed.add(nested[index].getName().getIdentifier());
		} else
			fClassNamesUsed= Collections.emptySet();
	}
}
 
Example #3
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private RefactoringStatus checkConstructorParameterNames() {
	RefactoringStatus result= new RefactoringStatus();
	CompilationUnit cuNode= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(fType.getCompilationUnit(), false);
	MethodDeclaration[] nodes= getConstructorDeclarationNodes(findTypeDeclaration(fType, cuNode));
	for (int i= 0; i < nodes.length; i++) {
		MethodDeclaration constructor= nodes[i];
		for (Iterator<SingleVariableDeclaration> iter= constructor.parameters().iterator(); iter.hasNext();) {
			SingleVariableDeclaration param= iter.next();
			if (fEnclosingInstanceFieldName.equals(param.getName().getIdentifier())) {
				String[] keys= new String[] { BasicElementLabels.getJavaElementName(param.getName().getIdentifier()), BasicElementLabels.getJavaElementName(fType.getElementName())};
				String msg= Messages.format(RefactoringCoreMessages.MoveInnerToTopRefactoring_name_used, keys);
				result.addError(msg, JavaStatusContext.create(fType.getCompilationUnit(), param));
			}
		}
	}
	return result;
}
 
Example #4
Source File: ChangeUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static void convertMoveCompilationUnitChange(WorkspaceEdit edit, MoveCompilationUnitChange change) throws JavaModelException {
	IPackageFragment newPackage = change.getDestinationPackage();
	ICompilationUnit unit = change.getCu();
	CompilationUnit astCU = RefactoringASTParser.parseWithASTProvider(unit, true, new NullProgressMonitor());
	ASTRewrite rewrite = ASTRewrite.create(astCU.getAST());

	IPackageDeclaration[] packDecls = unit.getPackageDeclarations();
	String oldPackageName = packDecls.length > 0 ? packDecls[0].getElementName() : "";
	if (!Objects.equals(oldPackageName, newPackage.getElementName())) {
		// update the package declaration
		if (updatePackageStatement(astCU, newPackage.getElementName(), rewrite, unit)) {
			convertTextEdit(edit, unit, rewrite.rewriteAST());
		}
	}

	RenameFile cuResourceChange = new RenameFile();
	cuResourceChange.setOldUri(JDTUtils.toURI(unit));
	IPath newCUPath = newPackage.getResource().getLocation().append(unit.getPath().lastSegment());
	String newUri = ResourceUtils.fixURI(newCUPath.toFile().toURI());
	cuResourceChange.setNewUri(newUri);
	edit.getDocumentChanges().add(Either.forRight(cuResourceChange));
}
 
Example #5
Source File: OverrideMethodsOperation.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static TextEdit addOverridableMethods(IType type, OverridableMethod[] overridableMethods) {
	if (type == null || type.getCompilationUnit() == null || overridableMethods == null || overridableMethods.length == 0) {
		return null;
	}

	RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL);
	CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true);
	try {
		ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
		if (typeBinding == null) {
			return null;
		}

		IMethodBinding[] methodBindings = convertToMethodBindings(astRoot, typeBinding, overridableMethods);
		return createTextEditForOverridableMethods(type.getCompilationUnit(), astRoot, typeBinding, methodBindings);
	} catch (CoreException e) {
		JavaLanguageServerPlugin.logException("Add overridable methods", e);
	}

	return null;
}
 
Example #6
Source File: ExtractTempRefactoring.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 {
	try {
		pm.beginTask("", 6); //$NON-NLS-1$

		RefactoringStatus result= Checks.validateModifiesFiles(ResourceUtil.getFiles(new ICompilationUnit[] { fCu}), getValidationContext());
		if (result.hasFatalError())
			return result;

		if (fCompilationUnitNode == null) {
			fCompilationUnitNode= RefactoringASTParser.parseWithASTProvider(fCu, true, new SubProgressMonitor(pm, 3));
		} else {
			pm.worked(3);
		}

		result.merge(checkSelection(new SubProgressMonitor(pm, 3)));
		if (!result.hasFatalError() && isLiteralNodeSelected())
			fReplaceAllOccurrences= false;
		return result;

	} finally {
		pm.done();
	}
}
 
Example #7
Source File: ConstructorReferenceFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private SearchResultGroup[] removeUnrealReferences(SearchResultGroup[] groups) {
	List<SearchResultGroup> result= new ArrayList<SearchResultGroup>(groups.length);
	for (int i= 0; i < groups.length; i++) {
		SearchResultGroup group= groups[i];
		ICompilationUnit cu= group.getCompilationUnit();
		if (cu == null)
			continue;
		CompilationUnit cuNode= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(cu, false);
		SearchMatch[] allSearchResults= group.getSearchResults();
		List<SearchMatch> realConstructorReferences= new ArrayList<SearchMatch>(Arrays.asList(allSearchResults));
		for (int j= 0; j < allSearchResults.length; j++) {
			SearchMatch searchResult= allSearchResults[j];
			if (! isRealConstructorReferenceNode(ASTNodeSearchUtil.getAstNode(searchResult, cuNode)))
				realConstructorReferences.remove(searchResult);
		}
		if (! realConstructorReferences.isEmpty())
			result.add(new SearchResultGroup(group.getResource(), realConstructorReferences.toArray(new SearchMatch[realConstructorReferences.size()])));
	}
	return result.toArray(new SearchResultGroup[result.size()]);
}
 
Example #8
Source File: ConstructorReferenceFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private List<SearchMatch> getImplicitConstructorReferencesInClassCreations(WorkingCopyOwner owner, IProgressMonitor pm, RefactoringStatus status) throws JavaModelException {
	//XXX workaround for jdt core bug 23112
	SearchPattern pattern= SearchPattern.createPattern(fType, IJavaSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
	IJavaSearchScope scope= RefactoringScopeFactory.create(fType);
	SearchResultGroup[] refs= RefactoringSearchEngine.search(pattern, owner, scope, pm, status);
	List<SearchMatch> result= new ArrayList<SearchMatch>();
	for (int i= 0; i < refs.length; i++) {
		SearchResultGroup group= refs[i];
		ICompilationUnit cu= group.getCompilationUnit();
		if (cu == null)
			continue;
		CompilationUnit cuNode= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(cu, false);
		SearchMatch[] results= group.getSearchResults();
		for (int j= 0; j < results.length; j++) {
			SearchMatch searchResult= results[j];
			ASTNode node= ASTNodeSearchUtil.getAstNode(searchResult, cuNode);
			if (isImplicitConstructorReferenceNodeInClassCreations(node))
				result.add(searchResult);
		}
	}
	return result;
}
 
Example #9
Source File: HashCodeEqualsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static TextEdit generateHashCodeEqualsTextEdit(IType type, LspVariableBinding[] fields, boolean regenerate, boolean useJava7Objects, boolean useInstanceof, boolean useBlocks, boolean generateComments) {
	if (type == null) {
		return null;
	}
	try {
		RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL);
		CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true);
		ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
		if (typeBinding != null) {
			IVariableBinding[] variableBindings = JdtDomModels.convertToVariableBindings(typeBinding, fields);
			CodeGenerationSettings codeGenSettings = new CodeGenerationSettings();
			codeGenSettings.createComments = generateComments;
			codeGenSettings.overrideAnnotation = true;
			GenerateHashCodeEqualsOperation operation = new GenerateHashCodeEqualsOperation(typeBinding, variableBindings, astRoot, null, codeGenSettings, useInstanceof, useJava7Objects, regenerate, false, false);
			operation.setUseBlocksForThen(useBlocks);
			operation.run(null);
			return operation.getResultingEdit();
		}
	} catch (CoreException e) {
		JavaLanguageServerPlugin.logException("Generate hashCode and equals methods", e);
	}
	return null;
}
 
Example #10
Source File: HashCodeEqualsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static CheckHashCodeEqualsResponse checkHashCodeEqualsStatus(IType type) {
	CheckHashCodeEqualsResponse response = new CheckHashCodeEqualsResponse();
	if (type == null) {
		return response;
	}
	try {
		RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL);
		CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true);
		ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
		if (typeBinding != null) {
			response.type = type.getTypeQualifiedName();
			response.fields = JdtDomModels.getDeclaredFields(typeBinding, false);
			response.existingMethods = findExistingMethods(typeBinding);
		}
	} catch (JavaModelException e) {
		JavaLanguageServerPlugin.logException("Check hashCode and equals status", e);
	}
	return response;
}
 
Example #11
Source File: GenerateToStringHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static TextEdit generateToString(IType type, LspVariableBinding[] fields, ToStringGenerationSettingsCore settings) {
	if (type == null) {
		return null;
	}

	try {
		RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL);
		CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true);
		ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
		if (typeBinding != null) {
			IVariableBinding[] selectedFields = JdtDomModels.convertToVariableBindings(typeBinding, fields);
			GenerateToStringOperation operation = GenerateToStringOperation.createOperation(typeBinding, selectedFields, astRoot, null, settings, false, false);
			operation.run(null);
			return operation.getResultingEdit();
		}
	} catch (CoreException e) {
		JavaLanguageServerPlugin.logException("Failed to generate toString()", e);
	}
	return null;
}
 
Example #12
Source File: GenerateToStringHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static CheckToStringResponse checkToStringStatus(IType type) {
	CheckToStringResponse response = new CheckToStringResponse();
	if (type == null) {
		return response;
	}

	try {
		RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL);
		CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true);
		ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
		if (typeBinding != null) {
			response.type = type.getTypeQualifiedName();
			response.fields = JdtDomModels.getDeclaredFields(typeBinding, false);
			response.exists = Stream.of(typeBinding.getDeclaredMethods()).anyMatch(method -> method.getName().equals(METHODNAME_TOSTRING) && method.getParameterTypes().length == 0);
		}
	} catch (JavaModelException e) {
		JavaLanguageServerPlugin.logException("Failed to check toString status", e);
	}

	return response;
}
 
Example #13
Source File: InferTypeArgumentsTCModel.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public TypeVariable2 makeTypeVariable(Type type) {
	ICompilationUnit cu= RefactoringASTParser.getCompilationUnit(type);
	TType ttype= getBoxedType(type.resolveBinding(), /*no boxing*/null);
	if (ttype == null)
		return null;

	CompilationUnitRange range= new CompilationUnitRange(cu, type);
	TypeVariable2 typeVariable= new TypeVariable2(ttype, range);
	TypeVariable2 storedCv= (TypeVariable2) storedCv(typeVariable);
	if (storedCv == typeVariable) {
		fCuScopedConstraintVariables.add(storedCv);
		if (isAGenericType(ttype))
			makeElementVariables(storedCv, ttype);
		makeArrayElementVariable(storedCv);
		if (fStoreToString)
			storedCv.setData(ConstraintVariable2.TO_STRING, type.toString());
	}
	return storedCv;
}
 
Example #14
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 #15
Source File: SuperTypeRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the method which references the specified ast node.
 *
 * @param node
 *            the ast node
 * @return the referencing method
 * @throws JavaModelException
 *             if an error occurs
 */
protected final IMethod getReferencingMethod(final ASTNode node) throws JavaModelException {
	if (node instanceof Type) {
		final BodyDeclaration parent= (BodyDeclaration) ASTNodes.getParent(node, BodyDeclaration.class);
		if (parent instanceof MethodDeclaration) {
			final IMethodBinding binding= ((MethodDeclaration) parent).resolveBinding();
			if (binding != null) {
				final ICompilationUnit unit= RefactoringASTParser.getCompilationUnit(node);
				final IJavaElement element= unit.getElementAt(node.getStartPosition());
				if (element instanceof IMethod)
					return (IMethod) element;
			}
		}
	}
	return null;
}
 
Example #16
Source File: SuperTypeRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Computes the compilation units of methods referencing the specified type
 * occurrences.
 *
 * @param units
 *            the compilation unit map (element type:
 *            <code>&lt;IJavaProject, Set&lt;ICompilationUnit&gt;&gt;</code>)
 * @param nodes
 *            the ast nodes representing the type occurrences
 * @throws JavaModelException
 *             if an error occurs
 */
protected final void getMethodReferencingCompilationUnits(final Map<IJavaProject, Set<ICompilationUnit>> units, final ASTNode[] nodes) throws JavaModelException {
	ASTNode node= null;
	IMethod method= null;
	IJavaProject project= null;
	for (int index= 0; index < nodes.length; index++) {
		node= nodes[index];
		project= RefactoringASTParser.getCompilationUnit(node).getJavaProject();
		if (project != null) {
			method= getReferencingMethod(node);
			if (method != null) {
				Set<ICompilationUnit> set= units.get(project);
				if (set == null) {
					set= new HashSet<ICompilationUnit>();
					units.put(project, set);
				}
				final ICompilationUnit unit= method.getCompilationUnit();
				if (unit != null)
					set.add(unit);
			}
		}
	}
}
 
Example #17
Source File: SuperTypeRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Computes the compilation units of fields referencing the specified type
 * occurrences.
 *
 * @param units
 *            the compilation unit map (element type:
 *            <code>&lt;IJavaProject, Set&lt;ICompilationUnit&gt;&gt;</code>)
 * @param nodes
 *            the ast nodes representing the type occurrences
 * @throws JavaModelException
 *             if an error occurs
 */
protected final void getFieldReferencingCompilationUnits(final Map<IJavaProject, Set<ICompilationUnit>> units, final ASTNode[] nodes) throws JavaModelException {
	ASTNode node= null;
	IField field= null;
	IJavaProject project= null;
	for (int index= 0; index < nodes.length; index++) {
		node= nodes[index];
		project= RefactoringASTParser.getCompilationUnit(node).getJavaProject();
		if (project != null) {
			final List<IField> fields= getReferencingFields(node, project);
			for (int offset= 0; offset < fields.size(); offset++) {
				field= fields.get(offset);
				Set<ICompilationUnit> set= units.get(project);
				if (set == null) {
					set= new HashSet<ICompilationUnit>();
					units.put(project, set);
				}
				final ICompilationUnit unit= field.getCompilationUnit();
				if (unit != null)
					set.add(unit);
			}
		}
	}
}
 
Example #18
Source File: ExtractTempRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
	try {
		pm.beginTask("", 6); //$NON-NLS-1$

		RefactoringStatus result = Checks.validateModifiesFiles(ResourceUtil.getFiles(new ICompilationUnit[] { fCu }), getValidationContext(), pm);
		if (result.hasFatalError()) {
			return result;
		}

		if (fCompilationUnitNode == null) {
			fCompilationUnitNode = RefactoringASTParser.parseWithASTProvider(fCu, true, new SubProgressMonitor(pm, 3));
		} else {
			pm.worked(3);
		}

		result.merge(checkSelection(new SubProgressMonitor(pm, 3)));
		if (!result.hasFatalError() && isLiteralNodeSelected()) {
			fReplaceAllOccurrences = false;
		}
		return result;

	} finally {
		pm.done();
	}
}
 
Example #19
Source File: CleanUpPostSaveListener.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private CompilationUnit createAst(ICompilationUnit unit, Map<String, String> cleanUpOptions, IProgressMonitor monitor) {
	IJavaProject project= unit.getJavaProject();
	if (compatibleOptions(project, cleanUpOptions)) {
		CompilationUnit ast= SharedASTProvider.getAST(unit, SharedASTProvider.WAIT_NO, monitor);
		if (ast != null)
			return ast;
	}

	ASTParser parser= CleanUpRefactoring.createCleanUpASTParser();
	parser.setSource(unit);

	Map<String, String> compilerOptions= RefactoringASTParser.getCompilerOptions(unit.getJavaProject());
	compilerOptions.putAll(cleanUpOptions);
	parser.setCompilerOptions(compilerOptions);

	return (CompilationUnit)parser.createAST(monitor);
}
 
Example #20
Source File: InlineAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void run(ITextSelection selection) {
	if (!ActionUtil.isEditable(fEditor))
		return;

	ITypeRoot typeRoot= SelectionConverter.getInput(fEditor);
	if (typeRoot == null)
		return;

	CompilationUnit node= RefactoringASTParser.parseWithASTProvider(typeRoot, true, null);

	if (typeRoot instanceof ICompilationUnit) {
		ICompilationUnit cu= (ICompilationUnit) typeRoot;
		if (fInlineTemp.isEnabled() && fInlineTemp.tryInlineTemp(cu, node, selection, getShell()))
			return;

		if (fInlineConstant.isEnabled() && fInlineConstant.tryInlineConstant(cu, node, selection, getShell()))
			return;
	}
	//InlineMethod is last (also tries enclosing element):
	if (fInlineMethod.isEnabled() && fInlineMethod.tryInlineMethod(typeRoot, node, selection, getShell()))
		return;

	MessageDialog.openInformation(getShell(), RefactoringMessages.InlineAction_dialog_title, RefactoringMessages.InlineAction_select);
}
 
Example #21
Source File: ASTCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static CompilationUnit getCuNode(WorkingCopyOwner workingCopyOwner, ICompilationUnit cu) {
	ASTParser p = ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	p.setSource(cu);
	p.setResolveBindings(true);
	p.setWorkingCopyOwner(workingCopyOwner);
	p.setCompilerOptions(RefactoringASTParser.getCompilerOptions(cu));
	return (CompilationUnit) p.createAST(null);
}
 
Example #22
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 #23
Source File: InlineConstantAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void run(int offset, int length, ICompilationUnit cu) {
	Assert.isNotNull(cu);
	Assert.isTrue(offset >= 0);
	Assert.isTrue(length >= 0);
	if (!ActionUtil.isEditable(fEditor, getShell(), cu))
		return;
	CompilationUnit node= RefactoringASTParser.parseWithASTProvider(cu, true, null);
	if (!RefactoringExecutionStarter.startInlineConstantRefactoring(cu, node, offset, length, getShell())) {
		MessageDialog.openInformation(getShell(), RefactoringMessages.InlineConstantAction_dialog_title, RefactoringMessages.InlineConstantAction_no_constant_reference_or_declaration);
	}
}
 
Example #24
Source File: TypeContextChecker.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ITypeBinding resolveSuperClass(String superclass, IType typeHandle, StubTypeContext superClassContext) {
	StringBuffer cuString= new StringBuffer();
	cuString.append(superClassContext.getBeforeString());
	cuString.append(superclass);
	cuString.append(superClassContext.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);
			ASTNode type= NodeFinder.perform(compilationUnit, superClassContext.getBeforeString().length(), superclass.length());
			if (type instanceof Type) {
				return handleBug84585(((Type) type).resolveBinding());
			} else if (type instanceof Name) {
				ASTNode parent= type.getParent();
				if (parent instanceof Type)
					return handleBug84585(((Type) parent).resolveBinding());
			}
			throw new IllegalStateException();
		} finally {
			wc.discardWorkingCopy();
		}
	} catch (JavaModelException e) {
		return null;
	}
}
 
Example #25
Source File: DeleteChangeCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static Change createDeleteChange(ICompilationUnit cu, List<IJavaElement> javaElements, TextChangeManager manager) throws CoreException {
	CompilationUnit cuNode= RefactoringASTParser.parseWithASTProvider(cu, false, null);
	CompilationUnitRewrite rewriter= new CompilationUnitRewrite(cu, cuNode);
	IJavaElement[] elements= javaElements.toArray(new IJavaElement[javaElements.size()]);
	ASTNodeDeleteUtil.markAsDeleted(elements, rewriter, null);
	return addTextEditFromRewrite(manager, cu, rewriter.getASTRewrite());
}
 
Example #26
Source File: InlineMethodAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void run(int offset, int length, ITypeRoot typeRoot) {
	if (!ActionUtil.isEditable(fEditor, getShell(), typeRoot))
		return;
	CompilationUnit compilationUnit= RefactoringASTParser.parseWithASTProvider(typeRoot, true, null);
	if (!RefactoringExecutionStarter.startInlineMethodRefactoring(typeRoot, compilationUnit, offset, length, getShell())) {
		MessageDialog.openInformation(getShell(), RefactoringMessages.InlineMethodAction_dialog_title, RefactoringMessages.InlineMethodAction_no_method_invocation_or_declaration_selected);
	}
}
 
Example #27
Source File: InlineMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static SourceProvider resolveSourceProvider(RefactoringStatus status, ITypeRoot typeRoot, ASTNode invocation) {
	CompilationUnit root= (CompilationUnit)invocation.getRoot();
	IMethodBinding methodBinding= Invocations.resolveBinding(invocation);
	if (methodBinding == null) {
		status.addFatalError(RefactoringCoreMessages.InlineMethodRefactoring_error_noMethodDeclaration);
		return null;
	}
	MethodDeclaration declaration= (MethodDeclaration)root.findDeclaringNode(methodBinding);
	if (declaration != null) {
		return new SourceProvider(typeRoot, declaration);
	}
	IMethod method= (IMethod)methodBinding.getJavaElement();
	if (method != null) {
		CompilationUnit methodDeclarationAstRoot;
		ICompilationUnit methodCu= method.getCompilationUnit();
		if (methodCu != null) {
			methodDeclarationAstRoot= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(methodCu, true);
		} else {
			IClassFile classFile= method.getClassFile();
			if (! JavaElementUtil.isSourceAvailable(classFile)) {
				String methodLabel= JavaElementLabels.getTextLabel(method, JavaElementLabels.M_FULLY_QUALIFIED | JavaElementLabels.M_PARAMETER_TYPES);
				status.addFatalError(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_error_classFile, methodLabel));
				return null;
			}
			methodDeclarationAstRoot= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(classFile, true);
		}
		ASTNode node= methodDeclarationAstRoot.findDeclaringNode(methodBinding.getMethodDeclaration().getKey());
		if (node instanceof MethodDeclaration) {
			return new SourceProvider(methodDeclarationAstRoot.getTypeRoot(), (MethodDeclaration) node);
		}
	}
	status.addFatalError(RefactoringCoreMessages.InlineMethodRefactoring_error_noMethodDeclaration);
	return null;
}
 
Example #28
Source File: SuperTypeRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the field which corresponds to the specified variable declaration
 * fragment
 *
 * @param fragment
 *            the variable declaration fragment
 * @return the corresponding field
 * @throws JavaModelException
 *             if an error occurs
 */
protected final IField getCorrespondingField(final VariableDeclarationFragment fragment) throws JavaModelException {
	final IBinding binding= fragment.getName().resolveBinding();
	if (binding instanceof IVariableBinding) {
		final IVariableBinding variable= (IVariableBinding) binding;
		if (variable.isField()) {
			final ICompilationUnit unit= RefactoringASTParser.getCompilationUnit(fragment);
			final IJavaElement element= unit.getElementAt(fragment.getStartPosition());
			if (element instanceof IField)
				return (IField) element;
		}
	}
	return null;
}
 
Example #29
Source File: InferTypeArgumentsTCModel.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public CastVariable2 makeCastVariable(CastExpression castExpression, ConstraintVariable2 expressionCv) {
	ITypeBinding typeBinding= castExpression.resolveTypeBinding();
	ICompilationUnit cu= RefactoringASTParser.getCompilationUnit(castExpression);
	CompilationUnitRange range= new CompilationUnitRange(cu, castExpression);
	CastVariable2 castCv= new CastVariable2(createTType(typeBinding), range, expressionCv);
	fCastVariables.add(castCv);
	return castCv;
}
 
Example #30
Source File: RenameAnalyzeUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * This method analyzes a set of local variable renames inside one cu. It checks whether
 * any new compile errors have been introduced by the rename(s) and whether the correct
 * node(s) has/have been renamed.
 *
 * @param analyzePackages the LocalAnalyzePackages containing the information about the local renames
 * @param cuChange the TextChange containing all local variable changes to be applied.
 * @param oldCUNode the fully (incl. bindings) resolved AST node of the original compilation unit
 * @param recovery whether statements and bindings recovery should be performed when parsing the changed CU
 * @return a RefactoringStatus containing errors if compile errors or wrongly renamed nodes are found
 * @throws CoreException thrown if there was an error greating the preview content of the change
 */
public static RefactoringStatus analyzeLocalRenames(LocalAnalyzePackage[] analyzePackages, TextChange cuChange, CompilationUnit oldCUNode, boolean recovery) throws CoreException {

	RefactoringStatus result= new RefactoringStatus();
	ICompilationUnit compilationUnit= (ICompilationUnit) oldCUNode.getJavaElement();

	String newCuSource= cuChange.getPreviewContent(new NullProgressMonitor());
	CompilationUnit newCUNode= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(newCuSource, compilationUnit, true, recovery, null);

	result.merge(analyzeCompileErrors(newCuSource, newCUNode, oldCUNode));
	if (result.hasError())
		return result;

	for (int i= 0; i < analyzePackages.length; i++) {
		ASTNode enclosing= getEnclosingBlockOrMethodOrLambda(analyzePackages[i].fDeclarationEdit, cuChange, newCUNode);

		// get new declaration
		IRegion newRegion= RefactoringAnalyzeUtil.getNewTextRange(analyzePackages[i].fDeclarationEdit, cuChange);
		ASTNode newDeclaration= NodeFinder.perform(newCUNode, newRegion.getOffset(), newRegion.getLength());
		Assert.isTrue(newDeclaration instanceof Name);

		VariableDeclaration declaration= getVariableDeclaration((Name) newDeclaration);
		Assert.isNotNull(declaration);

		SimpleName[] problemNodes= ProblemNodeFinder.getProblemNodes(enclosing, declaration, analyzePackages[i].fOccurenceEdits, cuChange);
		result.merge(RefactoringAnalyzeUtil.reportProblemNodes(newCuSource, problemNodes));
	}
	return result;
}