Java Code Examples for org.eclipse.jdt.internal.corext.dom.Bindings#getBindingOfParentType()

The following examples show how to use org.eclipse.jdt.internal.corext.dom.Bindings#getBindingOfParentType() . 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: SemanticHighlightings.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean consumes(final SemanticToken token) {
	final SimpleName node = token.getNode();
	if (node.isDeclaration()) {
		return false;
	}

	final IBinding binding = token.getBinding();
	if (binding == null || binding.getKind() != IBinding.VARIABLE) {
		return false;
	}

	ITypeBinding currentType = Bindings.getBindingOfParentType(node);
	ITypeBinding declaringType = ((IVariableBinding) binding).getDeclaringClass();
	if (declaringType == null || currentType == declaringType) {
		return false;
	}

	return Bindings.isSuperType(declaringType, currentType);
}
 
Example 2
Source File: ModifierCorrectionSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static int getNeededVisibility(ASTNode currNode, ITypeBinding targetType, IBinding binding) {
	ITypeBinding currNodeBinding = Bindings.getBindingOfParentType(currNode);
	if (currNodeBinding == null) { // import
		return Modifier.PUBLIC;
	}

	if (Bindings.isSuperType(targetType, currNodeBinding)) {
		if (binding != null && (JdtFlags.isProtected(binding) || binding.getKind() == IBinding.TYPE)) {
			return Modifier.PUBLIC;
		}
		return Modifier.PROTECTED;
	}

	if (currNodeBinding.getPackage().getKey().equals(targetType.getPackage().getKey())) {
		return 0;
	}
	return Modifier.PUBLIC;
}
 
Example 3
Source File: ModifierCorrectionSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static int getNeededVisibility(ASTNode currNode, ITypeBinding targetType, IBinding binding) {
	ITypeBinding currNodeBinding= Bindings.getBindingOfParentType(currNode);
	if (currNodeBinding == null) { // import
		return Modifier.PUBLIC;
	}

	if (Bindings.isSuperType(targetType, currNodeBinding)) {
		if (binding != null && (JdtFlags.isProtected(binding) || binding.getKind() == IBinding.TYPE)) {
			return Modifier.PUBLIC;
		}
		return Modifier.PROTECTED;
	}

	if (currNodeBinding.getPackage().getKey().equals(targetType.getPackage().getKey())) {
		return 0;
	}
	return Modifier.PUBLIC;
}
 
Example 4
Source File: SemanticHighlightings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean consumes(final SemanticToken token) {
	final SimpleName node= token.getNode();
	if (node.isDeclaration()) {
		return false;
	}

	final IBinding binding= token.getBinding();
	if (binding == null || binding.getKind() != IBinding.VARIABLE) {
		return false;
	}

	ITypeBinding currentType= Bindings.getBindingOfParentType(node);
	ITypeBinding declaringType= ((IVariableBinding) binding).getDeclaringClass();
	if (declaringType == null || currentType == declaringType)
		return false;

	return Bindings.isSuperType(declaringType, currentType);
}
 
Example 5
Source File: SemanticHighlightings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean consumes(SemanticToken token) {
	SimpleName node= token.getNode();
	if (node.isDeclaration())
		return false;

	IBinding binding= token.getBinding();
	if (binding == null || binding.getKind() != IBinding.METHOD)
		return false;

	ITypeBinding currentType= Bindings.getBindingOfParentType(node);
	ITypeBinding declaringType= ((IMethodBinding) binding).getDeclaringClass();
	if (currentType == declaringType || currentType == null)
		return false;

	return Bindings.isSuperType(declaringType, currentType);
}
 
Example 6
Source File: SemanticHighlightings.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean consumes(SemanticToken token) {
	SimpleName node = token.getNode();
	if (node.isDeclaration()) {
		return false;
	}

	IBinding binding = token.getBinding();
	if (binding == null || binding.getKind() != IBinding.METHOD) {
		return false;
	}

	ITypeBinding currentType = Bindings.getBindingOfParentType(node);
	ITypeBinding declaringType = ((IMethodBinding) binding).getDeclaringClass();
	if (currentType == declaringType || currentType == null) {
		return false;
	}

	return Bindings.isSuperType(declaringType, currentType);
}
 
Example 7
Source File: OrganizeImportsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean needsImport(ITypeBinding typeBinding, SimpleName ref) {
	if (!typeBinding.isTopLevel() && !typeBinding.isMember() || typeBinding.isRecovered()) {
		return false; // no imports for anonymous, local, primitive types or parameters types
	}
	int modifiers= typeBinding.getModifiers();
	if (Modifier.isPrivate(modifiers)) {
		return false; // imports for privates are not required
	}
	ITypeBinding currTypeBinding= Bindings.getBindingOfParentType(ref);
	if (currTypeBinding == null) {
		if (ASTNodes.getParent(ref, ASTNode.PACKAGE_DECLARATION) != null) {
			return true; // reference in package-info.java
		}
		return false; // not in a type
	}
	if (!Modifier.isPublic(modifiers)) {
		if (!currTypeBinding.getPackage().getName().equals(typeBinding.getPackage().getName())) {
			return false; // not visible
		}
	}

	ASTNode parent= ref.getParent();
	while (parent instanceof Type) {
		parent= parent.getParent();
	}
	if (parent instanceof AbstractTypeDeclaration && parent.getParent() instanceof CompilationUnit) {
		return true;
	}

	if (typeBinding.isMember()) {
		if (fAnalyzer.isDeclaredInScope(typeBinding, ref, ScopeAnalyzer.TYPES | ScopeAnalyzer.CHECK_VISIBILITY))
			return false;
	}
	return true;
}
 
Example 8
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void addNewFieldProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding, ITypeBinding declaringTypeBinding, SimpleName simpleName, boolean isWriteAccess, Collection<ICommandAccess> proposals) throws JavaModelException {
	// new variables
	ICompilationUnit targetCU;
	ITypeBinding senderDeclBinding;
	if (binding != null) {
		senderDeclBinding= binding.getTypeDeclaration();
		targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, senderDeclBinding);
	} else { // binding is null for accesses without qualifier
		senderDeclBinding= declaringTypeBinding;
		targetCU= cu;
	}

	if (!senderDeclBinding.isFromSource() || targetCU == null) {
		return;
	}

	boolean mustBeConst= ASTResolving.isInsideModifiers(simpleName);

	addNewFieldForType(targetCU, binding, senderDeclBinding, simpleName, isWriteAccess, mustBeConst, proposals);

	if (binding == null && senderDeclBinding.isNested()) {
		ASTNode anonymDecl= astRoot.findDeclaringNode(senderDeclBinding);
		if (anonymDecl != null) {
			ITypeBinding bind= Bindings.getBindingOfParentType(anonymDecl.getParent());
			if (!bind.isAnonymous()) {
				addNewFieldForType(targetCU, bind, bind, simpleName, isWriteAccess, mustBeConst, proposals);
			}
		}
	}
}
 
Example 9
Source File: CodeStyleFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static String getThisExpressionQualifier(ITypeBinding declaringClass, ImportRewrite imports, SimpleName name) {
	ITypeBinding parentType= Bindings.getBindingOfParentType(name);
	ITypeBinding currType= parentType;
	while (currType != null && !Bindings.isSuperType(declaringClass, currType)) {
		currType= currType.getDeclaringClass();
	}
	if (currType == null) {
		declaringClass= declaringClass.getTypeDeclaration();
		currType= parentType;
		while (currType != null && !Bindings.isSuperType(declaringClass, currType)) {
			currType= currType.getDeclaringClass();
		}
	}
	if (currType != parentType) {
		if (currType == null)
			return null;

		if (currType.isAnonymous())
			//If we access a field of a super class of an anonymous class
			//then we can only qualify with 'this' but not with outer.this
			//see bug 115277
			return null;

		return imports.addImport(currType);
	} else {
		return ""; //$NON-NLS-1$
	}
}
 
Example 10
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static void addNewFieldProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding,
		ITypeBinding declaringTypeBinding, SimpleName simpleName, boolean isWriteAccess,
		Collection<ChangeCorrectionProposal> proposals) throws JavaModelException {
	// new variables
	ICompilationUnit targetCU;
	ITypeBinding senderDeclBinding;
	if (binding != null) {
		senderDeclBinding= binding.getTypeDeclaration();
		targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, senderDeclBinding);
	} else { // binding is null for accesses without qualifier
		senderDeclBinding= declaringTypeBinding;
		targetCU= cu;
	}

	if (!senderDeclBinding.isFromSource() || targetCU == null) {
		return;
	}

	boolean mustBeConst= ASTResolving.isInsideModifiers(simpleName);

	addNewFieldForType(targetCU, binding, senderDeclBinding, simpleName, isWriteAccess, mustBeConst, proposals);

	if (binding == null && senderDeclBinding.isNested()) {
		ASTNode anonymDecl= astRoot.findDeclaringNode(senderDeclBinding);
		if (anonymDecl != null) {
			ITypeBinding bind= Bindings.getBindingOfParentType(anonymDecl.getParent());
			if (!bind.isAnonymous()) {
				addNewFieldForType(targetCU, bind, bind, simpleName, isWriteAccess, mustBeConst, proposals);
			}
		}
	}
}
 
Example 11
Source File: QuickAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static boolean getAssignAllParamsToFieldsProposals(IInvocationContext context, ASTNode node, Collection<ChangeCorrectionProposal> resultingCollections) {
	node = ASTNodes.getNormalizedNode(node);
	ASTNode parent = node.getParent();
	if (!(parent instanceof SingleVariableDeclaration) || !(parent.getParent() instanceof MethodDeclaration)) {
		return false;
	}
	MethodDeclaration methodDecl = (MethodDeclaration) parent.getParent();
	if (methodDecl.getBody() == null) {
		return false;
	}
	List<SingleVariableDeclaration> parameters = methodDecl.parameters();
	if (parameters.size() <= 1) {
		return false;
	}
	ITypeBinding parentType = Bindings.getBindingOfParentType(node);
	if (parentType == null || parentType.isInterface()) {
		return false;
	}
	for (SingleVariableDeclaration param : parameters) {
		IVariableBinding binding = param.resolveBinding();
		if (binding == null || binding.getType() == null) {
			return false;
		}
	}
	if (resultingCollections == null) {
		return true;
	}

	AssignToVariableAssistProposal fieldProposal = new AssignToVariableAssistProposal(context.getCompilationUnit(), parameters, IProposalRelevance.ASSIGN_ALL_PARAMS_TO_NEW_FIELDS);
	resultingCollections.add(fieldProposal);
	return true;
}
 
Example 12
Source File: ImplementationCollector.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private List<T> findMethodImplementations(IProgressMonitor monitor) throws CoreException {
	IMethod method = (IMethod) javaElement;
	try {
		if (cannotBeOverriddenMethod(method)) {
			return null;
		}
	} catch (JavaModelException e) {
		JavaLanguageServerPlugin.logException("Find method implementations failure ", e);
		return null;
	}

	CompilationUnit ast = CoreASTProvider.getInstance().getAST(typeRoot, CoreASTProvider.WAIT_YES, monitor);
	if (ast == null) {
		return null;
	}

	ASTNode node = NodeFinder.perform(ast, region.getOffset(), region.getLength());
	ITypeBinding parentTypeBinding = null;
	if (node instanceof SimpleName) {
		ASTNode parent = node.getParent();
		if (parent instanceof MethodInvocation) {
			Expression expression = ((MethodInvocation) parent).getExpression();
			if (expression == null) {
				parentTypeBinding= Bindings.getBindingOfParentType(node);
			} else {
				parentTypeBinding = expression.resolveTypeBinding();
			}
		} else if (parent instanceof SuperMethodInvocation) {
			// Directly go to the super method definition
			return Collections.singletonList(mapper.convert(method, 0, 0));
		} else if (parent instanceof MethodDeclaration) {
			parentTypeBinding = Bindings.getBindingOfParentType(node);
		}
	}
	final IType receiverType = getType(parentTypeBinding);
	if (receiverType == null) {
		return null;
	}

	final List<T> results = new ArrayList<>();
	try {
		String methodLabel = JavaElementLabelsCore.getElementLabel(method, JavaElementLabelsCore.DEFAULT_QUALIFIED);
		monitor.beginTask(Messages.format(JavaElementImplementationHyperlink_search_method_implementors, methodLabel), 10);
		SearchRequestor requestor = new SearchRequestor() {
			@Override
			public void acceptSearchMatch(SearchMatch match) throws CoreException {
				if (match.getAccuracy() == SearchMatch.A_ACCURATE) {
					Object element = match.getElement();
					if (element instanceof IMethod) {
						IMethod methodFound = (IMethod) element;
						if (!JdtFlags.isAbstract(methodFound)) {
							T result = mapper.convert(methodFound, match.getOffset(), match.getLength());
							if (result != null) {
								results.add(result);
							}
						}
					}
				}
			}
		};

		IJavaSearchScope hierarchyScope;
		if (receiverType.isInterface()) {
			hierarchyScope = SearchEngine.createHierarchyScope(method.getDeclaringType());
		} else {
			if (isFullHierarchyNeeded(new SubProgressMonitor(monitor, 3), method, receiverType)) {
				hierarchyScope = SearchEngine.createHierarchyScope(receiverType);
			} else {
				boolean isMethodAbstract = JdtFlags.isAbstract(method);
				hierarchyScope = SearchEngine.createStrictHierarchyScope(null, receiverType, true, isMethodAbstract, null);
			}
		}

		int limitTo = IJavaSearchConstants.DECLARATIONS | IJavaSearchConstants.IGNORE_DECLARING_TYPE | IJavaSearchConstants.IGNORE_RETURN_TYPE;
		SearchPattern pattern = SearchPattern.createPattern(method, limitTo);
		Assert.isNotNull(pattern);
		SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
		SearchEngine engine = new SearchEngine();
		engine.search(pattern, participants, hierarchyScope, requestor, new SubProgressMonitor(monitor, 7));
		if (monitor.isCanceled()) {
			throw new OperationCanceledException();
		}
	} finally {
		monitor.done();
	}
	return results;
}
 
Example 13
Source File: CodeStyleFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean visit(final FieldAccess node) {
	if (!fRemoveFieldQualifiers)
		return true;

	Expression expression= node.getExpression();
	if (!(expression instanceof ThisExpression))
		return true;

	final SimpleName name= node.getName();
	if (hasConflict(expression.getStartPosition(), name, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY))
		return true;

	Name qualifier= ((ThisExpression) expression).getQualifier();
	if (qualifier != null) {
		ITypeBinding outerClass= (ITypeBinding) qualifier.resolveBinding();
		if (outerClass == null)
			return true;

		IVariableBinding nameBinding= (IVariableBinding) name.resolveBinding();
		if (nameBinding == null)
			return true;

		ITypeBinding variablesDeclaringClass= nameBinding.getDeclaringClass();
		if (outerClass != variablesDeclaringClass)
			//be conservative: We have a reference to a field of an outer type, and this type inherited
			//the field. It's possible that the inner type inherits the same field. We must not remove
			//the qualifier in this case.
			return true;
		
		ITypeBinding enclosingTypeBinding= Bindings.getBindingOfParentType(node);
		if (enclosingTypeBinding == null || Bindings.isSuperType(variablesDeclaringClass, enclosingTypeBinding))
			//We have a reference to a field of an outer type, and this type inherited
			//the field. The inner type inherits the same field. We must not remove
			//the qualifier in this case.
			return true;
	}

	fOperations.add(new CompilationUnitRewriteOperation() {
		@Override
		public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {
			ASTRewrite rewrite= cuRewrite.getASTRewrite();
			TextEditGroup group= createTextEditGroup(FixMessages.CodeStyleFix_removeThis_groupDescription, cuRewrite);
			rewrite.replace(node, rewrite.createCopyTarget(name), group);
		}
	});
	return super.visit(node);
}
 
Example 14
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static void addQualifierToOuterProposal(IInvocationContext context, MethodInvocation invocationNode,
		IMethodBinding binding, Collection<ChangeCorrectionProposal> proposals) {
	ITypeBinding declaringType= binding.getDeclaringClass();
	ITypeBinding parentType= Bindings.getBindingOfParentType(invocationNode);
	ITypeBinding currType= parentType;

	boolean isInstanceMethod= !Modifier.isStatic(binding.getModifiers());

	while (currType != null && !Bindings.isSuperType(declaringType, currType)) {
		if (isInstanceMethod && Modifier.isStatic(currType.getModifiers())) {
			return;
		}
		currType= currType.getDeclaringClass();
	}
	if (currType == null || currType == parentType) {
		return;
	}

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

	String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetoouter_description,
			org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getTypeSignature(currType));
	ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(),
			rewrite, IProposalRelevance.QUALIFY_WITH_ENCLOSING_TYPE);

	ImportRewrite imports= proposal.createImportRewrite(context.getASTRoot());
	ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(invocationNode, imports);
	AST ast= invocationNode.getAST();

	String qualifier= imports.addImport(currType, importRewriteContext);
	Name name= ASTNodeFactory.newName(ast, qualifier);

	Expression newExpression;
	if (isInstanceMethod) {
		ThisExpression expr= ast.newThisExpression();
		expr.setQualifier(name);
		newExpression= expr;
	} else {
		newExpression= name;
	}

	rewrite.set(invocationNode, MethodInvocation.EXPRESSION_PROPERTY, newExpression, null);

	proposals.add(proposal);
}
 
Example 15
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static void addNewMethodProposals(ICompilationUnit cu, CompilationUnit astRoot, Expression sender,
		List<Expression> arguments, boolean isSuperInvocation, ASTNode invocationNode, String methodName,
		Collection<ChangeCorrectionProposal> proposals) throws JavaModelException {
	ITypeBinding nodeParentType= Bindings.getBindingOfParentType(invocationNode);
	ITypeBinding binding= null;
	if (sender != null) {
		binding= sender.resolveTypeBinding();
	} else {
		binding= nodeParentType;
		if (isSuperInvocation && binding != null) {
			binding= binding.getSuperclass();
		}
	}
	if (binding != null && binding.isFromSource()) {
		ITypeBinding senderDeclBinding= binding.getTypeDeclaration();

		ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, senderDeclBinding);
		if (targetCU != null) {
			String label;
			ITypeBinding[] parameterTypes= getParameterTypes(arguments);
			if (parameterTypes != null) {
				String sig = org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getMethodSignature(methodName, parameterTypes, false);
				boolean is18OrHigher= JavaModelUtil.is18OrHigher(targetCU.getJavaProject());

				boolean isSenderBindingInterface= senderDeclBinding.isInterface();
				if (nodeParentType == senderDeclBinding) {
					label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_description, sig);
				} else {
					label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, new Object[] { sig, BasicElementLabels.getJavaElementName(senderDeclBinding.getName()) } );
				}
				if (is18OrHigher || !isSenderBindingInterface
						|| (nodeParentType != senderDeclBinding && (!(sender instanceof SimpleName) || !((SimpleName) sender).getIdentifier().equals(senderDeclBinding.getName())))) {
					proposals.add(new NewMethodCorrectionProposal(label, targetCU, invocationNode, arguments,
							senderDeclBinding, IProposalRelevance.CREATE_METHOD));
				}

				if (senderDeclBinding.isNested() && cu.equals(targetCU) && sender == null && Bindings.findMethodInHierarchy(senderDeclBinding, methodName, (ITypeBinding[]) null) == null) { // no covering method
					ASTNode anonymDecl= astRoot.findDeclaringNode(senderDeclBinding);
					if (anonymDecl != null) {
						senderDeclBinding= Bindings.getBindingOfParentType(anonymDecl.getParent());
						isSenderBindingInterface= senderDeclBinding.isInterface();
						if (!senderDeclBinding.isAnonymous()) {
							if (is18OrHigher || !isSenderBindingInterface) {
								String[] args = new String[] { sig,
										org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getTypeSignature(senderDeclBinding) };
								label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, args);
								proposals.add(new NewMethodCorrectionProposal(label, targetCU, invocationNode,
										arguments, senderDeclBinding, IProposalRelevance.CREATE_METHOD));
							}
						}
					}
				}
			}
		}
	}
}
 
Example 16
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static boolean getAssignParamToFieldProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
	node= ASTNodes.getNormalizedNode(node);
	ASTNode parent= node.getParent();
	if (!(parent instanceof SingleVariableDeclaration) || !(parent.getParent() instanceof MethodDeclaration)) {
		return false;
	}
	SingleVariableDeclaration paramDecl= (SingleVariableDeclaration) parent;
	IVariableBinding binding= paramDecl.resolveBinding();

	MethodDeclaration methodDecl= (MethodDeclaration) parent.getParent();
	if (binding == null || methodDecl.getBody() == null) {
		return false;
	}
	ITypeBinding typeBinding= binding.getType();
	if (typeBinding == null) {
		return false;
	}

	if (resultingCollections == null) {
		return true;
	}

	ITypeBinding parentType= Bindings.getBindingOfParentType(node);
	if (parentType != null) {
		if (parentType.isInterface()) {
			return false;
		}
		// assign to existing fields
		CompilationUnit root= context.getASTRoot();
		IVariableBinding[] declaredFields= parentType.getDeclaredFields();
		boolean isStaticContext= ASTResolving.isInStaticContext(node);
		for (int i= 0; i < declaredFields.length; i++) {
			IVariableBinding curr= declaredFields[i];
			if (isStaticContext == Modifier.isStatic(curr.getModifiers()) && typeBinding.isAssignmentCompatible(curr.getType())) {
				ASTNode fieldDeclFrag= root.findDeclaringNode(curr);
				if (fieldDeclFrag instanceof VariableDeclarationFragment) {
					VariableDeclarationFragment fragment= (VariableDeclarationFragment) fieldDeclFrag;
					if (fragment.getInitializer() == null) {
						resultingCollections.add(new AssignToVariableAssistProposal(context.getCompilationUnit(), paramDecl, fragment, typeBinding, IProposalRelevance.ASSIGN_PARAM_TO_EXISTING_FIELD));
					}
				}
			}
		}
	}

	AssignToVariableAssistProposal fieldProposal= new AssignToVariableAssistProposal(context.getCompilationUnit(), paramDecl, null, typeBinding, IProposalRelevance.ASSIGN_PARAM_TO_NEW_FIELD);
	fieldProposal.setCommandId(ASSIGN_PARAM_TO_FIELD_ID);
	resultingCollections.add(fieldProposal);
	return true;
}
 
Example 17
Source File: QuickAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static boolean getAssignParamToFieldProposals(IInvocationContext context, ASTNode node, Collection<ChangeCorrectionProposal> resultingCollections) {
	node = ASTNodes.getNormalizedNode(node);
	ASTNode parent = node.getParent();
	if (!(parent instanceof SingleVariableDeclaration) || !(parent.getParent() instanceof MethodDeclaration)) {
		return false;
	}
	SingleVariableDeclaration paramDecl = (SingleVariableDeclaration) parent;
	IVariableBinding binding = paramDecl.resolveBinding();

	MethodDeclaration methodDecl = (MethodDeclaration) parent.getParent();
	if (binding == null || methodDecl.getBody() == null) {
		return false;
	}
	ITypeBinding typeBinding = binding.getType();
	if (typeBinding == null) {
		return false;
	}

	if (resultingCollections == null) {
		return true;
	}

	ITypeBinding parentType = Bindings.getBindingOfParentType(node);
	if (parentType != null) {
		if (parentType.isInterface()) {
			return false;
		}
		// assign to existing fields
		CompilationUnit root = context.getASTRoot();
		IVariableBinding[] declaredFields = parentType.getDeclaredFields();
		boolean isStaticContext = ASTResolving.isInStaticContext(node);
		for (int i = 0; i < declaredFields.length; i++) {
			IVariableBinding curr = declaredFields[i];
			if (isStaticContext == Modifier.isStatic(curr.getModifiers()) && typeBinding.isAssignmentCompatible(curr.getType())) {
				ASTNode fieldDeclFrag = root.findDeclaringNode(curr);
				if (fieldDeclFrag instanceof VariableDeclarationFragment) {
					VariableDeclarationFragment fragment = (VariableDeclarationFragment) fieldDeclFrag;
					if (fragment.getInitializer() == null) {
						resultingCollections.add(new AssignToVariableAssistProposal(context.getCompilationUnit(), paramDecl, fragment, typeBinding, IProposalRelevance.ASSIGN_PARAM_TO_EXISTING_FIELD));
					}
				}
			}
		}
	}

	AssignToVariableAssistProposal fieldProposal = new AssignToVariableAssistProposal(context.getCompilationUnit(), paramDecl, null, typeBinding, IProposalRelevance.ASSIGN_PARAM_TO_NEW_FIELD);
	resultingCollections.add(fieldProposal);
	return true;
}
 
Example 18
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static void addNewMethodProposals(ICompilationUnit cu, CompilationUnit astRoot, Expression sender, List<Expression> arguments, boolean isSuperInvocation, ASTNode invocationNode, String methodName, Collection<ICommandAccess> proposals) throws JavaModelException {
	ITypeBinding nodeParentType= Bindings.getBindingOfParentType(invocationNode);
	ITypeBinding binding= null;
	if (sender != null) {
		binding= sender.resolveTypeBinding();
	} else {
		binding= nodeParentType;
		if (isSuperInvocation && binding != null) {
			binding= binding.getSuperclass();
		}
	}
	if (binding != null && binding.isFromSource()) {
		ITypeBinding senderDeclBinding= binding.getTypeDeclaration();

		ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, senderDeclBinding);
		if (targetCU != null) {
			String label;
			Image image;
			ITypeBinding[] parameterTypes= getParameterTypes(arguments);
			if (parameterTypes != null) {
				String sig= ASTResolving.getMethodSignature(methodName, parameterTypes, false);

				if (ASTResolving.isUseableTypeInContext(parameterTypes, senderDeclBinding, false)) {
					if (nodeParentType == senderDeclBinding) {
						label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_description, sig);
						image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PRIVATE);
					} else {
						label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, new Object[] { sig, BasicElementLabels.getJavaElementName(senderDeclBinding.getName()) } );
						image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
					}
					proposals.add(new NewMethodCorrectionProposal(label, targetCU, invocationNode, arguments, senderDeclBinding, IProposalRelevance.CREATE_METHOD, image));
				}
				if (senderDeclBinding.isNested() && cu.equals(targetCU) && sender == null && Bindings.findMethodInHierarchy(senderDeclBinding, methodName, (ITypeBinding[]) null) == null) { // no covering method
					ASTNode anonymDecl= astRoot.findDeclaringNode(senderDeclBinding);
					if (anonymDecl != null) {
						senderDeclBinding= Bindings.getBindingOfParentType(anonymDecl.getParent());
						if (!senderDeclBinding.isAnonymous() && ASTResolving.isUseableTypeInContext(parameterTypes, senderDeclBinding, false)) {
							String[] args= new String[] { sig, ASTResolving.getTypeSignature(senderDeclBinding) };
							label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, args);
							image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PROTECTED);
							proposals.add(new NewMethodCorrectionProposal(label, targetCU, invocationNode, arguments, senderDeclBinding, IProposalRelevance.CREATE_METHOD, image));
						}
					}
				}
			}
		}
	}
}
 
Example 19
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static void addQualifierToOuterProposal(IInvocationContext context, MethodInvocation invocationNode, IMethodBinding binding, Collection<ICommandAccess> proposals) {
	ITypeBinding declaringType= binding.getDeclaringClass();
	ITypeBinding parentType= Bindings.getBindingOfParentType(invocationNode);
	ITypeBinding currType= parentType;

	boolean isInstanceMethod= !Modifier.isStatic(binding.getModifiers());

	while (currType != null && !Bindings.isSuperType(declaringType, currType)) {
		if (isInstanceMethod && Modifier.isStatic(currType.getModifiers())) {
			return;
		}
		currType= currType.getDeclaringClass();
	}
	if (currType == null || currType == parentType) {
		return;
	}

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

	String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetoouter_description, ASTResolving.getTypeSignature(currType));
	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.QUALIFY_WITH_ENCLOSING_TYPE, image);

	ImportRewrite imports= proposal.createImportRewrite(context.getASTRoot());
	ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(invocationNode, imports);
	AST ast= invocationNode.getAST();

	String qualifier= imports.addImport(currType, importRewriteContext);
	Name name= ASTNodeFactory.newName(ast, qualifier);

	Expression newExpression;
	if (isInstanceMethod) {
		ThisExpression expr= ast.newThisExpression();
		expr.setQualifier(name);
		newExpression= expr;
	} else {
		newExpression= name;
	}

	rewrite.set(invocationNode, MethodInvocation.EXPRESSION_PROPERTY, newExpression, null);

	proposals.add(proposal);
}