Java Code Examples for org.eclipse.jdt.core.dom.Assignment#setLeftHandSide()

The following examples show how to use org.eclipse.jdt.core.dom.Assignment#setLeftHandSide() . 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: RegularBuilderWithMethodAdderFragment.java    From SparkBuilderGenerator with MIT License 6 votes vote down vote up
private Block createWithMethodBody(AST ast, String originalFieldName, String builderFieldName) {
    Block newBlock = ast.newBlock();
    ReturnStatement builderReturnStatement = ast.newReturnStatement();
    builderReturnStatement.setExpression(ast.newThisExpression());

    Assignment newAssignment = ast.newAssignment();

    FieldAccess fieldAccess = ast.newFieldAccess();
    fieldAccess.setExpression(ast.newThisExpression());
    fieldAccess.setName(ast.newSimpleName(originalFieldName));
    newAssignment.setLeftHandSide(fieldAccess);
    newAssignment.setRightHandSide(ast.newSimpleName(builderFieldName));

    newBlock.statements().add(ast.newExpressionStatement(newAssignment));
    newBlock.statements().add(builderReturnStatement);
    return newBlock;
}
 
Example 2
Source File: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Generates the Assignment in an iterator based for, used in the first statement of an iterator
 * based <code>for</code> loop body, to retrieve the next element of the {@link Iterable}
 * instance.
 * 
 * @param rewrite the current instance of {@link ASTRewrite}
 * @param loopOverType the {@link ITypeBinding} of the loop variable
 * @param loopVariableName the name of the loop variable
 * @return an {@link Assignment}, which retrieves the next element of the {@link Iterable} using
 *         the active {@link Iterator}
 */
private Assignment getIteratorBasedForBodyAssignment(ASTRewrite rewrite, ITypeBinding loopOverType, SimpleName loopVariableName) {
	AST ast= rewrite.getAST();
	Assignment assignResolvedVariable= ast.newAssignment();

	// left hand side
	SimpleName resolvedVariableName= resolveLinkedVariableNameWithProposals(rewrite, loopOverType.getName(), loopVariableName.getIdentifier(), false);
	VariableDeclarationFragment resolvedVariableDeclarationFragment= ast.newVariableDeclarationFragment();
	resolvedVariableDeclarationFragment.setName(resolvedVariableName);
	VariableDeclarationExpression resolvedVariableDeclaration= ast.newVariableDeclarationExpression(resolvedVariableDeclarationFragment);
	resolvedVariableDeclaration.setType(getImportRewrite().addImport(loopOverType, ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite())));
	assignResolvedVariable.setLeftHandSide(resolvedVariableDeclaration);

	// right hand side
	MethodInvocation invokeIteratorNextExpression= ast.newMethodInvocation();
	invokeIteratorNextExpression.setName(ast.newSimpleName("next")); //$NON-NLS-1$
	SimpleName currentElementName= ast.newSimpleName(loopVariableName.getIdentifier());
	addLinkedPosition(rewrite.track(currentElementName), LinkedPositionGroup.NO_STOP, currentElementName.getIdentifier());
	invokeIteratorNextExpression.setExpression(currentElementName);
	assignResolvedVariable.setRightHandSide(invokeIteratorNextExpression);

	assignResolvedVariable.setOperator(Assignment.Operator.ASSIGN);

	return assignResolvedVariable;
}
 
Example 3
Source File: GenerateHashCodeEqualsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Statement prepareAssignment(Expression rightHand) {
	// result = PRIME*result + (...)
	InfixExpression mul= fAst.newInfixExpression();
	mul.setLeftOperand(fAst.newSimpleName(VARIABLE_NAME_PRIME));
	mul.setRightOperand(fAst.newSimpleName(VARIABLE_NAME_RESULT));
	mul.setOperator(Operator.TIMES);

	Assignment ass= fAst.newAssignment();
	ass.setLeftHandSide(fAst.newSimpleName(VARIABLE_NAME_RESULT));

	InfixExpression plus= fAst.newInfixExpression();
	plus.setLeftOperand(mul);
	plus.setOperator(Operator.PLUS);
	plus.setRightOperand(rightHand);

	ass.setRightHandSide(plus);

	return fAst.newExpressionStatement(ass);
}
 
Example 4
Source File: StagedBuilderWithMethodAdderFragment.java    From SparkBuilderGenerator with MIT License 6 votes vote down vote up
private Block createWithMethodBody(AST ast, BuilderField builderField) {
    String originalFieldName = builderField.getOriginalFieldName();
    String builderFieldName = builderField.getBuilderFieldName();

    Block newBlock = ast.newBlock();
    ReturnStatement builderReturnStatement = ast.newReturnStatement();
    builderReturnStatement.setExpression(ast.newThisExpression());

    Assignment newAssignment = ast.newAssignment();

    FieldAccess fieldAccess = ast.newFieldAccess();
    fieldAccess.setExpression(ast.newThisExpression());
    fieldAccess.setName(ast.newSimpleName(originalFieldName));
    newAssignment.setLeftHandSide(fieldAccess);
    newAssignment.setRightHandSide(ast.newSimpleName(builderFieldName));

    newBlock.statements().add(ast.newExpressionStatement(newAssignment));
    newBlock.statements().add(builderReturnStatement);
    return newBlock;
}
 
Example 5
Source File: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates an {@link Assignment} as first expression appearing in a <code>for</code> loop's
 * body. This Assignment declares a local variable and initializes it using the array's current
 * element identified by the loop index.
 * 
 * @param rewrite the current {@link ASTRewrite} instance
 * @param loopVariableName the name of the index variable in String representation
 * @return a completed {@link Assignment} containing the mentioned declaration and
 *         initialization
 */
private Assignment getForBodyAssignment(ASTRewrite rewrite, SimpleName loopVariableName) {
	AST ast= rewrite.getAST();
	ITypeBinding loopOverType= extractElementType(ast);

	Assignment assignResolvedVariable= ast.newAssignment();

	// left hand side
	SimpleName resolvedVariableName= resolveLinkedVariableNameWithProposals(rewrite, loopOverType.getName(), loopVariableName.getIdentifier(), false);
	VariableDeclarationFragment resolvedVariableDeclarationFragment= ast.newVariableDeclarationFragment();
	resolvedVariableDeclarationFragment.setName(resolvedVariableName);
	VariableDeclarationExpression resolvedVariableDeclaration= ast.newVariableDeclarationExpression(resolvedVariableDeclarationFragment);
	resolvedVariableDeclaration.setType(getImportRewrite().addImport(loopOverType, ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite())));
	assignResolvedVariable.setLeftHandSide(resolvedVariableDeclaration);

	// right hand side
	ArrayAccess access= ast.newArrayAccess();
	access.setArray((Expression) rewrite.createCopyTarget(fCurrentExpression));
	SimpleName indexName= ast.newSimpleName(loopVariableName.getIdentifier());
	addLinkedPosition(rewrite.track(indexName), LinkedPositionGroup.NO_STOP, indexName.getIdentifier());
	access.setIndex(indexName);
	assignResolvedVariable.setRightHandSide(access);

	assignResolvedVariable.setOperator(Assignment.Operator.ASSIGN);

	return assignResolvedVariable;
}
 
Example 6
Source File: AdvancedQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static Statement createAssignmentStatement(ASTRewrite rewrite, Assignment.Operator assignmentOperator, Expression origAssignee, Expression origAssigned) {
	AST ast= rewrite.getAST();
	Assignment elseAssignment= ast.newAssignment();
	elseAssignment.setOperator(assignmentOperator);
	elseAssignment.setLeftHandSide((Expression) rewrite.createCopyTarget(origAssignee));
	elseAssignment.setRightHandSide((Expression) rewrite.createCopyTarget(origAssigned));
	ExpressionStatement statement= ast.newExpressionStatement(elseAssignment);
	return statement;
}
 
Example 7
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 8
Source File: PublicConstructorWithMandatoryFieldsAdderFragment.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
public Block createMethodBody(AST ast, List<? extends BuilderField> builderFields) {
    Block body = ast.newBlock();
    for (BuilderField field : builderFields) {

        FieldAccess thisFieldAccess = createThisFieldAccess(ast, field);
        SimpleName parameterName = ast.newSimpleName(field.getBuilderFieldName());

        Assignment assignment = ast.newAssignment();
        assignment.setLeftHandSide(thisFieldAccess);
        assignment.setRightHandSide(parameterName);

        body.statements().add(ast.newExpressionStatement(assignment));
    }
    return body;
}
 
Example 9
Source File: PromoteTempToFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Statement createNewAssignmentStatement(ASTRewrite rewrite) {
AST ast= getAST();
Assignment assignment= ast.newAssignment();
SimpleName fieldName= ast.newSimpleName(fFieldName);
addLinkedName(rewrite, fieldName, true);
assignment.setLeftHandSide(fieldName);
assignment.setRightHandSide(getTempInitializerCopy(rewrite));
return ast.newExpressionStatement(assignment);
  }
 
Example 10
Source File: FieldSetterAdderFragment.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
public void populateBodyWithFieldSetCalls(AST ast, String rhsName, Block body, List<? extends BuilderField> builderFields) {
    for (BuilderField field : builderFields) {
        Assignment assignment = ast.newAssignment();

        FieldAccess fieldAccess = createThisFieldAccess(ast, field);
        assignment.setLeftHandSide(fieldAccess);

        FieldAccess builderFieldAccess = builderFieldAccessCreatorFragment.createBuilderFieldAccess(ast, rhsName, field);
        assignment.setRightHandSide(builderFieldAccess);

        body.statements().add(ast.newExpressionStatement(assignment));
    }
}
 
Example 11
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void createConstructor(final AbstractTypeDeclaration declaration, final ASTRewrite rewrite) throws CoreException {
	Assert.isNotNull(declaration);
	Assert.isNotNull(rewrite);
	final AST ast= declaration.getAST();
	final MethodDeclaration constructor= ast.newMethodDeclaration();
	constructor.setConstructor(true);
	constructor.setName(ast.newSimpleName(declaration.getName().getIdentifier()));
	final String comment= CodeGeneration.getMethodComment(fType.getCompilationUnit(), fType.getElementName(), fType.getElementName(), getNewConstructorParameterNames(), new String[0], null, null, StubUtility.getLineDelimiterUsed(fType.getJavaProject()));
	if (comment != null && comment.length() > 0) {
		final Javadoc doc= (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC);
		constructor.setJavadoc(doc);
	}
	if (fCreateInstanceField) {
		final SingleVariableDeclaration variable= ast.newSingleVariableDeclaration();
		final String name= getNameForEnclosingInstanceConstructorParameter();
		variable.setName(ast.newSimpleName(name));
		variable.setType(createEnclosingType(ast));
		constructor.parameters().add(variable);
		final Block body= ast.newBlock();
		final Assignment assignment= ast.newAssignment();
		if (fCodeGenerationSettings.useKeywordThis || fEnclosingInstanceFieldName.equals(fNameForEnclosingInstanceConstructorParameter)) {
			final FieldAccess access= ast.newFieldAccess();
			access.setExpression(ast.newThisExpression());
			access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
			assignment.setLeftHandSide(access);
		} else
			assignment.setLeftHandSide(ast.newSimpleName(fEnclosingInstanceFieldName));
		assignment.setRightHandSide(ast.newSimpleName(name));
		final Statement statement= ast.newExpressionStatement(assignment);
		body.statements().add(statement);
		constructor.setBody(body);
	} else
		constructor.setBody(ast.newBlock());
	rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertFirst(constructor, null);
}
 
Example 12
Source File: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates an {@link Assignment} as first expression appearing in an index based
 * <code>for</code> loop's body. This Assignment declares a local variable and initializes it
 * using the {@link List}'s current element identified by the loop index.
 * 
 * @param rewrite the current {@link ASTRewrite} instance
 * @param loopVariableName the name of the index variable in String representation
 * @return a completed {@link Assignment} containing the mentioned declaration and
 *         initialization
 */
private Expression getIndexBasedForBodyAssignment(ASTRewrite rewrite, SimpleName loopVariableName) {
	AST ast= rewrite.getAST();
	ITypeBinding loopOverType= extractElementType(ast);

	Assignment assignResolvedVariable= ast.newAssignment();

	// left hand side
	SimpleName resolvedVariableName= resolveLinkedVariableNameWithProposals(rewrite, loopOverType.getName(), loopVariableName.getIdentifier(), false);
	VariableDeclarationFragment resolvedVariableDeclarationFragment= ast.newVariableDeclarationFragment();
	resolvedVariableDeclarationFragment.setName(resolvedVariableName);
	VariableDeclarationExpression resolvedVariableDeclaration= ast.newVariableDeclarationExpression(resolvedVariableDeclarationFragment);
	resolvedVariableDeclaration.setType(getImportRewrite().addImport(loopOverType, ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite())));
	assignResolvedVariable.setLeftHandSide(resolvedVariableDeclaration);

	// right hand side
	MethodInvocation invokeGetExpression= ast.newMethodInvocation();
	invokeGetExpression.setName(ast.newSimpleName("get")); //$NON-NLS-1$
	SimpleName indexVariableName= ast.newSimpleName(loopVariableName.getIdentifier());
	addLinkedPosition(rewrite.track(indexVariableName), LinkedPositionGroup.NO_STOP, indexVariableName.getIdentifier());
	invokeGetExpression.arguments().add(indexVariableName);
	invokeGetExpression.setExpression((Expression) rewrite.createCopyTarget(fCurrentExpression));
	assignResolvedVariable.setRightHandSide(invokeGetExpression);

	assignResolvedVariable.setOperator(Assignment.Operator.ASSIGN);

	return assignResolvedVariable;
}
 
Example 13
Source File: ExtractFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private Statement createNewAssignmentStatement() throws JavaModelException {
	AST ast = fCURewrite.getAST();
	Assignment assignment = ast.newAssignment();
	SimpleName fieldName = ast.newSimpleName(fFieldName);
	ASTRewrite rewrite = fCURewrite.getASTRewrite();
	if (fLinkedProposalModel != null) {
		fLinkedProposalModel.getPositionGroup(KEY_NAME, true).addPosition(rewrite.track(fieldName), true);
	}

	assignment.setLeftHandSide(wrapAsFieldAccessExpression(fieldName));
	assignment.setRightHandSide(getSelectedExpression().createCopyTarget(rewrite, true));
	return ast.newExpressionStatement(assignment);
}
 
Example 14
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public boolean visit(final PrefixExpression node) {
  final Expression operand = node.getOperand();
  PrefixExpression.Operator _operator = node.getOperator();
  boolean _matched = false;
  if (Objects.equal(_operator, PrefixExpression.Operator.DECREMENT)) {
    _matched=true;
  }
  if (!_matched) {
    if (Objects.equal(_operator, PrefixExpression.Operator.INCREMENT)) {
      _matched=true;
    }
  }
  if (_matched) {
    if ((operand instanceof ArrayAccess)) {
      final String arrayName = this.computeArrayName(((ArrayAccess)operand));
      StringConcatenation _builder = new StringConcatenation();
      _builder.append("_tPreInx_");
      _builder.append(arrayName);
      final String idxName = _builder.toString();
      String op = "-";
      PrefixExpression.Operator _operator_1 = node.getOperator();
      boolean _equals = Objects.equal(_operator_1, PrefixExpression.Operator.INCREMENT);
      if (_equals) {
        op = "+";
      }
      StringConcatenation _builder_1 = new StringConcatenation();
      _builder_1.append("{val ");
      _builder_1.append(idxName);
      _builder_1.append("=");
      this.appendToBuffer(_builder_1.toString());
      ((ArrayAccess)operand).getIndex().accept(this);
      StringConcatenation _builder_2 = new StringConcatenation();
      _builder_2.append(" ");
      _builder_2.append("val ");
      _builder_2.append(idxName, " ");
      _builder_2.append("_res=");
      _builder_2.append(arrayName, " ");
      _builder_2.append(".get(");
      _builder_2.append(idxName, " ");
      _builder_2.append(")");
      _builder_2.append(op, " ");
      _builder_2.append("1");
      this.appendToBuffer(_builder_2.toString());
      StringConcatenation _builder_3 = new StringConcatenation();
      _builder_3.append(" ");
      _builder_3.append(arrayName, " ");
      _builder_3.append(".set(");
      _builder_3.append(idxName, " ");
      _builder_3.append(", ");
      _builder_3.append(idxName, " ");
      _builder_3.append("_res)  ");
      _builder_3.append(idxName, " ");
      _builder_3.append("_res}");
      this.appendToBuffer(_builder_3.toString());
      return false;
    } else {
      final AST dummyAST = AST.newAST(node.getAST().apiLevel());
      final Assignment assigment = dummyAST.newAssignment();
      final InfixExpression infixOp = dummyAST.newInfixExpression();
      ASTNode _copySubtree = ASTNode.copySubtree(dummyAST, operand);
      infixOp.setLeftOperand(((Expression) _copySubtree));
      PrefixExpression.Operator _operator_2 = node.getOperator();
      boolean _equals_1 = Objects.equal(_operator_2, PrefixExpression.Operator.DECREMENT);
      if (_equals_1) {
        infixOp.setOperator(InfixExpression.Operator.MINUS);
      } else {
        infixOp.setOperator(InfixExpression.Operator.PLUS);
      }
      infixOp.setRightOperand(dummyAST.newNumberLiteral("1"));
      ASTNode _copySubtree_1 = ASTNode.copySubtree(dummyAST, operand);
      final Expression leftSide = ((Expression) _copySubtree_1);
      assigment.setLeftHandSide(leftSide);
      assigment.setRightHandSide(infixOp);
      this.appendToBuffer("{");
      Type type = null;
      if ((operand instanceof SimpleName)) {
        type = this._aSTFlattenerUtils.findDeclaredType(((SimpleName)operand));
      }
      this.handleAssignment(assigment, leftSide, type);
      this.appendToBuffer("}");
      return false;
    }
  }
  if (!_matched) {
    if (Objects.equal(_operator, PrefixExpression.Operator.COMPLEMENT)) {
      _matched=true;
      node.getOperand().accept(this);
      this.appendToBuffer(".bitwiseNot");
    }
  }
  if (!_matched) {
    {
      this.appendToBuffer(node.getOperator().toString());
      node.getOperand().accept(this);
    }
  }
  return false;
}
 
Example 15
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public boolean visit(final PostfixExpression node) {
  final AST dummyAST = AST.newAST(node.getAST().apiLevel());
  final PostfixExpression.Operator pfOperator = node.getOperator();
  Expression _operand = node.getOperand();
  if ((_operand instanceof ArrayAccess)) {
    Expression _operand_1 = node.getOperand();
    final ArrayAccess pfOperand = ((ArrayAccess) _operand_1);
    if ((Objects.equal(pfOperator, PostfixExpression.Operator.INCREMENT) || 
      Objects.equal(pfOperator, PostfixExpression.Operator.DECREMENT))) {
      final String arrayName = this.computeArrayName(pfOperand);
      StringConcatenation _builder = new StringConcatenation();
      _builder.append("_postIndx_");
      _builder.append(arrayName);
      final String idxName = _builder.toString();
      StringConcatenation _builder_1 = new StringConcatenation();
      _builder_1.append("_postVal_");
      _builder_1.append(arrayName);
      final String tempVarName = _builder_1.toString();
      StringConcatenation _builder_2 = new StringConcatenation();
      _builder_2.append("{ var ");
      _builder_2.append(idxName);
      _builder_2.append("=");
      this.appendToBuffer(_builder_2.toString());
      pfOperand.getIndex().accept(this);
      StringConcatenation _builder_3 = new StringConcatenation();
      _builder_3.append(" ");
      _builder_3.append("var  ");
      this.appendToBuffer(_builder_3.toString());
      final VariableDeclarationFragment varDeclaration = dummyAST.newVariableDeclarationFragment();
      varDeclaration.setName(dummyAST.newSimpleName(tempVarName));
      ASTNode _copySubtree = ASTNode.copySubtree(dummyAST, pfOperand);
      final ArrayAccess arrayAccess = ((ArrayAccess) _copySubtree);
      arrayAccess.setIndex(dummyAST.newSimpleName(idxName));
      varDeclaration.setInitializer(arrayAccess);
      varDeclaration.accept(this);
      final InfixExpression infixOp = dummyAST.newInfixExpression();
      infixOp.setLeftOperand(dummyAST.newSimpleName(tempVarName));
      PostfixExpression.Operator _operator = node.getOperator();
      boolean _equals = Objects.equal(_operator, PostfixExpression.Operator.DECREMENT);
      if (_equals) {
        infixOp.setOperator(InfixExpression.Operator.MINUS);
      } else {
        infixOp.setOperator(InfixExpression.Operator.PLUS);
      }
      infixOp.setRightOperand(dummyAST.newNumberLiteral("1"));
      final Assignment assigment = dummyAST.newAssignment();
      ASTNode _copySubtree_1 = ASTNode.copySubtree(dummyAST, pfOperand);
      final ArrayAccess writeArray = ((ArrayAccess) _copySubtree_1);
      writeArray.setIndex(dummyAST.newSimpleName(idxName));
      assigment.setLeftHandSide(writeArray);
      ASTNode _copySubtree_2 = ASTNode.copySubtree(dummyAST, infixOp);
      assigment.setRightHandSide(((Expression) _copySubtree_2));
      assigment.accept(this);
      StringConcatenation _builder_4 = new StringConcatenation();
      String _xifexpression = null;
      boolean _needsReturnValue = this._aSTFlattenerUtils.needsReturnValue(node);
      if (_needsReturnValue) {
        _xifexpression = tempVarName;
      }
      _builder_4.append(_xifexpression);
      _builder_4.append(" }");
      this.appendToBuffer(_builder_4.toString());
      return false;
    }
  }
  node.getOperand().accept(this);
  this.appendToBuffer(pfOperator.toString());
  return false;
}
 
Example 16
Source File: ExtractMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private ASTNode[] createCallNodes(SnippetFinder.Match duplicate, int modifiers) {
	List<ASTNode> result= new ArrayList<ASTNode>(2);

	IVariableBinding[] locals= fAnalyzer.getCallerLocals();
	for (int i= 0; i < locals.length; i++) {
		result.add(createDeclaration(locals[i], null));
	}

	MethodInvocation invocation= fAST.newMethodInvocation();
	invocation.setName(fAST.newSimpleName(fMethodName));
	ASTNode typeNode= ASTResolving.findParentType(fAnalyzer.getEnclosingBodyDeclaration());
	RefactoringStatus status= new RefactoringStatus();
	while (fDestination != typeNode) {
		fAnalyzer.checkInput(status, fMethodName, typeNode);
		if (!status.isOK()) {
			SimpleName destinationTypeName= fAST.newSimpleName(ASTNodes.getEnclosingType(fDestination).getName());
			if ((modifiers & Modifier.STATIC) == 0) {
				ThisExpression thisExpression= fAST.newThisExpression();
				thisExpression.setQualifier(destinationTypeName);
				invocation.setExpression(thisExpression);
			} else {
				invocation.setExpression(destinationTypeName);
			}
			break;
		}
		typeNode= typeNode.getParent();
	}

	List<Expression> arguments= invocation.arguments();
	for (int i= 0; i < fParameterInfos.size(); i++) {
		ParameterInfo parameter= fParameterInfos.get(i);
		arguments.add(ASTNodeFactory.newName(fAST, getMappedName(duplicate, parameter)));
	}
	if (fLinkedProposalModel != null) {
		LinkedProposalPositionGroup nameGroup= fLinkedProposalModel.getPositionGroup(KEY_NAME, true);
		nameGroup.addPosition(fRewriter.track(invocation.getName()), false);
	}

	ASTNode call;
	int returnKind= fAnalyzer.getReturnKind();
	switch (returnKind) {
		case ExtractMethodAnalyzer.ACCESS_TO_LOCAL:
			IVariableBinding binding= fAnalyzer.getReturnLocal();
			if (binding != null) {
				VariableDeclarationStatement decl= createDeclaration(getMappedBinding(duplicate, binding), invocation);
				call= decl;
			} else {
				Assignment assignment= fAST.newAssignment();
				assignment.setLeftHandSide(ASTNodeFactory.newName(fAST,
						getMappedBinding(duplicate, fAnalyzer.getReturnValue()).getName()));
				assignment.setRightHandSide(invocation);
				call= assignment;
			}
			break;
		case ExtractMethodAnalyzer.RETURN_STATEMENT_VALUE:
			ReturnStatement rs= fAST.newReturnStatement();
			rs.setExpression(invocation);
			call= rs;
			break;
		default:
			call= invocation;
	}

	if (call instanceof Expression && !fAnalyzer.isExpressionSelected()) {
		call= fAST.newExpressionStatement((Expression)call);
	}
	result.add(call);

	// We have a void return statement. The code looks like
	// extracted();
	// return;
	if (returnKind == ExtractMethodAnalyzer.RETURN_STATEMENT_VOID && !fAnalyzer.isLastStatementSelected()) {
		result.add(fAST.newReturnStatement());
	}
	return result.toArray(new ASTNode[result.size()]);
}
 
Example 17
Source File: SelfEncapsulateFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private MethodDeclaration createSetterMethod(AST ast, ASTRewrite rewriter, String lineDelimiter) throws CoreException {
	FieldDeclaration field= (FieldDeclaration)ASTNodes.getParent(fFieldDeclaration, FieldDeclaration.class);
	Type type= field.getType();
	MethodDeclaration result= ast.newMethodDeclaration();
	result.setName(ast.newSimpleName(fSetterName));
	result.modifiers().addAll(ASTNodeFactory.newModifiers(ast, createModifiers()));
	if (fSetterMustReturnValue) {
		result.setReturnType2((Type)rewriter.createCopyTarget(type));
	}
	SingleVariableDeclaration param= ast.newSingleVariableDeclaration();
	result.parameters().add(param);
	param.setName(ast.newSimpleName(fArgName));
	param.setType((Type)rewriter.createCopyTarget(type));
	List<Dimension> extraDimensions= DimensionRewrite.copyDimensions(fFieldDeclaration.extraDimensions(), rewriter);
	param.extraDimensions().addAll(extraDimensions);

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

	String fieldAccess= createFieldAccess();
	String body= CodeGeneration.getSetterMethodBodyContent(fField.getCompilationUnit(), getTypeName(field.getParent()), fSetterName, fieldAccess, fArgName, lineDelimiter);
	if (body != null) {
		ASTNode setterNode= rewriter.createStringPlaceholder(body, ASTNode.BLOCK);
		block.statements().add(setterNode);
	} else {
		Assignment ass= ast.newAssignment();
		ass.setLeftHandSide((Expression) rewriter.createStringPlaceholder(fieldAccess, ASTNode.QUALIFIED_NAME));
		ass.setRightHandSide(ast.newSimpleName(fArgName));
		block.statements().add(ass);
	}
       if (fSetterMustReturnValue) {
       	ReturnStatement rs= ast.newReturnStatement();
       	rs.setExpression(ast.newSimpleName(fArgName));
       	block.statements().add(rs);
       }
       if (fGenerateJavadoc) {
		String string= CodeGeneration.getSetterComment(
			fField.getCompilationUnit() , getTypeName(field.getParent()), fSetterName,
			fField.getElementName(), ASTNodes.asString(type), fArgName,
			StubUtility.getBaseName(fField),
			lineDelimiter);
		if (string != null) {
			Javadoc javadoc= (Javadoc)fRewriter.createStringPlaceholder(string, ASTNode.JAVADOC);
			result.setJavadoc(javadoc);
		}
	}
	return result;
}
 
Example 18
Source File: StubUtility2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static MethodDeclaration createConstructorStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, ITypeBinding typeBinding, IMethodBinding superConstructor, IVariableBinding[] variableBindings, int modifiers, CodeGenerationSettings settings) throws CoreException {
	AST ast= rewrite.getAST();

	MethodDeclaration decl= ast.newMethodDeclaration();
	decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers & ~Modifier.ABSTRACT & ~Modifier.NATIVE));
	decl.setName(ast.newSimpleName(typeBinding.getName()));
	decl.setConstructor(true);

	List<SingleVariableDeclaration> parameters= decl.parameters();
	if (superConstructor != null) {
		createTypeParameters(imports, context, ast, superConstructor, decl);

		createParameters(unit.getJavaProject(), imports, context, ast, superConstructor, null, decl);

		createThrownExceptions(decl, superConstructor, imports, context, ast);
	}

	Block body= ast.newBlock();
	decl.setBody(body);

	String delimiter= StubUtility.getLineDelimiterUsed(unit);

	if (superConstructor != null) {
		SuperConstructorInvocation invocation= ast.newSuperConstructorInvocation();
		SingleVariableDeclaration varDecl= null;
		for (Iterator<SingleVariableDeclaration> iterator= parameters.iterator(); iterator.hasNext();) {
			varDecl= iterator.next();
			invocation.arguments().add(ast.newSimpleName(varDecl.getName().getIdentifier()));
		}
		body.statements().add(invocation);
	}

	List<String> prohibited= new ArrayList<String>();
	for (final Iterator<SingleVariableDeclaration> iterator= parameters.iterator(); iterator.hasNext();)
		prohibited.add(iterator.next().getName().getIdentifier());
	String param= null;
	List<String> list= new ArrayList<String>(prohibited);
	String[] excluded= null;
	for (int i= 0; i < variableBindings.length; i++) {
		SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
		var.setType(imports.addImport(variableBindings[i].getType(), ast, context));
		excluded= new String[list.size()];
		list.toArray(excluded);
		param= suggestParameterName(unit, variableBindings[i], excluded);
		list.add(param);
		var.setName(ast.newSimpleName(param));
		parameters.add(var);
	}

	list= new ArrayList<String>(prohibited);
	for (int i= 0; i < variableBindings.length; i++) {
		excluded= new String[list.size()];
		list.toArray(excluded);
		final String paramName= suggestParameterName(unit, variableBindings[i], excluded);
		list.add(paramName);
		final String fieldName= variableBindings[i].getName();
		Expression expression= null;
		if (paramName.equals(fieldName) || settings.useKeywordThis) {
			FieldAccess access= ast.newFieldAccess();
			access.setExpression(ast.newThisExpression());
			access.setName(ast.newSimpleName(fieldName));
			expression= access;
		} else
			expression= ast.newSimpleName(fieldName);
		Assignment assignment= ast.newAssignment();
		assignment.setLeftHandSide(expression);
		assignment.setRightHandSide(ast.newSimpleName(paramName));
		assignment.setOperator(Assignment.Operator.ASSIGN);
		body.statements().add(ast.newExpressionStatement(assignment));
	}

	if (settings != null && settings.createComments) {
		String string= CodeGeneration.getMethodComment(unit, typeBinding.getName(), decl, superConstructor, delimiter);
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}
 
Example 19
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;
}
 
Example 20
Source File: ExtractMethodRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private ASTNode[] createCallNodes(SnippetFinder.Match duplicate, int modifiers) {
	List<ASTNode> result = new ArrayList<>(2);

	IVariableBinding[] locals = fAnalyzer.getCallerLocals();
	for (int i = 0; i < locals.length; i++) {
		result.add(createDeclaration(locals[i], null));
	}

	MethodInvocation invocation = fAST.newMethodInvocation();
	invocation.setName(fAST.newSimpleName(fMethodName));
	ASTNode typeNode = ASTResolving.findParentType(fAnalyzer.getEnclosingBodyDeclaration());
	RefactoringStatus status = new RefactoringStatus();
	while (fDestination != typeNode) {
		fAnalyzer.checkInput(status, fMethodName, typeNode);
		if (!status.isOK()) {
			SimpleName destinationTypeName = fAST.newSimpleName(ASTNodes.getEnclosingType(fDestination).getName());
			if ((modifiers & Modifier.STATIC) == 0) {
				ThisExpression thisExpression = fAST.newThisExpression();
				thisExpression.setQualifier(destinationTypeName);
				invocation.setExpression(thisExpression);
			} else {
				invocation.setExpression(destinationTypeName);
			}
			break;
		}
		typeNode = typeNode.getParent();
	}

	List<Expression> arguments = invocation.arguments();
	for (int i = 0; i < fParameterInfos.size(); i++) {
		ParameterInfo parameter = fParameterInfos.get(i);
		arguments.add(ASTNodeFactory.newName(fAST, getMappedName(duplicate, parameter)));
	}
	if (fLinkedProposalModel != null) {
		LinkedProposalPositionGroupCore nameGroup = fLinkedProposalModel.getPositionGroup(KEY_NAME, true);
		nameGroup.addPosition(fRewriter.track(invocation.getName()), true);
	}

	ASTNode call;
	int returnKind = fAnalyzer.getReturnKind();
	switch (returnKind) {
		case ExtractMethodAnalyzer.ACCESS_TO_LOCAL:
			IVariableBinding binding = fAnalyzer.getReturnLocal();
			if (binding != null) {
				VariableDeclarationStatement decl = createDeclaration(getMappedBinding(duplicate, binding), invocation);
				call = decl;
			} else {
				Assignment assignment = fAST.newAssignment();
				assignment.setLeftHandSide(ASTNodeFactory.newName(fAST, getMappedBinding(duplicate, fAnalyzer.getReturnValue()).getName()));
				assignment.setRightHandSide(invocation);
				call = assignment;
			}
			break;
		case ExtractMethodAnalyzer.RETURN_STATEMENT_VALUE:
			ReturnStatement rs = fAST.newReturnStatement();
			rs.setExpression(invocation);
			call = rs;
			break;
		default:
			call = invocation;
	}

	if (call instanceof Expression && !fAnalyzer.isExpressionSelected()) {
		call = fAST.newExpressionStatement((Expression) call);
	}
	result.add(call);

	// We have a void return statement. The code looks like
	// extracted();
	// return;
	if (returnKind == ExtractMethodAnalyzer.RETURN_STATEMENT_VOID && !fAnalyzer.isLastStatementSelected()) {
		result.add(fAST.newReturnStatement());
	}
	return result.toArray(new ASTNode[result.size()]);
}