use of org.eclipse.jdt.ls.core.internal.handlers.JdtDomModels.LspVariableBinding in project eclipse.jdt.ls by eclipse.
the class MoveHandler method getInstanceMethodDestinations.
private static MoveDestinationsResponse getInstanceMethodDestinations(CodeActionParams params) {
final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.getTextDocument().getUri());
if (unit == null) {
return new MoveDestinationsResponse("Cannot find the compilation unit associated with " + params.getTextDocument().getUri());
}
MethodDeclaration methodDeclaration = getSelectedMethodDeclaration(unit, params);
if (methodDeclaration == null) {
return new MoveDestinationsResponse("The selected element is not a method.");
}
IMethodBinding methodBinding = methodDeclaration.resolveBinding();
if (methodBinding == null || !(methodBinding.getJavaElement() instanceof IMethod)) {
return new MoveDestinationsResponse("The selected element is not a method.");
}
IMethod method = (IMethod) methodBinding.getJavaElement();
MoveInstanceMethodProcessor processor = new MoveInstanceMethodProcessor(method, PreferenceManager.getCodeGenerationSettings(unit));
Refactoring refactoring = new MoveRefactoring(processor);
CheckConditionsOperation check = new CheckConditionsOperation(refactoring, CheckConditionsOperation.INITIAL_CONDITONS);
try {
check.run(new NullProgressMonitor());
if (check.getStatus().hasFatalError()) {
return new MoveDestinationsResponse(check.getStatus().getMessageMatchingSeverity(RefactoringStatus.FATAL));
}
IVariableBinding[] possibleTargets = processor.getPossibleTargets();
LspVariableBinding[] targets = Stream.of(possibleTargets).map(target -> new LspVariableBinding(target)).toArray(LspVariableBinding[]::new);
return new MoveDestinationsResponse(targets);
} catch (CoreException e) {
JavaLanguageServerPlugin.log(e);
}
return new MoveDestinationsResponse("Cannot find any target to move the method to.");
}
use of org.eclipse.jdt.ls.core.internal.handlers.JdtDomModels.LspVariableBinding in project eclipse.jdt.ls by eclipse.
the class SourceAssistProcessor method getSourceActionCommands.
public List<Either<Command, CodeAction>> getSourceActionCommands(CodeActionParams params, IInvocationContext context, IProblemLocationCore[] locations, IProgressMonitor monitor) {
List<Either<Command, CodeAction>> $ = new ArrayList<>();
ICompilationUnit cu = context.getCompilationUnit();
IType type = getSelectionType(context);
boolean isInTypeDeclaration = isInTypeDeclaration(context);
boolean isInImportDeclaration = isInImportDeclaration(context);
try {
// Generate Constructor QuickAssist
IJavaElement element = JDTUtils.findElementAtSelection(cu, params.getRange().getEnd().getLine(), params.getRange().getEnd().getCharacter(), this.preferenceManager, new NullProgressMonitor());
if (element instanceof IField || isInTypeDeclaration) {
Optional<Either<Command, CodeAction>> quickAssistGenerateConstructors = getGenerateConstructorsAction(params, context, type, JavaCodeActionKind.QUICK_ASSIST, monitor);
addSourceActionCommand($, params.getContext(), quickAssistGenerateConstructors);
}
} catch (JavaModelException e) {
JavaLanguageServerPlugin.logException(e);
}
// Generate Constructor Source Action
Optional<Either<Command, CodeAction>> sourceGenerateConstructors = getGenerateConstructorsAction(params, context, type, JavaCodeActionKind.SOURCE_GENERATE_CONSTRUCTORS, monitor);
addSourceActionCommand($, params.getContext(), sourceGenerateConstructors);
// Organize Imports
if (preferenceManager.getClientPreferences().isAdvancedOrganizeImportsSupported()) {
// Generate QuickAssist
if (isInImportDeclaration) {
Optional<Either<Command, CodeAction>> quickAssistOrganizeImports = getOrganizeImportsAction(params, JavaCodeActionKind.QUICK_ASSIST);
addSourceActionCommand($, params.getContext(), quickAssistOrganizeImports);
}
// Generate Source Action
Optional<Either<Command, CodeAction>> sourceOrganizeImports = getOrganizeImportsAction(params, CodeActionKind.SourceOrganizeImports);
addSourceActionCommand($, params.getContext(), sourceOrganizeImports);
} else {
CodeActionProposal organizeImportsProposal = (pm) -> {
TextEdit edit = getOrganizeImportsProposal(context, pm);
return convertToWorkspaceEdit(cu, edit);
};
// Generate QuickAssist
if (isInImportDeclaration) {
Optional<Either<Command, CodeAction>> sourceOrganizeImports = getCodeActionFromProposal(params.getContext(), context.getCompilationUnit(), CorrectionMessages.ReorgCorrectionsSubProcessor_organizeimports_description, JavaCodeActionKind.QUICK_ASSIST, organizeImportsProposal);
addSourceActionCommand($, params.getContext(), sourceOrganizeImports);
}
// Generate Source Action
Optional<Either<Command, CodeAction>> sourceOrganizeImports = getCodeActionFromProposal(params.getContext(), context.getCompilationUnit(), CorrectionMessages.ReorgCorrectionsSubProcessor_organizeimports_description, CodeActionKind.SourceOrganizeImports, organizeImportsProposal);
addSourceActionCommand($, params.getContext(), sourceOrganizeImports);
}
if (!UNSUPPORTED_RESOURCES.contains(cu.getResource().getName())) {
// Override/Implement Methods QuickAssist
if (isInTypeDeclaration) {
Optional<Either<Command, CodeAction>> quickAssistOverrideMethods = getOverrideMethodsAction(params, JavaCodeActionKind.QUICK_ASSIST);
addSourceActionCommand($, params.getContext(), quickAssistOverrideMethods);
}
// Override/Implement Methods Source Action
Optional<Either<Command, CodeAction>> sourceOverrideMethods = getOverrideMethodsAction(params, JavaCodeActionKind.SOURCE_OVERRIDE_METHODS);
addSourceActionCommand($, params.getContext(), sourceOverrideMethods);
}
// Generate Getter and Setter QuickAssist
if (isInTypeDeclaration) {
Optional<Either<Command, CodeAction>> quickAssistGetterSetter = getGetterSetterAction(params, context, type, JavaCodeActionKind.QUICK_ASSIST, isInTypeDeclaration);
addSourceActionCommand($, params.getContext(), quickAssistGetterSetter);
}
// Generate Getter and Setter Source Action
Optional<Either<Command, CodeAction>> sourceGetterSetter = getGetterSetterAction(params, context, type, JavaCodeActionKind.SOURCE_GENERATE_ACCESSORS, isInTypeDeclaration);
addSourceActionCommand($, params.getContext(), sourceGetterSetter);
// Generate hashCode() and equals()
if (supportsHashCodeEquals(context, type, monitor)) {
// Generate QuickAssist
if (isInTypeDeclaration) {
Optional<Either<Command, CodeAction>> quickAssistHashCodeEquals = getHashCodeEqualsAction(params, JavaCodeActionKind.QUICK_ASSIST);
addSourceActionCommand($, params.getContext(), quickAssistHashCodeEquals);
}
// Generate Source Action
Optional<Either<Command, CodeAction>> sourceActionHashCodeEquals = getHashCodeEqualsAction(params, JavaCodeActionKind.SOURCE_GENERATE_HASHCODE_EQUALS);
addSourceActionCommand($, params.getContext(), sourceActionHashCodeEquals);
}
// Generate toString()
if (supportsGenerateToString(type)) {
boolean nonStaticFields = true;
try {
nonStaticFields = hasFields(type, false);
} catch (JavaModelException e) {
// do nothing.
}
if (nonStaticFields) {
// Generate QuickAssist
if (isInTypeDeclaration) {
Optional<Either<Command, CodeAction>> generateToStringQuickAssist = getGenerateToStringAction(params, JavaCodeActionKind.QUICK_ASSIST);
addSourceActionCommand($, params.getContext(), generateToStringQuickAssist);
}
// Generate Source Action
Optional<Either<Command, CodeAction>> generateToStringCommand = getGenerateToStringAction(params, JavaCodeActionKind.SOURCE_GENERATE_TO_STRING);
addSourceActionCommand($, params.getContext(), generateToStringCommand);
} else {
CodeActionProposal generateToStringProposal = (pm) -> {
IJavaElement insertPosition = isInTypeDeclaration ? CodeGenerationUtils.findInsertElement(type, null) : CodeGenerationUtils.findInsertElement(type, context.getSelectionOffset());
TextEdit edit = GenerateToStringHandler.generateToString(type, new LspVariableBinding[0], insertPosition, pm);
return convertToWorkspaceEdit(cu, edit);
};
// Generate QuickAssist
if (isInTypeDeclaration) {
Optional<Either<Command, CodeAction>> generateToStringQuickAssist = getCodeActionFromProposal(params.getContext(), context.getCompilationUnit(), ActionMessages.GenerateToStringAction_label, JavaCodeActionKind.QUICK_ASSIST, generateToStringProposal);
addSourceActionCommand($, params.getContext(), generateToStringQuickAssist);
}
// Generate Source Action
Optional<Either<Command, CodeAction>> generateToStringCommand = getCodeActionFromProposal(params.getContext(), context.getCompilationUnit(), ActionMessages.GenerateToStringAction_label, JavaCodeActionKind.SOURCE_GENERATE_TO_STRING, generateToStringProposal);
addSourceActionCommand($, params.getContext(), generateToStringCommand);
}
}
// Generate Delegate Methods
Optional<Either<Command, CodeAction>> generateDelegateMethods = getGenerateDelegateMethodsAction(params, context, type);
addSourceActionCommand($, params.getContext(), generateDelegateMethods);
// Add final modifiers where possible
Optional<Either<Command, CodeAction>> generateFinalModifiers = addFinalModifierWherePossibleAction(context);
addSourceActionCommand($, params.getContext(), generateFinalModifiers);
return $;
}
use of org.eclipse.jdt.ls.core.internal.handlers.JdtDomModels.LspVariableBinding in project eclipse.jdt.ls by eclipse.
the class MoveHandler method moveInstanceMethod.
private static RefactorWorkspaceEdit moveInstanceMethod(CodeActionParams params, LspVariableBinding destination, IProgressMonitor monitor) {
final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.getTextDocument().getUri());
if (unit == null) {
return new RefactorWorkspaceEdit("Failed to move instance method because cannot find the compilation unit associated with " + params.getTextDocument().getUri());
}
MethodDeclaration methodDeclaration = getSelectedMethodDeclaration(unit, params);
if (methodDeclaration == null || destination == null) {
return new RefactorWorkspaceEdit("Failed to move instance method because no method is selected or no destination is specified.");
}
IMethodBinding methodBinding = methodDeclaration.resolveBinding();
if (methodBinding == null || !(methodBinding.getJavaElement() instanceof IMethod)) {
return new RefactorWorkspaceEdit("Failed to move instance method because the selected element is not a method.");
}
SubMonitor subMonitor = SubMonitor.convert(monitor, "Moving instance method...", 100);
IMethod method = (IMethod) methodBinding.getJavaElement();
MoveInstanceMethodProcessor processor = new MoveInstanceMethodProcessor(method, PreferenceManager.getCodeGenerationSettings(unit));
Refactoring refactoring = new MoveRefactoring(processor);
CheckConditionsOperation check = new CheckConditionsOperation(refactoring, CheckConditionsOperation.INITIAL_CONDITONS);
try {
check.run(subMonitor.split(20));
if (check.getStatus().getSeverity() >= RefactoringStatus.FATAL) {
JavaLanguageServerPlugin.logError("Failed to execute the 'move' refactoring.");
JavaLanguageServerPlugin.logError(check.getStatus().toString());
return new RefactorWorkspaceEdit("Failed to move instance method. Reason: " + check.getStatus().toString());
}
IVariableBinding[] possibleTargets = processor.getPossibleTargets();
Optional<IVariableBinding> target = Stream.of(possibleTargets).filter(possibleTarget -> Objects.equals(possibleTarget.getKey(), destination.bindingKey)).findFirst();
if (target.isPresent()) {
processor.setTarget(target.get());
processor.setDeprecateDelegates(false);
processor.setInlineDelegator(true);
processor.setRemoveDelegator(true);
check = new CheckConditionsOperation(refactoring, CheckConditionsOperation.FINAL_CONDITIONS);
check.run(subMonitor.split(60));
if (check.getStatus().getSeverity() >= RefactoringStatus.FATAL) {
JavaLanguageServerPlugin.logError("Failed to execute the 'move' refactoring.");
JavaLanguageServerPlugin.logError(check.getStatus().toString());
return new RefactorWorkspaceEdit("Failed to move instance method. Reason: " + check.getStatus().toString());
}
Change change = processor.createChange(subMonitor.split(20));
return new RefactorWorkspaceEdit(ChangeUtil.convertToWorkspaceEdit(change));
} else {
return new RefactorWorkspaceEdit("Failed to move instance method because cannot find the target " + destination.name);
}
} catch (CoreException e) {
JavaLanguageServerPlugin.log(e);
return new RefactorWorkspaceEdit("Failed to move instance method because of " + e.toString());
} finally {
subMonitor.done();
}
}
use of org.eclipse.jdt.ls.core.internal.handlers.JdtDomModels.LspVariableBinding in project eclipse.jdt.ls by eclipse.
the class MoveHandler method move.
public static RefactorWorkspaceEdit move(MoveParams moveParams, IProgressMonitor monitor) {
if (moveParams == null) {
return new RefactorWorkspaceEdit("moveParams should not be empty.");
}
try {
if ("moveResource".equalsIgnoreCase(moveParams.moveKind)) {
String targetUri = null;
if (moveParams.destination instanceof String) {
targetUri = (String) moveParams.destination;
} else {
String json = (moveParams.destination == null ? null : new Gson().toJson(moveParams.destination));
PackageNode packageNode = JSONUtility.toLsp4jModel(json, PackageNode.class);
if (packageNode == null) {
return new RefactorWorkspaceEdit("Invalid destination object: " + moveParams.destination);
}
targetUri = packageNode.uri;
}
return moveCU(moveParams.sourceUris, targetUri, moveParams.updateReferences, monitor);
} else if ("moveInstanceMethod".equalsIgnoreCase(moveParams.moveKind)) {
String json = (moveParams.destination == null ? null : new Gson().toJson(moveParams.destination));
LspVariableBinding variableBinding = JSONUtility.toLsp4jModel(json, LspVariableBinding.class);
if (variableBinding == null) {
return new RefactorWorkspaceEdit("Invalid destination object: " + moveParams.destination);
}
return moveInstanceMethod(moveParams.params, variableBinding, monitor);
} else if ("moveStaticMember".equalsIgnoreCase(moveParams.moveKind)) {
String typeName = resolveTargetTypeName(moveParams.destination);
return moveStaticMember(moveParams.params, typeName, monitor);
} else if ("moveTypeToNewFile".equalsIgnoreCase(moveParams.moveKind)) {
return moveTypeToNewFile(moveParams.params, monitor);
} else if ("moveTypeToClass".equalsIgnoreCase(moveParams.moveKind)) {
String typeName = resolveTargetTypeName(moveParams.destination);
return moveTypeToClass(moveParams.params, typeName, monitor);
}
} catch (IllegalArgumentException e) {
return new RefactorWorkspaceEdit(e.getMessage());
}
return new RefactorWorkspaceEdit("Unsupported move operation.");
}
use of org.eclipse.jdt.ls.core.internal.handlers.JdtDomModels.LspVariableBinding in project eclipse.jdt.ls by eclipse.
the class GenerateConstructorsHandler method checkConstructorStatus.
public static CheckConstructorsResponse checkConstructorStatus(IType type, IProgressMonitor monitor) {
if (type == null || type.getCompilationUnit() == null) {
return new CheckConstructorsResponse();
}
try {
CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(type.getCompilationUnit(), CoreASTProvider.WAIT_YES, monitor);
if (astRoot == null) {
return new CheckConstructorsResponse();
}
ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
if (typeBinding == null) {
return new CheckConstructorsResponse();
}
IMethodBinding[] superConstructors = getVisibleConstructors(astRoot, typeBinding);
Map<IJavaElement, IVariableBinding> fieldsToBindings = new HashMap<>();
for (IVariableBinding field : typeBinding.getDeclaredFields()) {
if (field.isSynthetic() || Modifier.isStatic(field.getModifiers())) {
continue;
}
if (Modifier.isFinal(field.getModifiers())) {
ASTNode declaringNode = astRoot.findDeclaringNode(field);
// Do not add final fields which have been set in the <clinit>
if (declaringNode instanceof VariableDeclarationFragment && ((VariableDeclarationFragment) declaringNode).getInitializer() != null) {
continue;
}
}
fieldsToBindings.put(field.getJavaElement(), field);
}
List<IVariableBinding> fields = new ArrayList<>();
// Sort the fields by the order in which they appear in the source or class file.
for (IField field : type.getFields()) {
IVariableBinding fieldBinding = fieldsToBindings.remove(field);
if (fieldBinding != null) {
fields.add(fieldBinding);
}
}
// @formatter:off
return new CheckConstructorsResponse(Arrays.stream(superConstructors).map(binding -> new LspMethodBinding(binding)).toArray(LspMethodBinding[]::new), fields.stream().map(binding -> new LspVariableBinding(binding)).toArray(LspVariableBinding[]::new));
// @formatter:on
} catch (JavaModelException e) {
JavaLanguageServerPlugin.logException("Failed to check constructor status", e);
}
return new CheckConstructorsResponse();
}
Aggregations