Java Code Examples for org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser#parse()

The following examples show how to use org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser#parse() . 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: 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 7
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 8
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 9
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 10
Source File: GenerateMethodAbstractAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
void initialize(IType type) throws JavaModelException {
	RefactoringASTParser parser= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL);
	fUnit= parser.parse(type.getCompilationUnit(), true);
	fTypeBinding= null;
	// type cannot be anonymous
	final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) ASTNodes.getParent(NodeFinder.perform(fUnit, type.getNameRange()),
			AbstractTypeDeclaration.class);
	if (declaration != null)
		fTypeBinding= declaration.resolveBinding();
}
 
Example 11
Source File: AddUnimplementedConstructorsAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public AddUnimplementedConstructorsContentProvider(IType type) throws JavaModelException {
	RefactoringASTParser parser= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL);
	fUnit= parser.parse(type.getCompilationUnit(), true);
	AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) ASTNodes.getParent(NodeFinder.perform(fUnit, type.getNameRange()), AbstractTypeDeclaration.class);
	if (declaration != null) {
		ITypeBinding binding= declaration.resolveBinding();
		if (binding != null)
			fMethodsList= StubUtility2.getVisibleConstructors(binding, true, false);
	}
}
 
Example 12
Source File: JsniReferenceChangeHelper.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
public void perform(IProgressMonitor pm, ICompilationUnit cu,
    TextEdit rootEdit) throws CoreException {

  // Remove the original edits we generated, since their offsets may have
  // been shifted by JDT edits that occurred "higher" in the source file
  TextEdit[] oldEdits = rootEdit.removeChildren();

  // Generate a new AST for this compilation unit
  RefactoringASTParser parser = new RefactoringASTParser(AST.JLS4);
  CompilationUnit astNode = parser.parse(cu, false);

  // Now re-validate the compilation unit's AST to get the JSNI Java
  // references' updated positions into the index
  JavaCompilationParticipant.validateCompilationUnit(astNode);

  // Get the index entries matching the old element by name only (we can't
  // resolve the references anymore because the old element no longer exists).
  IJavaElement oldElement = jsniReferenceChange.getRefactoringSupport().getOldElement();
  Set<IIndexedJavaRef> refs = JavaQueryParticipant.findWorkspaceReferences(
      oldElement, false);

  for (Iterator<IIndexedJavaRef> iterator = refs.iterator(); iterator.hasNext();) {
    IIndexedJavaRef ref = iterator.next();

    // Remove any matches that did not come from this compilation unit or
    // which don't resolve to the refactored Java Element
    if (!(ref.getSource().equals(cu.getPath()))
        || (!resolvesToRefactoredElement(cu, ref))) {
      iterator.remove();
    }
  }

  // Get the new edits for the references within this compilation unit (the
  // offsets may have changed if the JDT created edits above us in the
  // compilation unit).
  Set<TextEdit> newEdits = jsniReferenceChange.getRefactoringSupport().createEdits(
      refs).get(cu.getPath());
  assert (newEdits != null);
  assert (oldEdits.length == newEdits.size());

  // Add all those edits back onto this change's root edit
  rootEdit.addChildren(newEdits.toArray(new TextEdit[0]));
}