org.eclipse.jdt.core.dom.Name Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.Name. 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: NewCUProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static String getTypeName(int typeKind, Name node) {
	String name = ASTNodes.getSimpleNameIdentifier(node);

	if (isParameterizedType(typeKind, node)) {
		ASTNode parent = node.getParent();
		String typeArgBaseName = getGenericTypeArgBaseName(name);
		int nTypeArgs = ((ParameterizedType) parent.getParent()).typeArguments().size();
		StringBuilder buf = new StringBuilder(name);
		buf.append('<');
		if (nTypeArgs == 1) {
			buf.append(typeArgBaseName);
		} else {
			for (int i = 0; i < nTypeArgs; i++) {
				if (i != 0) {
					buf.append(", "); //$NON-NLS-1$
				}
				buf.append(typeArgBaseName).append(i + 1);
			}
		}
		buf.append('>');
		return buf.toString();
	}
	return name;
}
 
Example #2
Source File: RefactoringUtility.java    From JDeodorant with MIT License 6 votes vote down vote up
private static boolean isQualifiedType(Type type) {
	if(type instanceof SimpleType) {
		SimpleType simpleType = (SimpleType)type;
		Name name = simpleType.getName();
		if(name instanceof QualifiedName) {
			return true;
		}
	}
	else if(type instanceof QualifiedType) {
		QualifiedType qualifiedType = (QualifiedType)type;
		Type qualifier = qualifiedType.getQualifier();
		return isQualifiedType(qualifier);
	}
	else if(type instanceof ArrayType) {
		ArrayType arrayType = (ArrayType)type;
		Type elementType = arrayType.getElementType();
		return isQualifiedType(elementType);
	}
	else if(type instanceof ParameterizedType) {
		ParameterizedType parameterizedType = (ParameterizedType)type;
		Type erasureType = parameterizedType.getType();
		return isQualifiedType(erasureType);
	}
	return false;
}
 
Example #3
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean visit(final SuperMethodInvocation node) {
  Name _qualifier = node.getQualifier();
  boolean _tripleNotEquals = (_qualifier != null);
  if (_tripleNotEquals) {
    node.getQualifier().accept(this);
    this.appendToBuffer(".");
  }
  this.appendToBuffer("super.");
  boolean _isEmpty = node.typeArguments().isEmpty();
  boolean _not = (!_isEmpty);
  if (_not) {
    this.appendTypeParameters(node.typeArguments());
  }
  node.getName().accept(this);
  this.appendToBuffer("(");
  this.visitAllSeparatedByComma(node.arguments());
  this.appendToBuffer(")");
  return false;
}
 
Example #4
Source File: Checks.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @param e
 * @return int
 *          Checks.IS_RVALUE			if e is an rvalue
 *          Checks.IS_RVALUE_GUESSED	if e is guessed as an rvalue
 *          Checks.NOT_RVALUE_VOID  	if e is not an rvalue because its type is void
 *          Checks.NOT_RVALUE_MISC  	if e is not an rvalue for some other reason
 */
public static int checkExpressionIsRValue(Expression e) {
	if (e instanceof Name) {
		if(!(((Name) e).resolveBinding() instanceof IVariableBinding)) {
			return NOT_RVALUE_MISC;
		}
	}
	if (e instanceof Annotation)
		return NOT_RVALUE_MISC;
		

	ITypeBinding tb= e.resolveTypeBinding();
	boolean guessingRequired= false;
	if (tb == null) {
		guessingRequired= true;
		tb= ASTResolving.guessBindingForReference(e);
	}
	if (tb == null)
		return NOT_RVALUE_MISC;
	else if (tb.getName().equals("void")) //$NON-NLS-1$
		return NOT_RVALUE_VOID;

	return guessingRequired ? IS_RVALUE_GUESSED : IS_RVALUE;
}
 
Example #5
Source File: CreateDoPrivilegedBlockResolution.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected MethodInvocation createDoPrivilegedInvocation(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
    AST ast = rewrite.getAST();

    MethodInvocation doPrivilegedInvocation = ast.newMethodInvocation();
    ClassInstanceCreation privilegedActionCreation = createPrivilegedActionCreation(rewrite, classLoaderCreation);
    List<Expression> arguments = checkedList(doPrivilegedInvocation.arguments());

    if (!isStaticImport()) {
        Name accessControllerName;
        if (isUpdateImports()) {
            accessControllerName = ast.newSimpleName(AccessController.class.getSimpleName());
        } else {
            accessControllerName = ast.newName(AccessController.class.getName());
        }
        doPrivilegedInvocation.setExpression(accessControllerName);
    }
    doPrivilegedInvocation.setName(ast.newSimpleName(DO_PRIVILEGED_METHOD_NAME));
    arguments.add(privilegedActionCreation);

    return doPrivilegedInvocation;
}
 
Example #6
Source File: ConstructorFromSuperclassProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private SuperConstructorInvocation addEnclosingInstanceAccess(ASTRewrite rewrite, ImportRewriteContext importRewriteContext, List<SingleVariableDeclaration> parameters, String[] paramNames, ITypeBinding enclosingInstance) {
	AST ast= rewrite.getAST();
	SuperConstructorInvocation invocation= ast.newSuperConstructorInvocation();

	SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
	var.setType(getImportRewrite().addImport(enclosingInstance, ast, importRewriteContext));
	String[] enclosingArgNames= StubUtility.getArgumentNameSuggestions(getCompilationUnit().getJavaProject(), enclosingInstance.getTypeDeclaration().getName(), 0, paramNames);
	String firstName= enclosingArgNames[0];
	var.setName(ast.newSimpleName(firstName));
	parameters.add(var);

	Name enclosing= ast.newSimpleName(firstName);
	invocation.setExpression(enclosing);

	String key= "arg_name_" + firstName; //$NON-NLS-1$
	addLinkedPosition(rewrite.track(enclosing), false, key);
	for (int i= 0; i < enclosingArgNames.length; i++) {
		addLinkedPositionProposal(key, enclosingArgNames[i], null); // alternative names
	}
	return invocation;
}
 
Example #7
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static ITypeBinding extractExpressionType(SimpleType variableIdentifier) {
	ScopeAnalyzer analyzer= new ScopeAnalyzer((CompilationUnit) variableIdentifier.getRoot());
	// get the name of the variable to search the type for
	Name name= null;
	if (variableIdentifier.getName() instanceof SimpleName) {
		name= variableIdentifier.getName();
	} else if (variableIdentifier.getName() instanceof QualifiedName) {
		name= ((QualifiedName) variableIdentifier.getName()).getName();
	}

	// analyze variables which are available in the scope at the position of the quick assist invokation
	IBinding[] declarationsInScope= analyzer.getDeclarationsInScope(name.getStartPosition(), ScopeAnalyzer.VARIABLES);
	for (int i= 0; i < declarationsInScope.length; i++) {
		IBinding currentVariable= declarationsInScope[i];
		if (((IVariableBinding) currentVariable).getName().equals(name.getFullyQualifiedName())) {
			return ((IVariableBinding) currentVariable).getType();
		}
	}
	return null;
}
 
Example #8
Source File: RegionUpdaterFactory.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new region updater for the given text edit contained within the
 * given node.
 * 
 * @param originalEdit the text edit
 * @param node the most-specific node that contains the text edit
 * @param referenceUpdater an reference updater knowledgeable about the
 *          refactoring that is taking place
 * @param matcher an AST matcher knowledgeable about refactoring that is
 *          taking place
 * @return a region updater instance for the given text edit
 * @throws RefactoringException if there was an error creating a region
 *           updater
 */
public static RegionUpdater newRegionUpdater(ReplaceEdit originalEdit,
    ASTNode node, ReferenceUpdater referenceUpdater, ASTMatcher matcher)
    throws RefactoringException {

  if (node instanceof Name) {
    return new NameRegionUpdater(originalEdit, referenceUpdater, (Name) node,
        matcher);

  } else if (node instanceof TextElement) {
    return new TextElementRegionUpdater(originalEdit, referenceUpdater,
        (TextElement) node, matcher);
  }

  throw new RefactoringException("This AST node type is not supported");
}
 
Example #9
Source File: SuperTypeConstraintsCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public final void endVisit(final QualifiedName node) {
	final ASTNode parent= node.getParent();
	final Name qualifier= node.getQualifier();
	IBinding binding= qualifier.resolveBinding();
	if (binding instanceof ITypeBinding) {
		final ConstraintVariable2 variable= fModel.createTypeVariable((ITypeBinding) binding, new CompilationUnitRange(RefactoringASTParser.getCompilationUnit(node), new SourceRange(qualifier.getStartPosition(), qualifier.getLength())));
		if (variable != null)
			qualifier.setProperty(PROPERTY_CONSTRAINT_VARIABLE, variable);
	}
	binding= node.getName().resolveBinding();
	if (binding instanceof IVariableBinding && !(parent instanceof ImportDeclaration))
		endVisit((IVariableBinding) binding, qualifier, node);
	else if (binding instanceof ITypeBinding && parent instanceof MethodDeclaration)
		endVisit((ITypeBinding) binding, node);
}
 
Example #10
Source File: NameResolver.java    From SnowGraph with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluates fully qualified name of the Name object.
 */
private static String getFullName(Name name) {
    // check if the root node is a CompilationUnit
    if (name.getRoot().getClass() != CompilationUnit.class) {
        // cannot resolve a full name, CompilationUnit root node is missing
        return name.getFullyQualifiedName();
    }
    // get the root node
    CompilationUnit root = (CompilationUnit) name.getRoot();
    // check if the name is declared in the same file
    TypeDeclVisitor tdVisitor = new TypeDeclVisitor(name.getFullyQualifiedName());
    root.accept(tdVisitor);
    if (tdVisitor.getFound()) {
        // the name is the use of the TypeDeclaration in the same file
        return getFullName(tdVisitor.getTypeDecl());
    }
    // check if the name is declared in the same package or imported
    PckgImprtVisitor piVisitor = new PckgImprtVisitor(name.getFullyQualifiedName());
    root.accept(piVisitor);
    if (piVisitor.getFound()) {
        // the name is declared in the same package or imported
        return piVisitor.getFullName();
    }
    // could be a class from the java.lang (String) or a param name (T, E,...)
    return name.getFullyQualifiedName();
}
 
Example #11
Source File: OrganizeImportsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static void addImports(CompilationUnit root, ICompilationUnit unit, String[] favourites, ImportRewrite importRewrite, AST ast, ASTRewrite astRewrite, SimpleName node, boolean isMethod) throws JavaModelException {
	String name = node.getIdentifier();
	String[] imports = SimilarElementsRequestor.getStaticImportFavorites(unit, name, isMethod, favourites);
	if (imports.length > 1) {
		// See https://github.com/redhat-developer/vscode-java/issues/1472
		return;
	}
	for (int i = 0; i < imports.length; i++) {
		String curr = imports[i];
		String qualifiedTypeName = Signature.getQualifier(curr);
		String res = importRewrite.addStaticImport(qualifiedTypeName, name, isMethod, new ContextSensitiveImportRewriteContext(root, node.getStartPosition(), importRewrite));
		int dot = res.lastIndexOf('.');
		if (dot != -1) {
			String usedTypeName = importRewrite.addImport(qualifiedTypeName);
			Name newName = ast.newQualifiedName(ast.newName(usedTypeName), ast.newSimpleName(name));
			astRewrite.replace(node, newName, null);
		}
	}
}
 
Example #12
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static SimpleName getLeftMostSimpleName(Name name) {
	if (name instanceof SimpleName) {
		return (SimpleName)name;
	} else {
		final SimpleName[] result= new SimpleName[1];
		ASTVisitor visitor= new ASTVisitor() {
			@Override
			public boolean visit(QualifiedName qualifiedName) {
				Name left= qualifiedName.getQualifier();
				if (left instanceof SimpleName)
					result[0]= (SimpleName)left;
				else
					left.accept(this);
				return false;
			}
		};
		name.accept(visitor);
		return result[0];
	}
}
 
Example #13
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the topmost ancestor of <code>node</code> that is a {@link Type} (but not a {@link UnionType}).
 * <p>
 * <b>Note:</b> The returned node often resolves to a different binding than the given <code>node</code>!
 * 
 * @param node the starting node, can be <code>null</code>
 * @return the topmost type or <code>null</code> if the node is not a descendant of a type node
 * @see #getNormalizedNode(ASTNode)
 */
public static Type getTopMostType(ASTNode node) {
	ASTNode result= null;
	while (node instanceof Type && !(node instanceof UnionType)
			|| node instanceof Name
			|| node instanceof Annotation || node instanceof MemberValuePair
			|| node instanceof Expression) { // Expression could maybe be reduced to expression node types that can appear in an annotation
		result= node;
		node= node.getParent();
	}
	
	if (result instanceof Type)
		return (Type) result;
	
	return null;
}
 
Example #14
Source File: CodeStyleFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {
	ASTRewrite rewrite= cuRewrite.getASTRewrite();
	CompilationUnit compilationUnit= cuRewrite.getRoot();
	importType(fDeclaringClass, fName, cuRewrite.getImportRewrite(), compilationUnit);
	TextEditGroup group;
	if (fName.resolveBinding() instanceof IMethodBinding) {
		group= createTextEditGroup(FixMessages.CodeStyleFix_QualifyMethodWithDeclClass_description, cuRewrite);
	} else {
		group= createTextEditGroup(FixMessages.CodeStyleFix_QualifyFieldWithDeclClass_description, cuRewrite);
	}
	IJavaElement javaElement= fDeclaringClass.getJavaElement();
	if (javaElement instanceof IType) {
		Name qualifierName= compilationUnit.getAST().newName(((IType)javaElement).getElementName());
		SimpleName simpleName= (SimpleName)rewrite.createMoveTarget(fName);
		QualifiedName qualifiedName= compilationUnit.getAST().newQualifiedName(qualifierName, simpleName);
		rewrite.replace(fName, qualifiedName, group);
	}
}
 
Example #15
Source File: ConstantChecks.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private boolean checkName(Name name) {
	IBinding binding= name.resolveBinding();
	if (binding == null)
		return true;  /* If the binding is null because of compile errors etc.,
		                  scenarios which may have been deemed unacceptable in
		                  the presence of semantic information will be admitted. */

	// If name represents a member:
	if (binding instanceof IVariableBinding || binding instanceof IMethodBinding)
		return isMemberReferenceValidInClassInitialization(name);
	else if (binding instanceof ITypeBinding)
		return ! ((ITypeBinding) binding).isTypeVariable();
	else {
		return true; // e.g. a NameQualifiedType's qualifier, which can be a package binding
	}
}
 
Example #16
Source File: AssociativeInfixExpressionFragment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void replace(ASTRewrite rewrite, ASTNode replacement, TextEditGroup textEditGroup) {
	ASTNode groupNode= getGroupRoot();

	List<Expression> allOperands= findGroupMembersInOrderFor(getGroupRoot());
	if (allOperands.size() == fOperands.size()) {
		if (replacement instanceof Name && groupNode.getParent() instanceof ParenthesizedExpression) {
			// replace including the parenthesized expression around it
			rewrite.replace(groupNode.getParent(), replacement, textEditGroup);
		} else {
			rewrite.replace(groupNode, replacement, textEditGroup);
		}
		return;
	}

	rewrite.replace(fOperands.get(0), replacement, textEditGroup);
	int first= allOperands.indexOf(fOperands.get(0));
	int after= first + fOperands.size();
	for (int i= first + 1; i < after; i++) {
		rewrite.remove(allOperands.get(i), textEditGroup);
	}
}
 
Example #17
Source File: StructCache.java    From junion with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static Entry get(Name type) {
	IBinding b = type.resolveBinding();		
	if(b == null) {
		CompilerError.exec(CompilerError.TYPE_NOT_FOUND, type.toString() + ", " + type.getClass());
		return null;
	}
	if(b instanceof IPackageBinding) {
		return null;
	}
	if(b instanceof ITypeBinding) {
		return get((ITypeBinding)b);
	}
	if(b instanceof IVariableBinding) {
		IVariableBinding vb = (IVariableBinding)b;
		return get(vb.getType());		
	}
	Log.err("IGNORING BINFIND " + b + ", " + b.getClass());
	return null;
}
 
Example #18
Source File: MoveStaticMemberAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void rewriteName(Name name, ITypeBinding type) {
	AST creator= name.getAST();
	boolean fullyQualified= false;
	if (name instanceof QualifiedName) {
		SimpleName left= ASTNodes.getLeftMostSimpleName(name);
		if (left.resolveBinding() instanceof IPackageBinding)
			fullyQualified= true;
	}
	if (fullyQualified) {
		fCuRewrite.getASTRewrite().replace(
			name,
			ASTNodeFactory.newName(creator, type.getQualifiedName()),
			fCuRewrite.createGroupDescription(REFERENCE_UPDATE));
		fCuRewrite.getImportRemover().registerRemovedNode(name);
	} else {
		ImportRewriteContext context= new ContextSensitiveImportRewriteContext(name, fCuRewrite.getImportRewrite());
		Type result= fCuRewrite.getImportRewrite().addImport(type, fCuRewrite.getAST(), context);
		fCuRewrite.getImportRemover().registerAddedImport(type.getQualifiedName());
		Name n= ASTNodeFactory.newName(fCuRewrite.getAST(), ASTFlattener.asString(result));
		fCuRewrite.getASTRewrite().replace(
			name,
			n,
			fCuRewrite.createGroupDescription(REFERENCE_UPDATE));
		fCuRewrite.getImportRemover().registerRemovedNode(name);
		fNeedsImport= true;
	}
}
 
Example #19
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ASTNode getNewUnqualifiedTypeNode(ITypeBinding[] parameters, Name name) {
	final AST ast= name.getAST();
	boolean raw= false;
	final ITypeBinding binding= name.resolveTypeBinding();
	if (binding != null && binding.isRawType())
		raw= true;
	if (parameters != null && parameters.length > 0 && !raw) {
		final ParameterizedType type= ast.newParameterizedType(ast.newSimpleType(ast.newSimpleName(fType.getElementName())));
		for (int index= 0; index < parameters.length; index++)
			type.typeArguments().add(ast.newSimpleType(ast.newSimpleName(parameters[index].getName())));
		return type;
	}
	return ast.newSimpleType(ast.newSimpleName(fType.getElementName()));
}
 
Example #20
Source File: ASTResolving.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isWriteAccess(Name selectedNode) {
	ASTNode curr= selectedNode;
	ASTNode parent= curr.getParent();
	while (parent != null) {
		switch (parent.getNodeType()) {
			case ASTNode.QUALIFIED_NAME:
				if (((QualifiedName) parent).getQualifier() == curr) {
					return false;
				}
				break;
			case ASTNode.FIELD_ACCESS:
				if (((FieldAccess) parent).getExpression() == curr) {
					return false;
				}
				break;
			case ASTNode.SUPER_FIELD_ACCESS:
				break;
			case ASTNode.ASSIGNMENT:
				return ((Assignment) parent).getLeftHandSide() == curr;
			case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
			case ASTNode.SINGLE_VARIABLE_DECLARATION:
				return ((VariableDeclaration) parent).getName() == curr;
			case ASTNode.POSTFIX_EXPRESSION:
				return true;
			case ASTNode.PREFIX_EXPRESSION:
				PrefixExpression.Operator op= ((PrefixExpression) parent).getOperator();
				return op == PrefixExpression.Operator.DECREMENT || op == PrefixExpression.Operator.INCREMENT;
			default:
				return false;
		}

		curr= parent;
		parent= curr.getParent();
	}
	return false;
}
 
Example #21
Source File: RenameAnalyzeUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static VariableDeclaration getVariableDeclaration(Name node) {
	IBinding binding= node.resolveBinding();
	if (binding == null && node.getParent() instanceof VariableDeclaration)
		return (VariableDeclaration) node.getParent();

	if (binding != null && binding.getKind() == IBinding.VARIABLE) {
		CompilationUnit cu= (CompilationUnit) ASTNodes.getParent(node, CompilationUnit.class);
		return ASTNodes.findVariableDeclaration( ((IVariableBinding) binding), cu);
	}
	return null;
}
 
Example #22
Source File: OccurrencesFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean addPossibleStaticImport(Name node, IMethodBinding binding) {
	if (binding == null || node == null || !(fTarget instanceof IMethodBinding) || !Modifier.isStatic(binding.getModifiers()))
		return false;

	IMethodBinding targetMethodBinding= (IMethodBinding)fTarget;
	if ((fTargetIsStaticMethodImport || Modifier.isStatic(targetMethodBinding.getModifiers())) && (targetMethodBinding.getDeclaringClass().getTypeDeclaration() == binding.getDeclaringClass().getTypeDeclaration())) {
		if (node.getFullyQualifiedName().equals(targetMethodBinding.getName())) {
			fResult.add(new OccurrenceLocation(node.getStartPosition(), node.getLength(), 0, fReadDescription));
			return true;
		}
	}
	return false;
}
 
Example #23
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void addUninitializedLocalVariableProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ICompilationUnit cu= context.getCompilationUnit();

	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (!(selectedNode instanceof Name)) {
		return;
	}
	Name name= (Name) selectedNode;
	IBinding binding= name.resolveBinding();
	if (!(binding instanceof IVariableBinding)) {
		return;
	}
	IVariableBinding varBinding= (IVariableBinding) binding;

	CompilationUnit astRoot= context.getASTRoot();
	ASTNode node= astRoot.findDeclaringNode(binding);
	if (node instanceof VariableDeclarationFragment) {
		ASTRewrite rewrite= ASTRewrite.create(node.getAST());

		VariableDeclarationFragment fragment= (VariableDeclarationFragment) node;
		if (fragment.getInitializer() != null) {
			return;
		}
		Expression expression= ASTNodeFactory.newDefaultExpression(astRoot.getAST(), varBinding.getType());
		if (expression == null) {
			return;
		}
		rewrite.set(fragment, VariableDeclarationFragment.INITIALIZER_PROPERTY, expression, null);

		String label= CorrectionMessages.LocalCorrectionsSubProcessor_uninitializedvariable_description;
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);

		LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.INITIALIZE_VARIABLE, image);
		proposal.addLinkedPosition(rewrite.track(expression), false, "initializer"); //$NON-NLS-1$
		proposals.add(proposal);
	}
}
 
Example #24
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ASTNode getNewQualifiedNameNode(ITypeBinding[] parameters, Name name) {
	final AST ast= name.getAST();
	boolean raw= false;
	final ITypeBinding binding= name.resolveTypeBinding();
	if (binding != null && binding.isRawType())
		raw= true;
	if (parameters != null && parameters.length > 0 && !raw) {
		final ParameterizedType type= ast.newParameterizedType(ast.newSimpleType(ast.newName(fQualifiedTypeName)));
		for (int index= 0; index < parameters.length; index++)
			type.typeArguments().add(ast.newSimpleType(ast.newSimpleName(parameters[index].getName())));
		return type;
	}
	return ast.newName(fQualifiedTypeName);
}
 
Example #25
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(final ThisExpression it) {
  Name _qualifier = it.getQualifier();
  boolean _tripleNotEquals = (_qualifier != null);
  if (_tripleNotEquals) {
    it.getQualifier().accept(this);
    this.appendToBuffer(".");
  }
  this.appendToBuffer("this");
  return false;
}
 
Example #26
Source File: StringBuilderGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void initialize() {
	super.initialize();
	fBuilderVariableName= createNameSuggestion(getContext().is50orHigher() ? "builder" : "buffer", NamingConventions.VK_LOCAL); //$NON-NLS-1$ //$NON-NLS-2$
	fBuffer= new StringBuffer();
	VariableDeclarationFragment fragment= fAst.newVariableDeclarationFragment();
	fragment.setName(fAst.newSimpleName(fBuilderVariableName));
	ClassInstanceCreation classInstance= fAst.newClassInstanceCreation();
	Name typeName= addImport(getContext().is50orHigher() ? "java.lang.StringBuilder" : "java.lang.StringBuffer"); //$NON-NLS-1$ //$NON-NLS-2$
	classInstance.setType(fAst.newSimpleType(typeName));
	fragment.setInitializer(classInstance);
	VariableDeclarationStatement vStatement= fAst.newVariableDeclarationStatement(fragment);
	vStatement.setType(fAst.newSimpleType((Name)ASTNode.copySubtree(fAst, typeName)));
	toStringMethod.getBody().statements().add(vStatement);
}
 
Example #27
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
static CompilationUnitChange createAddImportChange(ICompilationUnit cu, Name name, String fullyQualifiedName) throws CoreException {
	String[] args= { BasicElementLabels.getJavaElementName(Signature.getSimpleName(fullyQualifiedName)),
			BasicElementLabels.getJavaElementName(Signature.getQualifier(fullyQualifiedName)) };
	String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_importtype_description, args);

	CompilationUnitChange cuChange= new CompilationUnitChange(label, cu);
	ImportRewrite importRewrite = CodeStyleConfiguration.createImportRewrite((CompilationUnit) name.getRoot(), true);
	importRewrite.addImport(fullyQualifiedName);
	cuChange.setEdit(importRewrite.rewriteImports(null));
	return cuChange;
}
 
Example #28
Source File: MoveStaticMemberAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void rewrite(SimpleName node, ITypeBinding type) {
	AST ast= node.getAST();
	ImportRewriteContext context= new ContextSensitiveImportRewriteContext(node, fCuRewrite.getImportRewrite());
	Type result= fCuRewrite.getImportRewrite().addImport(type, fCuRewrite.getAST(), context);
	fCuRewrite.getImportRemover().registerAddedImport(type.getQualifiedName());
	Name dummy= ASTNodeFactory.newName(fCuRewrite.getAST(), ASTFlattener.asString(result));
	QualifiedName name= ast.newQualifiedName(dummy, ast.newSimpleName(node.getIdentifier()));
	fCuRewrite.getASTRewrite().replace(node, name, fCuRewrite.createGroupDescription(REFERENCE_UPDATE));
	fCuRewrite.getImportRemover().registerRemovedNode(node);
	fProcessed.add(node);
	fNeedsImport= true;
}
 
Example #29
Source File: ImportReferencesCollector.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(MethodDeclaration node) {
	if (!isAffected(node)) {
		return false;
	}
	doVisitNode(node.getJavadoc());

	doVisitChildren(node.modifiers());
	doVisitChildren(node.typeParameters());

	if (!node.isConstructor()) {
		doVisitNode(node.getReturnType2());
	}
	// name not visited
	
	int apiLevel= node.getAST().apiLevel();
	if (apiLevel >= AST.JLS8) {
		doVisitNode(node.getReceiverType());
	}
	// receiverQualifier not visited:
	//   Enclosing class names cannot be shadowed by an import (qualification is always redundant).
	doVisitChildren(node.parameters());
	if (apiLevel >= AST.JLS8) {
		doVisitChildren(node.extraDimensions());
		doVisitChildren(node.thrownExceptionTypes());
	} else {
		Iterator<Name> iter= getThrownExceptions(node).iterator();
		while (iter.hasNext()) {
			typeRefFound(iter.next());
		}
	}
	if (!fSkipMethodBodies) {
		doVisitNode(node.getBody());
	}
	return false;
}
 
Example #30
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static String getSimpleNameIdentifier(Name name) {
	if (name.isQualifiedName()) {
		return ((QualifiedName) name).getName().getIdentifier();
	} else {
		return ((SimpleName) name).getIdentifier();
	}
}