Files
lucisv/crates/vlog_refactor/src/imports.rs
T

565 lines
23 KiB
Rust

//! Organize imports: drop what nothing uses, merge exact duplicates, sort the
//! run at the scope's top.
//!
//! The judgement — *which* imports anything uses — is not here. It is
//! [`vlog_semantic::import_usage`], because the lint rule that squiggles the
//! same lines has to ask exactly the same question and a second implementation
//! would eventually answer differently. What is here is the **editing**: which
//! lines one `import` item occupies, which of them form the contiguous run at
//! the top of a module, package, class or compilation unit, what order they
//! belong in, and the refusals that come from the text rather than from the
//! symbol table.
//!
//! Every import item is treated as the **block of whole lines** it occupies,
//! its own comments included, and the run is rewritten by writing those blocks
//! back in a new order. So a comment travels with the line it was written on,
//! byte for byte, and the splice verifier's piece comparison — which counts
//! every comment on both sides of the edit — is what proves it did
//! (`check::verify_splice`, CLAUDE.md invariant 3). An import carrying a
//! comment is never *deleted*: the comment would have nowhere to go, and
//! `never_dropped` would refuse the edit whole.
//!
//! See `docs/features/organize-imports/README.md`.
use std::path::{Path, PathBuf};
use vlog_parser::ast::{ClassDecl, Item, ItemKind, Module, SourceFile};
use vlog_parser::span::TextRange;
use vlog_parser::token::Comment;
use vlog_parser::{parse_source_tolerant, tokenize, ParseDiagnostic};
use vlog_semantic::{analyze, import_scopes, import_usage, ImportScope, Semantics};
use crate::rename::{display, Scope};
use crate::{check, RefactorEdit, TextEdit};
/// Sort the `import` run at the top of the scope the cursor is in, delete the
/// imports nothing there uses, and drop exact duplicates.
///
/// The scope is the innermost module, interface, package, class or
/// compilation unit covering `offset`. Nothing outside the cursor's own file
/// is edited: an `import` binds names in the scope that wrote it and nowhere
/// else.
pub fn organize_imports(
files: &[(PathBuf, String)],
file: &Path,
offset: u32,
) -> Result<RefactorEdit, String> {
Ok(organize(files, file, offset)?.0)
}
/// [`organize_imports`], plus what its code action's title promises: how many
/// imports it removes and how many it writes back in order.
pub fn organize_counts(
files: &[(PathBuf, String)],
file: &Path,
offset: u32,
) -> Result<(RefactorEdit, usize, usize), String> {
organize(files, file, offset)
}
/// The lightbulb's text, written here so every front end says the same thing.
pub fn organize_title(removed: usize, sorted: usize) -> String {
format!("lucisv: organize imports (removes {removed}, sorts {sorted})")
}
/// Every `import` item in a file that nothing in its scope uses, with the
/// sentence saying so.
///
/// The census half of the engine: no edit, no verification, one answer per
/// unused item. A scope the judgement refuses contributes nothing.
pub fn unused_imports(files: &[(PathBuf, String)], file: &Path) -> Vec<(TextRange, String)> {
let scope = Scope::build(files);
let Some(text) = scope.index_of(file).and_then(|i| scope.text(i)) else { return Vec::new() };
let (tree, diagnostics) = parse_source_tolerant(text);
if !diagnostics.is_empty() {
return Vec::new();
}
let Ok(tokens) = tokenize(text) else { return Vec::new() };
let semantics = analyze(&tree, text);
vlog_semantic::unused_imports(&tree, &semantics, &tokens, scope.index())
.into_iter()
.map(|found| (found.span, found.message()))
.collect()
}
/// Every package the scope at `offset` imports, or nothing when there is no
/// import run to organize there.
///
/// The **cheap gate**, and the fan-out namer with it: one parse of one file,
/// no workspace, no I/O — the same bargain `port_action_modules` strikes, and
/// for the same reason (a `textDocument/codeAction` arrives on every cursor
/// move). Empty exactly where [`organize_imports`] would find nothing to do
/// for want of a scope; a caller reads the named packages' files and hands
/// them, and nothing else, to the engine.
pub fn imported_packages(text: &str, offset: u32) -> Vec<String> {
let (tree, diagnostics) = parse_source_tolerant(text);
imported_packages_in(&tree, &diagnostics, text, offset)
}
/// [`imported_packages`] over a parse the caller already has.
///
/// The same answer, including the refusal on a buffer that did not parse
/// cleanly — `diagnostics` is that parse's own list and must come from the
/// same run as `tree`. `text` is still needed: the "is the cursor at the top"
/// question reads the source bytes of the import run's comment block. Take 5
/// §P1b; see `docs/features/perf5-p1/README.md`.
pub fn imported_packages_in(
tree: &SourceFile,
diagnostics: &[ParseDiagnostic],
text: &str,
offset: u32,
) -> Vec<String> {
if !diagnostics.is_empty() {
return Vec::new();
}
let Some(items) = container_at(tree, offset) else { return Vec::new() };
let imports: Vec<&Item> = items.iter().filter(|item| is_import(item)).collect();
if imports.is_empty() || !at_the_top(text, items, offset) {
return Vec::new();
}
let mut out: Vec<String> = Vec::new();
for item in imports {
let ItemKind::Import(paths) = &item.kind else { continue };
for path in paths {
if !out.contains(&path.pkg.text) {
out.push(path.pkg.text.clone());
}
}
}
out
}
/// Whether the cursor is somewhere the action belongs: in the scope's header
/// — everything before its first item — or on one of its import items' lines.
fn at_the_top(text: &str, items: &[Item], offset: u32) -> bool {
let Some(first) = items.first() else { return false };
if offset < block(text, first).map_or(first.span.start, |block| block.start) {
return true;
}
items.iter().filter(|item| is_import(item)).any(|item| {
block(text, item).is_some_and(|block| block.start <= offset && offset <= block.end)
})
}
fn is_import(item: &Item) -> bool {
matches!(item.kind, ItemKind::Import(_))
}
// ----------------------------------------------------------------------
// the plan
// ----------------------------------------------------------------------
fn organize(
files: &[(PathBuf, String)],
file: &Path,
offset: u32,
) -> Result<(RefactorEdit, usize, usize), String> {
let mut scope = Scope::build(files);
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
let (tree, diagnostics) = parse_source_tolerant(text);
let semantics = analyze(&tree, text);
let Ok(tokens) = tokenize(text) else { return Err(not_in_scope(file)) };
let (edits, warnings, removed, sorted) =
planned(scope.index(), file, text, &tree, &diagnostics, &semantics, &tokens, offset)?;
let what = "organizing the imports";
let plan = vec![(i, edits)];
check::verify_splice(&mut scope, &plan, "", what)?;
let Some((_, edits)) = plan.into_iter().next() else { return Err(not_in_scope(file)) };
let edit =
RefactorEdit { edits: vec![(file.to_path_buf(), edits)], warnings, created: Vec::new() };
Ok((edit, removed, sorted))
}
/// Everything the organization decides **before** it is verified: its edits,
/// the sentences about what it left alone, and the two counts a title
/// promises.
///
/// One reader, so the code action's offer and the edit it resolves to cannot
/// come to disagree about how many imports go and how many are sorted.
/// `tree`, `diagnostics`, `semantics` and `tokens` must all be of `text`.
#[allow(clippy::too_many_arguments)] // one call's worth of already-computed inputs, not state
fn planned(
index: &vlog_semantic::WorkspaceIndex,
file: &Path,
text: &str,
tree: &SourceFile,
diagnostics: &[ParseDiagnostic],
semantics: &Semantics,
tokens: &[vlog_parser::token::Token],
offset: u32,
) -> Result<(Vec<TextEdit>, Vec<String>, usize, usize), String> {
unparsed(file, diagnostics)?;
let here = scope_at(tree, semantics, offset)?;
let verdicts = import_usage(semantics, tokens, here.scope, index)?;
let mut blocks = Blocks::read(text, here.items, &verdicts)?;
let (edits, warnings, removed, sorted) = blocks.plan(text)?;
if edits.is_empty() {
return Err(match warnings.first() {
Some(sentence) => sentence.clone(),
None => "these imports are already sorted, and every one of them is used.".to_string(),
});
}
Ok((edits, warnings, removed, sorted))
}
/// What an organize-imports code action's title promises — how many imports it
/// removes and how many it writes back in order — **without** verifying the
/// splice or keeping the edit.
///
/// [`organize_counts`] answers the same two numbers by computing the whole
/// refactoring and running `check::verify_splice`, which rebuilds the index
/// over every in-scope file and re-analyzes them. A lazily-offered code action
/// throws that edit away and asks for it again on the click, so the offer pays
/// for a verification whose result nothing reads: take 5 §P1c measured that
/// verification as about two thirds of the offer's cost
/// (`docs/features/perf5-p1/README.md`).
///
/// Everything the *plan* refuses is refused here identically, with the same
/// sentence: a buffer that does not parse, no scope at the position, an
/// unknown package (`import_usage`'s own refusal), an import sharing a line,
/// and the "already sorted, every one used" answer. What is **not** reproduced
/// is `check::verify_splice`; the click recomputes and verifies the whole
/// refactoring, which is where an edit that would not survive it is refused.
pub fn organize_offer(
files: &[(PathBuf, String)],
file: &Path,
offset: u32,
) -> Result<(usize, usize), String> {
let scope = Scope::build(files);
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
let (tree, diagnostics) = parse_source_tolerant(text);
let semantics = analyze(&tree, text);
let Ok(tokens) = tokenize(text) else { return Err(not_in_scope(file)) };
let (_, _, removed, sorted) =
planned(scope.index(), file, text, &tree, &diagnostics, &semantics, &tokens, offset)?;
Ok((removed, sorted))
}
/// [`organize_offer`] over the parse, analysis and token stream the caller
/// already has.
///
/// All four must be of exactly the text `files` holds for `file` — an open
/// buffer's `Document` holds that quartet for its own bytes. A buffer that did
/// not lex holds no tokens, but it also holds a parse diagnostic, so
/// [`planned`] refuses it before the token stream is read.
pub fn organize_offer_in(
files: &[(PathBuf, String)],
file: &Path,
tree: &SourceFile,
diagnostics: &[ParseDiagnostic],
semantics: &Semantics,
tokens: &[vlog_parser::token::Token],
offset: u32,
) -> Result<(usize, usize), String> {
let scope = Scope::build(files);
let Some(i) = scope.index_of(file) else { return Err(not_in_scope(file)) };
let Some(text) = scope.text(i) else { return Err(not_in_scope(file)) };
let (_, _, removed, sorted) =
planned(scope.index(), file, text, tree, diagnostics, semantics, tokens, offset)?;
Ok((removed, sorted))
}
/// The innermost scope covering the cursor that may write `import` items.
fn scope_at<'t>(
tree: &'t SourceFile,
semantics: &Semantics,
offset: u32,
) -> Result<ImportScope<'t>, String> {
import_scopes(tree, semantics)
.into_iter()
.rfind(|here| here.span.contains(offset) || here.span.end == offset)
.ok_or_else(|| "there is no scope at this position to organize imports in.".to_string())
}
/// The items of the innermost module, package or class covering `offset`, or
/// the file's own — the tree-only twin of [`scope_at`], for the cheap gate.
fn container_at(tree: &SourceFile, offset: u32) -> Option<&[Item]> {
let mut found: &[Item] = &tree.items;
let mut items: &[Item] = &tree.items;
loop {
let inner = items.iter().find_map(|item| {
if !item.span.contains(offset) {
return None;
}
match &item.kind {
ItemKind::Module(m) => Some(nested(m)),
ItemKind::Package { items, .. } => Some(items.as_slice()),
ItemKind::Class(c) => Some(class_items(c)),
_ => None,
}
});
match inner {
Some(inner) => {
found = inner;
items = inner;
}
None => return Some(found),
}
}
}
fn nested(module: &Module) -> &[Item] {
&module.items
}
fn class_items(class: &ClassDecl) -> &[Item] {
&class.items
}
// ----------------------------------------------------------------------
// blocks
// ----------------------------------------------------------------------
/// One `import` item as the whole lines it occupies, with everything the plan
/// has to know about it.
struct Block {
/// The lines the item and its own comments cover, the final newline
/// excluded.
range: TextRange,
/// Sort key: package name, `*` before a named item, then the item name.
key: (String, u8, String),
/// The paths it writes, normalized — what makes two items duplicates.
paths: Vec<(String, Option<String>)>,
/// Whether any path of it could supply a name something uses.
used: bool,
/// Whether it carries a comment, which is what makes it undeletable.
commented: bool,
/// The item as written, for a sentence.
written: String,
}
/// The import items of one scope, in source order, with the run at the top
/// marked off.
struct Blocks {
blocks: Vec<Block>,
/// How many of `blocks`, from the front, form the contiguous run at the
/// scope's top.
run: usize,
}
impl Blocks {
/// Read one scope's import items, or say why they cannot be read.
fn read(
text: &str,
items: &[Item],
verdicts: &[vlog_semantic::ImportUse],
) -> Result<Blocks, String> {
let mut blocks = Vec::new();
for item in items {
let ItemKind::Import(paths) = &item.kind else { continue };
let Some(range) = block(text, item) else {
return Err(shared_line(text, item.span.start));
};
let mut used = false;
let mut keys = Vec::new();
let mut normalized = Vec::new();
for path in paths {
let Some(verdict) = verdicts.iter().find(|v| v.name_span == path.pkg.span) else {
return Err(LOST.to_string());
};
used |= verdict.used;
let item_name = verdict.item.clone();
keys.push((
verdict.package.clone(),
u8::from(item_name.is_some()),
item_name.clone().unwrap_or_default(),
));
normalized.push((verdict.package.clone(), item_name));
}
let Some(key) = keys.into_iter().min() else { continue };
blocks.push(Block {
range,
key,
paths: normalized,
used,
commented: !item.meta.leading.is_empty() || item.meta.trailing.is_some(),
written: text
.get(item.span.start as usize..item.span.end as usize)
.unwrap_or("")
.to_string(),
});
}
let run = run_length(text, items, &blocks);
Ok(Blocks { blocks, run })
}
/// The edits, the sentences about what was left alone, and the two counts
/// a title promises.
fn plan(&mut self, text: &str) -> Result<(Vec<TextEdit>, Vec<String>, usize, usize), String> {
let mut warnings = Vec::new();
let mut keep: Vec<bool> = Vec::with_capacity(self.blocks.len());
let mut seen: Vec<&[(String, Option<String>)]> = Vec::new();
for block in &self.blocks {
let duplicate = seen.contains(&block.paths.as_slice());
seen.push(&block.paths);
let drop = !block.used || duplicate;
if drop && block.commented {
warnings.push(commented(&block.written));
}
keep.push(!drop || block.commented);
}
let mut edits = Vec::new();
let mut removed = 0usize;
let mut sorted = 0usize;
// The run is one replacement: its surviving blocks, in order, written
// back as the lines they were.
let (head, tail) = self.blocks.split_at(self.run);
let mut written: Vec<&Block> =
head.iter().zip(&keep).filter(|(_, k)| **k).map(|(b, _)| b).collect();
written.sort_by(|a, b| a.key.cmp(&b.key));
if let (Some(first), Some(last)) = (head.first(), head.last()) {
// Nothing left of the run means its last newline goes too, or the
// deletion would leave a blank line where the imports were.
let end = match written.is_empty() {
true => (last.range.end as usize + 1).min(text.len()) as u32,
false => last.range.end,
};
let range = TextRange::new(first.range.start, end);
let new_text = written
.iter()
.map(|block| {
text.get(block.range.start as usize..block.range.end as usize).unwrap_or("")
})
.collect::<Vec<_>>()
.join("\n");
let old = text.get(range.start as usize..range.end as usize).unwrap_or("");
if new_text != old {
// The two counts are what the run's own edit does, so a title
// never promises a sort that was already true.
removed += head.len() - written.len();
sorted = written.len();
edits.push(TextEdit { range, new_text });
}
}
// Everything after the run is deleted where it is, one whole line at
// a time, or left alone.
for (block, keep) in tail.iter().zip(keep.get(self.run..).unwrap_or(&[])) {
if *keep {
continue;
}
removed += 1;
let end = (block.range.end as usize + 1).min(text.len()) as u32;
edits.push(TextEdit {
range: TextRange::new(block.range.start, end),
new_text: String::new(),
});
}
edits.sort_by_key(|edit| (edit.range.start, edit.range.end));
Ok((edits, warnings, removed, sorted))
}
}
/// How many of a scope's import items form the **contiguous run at its top**:
/// the leading items, all of them imports, each on the line after the one
/// before it.
///
/// A blank line between two imports ends the run rather than being swallowed:
/// a blank line is a grouping the author wrote, and an "organize" that erased
/// it would be reformatting rather than organizing.
fn run_length(text: &str, items: &[Item], blocks: &[Block]) -> usize {
let mut run = 0usize;
for (n, item) in items.iter().enumerate() {
if !is_import(item) || n != run {
break;
}
let Some(block) = blocks.get(run) else { break };
if let Some(previous) = run.checked_sub(1).and_then(|p| blocks.get(p)) {
let between = text.get(previous.range.end as usize..block.range.start as usize);
if between != Some("\n") {
break;
}
}
run += 1;
}
run
}
/// The whole lines one item occupies, its own comments included — or `None`
/// when the item shares a line with something else, which is the one layout
/// this refactoring will not rearrange.
fn block(text: &str, item: &Item) -> Option<TextRange> {
let mut spans: Vec<TextRange> = item.meta.leading.iter().map(|c: &Comment| c.span).collect();
spans.extend(item.meta.before_sep.iter().map(|c| c.span));
if let Some(comment) = &item.meta.trailing {
spans.push(comment.span);
}
spans.push(item.span);
spans.sort_by_key(|span| (span.start, span.end));
let first = spans.first()?.start;
let last = spans.iter().map(|span| span.end).max()?;
let start = line_start(text, first);
let end = line_end(text, last);
// Everything in the block that is not the item's own code or one of its
// own comments must be whitespace: anything else is another item's, and
// moving this block would move that too.
let mut cursor = start;
for span in &spans {
if span.start < cursor {
continue;
}
if !blank(text, cursor, span.start) {
return None;
}
cursor = cursor.max(span.end);
}
blank(text, cursor, end).then(|| TextRange::new(start, end))
}
fn blank(text: &str, from: u32, to: u32) -> bool {
text.get(from as usize..to as usize).is_some_and(|gap| gap.chars().all(char::is_whitespace))
}
fn line_start(text: &str, at: u32) -> u32 {
text.get(..at as usize).and_then(|head| head.rfind('\n')).map_or(0, |n| n as u32 + 1)
}
fn line_end(text: &str, at: u32) -> u32 {
match text.get(at as usize..).and_then(|tail| tail.find('\n')) {
Some(n) => at + n as u32,
None => text.len() as u32,
}
}
// ----------------------------------------------------------------------
// sentences
// ----------------------------------------------------------------------
const LOST: &str = "lucisv lost track of one of the imports it was reading, so it made no edits.";
fn not_in_scope(file: &Path) -> String {
format!("{} is not one of the files lucisv was given.", display(file))
}
fn shared_line(text: &str, at: u32) -> String {
let line = text.get(..at as usize).map_or(0, |head| head.matches('\n').count()) + 1;
format!(
"the import on line {line} shares its line with something else; lucisv organizes imports written one per line, so it made no edits."
)
}
fn commented(written: &str) -> String {
format!(
"`{}` is unused, but it carries a comment lucisv would have to delete with it; delete the comment first and lucisv will remove the line.",
written.trim_end_matches(';')
)
}
/// A file that does not parse is a file whose imports lucisv misread, and a
/// misread import list is one it would delete lines out of.
fn unparsed(file: &Path, diagnostics: &[ParseDiagnostic]) -> Result<(), String> {
match diagnostics.first() {
None => Ok(()),
Some(problem) => Err(format!(
"{} does not parse ({} at line {}), so lucisv will not organize its imports.",
display(file),
problem.message,
problem.line
)),
}
}