Java Code Examples for org.eclipse.jdt.internal.corext.dom.ASTNodes#getTypeBinding()

The following examples show how to use org.eclipse.jdt.internal.corext.dom.ASTNodes#getTypeBinding() . 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: GenerateToStringHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static CheckToStringResponse checkToStringStatus(IType type) {
	CheckToStringResponse response = new CheckToStringResponse();
	if (type == null) {
		return response;
	}

	try {
		RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL);
		CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true);
		ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
		if (typeBinding != null) {
			response.type = type.getTypeQualifiedName();
			response.fields = JdtDomModels.getDeclaredFields(typeBinding, false);
			response.exists = Stream.of(typeBinding.getDeclaredMethods()).anyMatch(method -> method.getName().equals(METHODNAME_TOSTRING) && method.getParameterTypes().length == 0);
		}
	} catch (JavaModelException e) {
		JavaLanguageServerPlugin.logException("Failed to check toString status", e);
	}

	return response;
}
 
Example 2
Source File: GenerateToStringHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static TextEdit generateToString(IType type, LspVariableBinding[] fields, ToStringGenerationSettingsCore settings) {
	if (type == null) {
		return null;
	}

	try {
		RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL);
		CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true);
		ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
		if (typeBinding != null) {
			IVariableBinding[] selectedFields = JdtDomModels.convertToVariableBindings(typeBinding, fields);
			GenerateToStringOperation operation = GenerateToStringOperation.createOperation(typeBinding, selectedFields, astRoot, null, settings, false, false);
			operation.run(null);
			return operation.getResultingEdit();
		}
	} catch (CoreException e) {
		JavaLanguageServerPlugin.logException("Failed to generate toString()", e);
	}
	return null;
}
 
Example 3
Source File: HashCodeEqualsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static CheckHashCodeEqualsResponse checkHashCodeEqualsStatus(IType type) {
	CheckHashCodeEqualsResponse response = new CheckHashCodeEqualsResponse();
	if (type == null) {
		return response;
	}
	try {
		RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL);
		CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true);
		ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
		if (typeBinding != null) {
			response.type = type.getTypeQualifiedName();
			response.fields = JdtDomModels.getDeclaredFields(typeBinding, false);
			response.existingMethods = findExistingMethods(typeBinding);
		}
	} catch (JavaModelException e) {
		JavaLanguageServerPlugin.logException("Check hashCode and equals status", e);
	}
	return response;
}
 
Example 4
Source File: HashCodeEqualsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static TextEdit generateHashCodeEqualsTextEdit(IType type, LspVariableBinding[] fields, boolean regenerate, boolean useJava7Objects, boolean useInstanceof, boolean useBlocks, boolean generateComments) {
	if (type == null) {
		return null;
	}
	try {
		RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL);
		CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true);
		ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
		if (typeBinding != null) {
			IVariableBinding[] variableBindings = JdtDomModels.convertToVariableBindings(typeBinding, fields);
			CodeGenerationSettings codeGenSettings = new CodeGenerationSettings();
			codeGenSettings.createComments = generateComments;
			codeGenSettings.overrideAnnotation = true;
			GenerateHashCodeEqualsOperation operation = new GenerateHashCodeEqualsOperation(typeBinding, variableBindings, astRoot, null, codeGenSettings, useInstanceof, useJava7Objects, regenerate, false, false);
			operation.setUseBlocksForThen(useBlocks);
			operation.run(null);
			return operation.getResultingEdit();
		}
	} catch (CoreException e) {
		JavaLanguageServerPlugin.logException("Generate hashCode and equals methods", e);
	}
	return null;
}
 
Example 5
Source File: OverrideMethodsOperation.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public static TextEdit addOverridableMethods(IType type, OverridableMethod[] overridableMethods) {
	if (type == null || type.getCompilationUnit() == null || overridableMethods == null || overridableMethods.length == 0) {
		return null;
	}

	RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL);
	CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true);
	try {
		ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
		if (typeBinding == null) {
			return null;
		}

		IMethodBinding[] methodBindings = convertToMethodBindings(astRoot, typeBinding, overridableMethods);
		return createTextEditForOverridableMethods(type.getCompilationUnit(), astRoot, typeBinding, methodBindings);
	} catch (CoreException e) {
		JavaLanguageServerPlugin.logException("Add overridable methods", e);
	}

	return null;
}
 
Example 6
Source File: SourceProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void updateTypeReferences(ASTRewrite rewriter, CallContext context) {
	ImportRewrite importer= context.importer;
	for (Iterator<SimpleName> iter= fAnalyzer.getTypesToImport().iterator(); iter.hasNext();) {
		Name element= iter.next();
		ITypeBinding binding= ASTNodes.getTypeBinding(element);
		if (binding != null && !binding.isLocal()) {
			// We have collected names not types. So we have to import
			// the declaration type if we reference a parameterized type
			// since we have an entry for every name node (e.g. one for
			// Vector and one for Integer in Vector<Integer>.
			if (binding.isParameterizedType()) {
				binding= binding.getTypeDeclaration();
			}
			String s= importer.addImport(binding);
			if (!ASTNodes.asString(element).equals(s)) {
				rewriter.replace(element, rewriter.createStringPlaceholder(s, ASTNode.SIMPLE_NAME), null);
			}
		}
	}
}
 
Example 7
Source File: AddDelegateMethodsAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
AddDelegateMethodsContentProvider(CompilationUnit astRoot, IType type, IField[] fields) throws JavaModelException {

			final ITypeBinding binding= ASTNodes.getTypeBinding(astRoot, type);
			if (binding != null) {
				fDelegateEntries= StubUtility2.getDelegatableMethods(binding);

				List<IVariableBinding> expanded= new ArrayList<IVariableBinding>();
				for (int index= 0; index < fields.length; index++) {
					VariableDeclarationFragment fragment= ASTNodeSearchUtil.getFieldDeclarationFragmentNode(fields[index], astRoot);
					if (fragment != null) {
						IVariableBinding variableBinding= fragment.resolveBinding();
						if (variableBinding != null)
							expanded.add(variableBinding);
					}
				}
				fExpanded= expanded.toArray(new IVariableBinding[expanded.size()]);
			}
		}
 
Example 8
Source File: SourceAssistProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private boolean supportsHashCodeEquals(IInvocationContext context, IType type) {
	try {
		if (type == null || type.isAnnotation() || type.isInterface() || type.isEnum() || type.getCompilationUnit() == null) {
			return false;
		}
		RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL);
		CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true);
		ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
		return (typeBinding == null) ? false : Arrays.stream(typeBinding.getDeclaredFields()).filter(f -> !Modifier.isStatic(f.getModifiers())).findAny().isPresent();
	} catch (JavaModelException e) {
		return false;
	}
}
 
Example 9
Source File: GenerateDelegateMethodsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static CheckDelegateMethodsResponse checkDelegateMethodsStatus(CodeActionParams params) {
	IType type = SourceAssistProcessor.getSelectionType(params);
	if (type == null || type.getCompilationUnit() == null) {
		return new CheckDelegateMethodsResponse();
	}

	try {
		RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL);
		CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true);
		ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
		if (typeBinding == null) {
			return new CheckDelegateMethodsResponse();
		}

		DelegateEntry[] delegateEntries = StubUtility2Core.getDelegatableMethods(typeBinding);
		Map<IVariableBinding, List<IMethodBinding>> fieldToMethods = new LinkedHashMap<>();
		for (DelegateEntry delegateEntry : delegateEntries) {
			List<IMethodBinding> methods = fieldToMethods.getOrDefault(delegateEntry.field, new ArrayList<>());
			methods.add(delegateEntry.delegateMethod);
			fieldToMethods.put(delegateEntry.field, methods);
		}

		//@formatter:off
		return new CheckDelegateMethodsResponse(fieldToMethods.entrySet().stream()
				.map(entry -> new LspDelegateField(entry.getKey(), entry.getValue().toArray(new IMethodBinding[0])))
				.toArray(LspDelegateField[]::new));
		//@formatter:on
	} catch (JavaModelException e) {
		JavaLanguageServerPlugin.logException("Failed to check delegate methods status", e);
	}

	return new CheckDelegateMethodsResponse();
}
 
Example 10
Source File: GenerateDelegateMethodsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static TextEdit generateDelegateMethods(IType type, LspDelegateEntry[] delegateEntries, CodeGenerationSettings settings) {
	if (type == null || type.getCompilationUnit() == null || delegateEntries == null || delegateEntries.length == 0) {
		return null;
	}

	try {
		RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL);
		CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true);
		ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
		if (typeBinding == null) {
			return null;
		}

		DelegateEntry[] methodEntries = StubUtility2Core.getDelegatableMethods(typeBinding);
		Map<String, DelegateEntry> delegateEntryMap = new HashMap<>();
		for (DelegateEntry methodEntry : methodEntries) {
			delegateEntryMap.put(methodEntry.field.getKey() + "#" + methodEntry.delegateMethod.getKey(), methodEntry);
		}

		//@formatter:off
		DelegateEntry[] selectedDelegateEntries = Arrays.stream(delegateEntries)
			.map(delegateEntry -> delegateEntryMap.get(delegateEntry.field.bindingKey + "#" + delegateEntry.delegateMethod.bindingKey))
			.filter(delegateEntry -> delegateEntry != null)
			.toArray(DelegateEntry[]::new);
		//@formatter:on
		AddDelegateMethodsOperation operation = new AddDelegateMethodsOperation(astRoot, selectedDelegateEntries, null, settings, false, false);
		operation.run(null);
		return operation.getResultingEdit();
	} catch (CoreException e) {
		JavaLanguageServerPlugin.logException("Failed to generate delegate methods", e);
	}

	return null;
}
 
Example 11
Source File: OverrideMethodsOperation.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static List<OverridableMethod> listOverridableMethods(IType type) {
	if (type == null || type.getCompilationUnit() == null) {
		return Collections.emptyList();
	}

	List<OverridableMethod> overridables = new ArrayList<>();
	RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL);
	CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true);
	try {
		ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
		if (typeBinding == null) {
			return overridables;
		}

		IMethodBinding cloneMethod = null;
		ITypeBinding cloneable = astRoot.getAST().resolveWellKnownType("java.lang.Cloneable");
		if (Bindings.isSuperType(cloneable, typeBinding)) {
			cloneMethod = resolveWellKnownCloneMethod(astRoot.getAST());
		}

		IPackageBinding pack = typeBinding.getPackage();
		IMethodBinding[] methods = StubUtility2Core.getOverridableMethods(astRoot.getAST(), typeBinding, false);
		for (IMethodBinding method : methods) {
			if (Bindings.isVisibleInHierarchy(method, pack)) {
				boolean toImplement = Objects.equals(method, cloneMethod);
				overridables.add(convertToSerializableMethod(method, toImplement));
			}
		}
	} catch (JavaModelException e) {
		JavaLanguageServerPlugin.logException("List overridable methods", e);
	}

	return overridables;
}
 
Example 12
Source File: JavaASTUtils.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public static ITypeBinding findTypeBinding(IType currentType) throws JavaModelException{
  final ASTParser parser = ASTParser.newParser(AST.JLS3);
  parser.setKind(ASTParser.K_COMPILATION_UNIT);
  parser.setSource(currentType.getCompilationUnit());
  parser.setResolveBindings(true);
  CompilationUnit unit = (CompilationUnit) parser.createAST(null);
  return ASTNodes.getTypeBinding(unit, currentType);
}
 
Example 13
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private RefactoringStatus updateMethodInvocation(MethodInvocation originalInvocation, IMember enclosing, CompilationUnitRewrite unitRewriter) throws JavaModelException {

		RefactoringStatus status= new RefactoringStatus();

		// If the method invocation utilizes type arguments, skip this
		// call as the new target method may have additional parameters
		if (originalInvocation.typeArguments().size() > 0)
			return createWarningAboutCall(enclosing, originalInvocation, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_type_arguments);

		MethodInvocation newInvocation= unitRewriter.getAST().newMethodInvocation();
		List<Expression> newInvocationArgs= newInvocation.arguments();
		List<Expression> originalInvocationArgs= originalInvocation.arguments();

		// static call => always use a qualifier
		String qualifier= unitRewriter.getImportRewrite().addImport(fIntermediaryTypeBinding);
		newInvocation.setExpression(ASTNodeFactory.newName(unitRewriter.getAST(), qualifier));
		newInvocation.setName(unitRewriter.getAST().newSimpleName(getIntermediaryMethodName()));

		final Expression expression= originalInvocation.getExpression();

		if (!isStaticTarget()) {
			// Add the expression as the first parameter
			if (expression == null) {
				// There is no expression for this call. Use a (possibly qualified) "this" expression.
				ThisExpression expr= unitRewriter.getAST().newThisExpression();
				RefactoringStatus qualifierStatus= qualifyThisExpression(expr, originalInvocation, enclosing, unitRewriter);
				status.merge(qualifierStatus);
				if (qualifierStatus.hasEntries())
					// warning means don't include this invocation
					return status;
				newInvocationArgs.add(expr);
			} else {
				Expression expressionAsParam= (Expression) unitRewriter.getASTRewrite().createMoveTarget(expression);
				newInvocationArgs.add(expressionAsParam);
			}
		} else {
			if (expression != null) {
				// Check if expression is the type name. If not, there may
				// be side effects (e.g. inside methods) -> don't update
				if (! (expression instanceof Name) || ASTNodes.getTypeBinding((Name) expression) == null)
					return createWarningAboutCall(enclosing, originalInvocation, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_static_expression_access);
			}
		}

		for (int i= 0; i < originalInvocationArgs.size(); i++) {
			Expression originalInvocationArg= originalInvocationArgs.get(i);
			Expression movedArg= (Expression) unitRewriter.getASTRewrite().createMoveTarget(originalInvocationArg);
			newInvocationArgs.add(movedArg);
		}

		unitRewriter.getASTRewrite().replace(originalInvocation, newInvocation,
				unitRewriter.createGroupDescription(RefactoringCoreMessages.IntroduceIndirectionRefactoring_group_description_replace_call));

		return status;
	}