org.eclipse.jdt.internal.corext.dom.ASTNodes Java Examples

The following examples show how to use org.eclipse.jdt.internal.corext.dom.ASTNodes. 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: SuperTypeRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the fields which reference the specified ast node.
 *
 * @param node
 *            the ast node
 * @param project
 *            the java project
 * @return the referencing fields
 * @throws JavaModelException
 *             if an error occurs
 */
protected final List<IField> getReferencingFields(final ASTNode node, final IJavaProject project) throws JavaModelException {
	List<IField> result= Collections.emptyList();
	if (node instanceof Type) {
		final BodyDeclaration parent= (BodyDeclaration) ASTNodes.getParent(node, BodyDeclaration.class);
		if (parent instanceof FieldDeclaration) {
			final List<VariableDeclarationFragment> fragments= ((FieldDeclaration) parent).fragments();
			result= new ArrayList<IField>(fragments.size());
			VariableDeclarationFragment fragment= null;
			for (final Iterator<VariableDeclarationFragment> iterator= fragments.iterator(); iterator.hasNext();) {
				fragment= iterator.next();
				final IField field= getCorrespondingField(fragment);
				if (field != null)
					result.add(field);
			}
		}
	}
	return result;
}
 
Example #2
Source File: AddDelegateMethodsAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
AddDelegateMethodsContentProvider(CompilationUnit astRoot, IType type, IField[] fields) throws JavaModelException {

			final ITypeBinding binding= ASTNodes.getTypeBinding(astRoot, type);
			if (binding != null) {
				fDelegateEntries= StubUtility2.getDelegatableMethods(binding);

				List<IVariableBinding> expanded= new ArrayList<IVariableBinding>();
				for (int index= 0; index < fields.length; index++) {
					VariableDeclarationFragment fragment= ASTNodeSearchUtil.getFieldDeclarationFragmentNode(fields[index], astRoot);
					if (fragment != null) {
						IVariableBinding variableBinding= fragment.resolveBinding();
						if (variableBinding != null)
							expanded.add(variableBinding);
					}
				}
				fExpanded= expanded.toArray(new IVariableBinding[expanded.size()]);
			}
		}
 
Example #3
Source File: QuickAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static String[] getUniqueParameterNames(MethodReference methodReference, IMethodBinding functionalMethod) throws JavaModelException {
	String[] parameterNames = ((IMethod) functionalMethod.getJavaElement()).getParameterNames();
	List<String> oldNames = new ArrayList<>(Arrays.asList(parameterNames));
	String[] newNames = new String[oldNames.size()];
	List<String> excludedNames = new ArrayList<>(ASTNodes.getVisibleLocalVariablesInScope(methodReference));

	for (int i = 0; i < oldNames.size(); i++) {
		String paramName = oldNames.get(i);
		List<String> allNamesToExclude = new ArrayList<>(excludedNames);
		allNamesToExclude.addAll(oldNames.subList(0, i));
		allNamesToExclude.addAll(oldNames.subList(i + 1, oldNames.size()));
		if (allNamesToExclude.contains(paramName)) {
			String newParamName = createName(paramName, allNamesToExclude);
			excludedNames.add(newParamName);
			newNames[i] = newParamName;
		} else {
			newNames[i] = paramName;
		}
	}
	return newNames;
}
 
Example #4
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 #5
Source File: AbstractCreateMethodProposal.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected ASTRewrite getRewrite() {
  CompilationUnit targetAstRoot = ASTResolving.createQuickFixAST(
      getCompilationUnit(), null);
  createImportRewrite(targetAstRoot);

  // Find the target type declaration
  TypeDeclaration typeDecl = JavaASTUtils.findTypeDeclaration(targetAstRoot,
      targetQualifiedTypeName);
  if (typeDecl == null) {
    return null;
  }

  ASTRewrite rewrite = ASTRewrite.create(targetAstRoot.getAST());

  // Generate the new method declaration
  MethodDeclaration methodDecl = createMethodDeclaration(rewrite.getAST());

  // Add the new method declaration to the interface
  ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(typeDecl);
  ListRewrite listRewriter = rewrite.getListRewrite(typeDecl, property);
  listRewriter.insertLast(methodDecl, null);

  return rewrite;
}
 
Example #6
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Expression handleSimpleNameAssignment(ASTNode replaceNode, ParameterObjectFactory pof, String parameterName, AST ast, IJavaProject javaProject, boolean useSuper) {
	if (replaceNode instanceof Assignment) {
		Assignment assignment= (Assignment) replaceNode;
		Expression rightHandSide= assignment.getRightHandSide();
		if (rightHandSide.getNodeType() == ASTNode.SIMPLE_NAME) {
			SimpleName sn= (SimpleName) rightHandSide;
			IVariableBinding binding= ASTNodes.getVariableBinding(sn);
			if (binding != null && binding.isField()) {
				if (fDescriptor.getType().getFullyQualifiedName().equals(binding.getDeclaringClass().getQualifiedName())) {
					FieldInfo fieldInfo= getFieldInfo(binding.getName());
					if (fieldInfo != null && binding == fieldInfo.pi.getOldBinding()) {
						return pof.createFieldReadAccess(fieldInfo.pi, parameterName, ast, javaProject, useSuper, null);
					}
				}
			}
		}
	}
	return null;
}
 
Example #7
Source File: AddArgumentCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Expression evaluateArgumentExpressions(AST ast, ITypeBinding requiredType, String key) {
	CompilationUnit root= (CompilationUnit) fCallerNode.getRoot();

	int offset= fCallerNode.getStartPosition();
	Expression best= null;
	ITypeBinding bestType= null;

	ScopeAnalyzer analyzer= new ScopeAnalyzer(root);
	IBinding[] bindings= analyzer.getDeclarationsInScope(offset, ScopeAnalyzer.VARIABLES);
	for (int i= 0; i < bindings.length; i++) {
		IVariableBinding curr= (IVariableBinding) bindings[i];
		ITypeBinding type= curr.getType();
		if (type != null && canAssign(type, requiredType) && testModifier(curr)) {
			if (best == null || isMoreSpecific(bestType, type)) {
				best= ast.newSimpleName(curr.getName());
				bestType= type;
			}
			addLinkedPositionProposal(key, curr.getName(), null);
		}
	}
	Expression defaultExpression= ASTNodeFactory.newDefaultExpression(ast, requiredType);
	if (best == null) {
		best= defaultExpression;
	}
	addLinkedPositionProposal(key, ASTNodes.asString(defaultExpression), null);
	return best;
}
 
Example #8
Source File: RefactoringAnalyzeUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static IProblem[] getIntroducedCompileProblems(CompilationUnit newCUNode, CompilationUnit oldCuNode) {
	Set<IProblem> subResult= new HashSet<IProblem>();
	Set<IProblem> oldProblems= getOldProblems(oldCuNode);
	IProblem[] newProblems= ASTNodes.getProblems(newCUNode, ASTNodes.INCLUDE_ALL_PARENTS, ASTNodes.PROBLEMS);
	for (int i= 0; i < newProblems.length; i++) {
		IProblem correspondingOld= findCorrespondingProblem(oldProblems, newProblems[i]);
		if (correspondingOld == null)
			subResult.add(newProblems[i]);
	}
	return subResult.toArray(new IProblem[subResult.size()]);
}
 
Example #9
Source File: JavadocTagsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static Set<String> getPreviousExceptionNames(List<Type> list, ASTNode missingNode) {
	Set<String> previousNames=  new HashSet<String>();
	for (int i= 0; i < list.size() && missingNode != list.get(i); i++) {
		Type curr= list.get(i);
		previousNames.add(ASTNodes.getTypeName(curr));
	}
	return previousNames;
}
 
Example #10
Source File: SelfEncapsulateFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private MethodDeclaration createGetterMethod(AST ast, ASTRewrite rewriter, String lineDelimiter) throws CoreException {
	FieldDeclaration field = ASTNodes.getParent(fFieldDeclaration, FieldDeclaration.class);
	Type type = field.getType();
	MethodDeclaration result = ast.newMethodDeclaration();
	result.setName(ast.newSimpleName(fGetterName));
	result.modifiers().addAll(ASTNodeFactory.newModifiers(ast, createModifiers()));
	Type returnType = DimensionRewrite.copyTypeAndAddDimensions(type, fFieldDeclaration.extraDimensions(), rewriter);
	result.setReturnType2(returnType);

	Block block = ast.newBlock();
	result.setBody(block);

	String body = CodeGeneration.getGetterMethodBodyContent(fField.getCompilationUnit(), getTypeName(field.getParent()), fGetterName, fField.getElementName(), lineDelimiter);
	if (body != null) {
		body = body.substring(0, body.lastIndexOf(lineDelimiter));
		ASTNode getterNode = rewriter.createStringPlaceholder(body, ASTNode.BLOCK);
		block.statements().add(getterNode);
	} else {
		ReturnStatement rs = ast.newReturnStatement();
		rs.setExpression(ast.newSimpleName(fField.getElementName()));
		block.statements().add(rs);
	}
	if (fGenerateJavadoc) {
		String string = CodeGeneration.getGetterComment(fField.getCompilationUnit(), getTypeName(field.getParent()), fGetterName, fField.getElementName(), ASTNodes.asString(type), StubUtility.getBaseName(fField), lineDelimiter);
		if (string != null) {
			Javadoc javadoc = (Javadoc) fRewriter.createStringPlaceholder(string, ASTNode.JAVADOC);
			result.setJavadoc(javadoc);
		}
	}
	return result;
}
 
Example #11
Source File: ExtractConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ExtractConstantDescriptor createRefactoringDescriptor() {
	final Map<String, String> arguments= new HashMap<String, String>();
	String project= null;
	IJavaProject javaProject= fCu.getJavaProject();
	if (javaProject != null)
		project= javaProject.getElementName();
	int flags= JavaRefactoringDescriptor.JAR_REFACTORING | JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
	if (JdtFlags.getVisibilityCode(fVisibility) != Modifier.PRIVATE)
		flags|= RefactoringDescriptor.STRUCTURAL_CHANGE;

	final String expression= ASTNodes.asString(fSelectedExpression.getAssociatedExpression());
	final String description= Messages.format(RefactoringCoreMessages.ExtractConstantRefactoring_descriptor_description_short, BasicElementLabels.getJavaElementName(fConstantName));
	final String header= Messages.format(RefactoringCoreMessages.ExtractConstantRefactoring_descriptor_description, new String[] { BasicElementLabels.getJavaElementName(fConstantName), BasicElementLabels.getJavaCodeString(expression)});
	final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
	comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractConstantRefactoring_constant_name_pattern, BasicElementLabels.getJavaElementName(fConstantName)));
	comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractConstantRefactoring_constant_expression_pattern, BasicElementLabels.getJavaCodeString(expression)));
	String visibility= fVisibility;
	if ("".equals(visibility)) //$NON-NLS-1$
		visibility= RefactoringCoreMessages.ExtractConstantRefactoring_default_visibility;
	comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractConstantRefactoring_visibility_pattern, visibility));
	if (fReplaceAllOccurrences)
		comment.addSetting(RefactoringCoreMessages.ExtractConstantRefactoring_replace_occurrences);
	if (fQualifyReferencesWithDeclaringClassName)
		comment.addSetting(RefactoringCoreMessages.ExtractConstantRefactoring_qualify_references);
	arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT, JavaRefactoringDescriptorUtil.elementToHandle(project, fCu));
	arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME, fConstantName);
	arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString()); //$NON-NLS-1$
	arguments.put(ATTRIBUTE_REPLACE, Boolean.valueOf(fReplaceAllOccurrences).toString());
	arguments.put(ATTRIBUTE_QUALIFY, Boolean.valueOf(fQualifyReferencesWithDeclaringClassName).toString());
	arguments.put(ATTRIBUTE_VISIBILITY, new Integer(JdtFlags.getVisibilityCode(fVisibility)).toString());

	ExtractConstantDescriptor descriptor= RefactoringSignatureDescriptorFactory.createExtractConstantDescriptor(project, description, comment.asString(), arguments, flags);
	return descriptor;
}
 
Example #12
Source File: AssignToVariableAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private VariableDeclarationFragment addFieldDeclaration(ASTRewrite rewrite, ASTNode newTypeDecl, int modifiers, Expression expression) {
	if (fExistingFragment != null) {
		return fExistingFragment;
	}

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

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

	FieldDeclaration newDecl= ast.newFieldDeclaration(newDeclFrag);

	Type type= evaluateType(ast);
	newDecl.setType(type);
	newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers));

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

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

	return newDeclFrag;
}
 
Example #13
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ASTNode typeToDeclaration(IType type, CompilationUnit root) throws JavaModelException {
	Name intermediateName= (Name) NodeFinder.perform(root, type.getNameRange());
	if (type.isAnonymous()) {
		return ASTNodes.getParent(intermediateName, AnonymousClassDeclaration.class);
	} else {
		return ASTNodes.getParent(intermediateName, AbstractTypeDeclaration.class);
	}
}
 
Example #14
Source File: ExtractMethodAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public void checkInput(RefactoringStatus status, String methodName, ASTNode destination) {
	ITypeBinding[] arguments = getArgumentTypes();
	ITypeBinding type = ASTNodes.getEnclosingType(destination);
	status.merge(Checks.checkMethodInType(type, methodName, arguments));
	ITypeBinding superClass = type.getSuperclass();
	if (superClass != null) {
		status.merge(Checks.checkMethodInHierarchy(superClass, methodName, null, arguments));
	}
	for (ITypeBinding superInterface : type.getInterfaces()) {
		status.merge(Checks.checkMethodInHierarchy(superInterface, methodName, null, arguments));
	}
}
 
Example #15
Source File: RefactoringAvailabilityTester.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isIntroduceFactoryAvailable(final JavaTextSelection selection) throws JavaModelException {
	final IJavaElement[] elements= selection.resolveElementAtOffset();
	if (elements.length == 1 && elements[0] instanceof IMethod)
		return isIntroduceFactoryAvailable((IMethod) elements[0]);

	// there's no IMethod for the default constructor
	if (!Checks.isAvailable(selection.resolveEnclosingElement()))
		return false;
	ASTNode node= selection.resolveCoveringNode();
	if (node == null) {
		ASTNode[] selectedNodes= selection.resolveSelectedNodes();
		if (selectedNodes != null && selectedNodes.length == 1) {
			node= selectedNodes[0];
			if (node == null)
				return false;
		} else {
			return false;
		}
	}

	if (node.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION)
		return true;

	node= ASTNodes.getNormalizedNode(node);
	if (node.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY)
		return true;

	return false;
}
 
Example #16
Source File: IntroduceParameterObjectProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isParameter(ParameterInfo pi, ASTNode node, List<SingleVariableDeclaration> enclosingMethodParameters, String qualifier) {
	if (node instanceof Name) {
		Name name= (Name) node;
		IVariableBinding binding= ASTNodes.getVariableBinding(name);
		if (binding != null && binding.isParameter()) {
			return binding.getName().equals(getNameInScope(pi, enclosingMethodParameters));
		} else {
			if (node instanceof QualifiedName) {
				QualifiedName qn= (QualifiedName) node;
				return qn.getFullyQualifiedName().equals(JavaModelUtil.concatenateName(qualifier, getNameInScope(pi, enclosingMethodParameters)));
			}
		}
	}
	return false;
}
 
Example #17
Source File: IntroduceParameterObjectProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.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.IntroduceParameterObjectRefactoring_cannotanalysemethod_compilererror,
			new String[] { messages[0].getMessage() }));
	return true;
}
 
Example #18
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 #19
Source File: HierarchyProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected static void copyJavadocNode(final ASTRewrite rewrite, final BodyDeclaration oldDeclaration, final BodyDeclaration newDeclaration) {
	final Javadoc predecessor= oldDeclaration.getJavadoc();
	if (predecessor != null) {
		String newString= ASTNodes.getNodeSource(predecessor, false, true);
		if (newString != null) {
			newDeclaration.setJavadoc((Javadoc) rewrite.createStringPlaceholder(newString, ASTNode.JAVADOC));
		}
	}
}
 
Example #20
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 #21
Source File: ExtractMethodRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private MethodDeclaration createNewMethod(ASTNode[] selectedNodes, String lineDelimiter, TextEditGroup substitute) throws CoreException {
	MethodDeclaration result = createNewMethodDeclaration();
	result.setBody(createMethodBody(selectedNodes, substitute, result.getModifiers()));
	if (fGenerateJavadoc) {
		AbstractTypeDeclaration enclosingType = ASTNodes.getParent(fAnalyzer.getEnclosingBodyDeclaration(), AbstractTypeDeclaration.class);
		String string = CodeGeneration.getMethodComment(fCUnit, enclosingType.getName().getIdentifier(), result, null, lineDelimiter);
		if (string != null) {
			Javadoc javadoc = (Javadoc) fRewriter.createStringPlaceholder(string, ASTNode.JAVADOC);
			result.setJavadoc(javadoc);
		}
	}
	return result;
}
 
Example #22
Source File: ChangeMethodSignatureProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private TagElement insertThrowsTag(ListRewrite tagRewriter, List<Type> exceptions, int currentIndex, TagElement newTagElement) {
	HashSet<String> previousNames= new HashSet<>();
	for (int n = 0; n < currentIndex; n++) {
		Type curr= exceptions.get(n);
		previousNames.add(ASTNodes.getTypeName(curr));
	}

	JavadocTagsSubProcessor.insertTag(tagRewriter, newTagElement, previousNames);
	return newTagElement;
}
 
Example #23
Source File: JavaSourceHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private int getNextElseOffset(Statement then, ITypeRoot editorInput) {
	int thenEnd= ASTNodes.getExclusiveEnd(then);
	try {
		TokenScanner scanner= new TokenScanner(editorInput);
		return scanner.getNextStartOffset(thenEnd, true);
	} catch (CoreException e) {
		// ignore
	}
	return -1;
}
 
Example #24
Source File: GetterSetterCorrectionSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Proposes a setter for this field.
 *
 * @param context
 *            the proposal parameter
 * @param relevance
 *            relevance of this proposal
 * @return the proposal if available or null
 */
private static ChangeCorrectionProposal addSetterProposal(ProposalParameter context, int relevance) {
	boolean isBoolean = isBoolean(context);
	String setterName = GetterSetterUtil.getSetterName(context.variableBinding, context.compilationUnit.getJavaProject(), null, isBoolean);
	ITypeBinding declaringType = context.variableBinding.getDeclaringClass();
	if (declaringType == null) {
		return null;
	}

	IMethodBinding method = Bindings.findMethodInHierarchy(declaringType, setterName, new ITypeBinding[] { context.variableBinding.getType() });
	if (method != null && Bindings.isVoidType(method.getReturnType()) && (Modifier.isStatic(method.getModifiers()) == Modifier.isStatic(context.variableBinding.getModifiers()))) {
		Expression assignedValue = getAssignedValue(context);
		if (assignedValue == null) {
			return null; //we don't know how to handle those cases.
		}
		Expression mi = createMethodInvocation(context, method, assignedValue);
		context.astRewrite.replace(context.accessNode.getParent(), mi, null);

		String label = Messages.format(CorrectionMessages.GetterSetterCorrectionSubProcessor_replacewithsetter_description, BasicElementLabels.getJavaCodeString(ASTNodes.asString(context.accessNode)));
		ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.compilationUnit, context.astRewrite, relevance);
		return proposal;
	} else {
		IJavaElement element = context.variableBinding.getJavaElement();
		if (element instanceof IField) {
			IField field = (IField) element;
			try {
				if (RefactoringAvailabilityTester.isSelfEncapsulateAvailable(field)) {
					return new SelfEncapsulateFieldProposal(relevance, field);
				}
			} catch (JavaModelException e) {
				JavaLanguageServerPlugin.log(e);
			}
		}
	}
	return null;
}
 
Example #25
Source File: PromoteTempToFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Expression getTempInitializerCopy(ASTRewrite rewrite) {
	final Expression initializer= (Expression) rewrite.createCopyTarget(getTempInitializer());
	if (initializer instanceof ArrayInitializer && ASTNodes.getDimensions(fTempDeclarationNode) > 0) {
		ArrayCreation arrayCreation= rewrite.getAST().newArrayCreation();
		arrayCreation.setType((ArrayType) ASTNodeFactory.newType(rewrite.getAST(), fTempDeclarationNode));
		arrayCreation.setInitializer((ArrayInitializer) initializer);
		return arrayCreation;
	}
	return initializer;
}
 
Example #26
Source File: LocalDeclarationAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(SimpleName node) {
	IVariableBinding binding= null;
	if (node.isDeclaration() || !considerNode(node) || (binding= ASTNodes.getLocalVariableBinding(node)) == null)
		return false;
	handleReferenceToLocal(node, binding);
	return true;
}
 
Example #27
Source File: ExtractMethodAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void checkExpression(RefactoringStatus status) {
	ASTNode[] nodes = getSelectedNodes();
	if (nodes != null && nodes.length == 1) {
		ASTNode node = nodes[0];
		if (node instanceof Type) {
			status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_type_reference, JavaStatusContext.create(fCUnit, node));
		} else if (node.getLocationInParent() == SwitchCase.EXPRESSION_PROPERTY) {
			status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_switch_case, JavaStatusContext.create(fCUnit, node));
		} else if (node instanceof Annotation || ASTNodes.getParent(node, Annotation.class) != null) {
			status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_from_annotation, JavaStatusContext.create(fCUnit, node));
		}
	}
}
 
Example #28
Source File: ExtractTempRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private final ExtractLocalDescriptor createRefactoringDescriptor() {
	final Map<String, String> arguments = new HashMap<>();
	String project = null;
	IJavaProject javaProject = fCu.getJavaProject();
	if (javaProject != null) {
		project = javaProject.getElementName();
	}
	final String description = Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_descriptor_description_short, BasicElementLabels.getJavaElementName(fTempName));
	final String expression = ASTNodes.asString(fSelectedExpression.getAssociatedExpression());
	final String header = Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_descriptor_description, new String[] { BasicElementLabels.getJavaElementName(fTempName), BasicElementLabels.getJavaCodeString(expression) });
	final JDTRefactoringDescriptorComment comment = new JDTRefactoringDescriptorComment(project, this, header);
	comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_name_pattern, BasicElementLabels.getJavaElementName(fTempName)));
	final BodyDeclaration decl = ASTNodes.getParent(fSelectedExpression.getAssociatedExpression(), BodyDeclaration.class);
	if (decl instanceof MethodDeclaration) {
		final IMethodBinding method = ((MethodDeclaration) decl).resolveBinding();
		final String label = method != null ? BindingLabelProviderCore.getBindingLabel(method, JavaElementLabels.ALL_FULLY_QUALIFIED) : BasicElementLabels.getJavaElementName('{' + JavaElementLabels.ELLIPSIS_STRING + '}');
		comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_destination_pattern, label));
	}
	comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_expression_pattern, BasicElementLabels.getJavaCodeString(expression)));
	if (fReplaceAllOccurrences) {
		comment.addSetting(RefactoringCoreMessages.ExtractTempRefactoring_replace_occurrences);
	}
	if (fDeclareFinal) {
		comment.addSetting(RefactoringCoreMessages.ExtractTempRefactoring_declare_final);
	}
	final ExtractLocalDescriptor descriptor = RefactoringSignatureDescriptorFactory.createExtractLocalDescriptor(project, description, comment.asString(), arguments, RefactoringDescriptor.NONE);
	arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT, JavaRefactoringDescriptorUtil.elementToHandle(project, fCu));
	arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME, fTempName);
	arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString()); //$NON-NLS-1$
	arguments.put(ATTRIBUTE_REPLACE, Boolean.valueOf(fReplaceAllOccurrences).toString());
	arguments.put(ATTRIBUTE_FINAL, Boolean.valueOf(fDeclareFinal).toString());
	return descriptor;
}
 
Example #29
Source File: ChangeMethodSignatureProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private TagElement findThrowsTag(MethodDeclaration decl, Type exception) {
	Javadoc javadoc= decl.getJavadoc();
	if (javadoc != null) {
		String name= ASTNodes.getTypeName(exception);
		return JavadocTagsSubProcessor.findThrowsTag(javadoc, name);
	}
	return null;
}
 
Example #30
Source File: SnippetFinder.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean match(SimpleName candidate, Object s) {
	if (!(s instanceof SimpleName)) {
		return false;
	}

	SimpleName snippet = (SimpleName) s;
	if (candidate.isDeclaration() != snippet.isDeclaration()) {
		return false;
	}

	IBinding cb = candidate.resolveBinding();
	IBinding sb = snippet.resolveBinding();
	if (cb == null || sb == null) {
		return false;
	}
	IVariableBinding vcb = ASTNodes.getVariableBinding(candidate);
	IVariableBinding vsb = ASTNodes.getVariableBinding(snippet);
	if (vcb == null || vsb == null) {
		return Bindings.equals(cb, sb);
	}
	if (!vcb.isField() && !vsb.isField() && Bindings.equals(vcb.getType(), vsb.getType())) {
		SimpleName mapped = fMatch.getMappedName(vsb);
		if (mapped != null) {
			IVariableBinding mappedBinding = ASTNodes.getVariableBinding(mapped);
			if (!Bindings.equals(vcb, mappedBinding)) {
				return false;
			}
		}
		fMatch.addLocal(vsb, candidate);
		return true;
	}
	return Bindings.equals(cb, sb);
}