Java Code Examples for org.eclipse.jdt.core.dom.VariableDeclarationFragment#getInitializer()

The following examples show how to use org.eclipse.jdt.core.dom.VariableDeclarationFragment#getInitializer() . 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: ReplaceTypeCodeWithStateStrategy.java    From JDeodorant with MIT License 6 votes vote down vote up
private Set<MethodDeclaration> getMethodDeclarationsWithinAnonymousClassDeclarations(FieldDeclaration fieldDeclaration) {
	Set<MethodDeclaration> methods = new LinkedHashSet<MethodDeclaration>();
	List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments();
	for(VariableDeclarationFragment fragment : fragments) {
		Expression expression = fragment.getInitializer();
		if(expression != null && expression instanceof ClassInstanceCreation) {
			ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation)expression;
			AnonymousClassDeclaration anonymousClassDeclaration = classInstanceCreation.getAnonymousClassDeclaration();
			if(anonymousClassDeclaration != null) {
				List<BodyDeclaration> bodyDeclarations = anonymousClassDeclaration.bodyDeclarations();
				for(BodyDeclaration bodyDeclaration : bodyDeclarations) {
					if(bodyDeclaration instanceof MethodDeclaration)
						methods.add((MethodDeclaration)bodyDeclaration);
				}
			}
		}
	}
	return methods;
}
 
Example 2
Source File: AstVisitor.java    From jdt2famix with Eclipse Public License 1.0 6 votes vote down vote up
private void visitFragment(VariableDeclarationFragment fragment, FieldDeclaration field) {
	Attribute attribute = importer.ensureAttributeForFragment(fragment, field);
	importer.createSourceAnchor(attribute, fragment);
	importer.ensureCommentFromBodyDeclaration(attribute, field);

	/*
	 * only the last fragment of a field contains the initializer code. thus, to
	 * create the access to each variable in the fragment we need to ask that last
	 * fragment we do not have to check the existence of that last fragment, because
	 * we already know that the field has at least one fragment
	 */
	VariableDeclarationFragment lastFragment = (VariableDeclarationFragment) field.fragments()
			.get(field.fragments().size() - 1);
	if (lastFragment.getInitializer() != null) {
		Access access = importer.createAccessFromExpression(fragment.getName());
		access.setIsWrite(true);
		importer.createAccessFromExpression((Expression) lastFragment.getInitializer());
	}
	attribute.setIsStub(false);
}
 
Example 3
Source File: HierarchyProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected static FieldDeclaration createNewFieldDeclarationNode(final ASTRewrite rewrite, final CompilationUnit unit, final IField field, final VariableDeclarationFragment oldFieldFragment, final TypeVariableMaplet[] mapping, final IProgressMonitor monitor, final RefactoringStatus status, final int modifiers) throws JavaModelException {
	final VariableDeclarationFragment newFragment= rewrite.getAST().newVariableDeclarationFragment();
	copyExtraDimensions(oldFieldFragment, newFragment);
	if (oldFieldFragment.getInitializer() != null) {
		Expression newInitializer= null;
		if (mapping.length > 0)
			newInitializer= createPlaceholderForExpression(oldFieldFragment.getInitializer(), field.getCompilationUnit(), mapping, rewrite);
		else
			newInitializer= createPlaceholderForExpression(oldFieldFragment.getInitializer(), field.getCompilationUnit(), rewrite);
		newFragment.setInitializer(newInitializer);
	}
	newFragment.setName(((SimpleName) ASTNode.copySubtree(rewrite.getAST(), oldFieldFragment.getName())));
	final FieldDeclaration newField= rewrite.getAST().newFieldDeclaration(newFragment);
	final FieldDeclaration oldField= ASTNodeSearchUtil.getFieldDeclarationNode(field, unit);
	copyJavadocNode(rewrite, oldField, newField);
	copyAnnotations(oldField, newField);
	newField.modifiers().addAll(ASTNodeFactory.newModifiers(rewrite.getAST(), modifiers));
	final Type oldType= oldField.getType();
	Type newType= null;
	if (mapping.length > 0) {
		newType= createPlaceholderForType(oldType, field.getCompilationUnit(), mapping, rewrite);
	} else
		newType= createPlaceholderForType(oldType, field.getCompilationUnit(), rewrite);
	newField.setType(newType);
	return newField;
}
 
Example 4
Source File: InferTypeArgumentsConstraintCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
	public void endVisit(VariableDeclarationFragment node) {
		VariableVariable2 cv= fTCModel.makeDeclaredVariableVariable(node.resolveBinding(), fCU);
		if (cv == null)
			return;

		setConstraintVariable(node, cv);

		//TODO: prune unused CV for local variables (but not fields)

		Expression initializer= node.getInitializer();
		if (initializer == null)
			return;

		ConstraintVariable2 initializerCv= getConstraintVariable(initializer);
		if (initializerCv == null)
			return;

		fTCModel.createElementEqualsConstraints(cv, initializerCv);

		// name= initializer  -->  [initializer] <= [name]
//		if (initializerCv instanceof CollectionElementVariable2)
//			fTCModel.createSubtypeConstraint(initializerCv, cv);
	}
 
Example 5
Source File: FlowAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void endVisit(VariableDeclarationFragment node) {
	if (skipNode(node)) {
		return;
	}

	IVariableBinding binding = node.resolveBinding();
	LocalFlowInfo nameInfo = null;
	Expression initializer = node.getInitializer();
	if (binding != null && !binding.isField() && initializer != null) {
		nameInfo = new LocalFlowInfo(binding, FlowInfo.WRITE, fFlowContext);
	}
	GenericSequentialFlowInfo info = processSequential(node, initializer);
	info.merge(nameInfo, fFlowContext);
}
 
Example 6
Source File: SurroundWith.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Split off initializer in <code>fragment</code> (if any) and add it as a new expression at the end of <code>statements</code>.
 * @param statements The home of the new expression.
 * @param fragment The fragment to split.
 * @param rewrite The rewrite to use.
 */
protected static void splitOffInitializer(List<ASTNode> statements, VariableDeclarationFragment fragment, ASTRewrite rewrite) {
	Expression initializer= fragment.getInitializer();
	if (initializer != null) {
		AST ast= rewrite.getAST();
		Assignment assignment= ast.newAssignment();
		assignment.setLeftHandSide((Expression)rewrite.createCopyTarget(fragment.getName()));
		assignment.setRightHandSide((Expression)rewrite.createMoveTarget(initializer));
		statements.add(ast.newExpressionStatement(assignment));
	}
}
 
Example 7
Source File: ASTResolving.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static ITypeBinding guessVariableType(List<VariableDeclarationFragment> fragments) {
	for (Iterator<VariableDeclarationFragment> iter= fragments.iterator(); iter.hasNext();) {
		VariableDeclarationFragment frag= iter.next();
		if (frag.getInitializer() != null) {
			return Bindings.normalizeTypeBinding(frag.getInitializer().resolveTypeBinding());
		}
	}
	return null;
}
 
Example 8
Source File: ConvertForLoopOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean validateLengthFragment(VariableDeclarationFragment fragment) {
	Expression initializer= fragment.getInitializer();
	if (initializer == null)
		return false;

	if (!validateLengthQuery(initializer))
		return false;

	IVariableBinding lengthBinding= (IVariableBinding)fragment.getName().resolveBinding();
	if (lengthBinding == null)
		return false;
	fLengthBinding= lengthBinding;

	return true;
}
 
Example 9
Source File: SerialVersionDefaultOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void addLinkedPositions(final ASTRewrite rewrite, final VariableDeclarationFragment fragment, final LinkedProposalModel positionGroups) {

	Assert.isNotNull(rewrite);
	Assert.isNotNull(fragment);

	final Expression initializer= fragment.getInitializer();
	if (initializer != null) {
		LinkedProposalPositionGroup group= new LinkedProposalPositionGroup(GROUP_INITIALIZER);
		group.addPosition(rewrite.track(initializer), true);
		positionGroups.addPositionGroup(group);
	}
}
 
Example 10
Source File: ConvertIterableLoopOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IStatus checkIteratorCondition() {

		List<Expression> initializers= getForStatement().initializers();
		if (initializers.size() != 1)
			return SEMANTIC_CHANGE_WARNING_STATUS;

		Expression expression= initializers.get(0);
		if (!(expression instanceof VariableDeclarationExpression))
			return SEMANTIC_CHANGE_WARNING_STATUS;

		VariableDeclarationExpression declaration= (VariableDeclarationExpression)expression;
		List<VariableDeclarationFragment> variableDeclarationFragments= declaration.fragments();
		if (variableDeclarationFragments.size() != 1)
			return SEMANTIC_CHANGE_WARNING_STATUS;

		VariableDeclarationFragment declarationFragment= variableDeclarationFragments.get(0);

		Expression initializer= declarationFragment.getInitializer();
		if (!(initializer instanceof MethodInvocation))
			return SEMANTIC_CHANGE_WARNING_STATUS;

		MethodInvocation methodInvocation= (MethodInvocation)initializer;
		String methodName= methodInvocation.getName().getIdentifier();
		if (!"iterator".equals(methodName) || methodInvocation.arguments().size() != 0) //$NON-NLS-1$
			return SEMANTIC_CHANGE_WARNING_STATUS;

		return StatusInfo.OK_STATUS;
	}
 
Example 11
Source File: FullConstraintCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public ITypeConstraint[] create(VariableDeclarationFragment vdf){
	if (vdf.getInitializer() == null)
		return new ITypeConstraint[0];
	return fTypeConstraintFactory.createSubtypeConstraint(
			fConstraintVariableFactory.makeExpressionOrTypeVariable(vdf.getInitializer(), getContext()),
			fConstraintVariableFactory.makeExpressionOrTypeVariable(vdf.getName(), getContext()));
}
 
Example 12
Source File: FlowAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void endVisit(VariableDeclarationFragment node) {
	if (skipNode(node))
		return;

	IVariableBinding binding= node.resolveBinding();
	LocalFlowInfo nameInfo= null;
	Expression initializer= node.getInitializer();
	if (binding != null && !binding.isField() && initializer != null) {
		nameInfo= new LocalFlowInfo(binding, FlowInfo.WRITE, fFlowContext);
	}
	GenericSequentialFlowInfo info= processSequential(node, initializer);
	info.merge(nameInfo, fFlowContext);
}
 
Example 13
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 14
Source File: OccurrencesFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public boolean visit(VariableDeclarationFragment node) {
	if (node.getParent() instanceof FieldDeclaration || node.getInitializer() != null)
		addWrite(node.getName(), node.resolveBinding());
	return true;
}
 
Example 15
Source File: NewVariableCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private ASTRewrite doAddField(CompilationUnit astRoot) {
	SimpleName node= fOriginalNode;
	boolean isInDifferentCU= false;

	ASTNode newTypeDecl= astRoot.findDeclaringNode(fSenderBinding);
	if (newTypeDecl == null) {
		astRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
		newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
		isInDifferentCU= true;
	}
	ImportRewrite imports= createImportRewrite(astRoot);
	ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(node), imports);

	if (newTypeDecl != null) {
		AST ast= newTypeDecl.getAST();

		ASTRewrite rewrite= ASTRewrite.create(ast);

		VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
		fragment.setName(ast.newSimpleName(node.getIdentifier()));

		Type type= evaluateVariableType(ast, imports, importRewriteContext, fSenderBinding);

		FieldDeclaration newDecl= ast.newFieldDeclaration(fragment);
		newDecl.setType(type);
		newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, evaluateFieldModifiers(newTypeDecl)));

		if (fSenderBinding.isInterface() || fVariableKind == CONST_FIELD) {
			fragment.setInitializer(ASTNodeFactory.newDefaultExpression(ast, type, 0));
		}

		ChildListPropertyDescriptor property= ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
		List<BodyDeclaration> decls= ASTNodes.<BodyDeclaration>getChildListProperty(newTypeDecl, property);

		int maxOffset= isInDifferentCU ? -1 : node.getStartPosition();

		int insertIndex= findFieldInsertIndex(decls, newDecl, maxOffset);

		ListRewrite listRewriter= rewrite.getListRewrite(newTypeDecl, property);
		listRewriter.insertAt(newDecl, insertIndex, null);

		ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(getLinkedProposalModel(), rewrite, newDecl.modifiers(), fSenderBinding.isInterface());

		addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
		if (!isInDifferentCU) {
			addLinkedPosition(rewrite.track(node), true, KEY_NAME);
		}
		addLinkedPosition(rewrite.track(fragment.getName()), false, KEY_NAME);

		if (fragment.getInitializer() != null) {
			addLinkedPosition(rewrite.track(fragment.getInitializer()), false, KEY_INITIALIZER);
		}
		return rewrite;
	}
	return null;
}
 
Example 16
Source File: AbstractSerialVersionOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException {
	final ASTRewrite rewrite= cuRewrite.getASTRewrite();
	VariableDeclarationFragment fragment= null;
	for (int i= 0; i < fNodes.length; i++) {
		final ASTNode node= fNodes[i];

		final AST ast= node.getAST();

		fragment= ast.newVariableDeclarationFragment();
		fragment.setName(ast.newSimpleName(NAME_FIELD));

		final FieldDeclaration declaration= ast.newFieldDeclaration(fragment);
		declaration.setType(ast.newPrimitiveType(PrimitiveType.LONG));
		declaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL));

		if (!addInitializer(fragment, node))
			continue;

		if (fragment.getInitializer() != null) {

			final TextEditGroup editGroup= createTextEditGroup(FixMessages.SerialVersion_group_description, cuRewrite);
			if (node instanceof AbstractTypeDeclaration)
				rewrite.getListRewrite(node, ((AbstractTypeDeclaration) node).getBodyDeclarationsProperty()).insertAt(declaration, 0, editGroup);
			else if (node instanceof AnonymousClassDeclaration)
				rewrite.getListRewrite(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup);
			else if (node instanceof ParameterizedType) {
				final ParameterizedType type= (ParameterizedType) node;
				final ASTNode parent= type.getParent();
				if (parent instanceof ClassInstanceCreation) {
					final ClassInstanceCreation creation= (ClassInstanceCreation) parent;
					final AnonymousClassDeclaration anonymous= creation.getAnonymousClassDeclaration();
					if (anonymous != null)
						rewrite.getListRewrite(anonymous, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup);
				}
			} else
				Assert.isTrue(false);

			addLinkedPositions(rewrite, fragment, positionGroups);
		}

		final String comment= CodeGeneration.getFieldComment(fUnit, declaration.getType().toString(), NAME_FIELD, StubUtility.getLineDelimiterUsed(fUnit));
		if (comment != null && comment.length() > 0) {
			final Javadoc doc= (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC);
			declaration.setJavadoc(doc);
		}
	}
	if (fragment == null)
		return;

	positionGroups.setEndPosition(rewrite.track(fragment));
}
 
Example 17
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private FieldDeclaration performFieldRewrite(IType type, ParameterObjectFactory pof, RefactoringStatus status) throws CoreException {
	fBaseCURewrite= new CompilationUnitRewrite(type.getCompilationUnit());
	SimpleName name= (SimpleName) NodeFinder.perform(fBaseCURewrite.getRoot(), type.getNameRange());
	TypeDeclaration typeNode= (TypeDeclaration) ASTNodes.getParent(name, ASTNode.TYPE_DECLARATION);
	ASTRewrite rewrite= fBaseCURewrite.getASTRewrite();
	int modifier= Modifier.PRIVATE;
	TextEditGroup removeFieldGroup= fBaseCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractClassRefactoring_group_remove_field);
	FieldDeclaration lastField= null;
	initializeDeclaration(typeNode);
	for (Iterator<FieldInfo> iter= fVariables.values().iterator(); iter.hasNext();) {
		FieldInfo pi= iter.next();
		if (isCreateField(pi)) {
			VariableDeclarationFragment vdf= pi.declaration;
			FieldDeclaration parent= (FieldDeclaration) vdf.getParent();
			if (lastField == null)
				lastField= parent;
			else if (lastField.getStartPosition() < parent.getStartPosition())
				lastField= parent;

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

			if (fDescriptor.isCreateTopLevel()) {
				IVariableBinding binding= vdf.resolveBinding();
				ITypeRoot typeRoot= fBaseCURewrite.getCu();
				if (binding == null || binding.getType() == null){
					status.addFatalError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_fatal_error_cannot_resolve_binding, BasicElementLabels.getJavaElementName(pi.name)), JavaStatusContext.create(typeRoot, vdf));
				} else {
					ITypeBinding typeBinding= binding.getType();
					if (Modifier.isPrivate(typeBinding.getModifiers())){
						status.addError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_error_referencing_private_class, BasicElementLabels.getJavaElementName(typeBinding.getName())), JavaStatusContext.create(typeRoot, vdf));
					} else if (Modifier.isProtected(typeBinding.getModifiers())){
						ITypeBinding declaringClass= typeBinding.getDeclaringClass();
						if (declaringClass != null) {
							IPackageBinding package1= declaringClass.getPackage();
							if (package1 != null && !fDescriptor.getPackage().equals(package1.getName())){
								status.addError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_error_referencing_protected_class, new String[] {BasicElementLabels.getJavaElementName(typeBinding.getName()), BasicElementLabels.getJavaElementName(fDescriptor.getPackage())}), JavaStatusContext.create(typeRoot, vdf));
							}
						}
					}
				}
			}
			Expression initializer= vdf.getInitializer();
			if (initializer != null)
				pi.initializer= initializer;
			int modifiers= parent.getModifiers();
			if (!MemberVisibilityAdjustor.hasLowerVisibility(modifiers, modifier)){
				modifier= modifiers;
			}
		}
	}
	FieldDeclaration fieldDeclaration= createParameterObjectField(pof, typeNode, modifier);
	ListRewrite bodyDeclList= rewrite.getListRewrite(typeNode, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
	if (lastField != null)
		bodyDeclList.insertAfter(fieldDeclaration, lastField, null);
	else
		bodyDeclList.insertFirst(fieldDeclaration, null);
	return fieldDeclaration;
}
 
Example 18
Source File: AbstractLoopUtilities.java    From JDeodorant with MIT License 4 votes vote down vote up
public static List<ASTNode> getVariableDeclarationsAndAssignmentsContainingAccessUsingVariable(Statement body, ControlVariable variable)
{
	StatementExtractor statementExtractor = new StatementExtractor();
	ExpressionExtractor expressionExtractor = new ExpressionExtractor();
	ArrayList<ASTNode> returnList = new ArrayList<ASTNode>();
	List<Statement> variableDeclarationStatements = statementExtractor.getVariableDeclarationStatements(body);
	List<Expression> assignments = expressionExtractor.getAssignments(body);
	for (Statement currentStatement : variableDeclarationStatements)
	{
		List<VariableDeclarationFragment> fragments = ((VariableDeclarationStatement)currentStatement).fragments();
		for (VariableDeclarationFragment fragment : fragments)
		{
			Expression initializer = fragment.getInitializer();
			if (isAccessUsingVariable(initializer, variable))
			{
				returnList.add(fragment);
			}
		}
	}
	for (Expression currentExpression : assignments)
	{
		Assignment currentAssignment = (Assignment)currentExpression;
		Expression rightHandSide = currentAssignment.getRightHandSide();
		if (isAccessUsingVariable(rightHandSide, variable))
		{
			returnList.add(currentAssignment);
		}
	}
	List<Expression> methodInvocations = expressionExtractor.getMethodInvocations(body);
	for (Expression expression : methodInvocations)
	{
		if (expression instanceof MethodInvocation)
		{
			MethodInvocation methodInvocation = (MethodInvocation)expression;
			Expression methodInvocationExpression = methodInvocation.getExpression();
			if(methodInvocationExpression != null)
			{
				if (isAccessUsingVariable(methodInvocationExpression, variable))
				{
					returnList.add(methodInvocation);
				}
			}
		}
	}
	return returnList;
}
 
Example 19
Source File: NumberOfAssignments.java    From ck with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(VariableDeclarationFragment node) {
	if(node.getInitializer()!=null)
		qty++;
}
 
Example 20
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;
}