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

The following examples show how to use org.eclipse.jdt.core.dom.VariableDeclarationFragment#getParent() . 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: RefactoringUtility.java    From JDeodorant with MIT License 6 votes vote down vote up
private static Type extractType(VariableDeclaration variableDeclaration) {
	Type returnedVariableType = null;
	if(variableDeclaration instanceof SingleVariableDeclaration) {
		SingleVariableDeclaration singleVariableDeclaration = (SingleVariableDeclaration)variableDeclaration;
		returnedVariableType = singleVariableDeclaration.getType();
	}
	else if(variableDeclaration instanceof VariableDeclarationFragment) {
		VariableDeclarationFragment fragment = (VariableDeclarationFragment)variableDeclaration;
		if(fragment.getParent() instanceof VariableDeclarationStatement) {
			VariableDeclarationStatement variableDeclarationStatement = (VariableDeclarationStatement)fragment.getParent();
			returnedVariableType = variableDeclarationStatement.getType();
		}
		else if(fragment.getParent() instanceof VariableDeclarationExpression) {
			VariableDeclarationExpression variableDeclarationExpression = (VariableDeclarationExpression)fragment.getParent();
			returnedVariableType = variableDeclarationExpression.getType();
		}
		else if(fragment.getParent() instanceof FieldDeclaration) {
			FieldDeclaration fieldDeclaration = (FieldDeclaration)fragment.getParent();
			returnedVariableType = fieldDeclaration.getType();
		}
	}
	return returnedVariableType;
}
 
Example 2
Source File: VariableDeclaration.java    From RefactoringMiner with MIT License 6 votes vote down vote up
private static CodeElementType extractVariableDeclarationType(org.eclipse.jdt.core.dom.VariableDeclaration variableDeclaration) {
	if(variableDeclaration instanceof SingleVariableDeclaration) {
		return CodeElementType.SINGLE_VARIABLE_DECLARATION;
	}
	else if(variableDeclaration instanceof VariableDeclarationFragment) {
		VariableDeclarationFragment fragment = (VariableDeclarationFragment)variableDeclaration;
		if(fragment.getParent() instanceof VariableDeclarationStatement) {
			return CodeElementType.VARIABLE_DECLARATION_STATEMENT;
		}
		else if(fragment.getParent() instanceof VariableDeclarationExpression) {
			return CodeElementType.VARIABLE_DECLARATION_EXPRESSION;
		}
		else if(fragment.getParent() instanceof FieldDeclaration) {
			return CodeElementType.FIELD_DECLARATION;
		}
	}
	return null;
}
 
Example 3
Source File: VariableDeclaration.java    From RefactoringMiner with MIT License 6 votes vote down vote up
private static Type extractType(org.eclipse.jdt.core.dom.VariableDeclaration variableDeclaration) {
	Type returnedVariableType = null;
	if(variableDeclaration instanceof SingleVariableDeclaration) {
		SingleVariableDeclaration singleVariableDeclaration = (SingleVariableDeclaration)variableDeclaration;
		returnedVariableType = singleVariableDeclaration.getType();
	}
	else if(variableDeclaration instanceof VariableDeclarationFragment) {
		VariableDeclarationFragment fragment = (VariableDeclarationFragment)variableDeclaration;
		if(fragment.getParent() instanceof VariableDeclarationStatement) {
			VariableDeclarationStatement variableDeclarationStatement = (VariableDeclarationStatement)fragment.getParent();
			returnedVariableType = variableDeclarationStatement.getType();
		}
		else if(fragment.getParent() instanceof VariableDeclarationExpression) {
			VariableDeclarationExpression variableDeclarationExpression = (VariableDeclarationExpression)fragment.getParent();
			returnedVariableType = variableDeclarationExpression.getType();
		}
		else if(fragment.getParent() instanceof FieldDeclaration) {
			FieldDeclaration fieldDeclaration = (FieldDeclaration)fragment.getParent();
			returnedVariableType = fieldDeclaration.getType();
		}
	}
	return returnedVariableType;
}
 
Example 4
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(final VariableDeclarationFragment it) {
  it.getName().accept(this);
  Expression _initializer = it.getInitializer();
  boolean _tripleNotEquals = (_initializer != null);
  if (_tripleNotEquals) {
    this.appendToBuffer("=");
    final Type type = this._aSTFlattenerUtils.findDeclaredType(it.getName());
    if ((this._aSTFlattenerUtils.needPrimitiveCast(type) && (!this.hasDimensions(it)))) {
      this.appendToBuffer("(");
      it.getInitializer().accept(this);
      StringConcatenation _builder = new StringConcatenation();
      _builder.append(") as ");
      _builder.append(type);
      this.appendToBuffer(_builder.toString());
    } else {
      it.getInitializer().accept(this);
    }
  } else {
    ASTNode _parent = it.getParent();
    if ((_parent instanceof VariableDeclarationStatement)) {
      ASTNode _parent_1 = it.getParent();
      boolean _isFinal = this._aSTFlattenerUtils.isFinal(((VariableDeclarationStatement) _parent_1).modifiers());
      if (_isFinal) {
        this.appendToBuffer("/* FIXME empty initializer for final variable is not supported */");
        this.addProblem(it, "Empty initializer for final variables is not supported.");
      }
    }
  }
  return false;
}
 
Example 5
Source File: Visitor.java    From RefactoringMiner with MIT License 5 votes vote down vote up
public boolean visit(VariableDeclarationFragment node) {
	if(!(node.getParent() instanceof LambdaExpression)) {
		VariableDeclaration variableDeclaration = new VariableDeclaration(cu, filePath, node);
		variableDeclarations.add(variableDeclaration);
		if(current.getUserObject() != null) {
			AnonymousClassDeclarationObject anonymous = (AnonymousClassDeclarationObject)current.getUserObject();
			anonymous.getVariableDeclarations().add(variableDeclaration);
		}
	}
	return super.visit(node);
}
 
Example 6
Source File: ReplaceTypeCodeWithStateStrategy.java    From JDeodorant with MIT License 5 votes vote down vote up
private void modifyContext() {
	boolean typeFieldInSingleFragment = false;
	VariableDeclarationFragment fragment = typeCheckElimination.getTypeField();
	if(fragment != null) {
		FieldDeclaration fieldDeclaration = (FieldDeclaration)fragment.getParent();
		if(fieldDeclaration.fragments().size() == 1) {
			typeFieldInSingleFragment = true;
		}
	}
	if(typeFieldInSingleFragment) {
		replacePrimitiveStateField();
	}
	else {
		createStateField();
		removePrimitiveStateField();
	}
	generateSetterMethodForStateField();
	generateGetterMethodForStateField();
	replaceConditionalStructureWithPolymorphicMethodInvocation();
	
	generateGettersForAccessedFields();
	generateSettersForAssignedFields();
	setPublicModifierToStaticFields();
	setPublicModifierToAccessedMethods();
	
	addRequiredImportDeclarationsToContext();
}
 
Example 7
Source File: ExtractMethodAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(VariableDeclarationFragment node) {
	boolean result= super.visit(node);
	if (isFirstSelectedNode(node)) {
		if (node.getParent() instanceof FieldDeclaration) {
			invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment_from_field, JavaStatusContext.create(fCUnit, node));
		} else {
			invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment, JavaStatusContext.create(fCUnit, node));
		}
		return false;
	}
	return result;
}
 
Example 8
Source File: ConvertForLoopOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private SingleVariableDeclaration createParameterDeclaration(String parameterName, VariableDeclarationFragment fragement, Expression arrayAccess, ForStatement statement, ImportRewrite importRewrite, ASTRewrite rewrite, TextEditGroup group, LinkedProposalPositionGroup pg, boolean makeFinal) {
	CompilationUnit compilationUnit= (CompilationUnit)arrayAccess.getRoot();
	AST ast= compilationUnit.getAST();

	SingleVariableDeclaration result= ast.newSingleVariableDeclaration();

	SimpleName name= ast.newSimpleName(parameterName);
	pg.addPosition(rewrite.track(name), true);
	result.setName(name);

	ITypeBinding arrayTypeBinding= arrayAccess.resolveTypeBinding();
	Type type= importType(arrayTypeBinding.getElementType(), statement, importRewrite, compilationUnit);
	if (arrayTypeBinding.getDimensions() != 1) {
		type= ast.newArrayType(type, arrayTypeBinding.getDimensions() - 1);
	}
	result.setType(type);

	if (fragement != null) {
		VariableDeclarationStatement declaration= (VariableDeclarationStatement)fragement.getParent();
		ModifierRewrite.create(rewrite, result).copyAllModifiers(declaration, group);
	}
	if (makeFinal && (fragement == null || ASTNodes.findModifierNode(Modifier.FINAL, ASTNodes.getModifiers(fragement)) == null)) {
		ModifierRewrite.create(rewrite, result).setModifiers(Modifier.FINAL, 0, group);
	}

	return result;
}
 
Example 9
Source File: ExtractMethodAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(VariableDeclarationFragment node) {
	boolean result = super.visit(node);
	if (isFirstSelectedNode(node)) {
		if (node.getParent() instanceof FieldDeclaration) {
			invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment_from_field, JavaStatusContext.create(fCUnit, node));
		} else {
			invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment, JavaStatusContext.create(fCUnit, node));
		}
		return false;
	}
	return result;
}
 
Example 10
Source File: JavaParseTreeBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(VariableDeclarationFragment node) {
       String name= getFieldName(node);
       ASTNode parent= node.getParent();
       push(JavaNode.FIELD, name, parent.getStartPosition(), parent.getLength());
       return false;
   }
 
Example 11
Source File: JavaParseTreeBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private String getFieldName(VariableDeclarationFragment node) {
    StringBuffer buffer= new StringBuffer();
    buffer.append(node.getName().toString());
    ASTNode parent= node.getParent();
    if (parent instanceof FieldDeclaration) {
        FieldDeclaration fd= (FieldDeclaration) parent;
        buffer.append(" : "); //$NON-NLS-1$
        buffer.append(getType(fd.getType()));
    }
    return buffer.toString();
}
 
Example 12
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Remove the field or variable declaration including the initializer.
 * @param rewrite the AST rewriter to use
 * @param reference a reference to the variable to remove
 * @param group the text edit group to use
 */
private void removeVariableReferences(ASTRewrite rewrite, SimpleName reference, TextEditGroup group) {
	ASTNode parent= reference.getParent();
	while (parent instanceof QualifiedName) {
		parent= parent.getParent();
	}
	if (parent instanceof FieldAccess) {
		parent= parent.getParent();
	}

	int nameParentType= parent.getNodeType();
	if (nameParentType == ASTNode.ASSIGNMENT) {
		Assignment assignment= (Assignment) parent;
		Expression rightHand= assignment.getRightHandSide();

		ASTNode assignParent= assignment.getParent();
		if (assignParent.getNodeType() == ASTNode.EXPRESSION_STATEMENT && rightHand.getNodeType() != ASTNode.ASSIGNMENT) {
			removeVariableWithInitializer(rewrite, rightHand, assignParent, group);
		}	else {
			rewrite.replace(assignment, rewrite.createCopyTarget(rightHand), group);
		}
	} else if (nameParentType == ASTNode.SINGLE_VARIABLE_DECLARATION) {
		rewrite.remove(parent, group);
	} else if (nameParentType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
		VariableDeclarationFragment frag= (VariableDeclarationFragment) parent;
		ASTNode varDecl= frag.getParent();
		List<VariableDeclarationFragment> fragments;
		if (varDecl instanceof VariableDeclarationExpression) {
			fragments= ((VariableDeclarationExpression) varDecl).fragments();
		} else if (varDecl instanceof FieldDeclaration) {
			fragments= ((FieldDeclaration) varDecl).fragments();
		} else {
			fragments= ((VariableDeclarationStatement) varDecl).fragments();
		}
		Expression initializer = frag.getInitializer();
		ArrayList<Expression> sideEffects= new ArrayList<Expression>();
		if (initializer != null) {
			initializer.accept(new SideEffectFinder(sideEffects));
		}
		boolean sideEffectInitializer= sideEffects.size() > 0;
		if (fragments.size() == fUnusedNames.length) {
			if (fForceRemove) {
				rewrite.remove(varDecl, group);
				return;
			}
			if (parent.getParent() instanceof FieldDeclaration) {
				rewrite.remove(varDecl, group);
				return;
			}
			if (sideEffectInitializer) {
				Statement[] wrapped= new Statement[sideEffects.size()];
				for (int i= 0; i < wrapped.length; i++) {
					Expression sideEffect= sideEffects.get(i);
					Expression movedInit= (Expression) rewrite.createMoveTarget(sideEffect);
					wrapped[i]= rewrite.getAST().newExpressionStatement(movedInit);
				}
				StatementRewrite statementRewrite= new StatementRewrite(rewrite, new ASTNode[] { varDecl });
				statementRewrite.replace(wrapped, group);
			} else {
				rewrite.remove(varDecl, group);
			}
		} else {
			if (fForceRemove) {
				rewrite.remove(frag, group);
				return;
			}
			//multiple declarations in one line
			ASTNode declaration = parent.getParent();
			if (declaration instanceof FieldDeclaration) {
				rewrite.remove(frag, group);
				return;
			}
			if (declaration instanceof VariableDeclarationStatement) {
				splitUpDeclarations(rewrite, group, frag, (VariableDeclarationStatement) declaration, sideEffects);
				rewrite.remove(frag, group);
				return;
			}
			if (declaration instanceof VariableDeclarationExpression) {
				//keep constructors and method invocations
				if (!sideEffectInitializer){
					rewrite.remove(frag, group);
				}
			}
		}
	} else if (nameParentType == ASTNode.POSTFIX_EXPRESSION || nameParentType == ASTNode.PREFIX_EXPRESSION) {
		Expression expression= (Expression)parent;
		ASTNode expressionParent= expression.getParent();
		if (expressionParent.getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
			removeStatement(rewrite, expressionParent, group);
		} else {
			rewrite.remove(expression, group);
		}
	}
}
 
Example 13
Source File: PolymorphismRefactoring.java    From JDeodorant with MIT License 4 votes vote down vote up
protected void generateSettersForAssignedFields() {
	AST contextAST = sourceTypeDeclaration.getAST();
	Set<VariableDeclarationFragment> assignedFields = new LinkedHashSet<VariableDeclarationFragment>();
	assignedFields.addAll(typeCheckElimination.getAssignedFields());
	assignedFields.addAll(typeCheckElimination.getSuperAssignedFields());
	for(VariableDeclarationFragment fragment : assignedFields) {
		IMethodBinding setterMethodBinding = null;
		if(typeCheckElimination.getSuperAssignedFields().contains(fragment)) {
			for(IVariableBinding fieldBinding : typeCheckElimination.getSuperAssignedFieldBindings()) {
				if(fieldBinding.isEqualTo(fragment.resolveBinding())) {
					setterMethodBinding = typeCheckElimination.getSetterMethodBindingOfSuperAssignedField(fieldBinding);
					break;
				}
			}
		}
		else {
			setterMethodBinding = findSetterMethodInContext(fragment.resolveBinding());
		}
		if(setterMethodBinding == null) {
			FieldDeclaration fieldDeclaration = (FieldDeclaration)fragment.getParent();
			if(!fragment.equals(typeCheckElimination.getTypeField())) {
				ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST());
				MethodDeclaration newMethodDeclaration = contextAST.newMethodDeclaration();
				sourceRewriter.set(newMethodDeclaration, MethodDeclaration.RETURN_TYPE2_PROPERTY, contextAST.newPrimitiveType(PrimitiveType.VOID), null);
				ListRewrite methodDeclarationModifiersRewrite = sourceRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.MODIFIERS2_PROPERTY);
				methodDeclarationModifiersRewrite.insertLast(contextAST.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD), null);
				String methodName = fragment.getName().getIdentifier();
				methodName = "set" + methodName.substring(0,1).toUpperCase() + methodName.substring(1,methodName.length());
				sourceRewriter.set(newMethodDeclaration, MethodDeclaration.NAME_PROPERTY, contextAST.newSimpleName(methodName), null);
				ListRewrite methodDeclarationParametersRewrite = sourceRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.PARAMETERS_PROPERTY);
				SingleVariableDeclaration parameter = contextAST.newSingleVariableDeclaration();
				sourceRewriter.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, fieldDeclaration.getType(), null);
				sourceRewriter.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, fragment.getName(), null);
				methodDeclarationParametersRewrite.insertLast(parameter, null);
				Block methodDeclarationBody = contextAST.newBlock();
				ListRewrite methodDeclarationBodyStatementsRewrite = sourceRewriter.getListRewrite(methodDeclarationBody, Block.STATEMENTS_PROPERTY);
				Assignment assignment = contextAST.newAssignment();
				sourceRewriter.set(assignment, Assignment.RIGHT_HAND_SIDE_PROPERTY, fragment.getName(), null);
				sourceRewriter.set(assignment, Assignment.OPERATOR_PROPERTY, Assignment.Operator.ASSIGN, null);
				FieldAccess fieldAccess = contextAST.newFieldAccess();
				sourceRewriter.set(fieldAccess, FieldAccess.EXPRESSION_PROPERTY, contextAST.newThisExpression(), null);
				sourceRewriter.set(fieldAccess, FieldAccess.NAME_PROPERTY, fragment.getName(), null);
				sourceRewriter.set(assignment, Assignment.LEFT_HAND_SIDE_PROPERTY, fieldAccess, null);
				ExpressionStatement expressionStatement = contextAST.newExpressionStatement(assignment);
				methodDeclarationBodyStatementsRewrite.insertLast(expressionStatement, null);
				sourceRewriter.set(newMethodDeclaration, MethodDeclaration.BODY_PROPERTY, methodDeclarationBody, null);
				ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
				contextBodyRewrite.insertLast(newMethodDeclaration, null);
				try {
					TextEdit sourceEdit = sourceRewriter.rewriteAST();
					ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
					CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit);
					change.getEdit().addChild(sourceEdit);
					change.addTextEditGroup(new TextEditGroup("Create setter method for assigned field", new TextEdit[] {sourceEdit}));
				} catch (JavaModelException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
 
Example 14
Source File: PolymorphismRefactoring.java    From JDeodorant with MIT License 4 votes vote down vote up
protected void generateGettersForAccessedFields() {
	AST contextAST = sourceTypeDeclaration.getAST();
	Set<VariableDeclarationFragment> accessedFields = new LinkedHashSet<VariableDeclarationFragment>();
	accessedFields.addAll(typeCheckElimination.getAccessedFields());
	accessedFields.addAll(typeCheckElimination.getSuperAccessedFields());
	for(VariableDeclarationFragment fragment : accessedFields) {
		if((fragment.resolveBinding().getModifiers() & Modifier.STATIC) == 0) {
			IMethodBinding getterMethodBinding = null;
			if(typeCheckElimination.getSuperAccessedFields().contains(fragment)) {
				for(IVariableBinding fieldBinding : typeCheckElimination.getSuperAccessedFieldBindings()) {
					if(fieldBinding.isEqualTo(fragment.resolveBinding())) {
						getterMethodBinding = typeCheckElimination.getGetterMethodBindingOfSuperAccessedField(fieldBinding);
						break;
					}
				}
			}
			else {
				getterMethodBinding = findGetterMethodInContext(fragment.resolveBinding());
			}
			if(getterMethodBinding == null) {
				FieldDeclaration fieldDeclaration = (FieldDeclaration)fragment.getParent();
				int modifiers = fieldDeclaration.getModifiers();
				if(!fragment.equals(typeCheckElimination.getTypeField()) &&
						!((modifiers & Modifier.PUBLIC) != 0 && (modifiers & Modifier.STATIC) != 0)) {
					ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST());
					MethodDeclaration newMethodDeclaration = contextAST.newMethodDeclaration();
					sourceRewriter.set(newMethodDeclaration, MethodDeclaration.RETURN_TYPE2_PROPERTY, fieldDeclaration.getType(), null);
					ListRewrite methodDeclarationModifiersRewrite = sourceRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.MODIFIERS2_PROPERTY);
					methodDeclarationModifiersRewrite.insertLast(contextAST.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD), null);
					String methodName = fragment.getName().getIdentifier();
					methodName = "get" + methodName.substring(0,1).toUpperCase() + methodName.substring(1,methodName.length());
					sourceRewriter.set(newMethodDeclaration, MethodDeclaration.NAME_PROPERTY, contextAST.newSimpleName(methodName), null);
					Block methodDeclarationBody = contextAST.newBlock();
					ListRewrite methodDeclarationBodyStatementsRewrite = sourceRewriter.getListRewrite(methodDeclarationBody, Block.STATEMENTS_PROPERTY);
					ReturnStatement returnStatement = contextAST.newReturnStatement();
					sourceRewriter.set(returnStatement, ReturnStatement.EXPRESSION_PROPERTY, fragment.getName(), null);
					methodDeclarationBodyStatementsRewrite.insertLast(returnStatement, null);
					sourceRewriter.set(newMethodDeclaration, MethodDeclaration.BODY_PROPERTY, methodDeclarationBody, null);
					ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
					contextBodyRewrite.insertLast(newMethodDeclaration, null);
					try {
						TextEdit sourceEdit = sourceRewriter.rewriteAST();
						ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
						CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit);
						change.getEdit().addChild(sourceEdit);
						change.addTextEditGroup(new TextEditGroup("Create getter method for accessed field", new TextEdit[] {sourceEdit}));
					} catch (JavaModelException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
 
Example 15
Source File: RemoveDeclarationCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Remove the field or variable declaration including the initializer.
 * @param rewrite the ast rewrite
 * @param reference the reference
 */
private void removeVariableReferences(ASTRewrite rewrite, SimpleName reference) {
	ASTNode parent= reference.getParent();
	while (parent instanceof QualifiedName) {
		parent= parent.getParent();
	}
	if (parent instanceof FieldAccess) {
		parent= parent.getParent();
	}

	int nameParentType= parent.getNodeType();
	if (nameParentType == ASTNode.ASSIGNMENT) {
		Assignment assignment= (Assignment) parent;
		Expression rightHand= assignment.getRightHandSide();

		ASTNode assignParent= assignment.getParent();
		if (assignParent.getNodeType() == ASTNode.EXPRESSION_STATEMENT && rightHand.getNodeType() != ASTNode.ASSIGNMENT) {
			removeVariableWithInitializer(rewrite, rightHand, assignParent);
		}	else {
			rewrite.replace(assignment, rewrite.createCopyTarget(rightHand), null);
		}
	} else if (nameParentType == ASTNode.SINGLE_VARIABLE_DECLARATION) {
		rewrite.remove(parent, null);
	} else if (nameParentType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
		VariableDeclarationFragment frag= (VariableDeclarationFragment) parent;
		ASTNode varDecl= frag.getParent();
		List<VariableDeclarationFragment> fragments;
		if (varDecl instanceof VariableDeclarationExpression) {
			fragments= ((VariableDeclarationExpression) varDecl).fragments();
		} else if (varDecl instanceof FieldDeclaration) {
			fragments= ((FieldDeclaration) varDecl).fragments();
		} else {
			fragments= ((VariableDeclarationStatement) varDecl).fragments();
		}
		if (fragments.size() == 1) {
			rewrite.remove(varDecl, null);
		} else {
			rewrite.remove(frag, null); // don't try to preserve
		}
	}
}
 
Example 16
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 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: AssignToVariableAssistProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private ASTRewrite doAddField(ASTRewrite rewrite, ASTNode nodeToAssign, ITypeBinding typeBinding, int index) {
	boolean isParamToField= nodeToAssign.getNodeType() == ASTNode.SINGLE_VARIABLE_DECLARATION;

	ASTNode newTypeDecl= ASTResolving.findParentType(nodeToAssign);
	if (newTypeDecl == null) {
		return null;
	}

	Expression expression= isParamToField ? ((SingleVariableDeclaration) nodeToAssign).getName() : ((ExpressionStatement) nodeToAssign).getExpression();

	AST ast= newTypeDecl.getAST();

	createImportRewrite((CompilationUnit) nodeToAssign.getRoot());

	BodyDeclaration bodyDecl= ASTResolving.findParentBodyDeclaration(nodeToAssign);
	Block body;
	if (bodyDecl instanceof MethodDeclaration) {
		body= ((MethodDeclaration) bodyDecl).getBody();
	} else if (bodyDecl instanceof Initializer) {
		body= ((Initializer) bodyDecl).getBody();
	} else {
		return null;
	}

	IJavaProject project= getCompilationUnit().getJavaProject();
	boolean isAnonymous= newTypeDecl.getNodeType() == ASTNode.ANONYMOUS_CLASS_DECLARATION;
	boolean isStatic= Modifier.isStatic(bodyDecl.getModifiers()) && !isAnonymous;
	int modifiers= Modifier.PRIVATE;
	if (isStatic) {
		modifiers |= Modifier.STATIC;
	}

	VariableDeclarationFragment newDeclFrag= addFieldDeclaration(rewrite, newTypeDecl, modifiers, expression, nodeToAssign, typeBinding, index);
	String varName= newDeclFrag.getName().getIdentifier();

	Assignment assignment= ast.newAssignment();
	assignment.setRightHandSide((Expression) rewrite.createCopyTarget(expression));

	boolean needsThis= StubUtility.useThisForFieldAccess(project);
	if (isParamToField) {
		needsThis |= varName.equals(((SimpleName) expression).getIdentifier());
	}

	SimpleName accessName= ast.newSimpleName(varName);
	if (needsThis) {
		FieldAccess fieldAccess= ast.newFieldAccess();
		fieldAccess.setName(accessName);
		if (isStatic) {
			String typeName= ((AbstractTypeDeclaration) newTypeDecl).getName().getIdentifier();
			fieldAccess.setExpression(ast.newSimpleName(typeName));
		} else {
			fieldAccess.setExpression(ast.newThisExpression());
		}
		assignment.setLeftHandSide(fieldAccess);
	} else {
		assignment.setLeftHandSide(accessName);
	}

	ASTNode selectionNode;
	if (isParamToField) {
		// assign parameter to field
		ExpressionStatement statement= ast.newExpressionStatement(assignment);
		int insertIdx= findAssignmentInsertIndex(body.statements(), nodeToAssign) + index;
		rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY).insertAt(statement, insertIdx, null);
		selectionNode= statement;
	} else {
		if (needsSemicolon(expression)) {
			rewrite.replace(expression, ast.newExpressionStatement(assignment), null);
		} else {
			rewrite.replace(expression, assignment, null);
		}
		selectionNode= nodeToAssign;
	}

	addLinkedPosition(rewrite.track(newDeclFrag.getName()), false, KEY_NAME + index);
	if (!isParamToField) {
		FieldDeclaration fieldDeclaration= (FieldDeclaration) newDeclFrag.getParent();
		addLinkedPosition(rewrite.track(fieldDeclaration.getType()), false, KEY_TYPE);
	}
	addLinkedPosition(rewrite.track(accessName), true, KEY_NAME + index);
	IVariableBinding variableBinding= newDeclFrag.resolveBinding();
	if (variableBinding != null) {
		SimpleName[] linkedNodes= LinkedNodeFinder.findByBinding(nodeToAssign.getRoot(), variableBinding);
		for (int i= 0; i < linkedNodes.length; i++) {
			addLinkedPosition(rewrite.track(linkedNodes[i]), false, KEY_NAME + index);
		}
	}
	setEndPosition(rewrite.track(selectionNode));

	return rewrite;
}