Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Diagnostic and Quickfix for \usepackage duplicates and ordering #1280

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions crates/base-db/src/semantics/tex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ impl Semantics {
self.links.push(Link {
kind,
path: Span::from(&path),
full_range: latex::small_range(&include),
base_dir: None,
});
}
Expand All @@ -132,11 +133,13 @@ impl Semantics {
};
let text = format!("{base_dir}{}", path.to_string());
let range = latex::small_range(&path);
let full_range = latex::small_range(&import);

self.links.push(Link {
kind: LinkKind::Tex,
path: Span { text, range },
base_dir: Some(base_dir),
full_range,
});
}

Expand Down Expand Up @@ -373,6 +376,7 @@ pub struct Link {
pub kind: LinkKind,
pub path: Span,
pub base_dir: Option<String>,
pub full_range: TextRange,
}

impl Link {
Expand Down
27 changes: 27 additions & 0 deletions crates/base-db/src/util/queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,33 @@ pub trait Object {
}
}

impl Object for tex::Link {
fn name_text(&self) -> &str {
&self.path.text
}

fn name_range(&self) -> TextRange {
self.path.range
}

fn full_range(&self) -> TextRange {
self.full_range
}

fn kind(&self) -> ObjectKind {
ObjectKind::Definition
}

fn find<'db>(document: &'db Document) -> Box<dyn Iterator<Item = &'db Self> + 'db> {
let data = document.data.as_tex();
let iter = data
.into_iter()
.flat_map(|data| data.semantics.links.iter());

Box::new(iter)
}
}

impl Object for tex::Label {
fn name_text(&self) -> &str {
&self.name.text
Expand Down
25 changes: 25 additions & 0 deletions crates/diagnostics/src/imports.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use base_db::{semantics::tex::Link, util::queries, Workspace};
use rustc_hash::FxHashMap;
use url::Url;

use crate::{types::Diagnostic, ImportError};

pub fn detect_duplicate_imports(
workspace: &Workspace,
results: &mut FxHashMap<Url, Vec<Diagnostic>>,
) {
for conflict in queries::Conflict::find_all::<Link>(workspace) {
let others = conflict
.rest
.iter()
.map(|location| (location.document.uri.clone(), location.range))
.collect();

let diagnostic =
Diagnostic::Import(conflict.main.range, ImportError::DuplicateImport(others));
results
.entry(conflict.main.document.uri.clone())
.or_default()
.push(diagnostic);
}
}
1 change: 1 addition & 0 deletions crates/diagnostics/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod grammar;
mod labels;
mod manager;
mod types;
mod imports;

pub use manager::Manager;
pub use types::*;
Expand Down
1 change: 1 addition & 0 deletions crates/diagnostics/src/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ impl Manager {
super::citations::detect_duplicate_entries(workspace, &mut results);
super::labels::detect_duplicate_labels(workspace, &mut results);
super::labels::detect_undefined_and_unused_labels(workspace, &mut results);
super::imports::detect_duplicate_imports(workspace, &mut results);

results.retain(|uri, _| {
workspace
Expand Down
13 changes: 13 additions & 0 deletions crates/diagnostics/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ impl std::fmt::Debug for TexError {
}
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ImportError {
OrderingConflict,
DuplicateImport(Vec<(Url, TextRange)>),
}

#[derive(PartialEq, Eq, Clone)]
pub enum BibError {
ExpectingLCurly,
Expand Down Expand Up @@ -89,6 +95,7 @@ pub enum Diagnostic {
Bib(TextRange, BibError),
Build(TextRange, BuildError),
Chktex(ChktexError),
Import(TextRange, ImportError)
}

impl Diagnostic {
Expand All @@ -114,6 +121,10 @@ impl Diagnostic {
},
Diagnostic::Build(_, error) => &error.message,
Diagnostic::Chktex(error) => &error.message,
Diagnostic::Import(_, error) => match error {
ImportError::OrderingConflict => todo!(),
ImportError::DuplicateImport(_) => "Duplicate Package imported.",
}
}
}

Expand All @@ -127,6 +138,7 @@ impl Diagnostic {
let end = line_index.offset(error.end)?;
TextRange::new(start, end)
}
Diagnostic::Import(range, _) => *range,
})
}

Expand All @@ -152,6 +164,7 @@ impl Diagnostic {
},
Diagnostic::Chktex(_) => None,
Diagnostic::Build(_, _) => None,
Diagnostic::Import(_, _) => None,
}
}
}
180 changes: 180 additions & 0 deletions crates/texlab/src/action.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
use std::collections::HashMap;

use base_db::Workspace;
use diagnostics::{Diagnostic, ImportError};
use lsp_types::{CodeAction, CodeActionKind, CodeActionParams, TextEdit, WorkspaceEdit};
use rowan::{TextRange, TextSize};
use rustc_hash::FxBuildHasher;

use crate::util::{line_index_ext::LineIndexExt, to_proto};

pub fn remove_duplicate_imports(
diagnostics_map: HashMap<lsp_types::Url, Vec<diagnostics::Diagnostic>, FxBuildHasher>,
params: CodeActionParams,
workspace: parking_lot::lock_api::RwLockReadGuard<'_, parking_lot::RawRwLock, Workspace>,
) -> Vec<CodeAction> {
let mut actions = Vec::new();
let url = params.text_document.uri.clone();
let document = workspace.lookup(&url).unwrap();

let diagnostics = diagnostics_map
.get(&url)
.unwrap()
.iter()
.filter(|diag| matches!(diag, Diagnostic::Import(_, ImportError::DuplicateImport(_))))
.collect::<Vec<_>>();

let cursor_position = params.range.start;

let cursor_diag = diagnostics.iter().find(|diag| {
let line_index = &workspace
.lookup(&params.text_document.uri)
.unwrap()
.line_index;
let range = diag.range(&line_index).unwrap();
range.contains(line_index.offset_lsp(cursor_position).unwrap())
});

if let Some(diag) = cursor_diag {
let package_name = get_package_name(&workspace, &params, diag);

let filtered_diagnostics: Vec<_> = diagnostics
.clone()
.into_iter()
.filter(|diag| get_package_name(&workspace, &params, diag) == package_name)
.collect();

let import_diags: Vec<lsp_types::Diagnostic> = filtered_diagnostics
.clone()
.iter()
.map(|diag| to_proto::diagnostic(&workspace, document, diag).unwrap())
.collect();

for diag in filtered_diagnostics {
let line_index = &workspace
.lookup(&params.text_document.uri)
.unwrap()
.line_index;
let range = diag.range(&line_index).unwrap();
let start_line = line_index
.line_col_lsp_range(TextRange::at(range.start(), TextSize::from(0)))
.unwrap()
.start
.line;

actions.push(CodeAction {
title: format!(
"Remove duplicate package: {}, line {}.",
get_package_name(&workspace, &params, diag),
(1 + start_line)
),
kind: Some(CodeActionKind::QUICKFIX),
diagnostics: Some(import_diags.clone()),
edit: Some(WorkspaceEdit {
changes: Some(
vec![(
url.clone(),
vec![TextEdit {
range: get_line_range(&workspace, &params, diag),
new_text: "".to_string(),
}],
)]
.into_iter()
.collect(),
),
document_changes: None,
change_annotations: None,
}),
command: None,
is_preferred: None,
disabled: None,
data: None,
});
}
}

let mut seen_packages = HashMap::new();
let all_diags = diagnostics
.iter()
.filter(|diag| {
let package_name = get_package_name(&workspace, &params, diag);
if seen_packages.contains_key(&package_name) {
true
} else {
seen_packages.insert(package_name, true);
false
}
})
.collect::<Vec<_>>();

let mut all_diags_edit = Vec::new();

for diag in all_diags {
all_diags_edit.push(TextEdit {
range: get_line_range(&workspace, &params, diag),
new_text: "".to_string(),
});
}

if all_diags_edit.is_empty() {
return actions;
}

let import_diags: Vec<lsp_types::Diagnostic> = diagnostics
.clone()
.iter()
.map(|diag| to_proto::diagnostic(&workspace, document, diag).unwrap())
.collect();

actions.push(CodeAction {
title: "Remove all duplicate package.".to_string(),
kind: Some(CodeActionKind::QUICKFIX),
diagnostics: Some(import_diags.clone()),
edit: Some(WorkspaceEdit {
changes: Some(vec![(url.clone(), all_diags_edit)].into_iter().collect()),
document_changes: None,
change_annotations: None,
}),
command: None,
is_preferred: None,
disabled: None,
data: None,
});

actions
}

fn get_line_range(
workspace: &Workspace,
params: &CodeActionParams,
diag: &Diagnostic,
) -> lsp_types::Range {
let line_index = &workspace
.lookup(&params.text_document.uri)
.unwrap()
.line_index;
let range = diag.range(&line_index).unwrap();
let start_line = line_index
.line_col_lsp_range(TextRange::at(range.start(), TextSize::from(0)))
.unwrap()
.start
.line;
let end_line = line_index
.line_col_lsp_range(TextRange::new(range.end(), range.end()))
.unwrap()
.end
.line;
let start = lsp_types::Position::new(start_line, 0);
let end = lsp_types::Position::new(end_line + 1, 0);
lsp_types::Range::new(start, end)
}

fn get_package_name(workspace: &Workspace, params: &CodeActionParams, diag: &Diagnostic) -> String {
let document = workspace.lookup(&params.text_document.uri).unwrap();
let line_index = document.line_index.clone();
let range = diag.range(&line_index).unwrap();
let start = usize::from(range.start());
let end = usize::from(range.end());
let text = &document.text[start..end];
text.to_string()
}
1 change: 1 addition & 0 deletions crates/texlab/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@ mod client;
pub(crate) mod features;
mod server;
pub(crate) mod util;
mod action;

pub use self::{client::LspClient, server::Server};
11 changes: 9 additions & 2 deletions crates/texlab/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use std::{
time::Duration,
};

use crate::action;
use anyhow::Result;
use base_db::{deps, Owner, Workspace};
use commands::{BuildCommand, CleanCommand, CleanTarget, ForwardSearch};
Expand Down Expand Up @@ -174,6 +175,7 @@ impl Server {
..Default::default()
}),
inlay_hint_provider: Some(OneOf::Left(true)),
code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
..ServerCapabilities::default()
}
}
Expand Down Expand Up @@ -781,9 +783,14 @@ impl Server {
Ok(())
}

fn code_actions(&self, id: RequestId, _params: CodeActionParams) -> Result<()> {
fn code_actions(&self, id: RequestId, params: CodeActionParams) -> Result<()> {
let workspace = self.workspace.read();
let diagnostics = self.diagnostic_manager.get(&workspace);

let actions = action::remove_duplicate_imports(diagnostics, params, workspace);

self.client
.send_response(lsp_server::Response::new_ok(id, Vec::<CodeAction>::new()))?;
.send_response(lsp_server::Response::new_ok(id, actions))?;
Ok(())
}

Expand Down
Loading