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

The following examples show how to use org.eclipse.jdt.core.dom.ITypeBinding. 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: Resolver.java    From DesigniteJava with Apache License 2.0 6 votes vote down vote up
private void addNonPrimitiveParameters(SM_Project parentProject, TypeInfo typeInfo, ITypeBinding iType) {
	if (iType.isFromSource() && iType.getModifiers() != 0) {
		SM_Type inferredBasicType = findType(iType.getName(), iType.getPackage().getName(), parentProject);
		addParameterIfNotAlreadyExists(typeInfo, inferredBasicType);
	}
	for (ITypeBinding typeParameter : iType.getTypeArguments()) {
		if (typeParameter.isParameterizedType()) {
			addNonPrimitiveParameters(parentProject, typeInfo, typeParameter);
		} else {
			if (typeParameter.isFromSource() && typeParameter.getModifiers() != 0) {
				SM_Type inferredType = findType(typeParameter.getName(), typeParameter.getPackage().getName(),
						parentProject);
				if (inferredType != null) {
					addParameterIfNotAlreadyExists(typeInfo, inferredType);
				}
			}
		}
	}
}
 
Example #2
Source File: ASTResolving.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static String getMethodSignature(String name, ITypeBinding[] params, boolean isVarArgs) {
	StringBuffer buf= new StringBuffer();
	buf.append(name).append('(');
	for (int i= 0; i < params.length; i++) {
		if (i > 0) {
			buf.append(JavaElementLabels.COMMA_STRING);
		}
		if (isVarArgs && i == params.length - 1) {
			buf.append(getTypeSignature(params[i].getElementType()));
			buf.append("..."); //$NON-NLS-1$
		} else {
			buf.append(getTypeSignature(params[i]));
		}
	}
	buf.append(')');
	return BasicElementLabels.getJavaElementName(buf.toString());
}
 
Example #3
Source File: ASTResolving.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean isVariableDefinedInContext(IBinding binding, ITypeBinding typeVariable) {
	if (binding.getKind() == IBinding.VARIABLE) {
		IVariableBinding var= (IVariableBinding) binding;
		binding= var.getDeclaringMethod();
		if (binding == null) {
			binding= var.getDeclaringClass();
		}
	}
	if (binding instanceof IMethodBinding) {
		if (binding == typeVariable.getDeclaringMethod()) {
			return true;
		}
		binding= ((IMethodBinding) binding).getDeclaringClass();
	}

	while (binding instanceof ITypeBinding) {
		if (binding == typeVariable.getDeclaringClass()) {
			return true;
		}
		if (Modifier.isStatic(binding.getModifiers())) {
			break;
		}
		binding= ((ITypeBinding) binding).getDeclaringClass();
	}
	return false;
}
 
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 initializeDestinations() {
	List<ASTNode> result= new ArrayList<ASTNode>();
	BodyDeclaration decl= fAnalyzer.getEnclosingBodyDeclaration();
	ASTNode current= ASTResolving.findParentType(decl.getParent());
	if (fAnalyzer.isValidDestination(current)) {
		result.add(current);
	}
	if (current != null && (decl instanceof MethodDeclaration || decl instanceof Initializer || decl instanceof FieldDeclaration)) {
		ITypeBinding binding= ASTNodes.getEnclosingType(current);
		ASTNode next= ASTResolving.findParentType(current.getParent());
		while (next != null && binding != null && binding.isNested()) {
			if (fAnalyzer.isValidDestination(next)) {
				result.add(next);
			}
			current= next;
			binding= ASTNodes.getEnclosingType(current);
			next= ASTResolving.findParentType(next.getParent());
		}
	}
	fDestinations= result.toArray(new ASTNode[result.size()]);
	fDestination= fDestinations[fDestinationIndex];
}
 
Example #5
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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);
}
 
Example #6
Source File: Binding2JavaModel.java    From lapse-plus with GNU General Public License v3.0 6 votes vote down vote up
public static ICompilationUnit findCompilationUnit(ITypeBinding typeBinding, IJavaProject project) throws JavaModelException {
    if (!typeBinding.isFromSource()) {
        return null;
    }
    while (typeBinding != null && !typeBinding.isTopLevel()) {
        typeBinding= typeBinding.getDeclaringClass();
    }
    if (typeBinding != null) {
        IPackageBinding pack= typeBinding.getPackage();
        String packageName= pack.isUnnamed() ? "" : pack.getName(); //$NON-NLS-1$
        IType type= project.findType(packageName, typeBinding.getName());
        if (type != null) {
            return type.getCompilationUnit();
        }
    }
    return null;
}
 
Example #7
Source File: JavadocTagsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void getInvalidQualificationProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode node= problem.getCoveringNode(context.getASTRoot());
	if (!(node instanceof Name)) {
		return;
	}
	Name name= (Name) node;
	IBinding binding= name.resolveBinding();
	if (!(binding instanceof ITypeBinding)) {
		return;
	}
	ITypeBinding typeBinding= (ITypeBinding)binding;

	AST ast= node.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);
	rewrite.replace(name, ast.newName(typeBinding.getQualifiedName()), null);

	String label= CorrectionMessages.JavadocTagsSubProcessor_qualifylinktoinner_description;
	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.QUALIFY_INNER_TYPE_NAME, image);

	proposals.add(proposal);
}
 
Example #8
Source File: NewAsyncRemoteServiceInterfaceCreationWizardPage.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
private static List<IMethodBinding> computeOverridableMethodsForInterface(
    ITypeBinding interfaceBinding) {
  assert (interfaceBinding.isInterface());

  List<ITypeBinding> superInterfaces = new ArrayList<ITypeBinding>();
  RemoteServiceUtilities.expandSuperInterfaces(interfaceBinding,
      superInterfaces);

  List<IMethodBinding> overridableMethods = new ArrayList<IMethodBinding>();
  for (ITypeBinding superInterface : superInterfaces) {
    for (IMethodBinding declaredMethod : superInterface.getDeclaredMethods()) {
      if (findOverridingMethod(declaredMethod, overridableMethods) == null) {
        overridableMethods.add(declaredMethod);
      }
    }
  }

  return overridableMethods;
}
 
Example #9
Source File: SurroundWith.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void qualifyThisExpressions(ASTNode node, final ASTRewrite rewrite, final ImportRewrite importRewrite, final ImportRewriteContext importRewriteContext) {
	node.accept(new GenericVisitor() {
		/**
		 * {@inheritDoc}
		 */
		@Override
		public boolean visit(ThisExpression thisExpr) {
			if (thisExpr.getQualifier() == null) {
				ITypeBinding typeBinding= thisExpr.resolveTypeBinding();
				if (typeBinding != null) {
					String typeName= importRewrite.addImport(typeBinding.getTypeDeclaration(), importRewriteContext);
					SimpleName simpleName= thisExpr.getAST().newSimpleName(typeName);
					rewrite.set(thisExpr, ThisExpression.QUALIFIER_PROPERTY, simpleName, null);
				}
			}
			return super.visit(thisExpr);
		}
	});
}
 
Example #10
Source File: AccessAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public AccessAnalyzer(SelfEncapsulateFieldRefactoring refactoring, ICompilationUnit unit, IVariableBinding field, ITypeBinding declaringClass, ASTRewrite rewriter, ImportRewrite importRewrite) {
	Assert.isNotNull(refactoring);
	Assert.isNotNull(unit);
	Assert.isNotNull(field);
	Assert.isNotNull(declaringClass);
	Assert.isNotNull(rewriter);
	Assert.isNotNull(importRewrite);
	fCUnit= unit;
	fFieldBinding= field.getVariableDeclaration();
	fDeclaringClassBinding= declaringClass;
	fRewriter= rewriter;
	fImportRewriter= importRewrite;
	fGroupDescriptions= new ArrayList<TextEditGroup>();
	fGetter= refactoring.getGetterName();
	fSetter= refactoring.getSetterName();
	fEncapsulateDeclaringClass= refactoring.getEncapsulateDeclaringClass();
	try {
		fIsFieldFinal= Flags.isFinal(refactoring.getField().getFlags());
	} catch (JavaModelException e) {
		// assume non final field
	}
	fStatus= new RefactoringStatus();
}
 
Example #11
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 ArrayInitializer node) {
	final ITypeBinding binding= node.resolveTypeBinding();
	if (binding != null && binding.isArray()) {
		final ConstraintVariable2 ancestor= fModel.createIndependentTypeVariable(binding.getElementType());
		if (ancestor != null) {
			node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, ancestor);
			Expression expression= null;
			ConstraintVariable2 descendant= null;
			final List<Expression> expressions= node.expressions();
			for (int index= 0; index < expressions.size(); index++) {
				expression= expressions.get(index);
				descendant= (ConstraintVariable2) expression.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
				if (descendant != null)
					fModel.createSubtypeConstraint(descendant, ancestor);
			}
		}
	}
}
 
Example #12
Source File: AbstractToStringGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * This method initializes all variables used in the process of generating <code>toString</code>
 * method.
 */
protected void initialize() {
	needMaxLenVariable= false;
	needCollectionToStringMethod= false;
	typesThatNeedArrayToStringMethod= new ArrayList<ITypeBinding>();

	checkNeedForHelperMethods();

	toStringMethod= fAst.newMethodDeclaration();
	toStringMethod.modifiers().addAll(ASTNodeFactory.newModifiers(fAst, Modifier.PUBLIC));
	toStringMethod.setName(fAst.newSimpleName(METHODNAME_TO_STRING));
	toStringMethod.setConstructor(false);
	toStringMethod.setReturnType2(fAst.newSimpleType(fAst.newName(TYPENAME_STRING)));

	Block body= fAst.newBlock();
	toStringMethod.setBody(body);
	
	fMaxLenVariableName= createNameSuggestion(MAX_LEN_VARIABLE_NAME, NamingConventions.VK_LOCAL);
}
 
Example #13
Source File: NewAnnotationMemberProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private Type getNewType(ASTRewrite rewrite) {
	AST ast= rewrite.getAST();
	Type newTypeNode= null;
	ITypeBinding binding= null;
	if (fInvocationNode.getLocationInParent() == MemberValuePair.NAME_PROPERTY) {
		Expression value= ((MemberValuePair) fInvocationNode.getParent()).getValue();
		binding= value.resolveTypeBinding();
	} else if (fInvocationNode instanceof Expression) {
		binding= ((Expression) fInvocationNode).resolveTypeBinding();
	}
	if (binding != null) {
		ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(fInvocationNode, getImportRewrite());
		newTypeNode= getImportRewrite().addImport(binding, ast, importRewriteContext);
	}
	if (newTypeNode == null) {
		newTypeNode= ast.newSimpleType(ast.newSimpleName("String")); //$NON-NLS-1$
	}
	return newTypeNode;
}
 
Example #14
Source File: InJavaImporter.java    From jdt2famix with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * We pass the signature because we want to get it from the node, but there can
 * be different types of nodes (funny JDT).
 */
public Invocation createInvocationFromMethodBinding(IMethodBinding binding, String signature) {

	Invocation invocation = new Invocation();
	if (topOfContainerStack() instanceof Method)
		invocation.setSender((Method) topOfContainerStack());
	if (binding != null && binding.getMethodDeclaration() != null) {
		IMethodBinding methodDeclarationBinding = binding.getMethodDeclaration();
		ITypeBinding declaringClass = null;
		if (methodDeclarationBinding.getDeclaringClass() != null)
			declaringClass = methodDeclarationBinding.getDeclaringClass();
		else
			declaringClass = binding.getDeclaringClass();
		Type ensureTypeFromTypeBinding = ensureTypeFromTypeBinding(declaringClass);
		invocation
				.addCandidates(ensureMethodFromMethodBinding(methodDeclarationBinding, ensureTypeFromTypeBinding));
	}
	invocation.setSignature(signature);
	repository.add(invocation);
	return invocation;
}
 
Example #15
Source File: ScopeAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public IBinding[] getDeclarationsInScope(int offset, int flags) {
	org.eclipse.jdt.core.dom.NodeFinder finder= new org.eclipse.jdt.core.dom.NodeFinder(fRoot, offset, 0);
	ASTNode node= finder.getCoveringNode();
	if (node == null) {
		return NO_BINDING;
	}

	if (node instanceof SimpleName) {
		return getDeclarationsInScope((SimpleName) node, flags);
	}

	try {
		ITypeBinding binding= Bindings.getBindingOfParentType(node);
		DefaultBindingRequestor requestor= new DefaultBindingRequestor(binding, flags);
		addLocalDeclarations(node, offset, flags, requestor);
		if (binding != null) {
			addTypeDeclarations(binding, flags, requestor);
		}
		List<IBinding> result= requestor.getResult();
		return result.toArray(new IBinding[result.size()]);
	} finally {
		clearLists();
	}
}
 
Example #16
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel linkedModel) throws CoreException {
	ASTRewrite rewrite= cuRewrite.getASTRewrite();
	IBinding binding= fUnusedName.resolveBinding();
	CompilationUnit root= (CompilationUnit) fUnusedName.getRoot();
	String displayString= FixMessages.UnusedCodeFix_RemoveUnusedTypeParameter_description;
	TextEditGroup group= createTextEditGroup(displayString, cuRewrite);

	if (binding.getKind() == IBinding.TYPE) {
		ITypeBinding decl= ((ITypeBinding) binding).getTypeDeclaration();
		ASTNode declaration= root.findDeclaringNode(decl);
		if (declaration.getParent() instanceof TypeDeclarationStatement) {
			declaration= declaration.getParent();
		}
		rewrite.remove(declaration, group);
	}
}
 
Example #17
Source File: BindingLabelProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static ImageDescriptor getTypeImageDescriptor(boolean inner, ITypeBinding binding, int flags) {
	if (binding.isEnum())
		return JavaPluginImages.DESC_OBJS_ENUM;
	else if (binding.isAnnotation())
		return JavaPluginImages.DESC_OBJS_ANNOTATION;
	else if (binding.isInterface()) {
		if ((flags & JavaElementImageProvider.LIGHT_TYPE_ICONS) != 0)
			return JavaPluginImages.DESC_OBJS_INTERFACEALT;
		if (inner)
			return getInnerInterfaceImageDescriptor(binding.getModifiers());
		return getInterfaceImageDescriptor(binding.getModifiers());
	} else if (binding.isClass()) {
		if ((flags & JavaElementImageProvider.LIGHT_TYPE_ICONS) != 0)
			return JavaPluginImages.DESC_OBJS_CLASSALT;
		if (inner)
			return getInnerClassImageDescriptor(binding.getModifiers());
		return getClassImageDescriptor(binding.getModifiers());
	} else if (binding.isTypeVariable()) {
		return JavaPluginImages.DESC_OBJS_TYPEVARIABLE;
	}
	// primitive type, wildcard
	return null;
}
 
Example #18
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addTypeQualification(final Type type, final CompilationUnitRewrite targetRewrite, final TextEditGroup group) {
	Assert.isNotNull(type);
	Assert.isNotNull(targetRewrite);
	final ITypeBinding binding= type.resolveBinding();
	if (binding != null) {
		final ITypeBinding declaring= binding.getDeclaringClass();
		if (declaring != null) {
			if (type instanceof SimpleType) {
				final SimpleType simpleType= (SimpleType) type;
				addSimpleTypeQualification(targetRewrite, declaring, simpleType, group);
			} else if (type instanceof ParameterizedType) {
				final ParameterizedType parameterizedType= (ParameterizedType) type;
				final Type rawType= parameterizedType.getType();
				if (rawType instanceof SimpleType)
					addSimpleTypeQualification(targetRewrite, declaring, (SimpleType) rawType, group);
			}
		}
	}
}
 
Example #19
Source File: EnhancedForLoop.java    From JDeodorant with MIT License 6 votes vote down vote up
private static AbstractControlVariable generateConditionControlVariable(Expression dataStructure)
{
	// initialize startValue
	VariableValue startValue = new VariableValue(0);
	// initialize endValue
	VariableValue endValue = null;
	ITypeBinding dataStructureBinding = dataStructure.resolveTypeBinding();
	// if the dataStructure is an array or a mehtodInvocation returning and array (both covered by the first expression) OR
	// the data structure is a collection or the data structure is a methodInvocation returning a collection (both covered by the second expression)
	// These are the only cases supported by the JAVA enhanced for loop
	if (dataStructureBinding.isArray() || AbstractLoopUtilities.isCollection(dataStructureBinding))
	{
		endValue = new VariableValue(VariableValue.ValueType.DATA_STRUCTURE_SIZE);
	}
	// initialize variableUpdaters
	List<VariableUpdater> variableUpdaters = new ArrayList<VariableUpdater>();
	variableUpdaters.add(new VariableUpdater(1));
	if (endValue == null)
	{
		return null;
	}
	return new AbstractControlVariable(startValue, endValue, variableUpdaters, dataStructure);
}
 
Example #20
Source File: MissingReturnTypeInLambdaCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected Expression computeProposals(AST ast, ITypeBinding returnBinding, int returnOffset, CompilationUnit root, Expression result) {
	ScopeAnalyzer analyzer= new ScopeAnalyzer(root);
	IBinding[] bindings= analyzer.getDeclarationsInScope(returnOffset, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY);

	org.eclipse.jdt.core.dom.NodeFinder finder= new org.eclipse.jdt.core.dom.NodeFinder(root, returnOffset, 0);
	ASTNode varDeclFrag= ASTResolving.findAncestor(finder.getCoveringNode(), ASTNode.VARIABLE_DECLARATION_FRAGMENT);
	IVariableBinding varDeclFragBinding= null;
	if (varDeclFrag != null)
		varDeclFragBinding= ((VariableDeclarationFragment) varDeclFrag).resolveBinding();
	for (int i= 0; i < bindings.length; i++) {
		IVariableBinding curr= (IVariableBinding) bindings[i];
		ITypeBinding type= curr.getType();
		// Bindings are compared to make sure that a lambda does not return a variable which is yet to be initialised.
		if (type != null && type.isAssignmentCompatible(returnBinding) && testModifier(curr) && !Bindings.equals(curr, varDeclFragBinding)) {
			if (result == null) {
				result= ast.newSimpleName(curr.getName());
			}
			addLinkedPositionProposal(RETURN_EXPRESSION_KEY, curr.getName(), null);
		}
	}
	return result;
}
 
Example #21
Source File: StubUtility2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static void createTypeParameters(ImportRewrite imports, ImportRewriteContext context, AST ast, IMethodBinding binding, MethodDeclaration decl) {
	ITypeBinding[] typeParams= binding.getTypeParameters();
	List<TypeParameter> typeParameters= decl.typeParameters();
	for (int i= 0; i < typeParams.length; i++) {
		ITypeBinding curr= typeParams[i];
		TypeParameter newTypeParam= ast.newTypeParameter();
		newTypeParam.setName(ast.newSimpleName(curr.getName()));
		ITypeBinding[] typeBounds= curr.getTypeBounds();
		if (typeBounds.length != 1 || !"java.lang.Object".equals(typeBounds[0].getQualifiedName())) {//$NON-NLS-1$
			List<Type> newTypeBounds= newTypeParam.typeBounds();
			for (int k= 0; k < typeBounds.length; k++) {
				newTypeBounds.add(imports.addImport(typeBounds[k], ast, context));
			}
		}
		typeParameters.add(newTypeParam);
	}
}
 
Example #22
Source File: FileVisitor.java    From repositoryminer with Apache License 2.0 6 votes vote down vote up
@Override
public boolean visit(TypeDeclaration node) {
	AbstractClass clazz = new AbstractClass();
	if (node.getSuperclassType() != null) {
		ITypeBinding bind = node.getSuperclassType().resolveBinding();
		clazz.setSuperClass(bind.getQualifiedName());
	}

	clazz.setInterface(node.isInterface());
	if (packageName != null) {
		clazz.setName(packageName+'.'+node.getName().getFullyQualifiedName());
	} else {
		clazz.setName(node.getName().getFullyQualifiedName());
	}

	TypeVisitor visitor = new TypeVisitor();
	node.accept(visitor);

	clazz.setMethods(visitor.getMethods());
	clazz.setStartPosition(node.getStartPosition());
	clazz.setEndPosition(node.getStartPosition() + node.getLength() - 1);
	clazz.setFields(visitor.getFields());
	
	types.add(clazz);
	return true;
}
 
Example #23
Source File: LocalCorrectionsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static boolean isSubtype(ITypeBinding curr, ITypeBinding[] addedExceptions) {
	while (curr != null) {
		for (int i = 0; i < addedExceptions.length; i++) {
			if (curr == addedExceptions[i]) {
				return true;
			}
		}
		curr = curr.getSuperclass();
	}
	return false;
}
 
Example #24
Source File: AbstractToStringGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 
 * @param member member to check
 * @return type of field or method's return type
 */
protected ITypeBinding getMemberType(Object member) {
	if (member instanceof IVariableBinding) {
		return ((IVariableBinding)member).getType();
	}
	if (member instanceof IMethodBinding) {
		return ((IMethodBinding)member).getReturnType();
	}
	return null;
}
 
Example #25
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 #26
Source File: TypeMismatchSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ITypeBinding boxUnboxPrimitives(ITypeBinding castType, ITypeBinding toCast, AST ast) {
	/*
	 * e.g:
	 * 	void m(toCast var) {
	 * 		castType i= var;
	 * 	}
	 */
	if (castType.isPrimitive() && !toCast.isPrimitive()) {
		return Bindings.getBoxedTypeBinding(castType, ast);
	} else if (!castType.isPrimitive() && toCast.isPrimitive()) {
		return Bindings.getUnboxedTypeBinding(castType, ast);
	} else {
		return castType;
	}
}
 
Example #27
Source File: AddArgumentCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Expression evaluateArgumentExpressions(AST ast, ITypeBinding requiredType, String key) {
	CompilationUnit root= (CompilationUnit) fCallerNode.getRoot();

	int offset= fCallerNode.getStartPosition();
	Expression best= null;
	ITypeBinding bestType= null;

	ScopeAnalyzer analyzer= new ScopeAnalyzer(root);
	IBinding[] bindings= analyzer.getDeclarationsInScope(offset, ScopeAnalyzer.VARIABLES);
	for (int i= 0; i < bindings.length; i++) {
		IVariableBinding curr= (IVariableBinding) bindings[i];
		ITypeBinding type= curr.getType();
		if (type != null && canAssign(type, requiredType) && testModifier(curr)) {
			if (best == null || isMoreSpecific(bestType, type)) {
				best= ast.newSimpleName(curr.getName());
				bestType= type;
			}
			addLinkedPositionProposal(key, curr.getName(), null);
		}
	}
	Expression defaultExpression= ASTNodeFactory.newDefaultExpression(ast, requiredType);
	if (best == null) {
		best= defaultExpression;
	}
	addLinkedPositionProposal(key, ASTNodes.asString(defaultExpression), null);
	return best;
}
 
Example #28
Source File: ToStringGenerationContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
ToStringGenerationContext(ToStringTemplateParser parser, Object[] selectedMembers, ToStringGenerationSettings settings, ITypeBinding type,
		CompilationUnitRewrite rewrite) {
	fParser= parser;
	fSelectedMembers= selectedMembers;
	fSettings= settings;
	fCustomBuilderSettings= settings.getCustomBuilderSettings();
	fType= type;
	fRewrite= rewrite;
}
 
Example #29
Source File: SystemObject.java    From JDeodorant with MIT License 5 votes vote down vote up
private boolean allStaticFieldsWithinSystemBoundary(List<SimpleName> staticFields) {
	for(SimpleName staticField : staticFields) {
		IBinding binding = staticField.resolveBinding();
		if(binding != null && binding.getKind() == IBinding.VARIABLE) {
			IVariableBinding variableBinding = (IVariableBinding)binding;
			ITypeBinding declaringClassTypeBinding = variableBinding.getDeclaringClass();
			if(declaringClassTypeBinding != null) {
				if(getPositionInClassList(declaringClassTypeBinding.getQualifiedName()) == -1 && !declaringClassTypeBinding.isEnum())
					return false;
			}
		}
	}
	return true;
}
 
Example #30
Source File: Resolver.java    From DesigniteJava with Apache License 2.0 5 votes vote down vote up
public SM_Type resolveType(Type type, SM_Project project) {
	ITypeBinding binding = type.resolveBinding();
	if (binding == null || binding.getPackage() == null) // instanceof String[] returns null package
		return null;
	SM_Package pkg = findPackage(binding.getPackage().getName(), project);
	if (pkg != null) {
		return findType(binding.getName(), pkg);
	}
	return null;
}