org.eclipse.jdt.core.dom.FieldAccess#setName ( )源码实例Demo

下面列出了org.eclipse.jdt.core.dom.FieldAccess#setName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

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;
}
 
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;
}
 
private static ASTRewriteCorrectionProposal createNoSideEffectProposal(IInvocationContext context, SimpleName nodeToQualify, IVariableBinding fieldBinding, String label, int relevance) {
	AST ast= nodeToQualify.getAST();

	Expression qualifier;
	if (Modifier.isStatic(fieldBinding.getModifiers())) {
		ITypeBinding declaringClass= fieldBinding.getDeclaringClass();
		qualifier= ast.newSimpleName(declaringClass.getTypeDeclaration().getName());
	} else {
		qualifier= ast.newThisExpression();
	}

	ASTRewrite rewrite= ASTRewrite.create(ast);
	FieldAccess access= ast.newFieldAccess();
	access.setName((SimpleName) rewrite.createCopyTarget(nodeToQualify));
	access.setExpression(qualifier);
	rewrite.replace(nodeToQualify, access, null);


	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
	return new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, relevance, image);
}
 
源代码4 项目: eclipse.jdt.ls   文件: ExtractFieldRefactoring.java
private FieldAccess wrapAsFieldAccess(SimpleName fieldName, AST ast) {
	Name qualifierName = null;
	try {
		if (isDeclaredInLambdaExpression()) {
			String enclosingTypeName = getEnclosingTypeName();
			qualifierName = ast.newSimpleName(enclosingTypeName);
		}
	} catch (JavaModelException e) {
		// do nothing.
	}

	FieldAccess fieldAccess = ast.newFieldAccess();
	ThisExpression thisExpression = ast.newThisExpression();
	if (qualifierName != null) {
		thisExpression.setQualifier(qualifierName);
	}
	fieldAccess.setExpression(thisExpression);
	fieldAccess.setName(fieldName);
	return fieldAccess;
}
 
/**
 * Helper to generate an index based <code>for</code> loop to iterate over an array.
 * 
 * @param ast the current {@link AST} instance to generate the {@link ASTRewrite} for
 * @return an applicable {@link ASTRewrite} instance
 */
private ASTRewrite generateForRewrite(AST ast) {
	ASTRewrite rewrite= ASTRewrite.create(ast);

	ForStatement loopStatement= ast.newForStatement();
	SimpleName loopVariableName= resolveLinkedVariableNameWithProposals(rewrite, "int", null, true); //$NON-NLS-1$
	loopStatement.initializers().add(getForInitializer(ast, loopVariableName));

	FieldAccess getArrayLengthExpression= ast.newFieldAccess();
	getArrayLengthExpression.setExpression((Expression) rewrite.createCopyTarget(fCurrentExpression));
	getArrayLengthExpression.setName(ast.newSimpleName("length")); //$NON-NLS-1$

	loopStatement.setExpression(getLinkedInfixExpression(rewrite, loopVariableName.getIdentifier(), getArrayLengthExpression, InfixExpression.Operator.LESS));
	loopStatement.updaters().add(getLinkedIncrementExpression(rewrite, loopVariableName.getIdentifier()));

	Block forLoopBody= ast.newBlock();
	forLoopBody.statements().add(ast.newExpressionStatement(getForBodyAssignment(rewrite, loopVariableName)));
	forLoopBody.statements().add(createBlankLineStatementWithCursorPosition(rewrite));
	loopStatement.setBody(forLoopBody);
	rewrite.replace(fCurrentNode, loopStatement, null);

	return rewrite;
}
 
@Override
public boolean visit(final ThisExpression node) {
	Assert.isNotNull(node);
	Name name= node.getQualifier();
	if (fCreateInstanceField && name != null) {
		ITypeBinding binding= node.resolveTypeBinding();
		if (binding != null && Bindings.equals(binding, fTypeBinding.getDeclaringClass())) {
			AST ast= node.getAST();
			Expression expression= null;
			if (fCodeGenerationSettings.useKeywordThis || fEnclosingInstanceFieldName.equals(fNameForEnclosingInstanceConstructorParameter)) {
				FieldAccess access= ast.newFieldAccess();
				access.setExpression(ast.newThisExpression());
				access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
				expression= access;
			} else {
				expression= ast.newSimpleName(fEnclosingInstanceFieldName);
			}
			fSourceRewrite.getASTRewrite().replace(node, expression, null);
		}
	}
	return super.visit(node);
}
 
private Expression generateQualifier(String paramName, AST ast, boolean useSuper, Expression qualifier) {
	SimpleName paramSimpleName= ast.newSimpleName(paramName);
	if (useSuper) {
		SuperFieldAccess sf= ast.newSuperFieldAccess();
		sf.setName(paramSimpleName);
		if (qualifier instanceof Name) {
			sf.setQualifier((Name) qualifier);
		}
		return sf;
	}
	if (qualifier != null) {
		FieldAccess parameterAccess= ast.newFieldAccess();
		parameterAccess.setExpression(qualifier);
		parameterAccess.setName(paramSimpleName);
		return parameterAccess;
	}
	return paramSimpleName;
}
 
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {
	ASTRewrite rewrite= cuRewrite.getASTRewrite();
	TextEditGroup group= createTextEditGroup(getDescription(), cuRewrite);
	AST ast= rewrite.getAST();

	FieldAccess fieldAccess= ast.newFieldAccess();

	ThisExpression thisExpression= ast.newThisExpression();
	if (fQualifier != null)
		thisExpression.setQualifier(ast.newName(fQualifier));

	fieldAccess.setExpression(thisExpression);
	fieldAccess.setName((SimpleName) rewrite.createMoveTarget(fName));

	rewrite.replace(fName, fieldAccess, group);
}
 
private Expression getThisAccess(String name, boolean forHashCode) {
	if (fSettings.useKeywordThis || needsThisQualification(name, forHashCode)) {
		FieldAccess fa= fAst.newFieldAccess();
		fa.setExpression(fAst.newThisExpression());
		fa.setName(fAst.newSimpleName(name));
		return fa;
	}
	return fAst.newSimpleName(name);
}
 
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);
}
 
private Expression createEnclosingInstanceCreationString(final ASTNode node, final ICompilationUnit cu) throws JavaModelException {
	Assert.isTrue((node instanceof ClassInstanceCreation) || (node instanceof SuperConstructorInvocation));
	Assert.isNotNull(cu);
	Expression expression= null;
	if (node instanceof ClassInstanceCreation)
		expression= ((ClassInstanceCreation) node).getExpression();
	else
		expression= ((SuperConstructorInvocation) node).getExpression();
	final AST ast= node.getAST();
	if (expression != null)
		return expression;
	else if (JdtFlags.isStatic(fType))
		return null;
	else if (isInsideSubclassOfDeclaringType(node))
		return ast.newThisExpression();
	else if ((node.getStartPosition() >= fType.getSourceRange().getOffset() && ASTNodes.getExclusiveEnd(node) <= fType.getSourceRange().getOffset() + fType.getSourceRange().getLength())) {
		if (fCodeGenerationSettings.useKeywordThis || fEnclosingInstanceFieldName.equals(fNameForEnclosingInstanceConstructorParameter)) {
			final FieldAccess access= ast.newFieldAccess();
			access.setExpression(ast.newThisExpression());
			access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
			return access;
		} else
			return ast.newSimpleName(fEnclosingInstanceFieldName);
	} else if (isInsideTypeNestedInDeclaringType(node)) {
		final ThisExpression qualified= ast.newThisExpression();
		qualified.setQualifier(ast.newSimpleName(fType.getDeclaringType().getElementName()));
		return qualified;
	}
	return null;
}
 
private Expression createQualifiedReadAccessExpressionForEnclosingInstance(AST ast) {
	ThisExpression expression= ast.newThisExpression();
	expression.setQualifier(ast.newName(new String[] { fType.getElementName()}));
	FieldAccess access= ast.newFieldAccess();
	access.setExpression(expression);
	access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
	return access;
}
 
private Expression createReadAccessExpressionForEnclosingInstance(AST ast) {
	if (fCodeGenerationSettings.useKeywordThis || fEnclosingInstanceFieldName.equals(fNameForEnclosingInstanceConstructorParameter)) {
		final FieldAccess access= ast.newFieldAccess();
		access.setExpression(ast.newThisExpression());
		access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
		return access;
	}
	return ast.newSimpleName(fEnclosingInstanceFieldName);
}
 
private Expression createFieldAccess(ParameterInfo pi, AST ast, Expression qualifier) {
	if (qualifier instanceof Name) {
		Name name= (Name) qualifier; //create FQN for IPOR
		return ast.newName(JavaModelUtil.concatenateName(name.getFullyQualifiedName(), pi.getNewName()));
	}
	FieldAccess fa= ast.newFieldAccess();
	fa.setName(ast.newSimpleName(pi.getNewName()));
	fa.setExpression(qualifier);
	return fa;
}
 
源代码15 项目: junion   文件: BaseTranslator.java
public MethodInvocation methodTmpArrayIndex(ASTNode ArrayExpression,
		SimpleName ArrayIdentifier, Entry TypeBind, List dims) {
	if(dims.size() < 1) throw new IllegalArgumentException();

	MethodInvocation m = ast.newMethodInvocation();
	m.setExpression(name(MEM0));
	m.setName(name("tmparr"));
	List args = m.arguments();
	if(dims.size() == 1) {
		args.add((Expression)copySubtreeIfHasParent(ArrayExpression));
	}
	else {
		FieldAccess fa = ast.newFieldAccess();
		fa.setExpression((Expression)copySubtreeIfHasParent(ArrayExpression));
		fa.setName(name("r"));
		args.add(fa);
	}
	args.add((Expression)copySubtreeIfHasParent(ArrayIdentifier));
	args.add(returnInt(0));
	
	if(dims.size() == 1)
		args.add(copySubtreeIfHasParent(dims.get(0)));
	else {
		MethodInvocation idx2 = ast.newMethodInvocation();
		idx2.setExpression((Expression)copySubtreeIfHasParent(ArrayIdentifier));
		idx2.setName(name(getIndexMethodName(dims.size())));
		idx2.setProperty(TYPEBIND_PROP, FieldType.LONG);
		for(int i = 0; i < dims.size(); i++) {
			idx2.arguments().add(copySubtreeIfHasParent(dims.get(i)));
		}
		
		for(int i = 0; i < dims.size(); i++) {
			ASTNode arg3 = (ASTNode)dims.get(i);
			MethodTmp tmp3 = getMethodTmp(arg3);
			if(tmp3 != null) {
				replaceMethodTmp(arg3, (MethodInvocation)arg3, tmp3, MethodType.get, null, Assignment.Operator.ASSIGN);
			}
		}
		args.add(idx2);
	}
	
	m.setProperty(TYPEBIND_PROP, TypeBind);
	m.setProperty(TYPEBIND_METHOD_TMP, new MethodTmp(TypebindMethodTmp.Array, TypeBind));
	return m;
}
 
源代码16 项目: junion   文件: BaseTranslator.java
public FieldAccess newEntryType(Entry e) {
	FieldAccess structType = ast.newFieldAccess();
	structType.setExpression(ast.newName(e.qualifiedName));
	structType.setName(name(STRUCT_TYPE_VAR));
	return structType;
}
 
private FieldAccess createThisFieldAccess(AST ast, BuilderField field) {
    FieldAccess fieldAccess = ast.newFieldAccess();
    fieldAccess.setExpression(ast.newThisExpression());
    fieldAccess.setName(ast.newSimpleName(field.getOriginalFieldName()));
    return fieldAccess;
}
 
public FieldAccess createBuilderFieldAccess(AST ast, String builderName, BuilderField field) {
    FieldAccess builderFieldAccess = ast.newFieldAccess();
    builderFieldAccess.setExpression(ast.newSimpleName(builderName));
    builderFieldAccess.setName(ast.newSimpleName(field.getOriginalFieldName()));
    return builderFieldAccess;
}
 
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;
}
 
public static MethodDeclaration createDelegationStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, IMethodBinding delegate, IVariableBinding delegatingField, CodeGenerationSettings settings) throws CoreException {
	Assert.isNotNull(delegate);
	Assert.isNotNull(delegatingField);
	Assert.isNotNull(settings);

	AST ast= rewrite.getAST();

	MethodDeclaration decl= ast.newMethodDeclaration();
	decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, delegate.getModifiers() & ~Modifier.SYNCHRONIZED & ~Modifier.ABSTRACT & ~Modifier.NATIVE));

	decl.setName(ast.newSimpleName(delegate.getName()));
	decl.setConstructor(false);

	createTypeParameters(imports, context, ast, delegate, decl);

	decl.setReturnType2(imports.addImport(delegate.getReturnType(), ast, context));

	List<SingleVariableDeclaration> params= createParameters(unit.getJavaProject(), imports, context, ast, delegate, null, decl);

	createThrownExceptions(decl, delegate, imports, context, ast);

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

	String delimiter= StubUtility.getLineDelimiterUsed(unit);

	Statement statement= null;
	MethodInvocation invocation= ast.newMethodInvocation();
	invocation.setName(ast.newSimpleName(delegate.getName()));
	List<Expression> arguments= invocation.arguments();
	for (int i= 0; i < params.size(); i++)
		arguments.add(ast.newSimpleName(params.get(i).getName().getIdentifier()));
	if (settings.useKeywordThis) {
		FieldAccess access= ast.newFieldAccess();
		access.setExpression(ast.newThisExpression());
		access.setName(ast.newSimpleName(delegatingField.getName()));
		invocation.setExpression(access);
	} else
		invocation.setExpression(ast.newSimpleName(delegatingField.getName()));
	if (delegate.getReturnType().isPrimitive() && delegate.getReturnType().getName().equals("void")) {//$NON-NLS-1$
		statement= ast.newExpressionStatement(invocation);
	} else {
		ReturnStatement returnStatement= ast.newReturnStatement();
		returnStatement.setExpression(invocation);
		statement= returnStatement;
	}
	body.statements().add(statement);

	ITypeBinding declaringType= delegatingField.getDeclaringClass();
	if (declaringType == null) { // can be null for
		return decl;
	}

	String qualifiedName= declaringType.getQualifiedName();
	IPackageBinding packageBinding= declaringType.getPackage();
	if (packageBinding != null) {
		if (packageBinding.getName().length() > 0 && qualifiedName.startsWith(packageBinding.getName()))
			qualifiedName= qualifiedName.substring(packageBinding.getName().length());
	}

	if (settings.createComments) {
		/*
		 * TODO: have API for delegate method comments This is an inlined
		 * version of
		 * {@link CodeGeneration#getMethodComment(ICompilationUnit, String, MethodDeclaration, IMethodBinding, String)}
		 */
		delegate= delegate.getMethodDeclaration();
		String declaringClassQualifiedName= delegate.getDeclaringClass().getQualifiedName();
		String linkToMethodName= delegate.getName();
		String[] parameterTypesQualifiedNames= StubUtility.getParameterTypeNamesForSeeTag(delegate);
		String string= StubUtility.getMethodComment(unit, qualifiedName, decl, delegate.isDeprecated(), linkToMethodName, declaringClassQualifiedName, parameterTypesQualifiedNames, true, delimiter);
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}