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

The following examples show how to use org.eclipse.jdt.core.dom.SingleVariableDeclaration. 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: FullConstraintCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public ITypeConstraint[] create(SingleVariableDeclaration svd){
	ITypeConstraint[] defines= fTypeConstraintFactory.createDefinesConstraint(
			fConstraintVariableFactory.makeExpressionOrTypeVariable(svd.getName(), getContext()),
			fConstraintVariableFactory.makeTypeVariable(svd.getType()));
	if (svd.getInitializer() == null)
		return defines;
	ITypeConstraint[] constraints = fTypeConstraintFactory.createSubtypeConstraint(
			fConstraintVariableFactory.makeExpressionOrTypeVariable(svd.getInitializer(), getContext()),
			fConstraintVariableFactory.makeExpressionOrTypeVariable(svd.getName(), getContext()));
	if (defines.length == 0 && constraints.length == 0){
		return new ITypeConstraint[0];
	} else if (defines.length == 0){
		return constraints;
	} else if (constraints.length == 0){
		return defines;
	} else {
		List<ITypeConstraint> all= new ArrayList<ITypeConstraint>();
		all.addAll(Arrays.asList(defines));
		all.addAll(Arrays.asList(constraints));
		return (ITypeConstraint[])all.toArray();
	}
}
 
Example #2
Source File: NullAnnotationsRewriteOperations.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
ParameterAnnotationRewriteOperation(CompilationUnit unit, MethodDeclaration method, String annotationToAdd, String annotationToRemove, String paramName, boolean allowRemove, String message) {
	fUnit= unit;
	fKey= method.resolveBinding().getKey();
	fAnnotationToAdd= annotationToAdd;
	fAnnotationToRemove= annotationToRemove;
	fAllowRemove= allowRemove;
	fMessage= message;
	for (Object param : method.parameters()) {
		SingleVariableDeclaration argument= (SingleVariableDeclaration) param;
		if (argument.getName().getIdentifier().equals(paramName)) {
			fArgument= argument;
			fKey+= argument.getName().getIdentifier();
			return;
		}
	}
	// shouldn't happen, we've checked that paramName indeed denotes a parameter.
	throw new RuntimeException("Argument " + paramName + " not found in method " + method.getName().getIdentifier()); //$NON-NLS-1$ //$NON-NLS-2$
}
 
Example #3
Source File: NodeUtils.java    From SimFix with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean visit(MethodDeclaration node) {
	int start = _unit.getLineNumber(node.getStartPosition());
	int end = _unit.getLineNumber(node.getStartPosition() + node.getLength());
	if(start <= _line && _line <= end){
		for(Object object : node.parameters()){
			SingleVariableDeclaration svd = (SingleVariableDeclaration) object;
			_vars.put(svd.getName().toString(), svd.getType());
		}
		
		if(node.getBody() != null){
			MethodVisitor methodVisitor = new MethodVisitor();
			node.getBody().accept(methodVisitor);
			methodVisitor.dumpVarMap();
		}
		return false;
	}
	return true;
}
 
Example #4
Source File: ExtractMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void initializeParameterInfos() {
	IVariableBinding[] arguments= fAnalyzer.getArguments();
	fParameterInfos= new ArrayList<ParameterInfo>(arguments.length);
	ASTNode root= fAnalyzer.getEnclosingBodyDeclaration();
	ParameterInfo vararg= null;
	for (int i= 0; i < arguments.length; i++) {
		IVariableBinding argument= arguments[i];
		if (argument == null)
			continue;
		VariableDeclaration declaration= ASTNodes.findVariableDeclaration(argument, root);
		boolean isVarargs= declaration instanceof SingleVariableDeclaration
			? ((SingleVariableDeclaration)declaration).isVarargs()
			: false;
		ParameterInfo info= new ParameterInfo(argument, getType(declaration, isVarargs), argument.getName(), i);
		if (isVarargs) {
			vararg= info;
		} else {
			fParameterInfos.add(info);
		}
	}
	if (vararg != null) {
		fParameterInfos.add(vararg);
	}
}
 
Example #5
Source File: FlowContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
boolean isExceptionCaught(ITypeBinding excpetionType) {
	for (Iterator<List<CatchClause>> exceptions= fExceptionStack.iterator(); exceptions.hasNext(); ) {
		for (Iterator<CatchClause> catchClauses= exceptions.next().iterator(); catchClauses.hasNext(); ) {
			SingleVariableDeclaration caughtException= catchClauses.next().getException();
			IVariableBinding binding= caughtException.resolveBinding();
			if (binding == null)
				continue;
			ITypeBinding caughtype= binding.getType();
			while (caughtype != null) {
				if (caughtype == excpetionType)
					return true;
				caughtype= caughtype.getSuperclass();
			}
		}
	}
	return false;
}
 
Example #6
Source File: MoveMethodRefactoring.java    From JDeodorant with MIT License 6 votes vote down vote up
private SimpleName addSourceClassParameterToMovedMethod(MethodDeclaration newMethodDeclaration, ASTRewrite targetRewriter) {
	AST ast = newMethodDeclaration.getAST();
	SingleVariableDeclaration parameter = ast.newSingleVariableDeclaration();
	SimpleName typeName = ast.newSimpleName(sourceTypeDeclaration.getName().getIdentifier());
	Type parameterType = ast.newSimpleType(typeName);
	targetRewriter.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, parameterType, null);
	String sourceTypeName = sourceTypeDeclaration.getName().getIdentifier();
	SimpleName parameterName = ast.newSimpleName(sourceTypeName.replaceFirst(Character.toString(sourceTypeName.charAt(0)), Character.toString(Character.toLowerCase(sourceTypeName.charAt(0)))));
	targetRewriter.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, parameterName, null);
	ListRewrite parametersRewrite = targetRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.PARAMETERS_PROPERTY);
	parametersRewrite.insertLast(parameter, null);
	this.additionalArgumentsAddedToMovedMethod.add("this");
	this.additionalTypeBindingsToBeImportedInTargetClass.add(sourceTypeDeclaration.resolveBinding());
	addParamTagElementToJavadoc(newMethodDeclaration, targetRewriter, parameterName.getIdentifier());
	setPublicModifierToSourceTypeDeclaration();
	return parameterName;
}
 
Example #7
Source File: MethodUtils.java    From tassal with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @param node
 * @return
 */
public static String getMethodType(final MethodDeclaration node) {
	final StringBuffer typeSb = new StringBuffer();
	if (node.getReturnType2() != null) {
		typeSb.append(node.getReturnType2().toString()).append("(");
	} else if (node.isConstructor()) {
		typeSb.append("constructor(");
	} else {
		typeSb.append("void(");
	}
	for (final Object svd : node.parameters()) {
		final SingleVariableDeclaration decl = (SingleVariableDeclaration) svd;
		typeSb.append(decl.getType().toString());
		typeSb.append(",");
	}
	typeSb.append(")");

	final String methodType = typeSb.toString();
	return methodType;
}
 
Example #8
Source File: VariableDeclarationFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static ModifierChangeOperation createAddFinalOperation(SimpleName name, ASTNode decl) {
	if (decl == null)
		return null;

	IBinding binding= name.resolveBinding();
	if (!canAddFinal(binding, decl))
		return null;

	if (decl instanceof SingleVariableDeclaration) {
		return new ModifierChangeOperation(decl, new ArrayList<VariableDeclarationFragment>(), Modifier.FINAL, Modifier.NONE);
	} else if (decl instanceof VariableDeclarationExpression) {
		return new ModifierChangeOperation(decl, new ArrayList<VariableDeclarationFragment>(), Modifier.FINAL, Modifier.NONE);
	} else if (decl instanceof VariableDeclarationFragment){
		VariableDeclarationFragment frag= (VariableDeclarationFragment)decl;
		decl= decl.getParent();
		if (decl instanceof FieldDeclaration || decl instanceof VariableDeclarationStatement) {
			List<VariableDeclarationFragment> list= new ArrayList<VariableDeclarationFragment>();
			list.add(frag);
			return new ModifierChangeOperation(decl, list, Modifier.FINAL, Modifier.NONE);
		} else if (decl instanceof VariableDeclarationExpression) {
			return new ModifierChangeOperation(decl, new ArrayList<VariableDeclarationFragment>(), Modifier.FINAL, Modifier.NONE);
		}
	}

	return null;
}
 
Example #9
Source File: SourceAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void initialize() {
	Block body= fDeclaration.getBody();
	// first collect the static imports. This is necessary to not mark
	// static imported fields and methods as implicit visible.
	fTypesToImport= new ArrayList<SimpleName>();
	fStaticsToImport= new ArrayList<SimpleName>();
	ImportReferencesCollector.collect(body, fTypeRoot.getJavaProject(), null, fTypesToImport, fStaticsToImport);

	// Now collect implicit references and name references
	body.accept(new UpdateCollector());

	int numberOfLocals= LocalVariableIndex.perform(fDeclaration);
	FlowContext context= new FlowContext(0, numberOfLocals + 1);
	context.setConsiderAccessMode(true);
	context.setComputeMode(FlowContext.MERGE);
	InOutFlowAnalyzer flowAnalyzer= new InOutFlowAnalyzer(context);
	FlowInfo info= flowAnalyzer.perform(getStatements());

	for (Iterator<SingleVariableDeclaration> iter= fDeclaration.parameters().iterator(); iter.hasNext();) {
		SingleVariableDeclaration element= iter.next();
		IVariableBinding binding= element.resolveBinding();
		ParameterData data= (ParameterData)element.getProperty(ParameterData.PROPERTY);
		data.setAccessMode(info.getAccessMode(context, binding));
	}
}
 
Example #10
Source File: ReferenceFinderUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static Set<ITypeBinding> getTypesUsedInDeclaration(MethodDeclaration methodDeclaration) {
	if (methodDeclaration == null)
		return new HashSet<ITypeBinding>(0);
	Set<ITypeBinding> result= new HashSet<ITypeBinding>();
	ITypeBinding binding= null;
	Type returnType= methodDeclaration.getReturnType2();
	if (returnType != null) {
		binding = returnType.resolveBinding();
		if (binding != null)
			result.add(binding);
	}

	for (Iterator<SingleVariableDeclaration> iter= methodDeclaration.parameters().iterator(); iter.hasNext();) {
		binding = iter.next().getType().resolveBinding();
		if (binding != null)
			result.add(binding);
	}

	for (Iterator<Type> iter= methodDeclaration.thrownExceptionTypes().iterator(); iter.hasNext();) {
		binding= iter.next().resolveBinding();
		if (binding != null)
			result.add(binding);
	}
	return result;
}
 
Example #11
Source File: JavaMethodDeclarationBindingExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Add argument-related features.
 *
 * @param md
 * @param features
 */
private void addArgumentFeatures(final MethodDeclaration md,
		final Set<String> features) {
	checkArgument(activeFeatures.contains(AvailableFeatures.ARGUMENTS));
	features.add("nParams:" + md.parameters().size());
	for (int i = 0; i < md.parameters().size(); i++) {
		final SingleVariableDeclaration varDecl = (SingleVariableDeclaration) md
				.parameters().get(i);
		features.add("param" + i + "Type:" + varDecl.getType().toString());
		for (final String namepart : JavaFeatureExtractor
				.getNameParts(varDecl.getName().toString())) {
			features.add("paramName:" + namepart);
		}
	}

	if (md.isVarargs()) {
		features.add("isVarArg");
	}
}
 
Example #12
Source File: JavaParseTreeBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private String getSignature(MethodDeclaration node) {
    StringBuffer buffer= new StringBuffer();
    buffer.append(node.getName().toString());
    buffer.append('(');
    boolean first= true;
    Iterator<SingleVariableDeclaration> iterator= node.parameters().iterator();
    while (iterator.hasNext()) {
    	SingleVariableDeclaration svd= iterator.next();
        if (!first)
            buffer.append(", "); //$NON-NLS-1$
        buffer.append(getType(svd.getType()));
        if (svd.isVarargs())
            buffer.append("..."); //$NON-NLS-1$
        first= false;
    }
    buffer.append(')');
    return buffer.toString();
}
 
Example #13
Source File: FullConstraintCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public ITypeConstraint[] create(CatchClause node) {
	SingleVariableDeclaration exception= node.getException();
	ConstraintVariable nameVariable= fConstraintVariableFactory.makeExpressionOrTypeVariable(exception.getName(), getContext());

	ITypeConstraint[] defines= fTypeConstraintFactory.createDefinesConstraint(
			nameVariable,
			fConstraintVariableFactory.makeTypeVariable(exception.getType()));

	ITypeBinding throwable= node.getAST().resolveWellKnownType("java.lang.Throwable"); //$NON-NLS-1$
	ITypeConstraint[] catchBound= fTypeConstraintFactory.createSubtypeConstraint(
			nameVariable,
			fConstraintVariableFactory.makeRawBindingVariable(throwable));

	ArrayList<ITypeConstraint> result= new ArrayList<ITypeConstraint>();
	result.addAll(Arrays.asList(defines));
	result.addAll(Arrays.asList(catchBound));
	return result.toArray(new ITypeConstraint[result.size()]);
}
 
Example #14
Source File: NewMethodCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void addNewParameters(ASTRewrite rewrite, List<String> takenNames, List<SingleVariableDeclaration> params, ImportRewriteContext context) throws CoreException {
	AST ast= rewrite.getAST();

	List<Expression> arguments= fArguments;

	for (int i= 0; i < arguments.size(); i++) {
		Expression elem= arguments.get(i);
		SingleVariableDeclaration param= ast.newSingleVariableDeclaration();

		// argument type
		String argTypeKey= "arg_type_" + i; //$NON-NLS-1$
		Type type= evaluateParameterType(ast, elem, argTypeKey, context);
		param.setType(type);

		// argument name
		String argNameKey= "arg_name_" + i; //$NON-NLS-1$
		String name= evaluateParameterName(takenNames, elem, type, argNameKey);
		param.setName(ast.newSimpleName(name));

		params.add(param);
	}
}
 
Example #15
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static void addEnhancedForWithoutTypeProposals(ICompilationUnit cu, ASTNode selectedNode,
		Collection<ChangeCorrectionProposal> proposals) {
	if (selectedNode instanceof SimpleName && (selectedNode.getLocationInParent() == SimpleType.NAME_PROPERTY || selectedNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY)) {
		ASTNode type= selectedNode.getParent();
		if (type.getLocationInParent() == SingleVariableDeclaration.TYPE_PROPERTY) {
			SingleVariableDeclaration svd= (SingleVariableDeclaration) type.getParent();
			if (svd.getLocationInParent() == EnhancedForStatement.PARAMETER_PROPERTY) {
				if (svd.getName().getLength() == 0) {
					SimpleName simpleName= (SimpleName) selectedNode;
					String name= simpleName.getIdentifier();
					int relevance= StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7;
					String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_create_loop_variable_description, BasicElementLabels.getJavaElementName(name));

					proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.LOCAL,
							simpleName, null, relevance));
				}
			}
		}
	}
}
 
Example #16
Source File: ChangeTypeRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
  * The selection corresponds to a ParameterizedType (return type of method)
 * @param pt the type
 * @return the message
  */
private String parameterizedTypeSelected(ParameterizedType pt) {
	ASTNode parent= pt.getParent();
	if (parent.getNodeType() == ASTNode.METHOD_DECLARATION){
		fMethodBinding= ((MethodDeclaration)parent).resolveBinding();
		fParamIndex= -1;
		fEffectiveSelectionStart= pt.getStartPosition();
		fEffectiveSelectionLength= pt.getLength();
		setOriginalType(pt.resolveBinding());
	} else if (parent.getNodeType() == ASTNode.SINGLE_VARIABLE_DECLARATION){
		return singleVariableDeclarationSelected((SingleVariableDeclaration)parent);
	} else if (parent.getNodeType() == ASTNode.VARIABLE_DECLARATION_STATEMENT){
		return variableDeclarationStatementSelected((VariableDeclarationStatement)parent);
	} else if (parent.getNodeType() == ASTNode.FIELD_DECLARATION){
		return fieldDeclarationSelected((FieldDeclaration)parent);
	} else {
		return nodeTypeNotSupported();
	}
	return null;
}
 
Example #17
Source File: ConstructorFromSuperclassProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.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, TypeLocation.PARAMETER));
	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]); // alternative names
	}
	return invocation;
}
 
Example #18
Source File: MethodDeclarationUtility.java    From JDeodorant with MIT License 6 votes vote down vote up
public static SimpleName isGetter(MethodDeclaration methodDeclaration) {
	Block methodBody = methodDeclaration.getBody();
	List<SingleVariableDeclaration> parameters = methodDeclaration.parameters();
	if(methodBody != null) {
		List<Statement> statements = methodBody.statements();
		if(statements.size() == 1 && parameters.size() == 0) {
			Statement statement = statements.get(0);
    		if(statement instanceof ReturnStatement) {
    			ReturnStatement returnStatement = (ReturnStatement)statement;
    			Expression returnStatementExpression = returnStatement.getExpression();
    			if(returnStatementExpression instanceof SimpleName) {
    				return (SimpleName)returnStatementExpression;
    			}
    			else if(returnStatementExpression instanceof FieldAccess) {
    				FieldAccess fieldAccess = (FieldAccess)returnStatementExpression;
    				return fieldAccess.getName();
    			}
    		}
		}
	}
	return null;
}
 
Example #19
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static void addEnhancedForWithoutTypeProposals(ICompilationUnit cu, ASTNode selectedNode, Collection<ICommandAccess> proposals) {
	if (selectedNode instanceof SimpleName && (selectedNode.getLocationInParent() == SimpleType.NAME_PROPERTY || selectedNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY)) {
		ASTNode type= selectedNode.getParent();
		if (type.getLocationInParent() == SingleVariableDeclaration.TYPE_PROPERTY) {
			SingleVariableDeclaration svd= (SingleVariableDeclaration) type.getParent();
			if (svd.getLocationInParent() == EnhancedForStatement.PARAMETER_PROPERTY) {
				if (svd.getName().getLength() == 0) {
					SimpleName simpleName= (SimpleName) selectedNode;
					String name= simpleName.getIdentifier();
					int relevance= StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7;
					String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_create_loop_variable_description, BasicElementLabels.getJavaElementName(name));
					Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
					
					proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.LOCAL, simpleName, null, relevance, image));
				}
			}
		}
	}
}
 
Example #20
Source File: IntroduceFactoryRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @return an array containing the argument names for the constructor
 * identified by <code>fCtorBinding</code>, if available, or default
 * names if unavailable (e.g. if the constructor resides in a binary unit).
 */
private String[] findCtorArgNames() {
	int			numArgs= fCtorBinding.getParameterTypes().length;
	String[]	names= new String[numArgs];

	CompilationUnit		ctorUnit= (CompilationUnit) ASTNodes.getParent(fCtorOwningClass, CompilationUnit.class);
	MethodDeclaration	ctorDecl= (MethodDeclaration) ctorUnit.findDeclaringNode(fCtorBinding.getKey());

	if (ctorDecl != null) {
		List<SingleVariableDeclaration>	formalArgs= ctorDecl.parameters();
		int i= 0;

		for(Iterator<SingleVariableDeclaration> iter= formalArgs.iterator(); iter.hasNext(); i++) {
			SingleVariableDeclaration svd= iter.next();

			names[i]= svd.getName().getIdentifier();
		}
		return names;
	}

	// Have no way of getting the formal argument names; just fake it.
	for(int i=0; i < numArgs; i++)
		names[i]= "arg" + (i+1); //$NON-NLS-1$

	return names;
}
 
Example #21
Source File: InferTypeArgumentsConstraintCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
	public void endVisit(SingleVariableDeclaration node) {
		// used for formal method parameters and catch clauses
		//TODO: extra dimensions?

//		ConstraintVariable2 typeCv= getConstraintVariable(node.getType()); //TODO: who needs this?

//		ConstraintVariable2 nameCv;
//		switch (node.getParent().getNodeType()) {
//			case ASTNode.METHOD_DECLARATION :
//				MethodDeclaration parent= (MethodDeclaration) node.getParent();
//				int index= parent.parameters().indexOf(node);
//				nameCv= fTCFactory.makeParameterTypeVariable(parent.resolveBinding(), index, node.getType());
//				//store source range even if variable not used in constraint here. TODO: move to visit(MethodDeclaration)?
//				break;
//			case ASTNode.CATCH_CLAUSE :
//				nameCv= fTCFactory.makeVariableVariable(node.resolveBinding());
//
//				break;
//			default:
//				unexpectedNode(node.getParent());
//		}
//		setConstraintVariable(node, nameCv);

		//TODO: Move this into visit(SimpleName) or leave it here?
//		ExpressionVariable2 name= fTCFactory.makeExpressionVariable(node.getName());
//		TypeVariable2 type= fTCFactory.makeTypeVariable(node.getType());
//		ITypeConstraint2[] nameEqualsType= fTCFactory.createEqualsConstraint(name, type);
//		addConstraints(nameEqualsType);

		//TODO: When can a SingleVariableDeclaration have an initializer? Never up to Java 1.5?
		Expression initializer= node.getInitializer();
		if (initializer == null)
			return;

//		ConstraintVariable2 initializerCv= getConstraintVariable(initializer);
//		ConstraintVariable2 nameCv= getConstraintVariable(node);
		//TODO: check: property has been set in visit(CatchClause), visit(MethodDeclaration), visit(EnhancedForStatament)
		//fTCFactory.createSubtypeConstraint(initializerCv, nameCv); //TODO: not for augment raw container clients
	}
 
Example #22
Source File: AssignToVariableAssistProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public AssignToVariableAssistProposal(ICompilationUnit cu, List<SingleVariableDeclaration> parameters, int relevance) {
	super("", JavaCodeActionKind.QUICK_ASSIST, cu, null, relevance); //$NON-NLS-1$

	fVariableKind= FIELD;
	fNodesToAssign= new ArrayList<>();
	fNodesToAssign.addAll(parameters);
	fTypeBinding= null;

	setDisplayName(CorrectionMessages.AssignToVariableAssistProposal_assignallparamstofields_description);
}
 
Example #23
Source File: AssignToVariableAssistProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public AssignToVariableAssistProposal(ICompilationUnit cu, SingleVariableDeclaration parameter, VariableDeclarationFragment existingFragment, ITypeBinding typeBinding, int relevance) {
	super("", JavaCodeActionKind.QUICK_ASSIST, cu, null, relevance); //$NON-NLS-1$

	fVariableKind= FIELD;
	fNodesToAssign= new ArrayList<>();
	fNodesToAssign.add(parameter);
	fTypeBinding= typeBinding;
	fExistingFragment= existingFragment;

	if (existingFragment == null) {
		setDisplayName(CorrectionMessages.AssignToVariableAssistProposal_assignparamtofield_description);
	} else {
		setDisplayName(Messages.format(CorrectionMessages.AssignToVariableAssistProposal_assigntoexistingfield_description, BasicElementLabels.getJavaElementName(existingFragment.getName().getIdentifier())));
	}
}
 
Example #24
Source File: NewVariableCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private boolean isEnhancedForStatementVariable(Statement statement, SimpleName name) {
	if (statement instanceof EnhancedForStatement) {
		EnhancedForStatement forStatement= (EnhancedForStatement) statement;
		SingleVariableDeclaration param= forStatement.getParameter();
		return param.getType() == name.getParent(); // strange recovery, see https://bugs.eclipse.org/180456
	}
	return false;
}
 
Example #25
Source File: SourceAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(SimpleName node) {
	addReferencesToName(node);
	IBinding binding= node.resolveBinding();
	if (binding instanceof ITypeBinding) {
		ITypeBinding type= (ITypeBinding)binding;
		if (type.isTypeVariable()) {
			addTypeVariableReference(type, node);
		}
	} else if (binding instanceof IVariableBinding) {
		IVariableBinding vb= (IVariableBinding)binding;
		if (vb.isField() && ! isStaticallyImported(node)) {
			Name topName= ASTNodes.getTopMostName(node);
			if (node == topName || node == ASTNodes.getLeftMostSimpleName(topName)) {
				StructuralPropertyDescriptor location= node.getLocationInParent();
				if (location != SingleVariableDeclaration.NAME_PROPERTY
					&& location != VariableDeclarationFragment.NAME_PROPERTY) {
					fImplicitReceivers.add(node);
				}
			}
		} else if (!vb.isField()) {
			// we have a local. Check if it is a parameter.
			ParameterData data= fParameters.get(binding);
			if (data != null) {
				ASTNode parent= node.getParent();
				if (parent instanceof Expression) {
					int precedence= OperatorPrecedence.getExpressionPrecedence((Expression)parent);
					if (precedence != Integer.MAX_VALUE) {
						data.setOperatorPrecedence(precedence);
					}
				}
			}
		}
	}
	return true;
}
 
Example #26
Source File: FindMethodVisitor.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
private  String buildMethodInfoString(MethodDeclaration node) {
	String currentClassName = getFullClazzName(node);
	if (currentClassName == null) {
		return null;
	}
	StringBuffer buffer = new StringBuffer(currentClassName + "#");

	String retType = "?";
	if (node.getReturnType2() != null) {
		retType = node.getReturnType2().toString();
	}
	StringBuffer param = new StringBuffer("?");
	for (Object object : node.parameters()) {
		if (!(object instanceof SingleVariableDeclaration)) {
			param.append(",?");
		} else {
			SingleVariableDeclaration singleVariableDeclaration = (SingleVariableDeclaration) object;
			param.append("," + singleVariableDeclaration.getType().toString());
		}
	}
	// add method return type
	buffer.append(retType + "#");
	// add method name
	buffer.append(node.getName().getFullyQualifiedName() + "#");
	// add method params, NOTE: the first parameter starts at index 1.
	buffer.append(param);
	return buffer.toString();
}
 
Example #27
Source File: IntroduceParameterObjectProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isParameter(ParameterInfo pi, ASTNode node, List<SingleVariableDeclaration> enclosingMethodParameters, String qualifier) {
	if (node instanceof Name) {
		Name name= (Name) node;
		IVariableBinding binding= ASTNodes.getVariableBinding(name);
		if (binding != null && binding.isParameter()) {
			return binding.getName().equals(getNameInScope(pi, enclosingMethodParameters));
		} else {
			if (node instanceof QualifiedName) {
				QualifiedName qn= (QualifiedName) node;
				return qn.getFullyQualifiedName().equals(JavaModelUtil.concatenateName(qualifier, getNameInScope(pi, enclosingMethodParameters)));
			}
		}
	}
	return false;
}
 
Example #28
Source File: ConstructorFromSuperclassProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void addLinkedRanges(ASTRewrite rewrite, MethodDeclaration newStub) {
	List<SingleVariableDeclaration> parameters= newStub.parameters();
	for (int i= 0; i < parameters.size(); i++) {
		SingleVariableDeclaration curr= parameters.get(i);
		String name= curr.getName().getIdentifier();
		addLinkedPosition(rewrite.track(curr.getType()), false, "arg_type_" + name); //$NON-NLS-1$
		addLinkedPosition(rewrite.track(curr.getName()), false, "arg_name_" + name); //$NON-NLS-1$
	}
}
 
Example #29
Source File: SuperTypeConstraintsCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public final void endVisit(final SingleVariableDeclaration node) {
	final ConstraintVariable2 ancestor= (ConstraintVariable2) node.getType().getProperty(PROPERTY_CONSTRAINT_VARIABLE);
	if (ancestor != null) {
		node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, ancestor);
		final Expression expression= node.getInitializer();
		if (expression != null) {
			final ConstraintVariable2 descendant= (ConstraintVariable2) expression.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
			if (descendant != null)
				fModel.createSubtypeConstraint(descendant, ancestor);
		}
	}
}
 
Example #30
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean isExplicitlyTypedLambda(Expression expression) {
	if (!(expression instanceof LambdaExpression))
		return false;
	LambdaExpression lambda= (LambdaExpression) expression;
	List<VariableDeclaration> parameters= lambda.parameters();
	if (parameters.isEmpty())
		return true;
	return parameters.get(0) instanceof SingleVariableDeclaration;
}