дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-22 01:20:46 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
14674cab36 |
No files matched your search
@@ -1,13 +1,4 @@
|
||||
//! In-memory index: one slot per file, with compact query-time tables derived from it.
|
||||
//!
|
||||
//! Queries never walk the fat `FileEntry` structs: `HotFiles`, `HotDirs` and `SymTable` hold
|
||||
//! only the fields a scan needs, packed in dense rows with interned strings, so a query
|
||||
//! streams contiguous memory instead of chasing `Box<[Sym]>` / `Box<str>` pointers.
|
||||
//! They are plain data, updated eagerly by `insert`/`remove` (every mutation needs `&mut
|
||||
//! IndexData`), and all queries run under the `IndexData` read lock: a scan therefore sees
|
||||
//! one consistent snapshot, and the only "invalidation" is the update itself. Space left
|
||||
//! behind by replaced/removed entries is reclaimed by compaction inside `insert`/`remove`
|
||||
//! once it dominates the table, and by `shrink`.
|
||||
//! In-memory index: one slot per file, symbols stored with their file.
|
||||
|
||||
use ide_core::{Range, SymbolKind};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -42,40 +33,6 @@ pub(crate) fn mask_bit(b: u8) -> u64 {
|
||||
}
|
||||
}
|
||||
|
||||
/// A substring of an interned text arena.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct Span {
|
||||
pub start: u32,
|
||||
pub len: u32,
|
||||
}
|
||||
|
||||
impl Span {
|
||||
/// A slice of nothing; used for optional fields (`None` containers).
|
||||
pub(crate) const NONE: Span = Span { start: u32::MAX, len: 0 };
|
||||
|
||||
/// Appends `s` to `arena`, returning the span it will occupy.
|
||||
///
|
||||
/// Spans are `u32`-addressed and `NONE` uses `u32::MAX` as its start, so an
|
||||
/// arena that reaches that bound cannot be represented. Fail loudly here
|
||||
/// instead of truncating the offsets: a wrapped span would make [`Self::get`]
|
||||
/// slice unrelated text, or panic far from the actual cause.
|
||||
#[inline]
|
||||
fn of(arena: &str, s: &str) -> Self {
|
||||
let start = u32::try_from(arena.len()).expect("index text arena exceeded the 4 GiB span limit");
|
||||
let len = u32::try_from(s.len()).expect("index text span exceeded the 4 GiB span limit");
|
||||
assert!(
|
||||
start != u32::MAX && start.checked_add(len).is_some(),
|
||||
"index text arena exceeded the 4 GiB span limit"
|
||||
);
|
||||
Self { start, len }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn get(self, arena: &str) -> &str {
|
||||
&arena[self.start as usize..(self.start + self.len) as usize]
|
||||
}
|
||||
}
|
||||
|
||||
/// Persisted per-file record (postcard in redb, keyed by the relative path).
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub(crate) struct FileRecord {
|
||||
@@ -95,12 +52,12 @@ pub(crate) struct StoredSymbol {
|
||||
pub range: Range,
|
||||
}
|
||||
|
||||
/// A symbol resolved out of [`SymTable`].
|
||||
pub(crate) struct SymRef<'a> {
|
||||
pub name: &'a str,
|
||||
pub(crate) struct Sym {
|
||||
pub name: Box<str>,
|
||||
pub kind: SymbolKind,
|
||||
pub container: Option<&'a str>,
|
||||
pub container: Option<Box<str>>,
|
||||
pub range: Range,
|
||||
pub mask: u64,
|
||||
}
|
||||
|
||||
pub(crate) struct FileEntry {
|
||||
@@ -116,34 +73,38 @@ pub(crate) struct FileEntry {
|
||||
pub mtime: u64,
|
||||
pub size: u64,
|
||||
pub hash: [u8; 32],
|
||||
/// Range of this file's symbols in [`IndexData::syms`].
|
||||
pub sym_start: u32,
|
||||
pub sym_len: u32,
|
||||
pub symbols: Box<[Sym]>,
|
||||
pub ignored: bool,
|
||||
}
|
||||
|
||||
impl FileEntry {
|
||||
/// Splits the record into the entry and its symbols; the symbols are flattened into
|
||||
/// the index-wide [`SymTable`] by [`IndexData::insert`].
|
||||
pub(crate) fn new(path: PathBuf, rel: String, record: FileRecord) -> (Self, Vec<StoredSymbol>) {
|
||||
pub(crate) fn new(path: PathBuf, rel: String, record: FileRecord) -> Self {
|
||||
let name_start = rel.rfind('/').map_or(0, |i| i + 1);
|
||||
let name = &rel[name_start..];
|
||||
let FileRecord { mtime, size, hash, symbols, ignored } = record;
|
||||
let entry = Self {
|
||||
let symbols = record
|
||||
.symbols
|
||||
.into_iter()
|
||||
.map(|s| Sym {
|
||||
mask: char_mask(&s.name),
|
||||
name: s.name.into_boxed_str(),
|
||||
kind: s.kind,
|
||||
container: s.container.map(String::into_boxed_str),
|
||||
range: s.range,
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
name_start_chars: rel[..name_start].chars().count() as u32,
|
||||
name_mask: char_mask(name),
|
||||
rel_mask: char_mask(&rel),
|
||||
name_start: name_start as u32,
|
||||
path,
|
||||
rel: rel.into_boxed_str(),
|
||||
mtime,
|
||||
size,
|
||||
hash,
|
||||
sym_start: 0,
|
||||
sym_len: 0,
|
||||
ignored,
|
||||
};
|
||||
(entry, symbols)
|
||||
mtime: record.mtime,
|
||||
size: record.size,
|
||||
hash: record.hash,
|
||||
symbols,
|
||||
ignored: record.ignored,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn name(&self) -> &str {
|
||||
@@ -154,391 +115,38 @@ impl FileEntry {
|
||||
&self.rel[..self.name_start as usize]
|
||||
}
|
||||
|
||||
pub(crate) fn record(&self) -> FileRecord {
|
||||
FileRecord {
|
||||
mtime: self.mtime,
|
||||
size: self.size,
|
||||
hash: self.hash,
|
||||
symbols: self
|
||||
.symbols
|
||||
.iter()
|
||||
.map(|s| StoredSymbol {
|
||||
name: s.name.to_string(),
|
||||
kind: s.kind,
|
||||
container: s.container.as_deref().map(str::to_owned),
|
||||
range: s.range,
|
||||
})
|
||||
.collect(),
|
||||
ignored: self.ignored,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the entry is out of date for `found` on disk.
|
||||
pub(crate) fn stale_for(&self, found: &crate::filter::Found) -> bool {
|
||||
self.mtime != found.mtime || self.size != found.size || self.ignored != found.ignored
|
||||
}
|
||||
}
|
||||
|
||||
/// The hot fields of one file slot, packed for the query scan; no pointers.
|
||||
pub(crate) struct FileRow {
|
||||
/// `rel` in [`HotFiles`]' arena.
|
||||
pub rel: Span,
|
||||
/// Byte offset of the file name inside `rel`.
|
||||
pub name_start: u32,
|
||||
pub sym_start: u32,
|
||||
pub sym_len: u32,
|
||||
/// Union of every symbol's [`char_mask`]: a selective symbol query can skip
|
||||
/// the whole file before touching its symbol range.
|
||||
pub sym_mask: u64,
|
||||
pub rel_mask: u64,
|
||||
pub name_mask: u64,
|
||||
/// Mask of the directory part (`rel[..name_start]`), precomputed for path queries.
|
||||
pub dir_mask: u64,
|
||||
/// `rel` is pure ASCII, so nucleo can match it without a UTF-32 conversion.
|
||||
pub ascii: bool,
|
||||
/// The slot holds a file; free slots keep a row so scans line up with `IndexData::files`.
|
||||
pub live: bool,
|
||||
}
|
||||
|
||||
impl FileRow {
|
||||
#[inline]
|
||||
pub(crate) fn rel<'a>(&self, arena: &'a str) -> &'a str {
|
||||
self.rel.get(arena)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn name<'a>(&self, arena: &'a str) -> &'a str {
|
||||
&self.rel.get(arena)[self.name_start as usize..]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn dir<'a>(&self, arena: &'a str) -> &'a str {
|
||||
&self.rel.get(arena)[..self.name_start as usize]
|
||||
}
|
||||
}
|
||||
|
||||
/// One dense row per file slot (same order and length as `IndexData::files`) plus the
|
||||
/// text arena the rows point into.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct HotFiles {
|
||||
pub rows: Vec<FileRow>,
|
||||
text: String,
|
||||
dead_text: usize,
|
||||
}
|
||||
|
||||
impl HotFiles {
|
||||
#[inline]
|
||||
pub(crate) fn text(&self) -> &str {
|
||||
&self.text
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn row(&self, slot: usize) -> Option<&FileRow> {
|
||||
self.rows.get(slot).filter(|row| row.live)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn row_of_slot(&self, slot: u32) -> Option<&FileRow> {
|
||||
self.row(slot as usize)
|
||||
}
|
||||
|
||||
/// `rel` of a live slot; candidate slots always are.
|
||||
#[inline]
|
||||
pub(crate) fn rel(&self, slot: u32) -> &str {
|
||||
self.rows[slot as usize].rel(&self.text)
|
||||
}
|
||||
|
||||
fn set(&mut self, slot: u32, row: FileRow) {
|
||||
if self.rows.len() as u32 == slot {
|
||||
self.rows.push(row);
|
||||
} else {
|
||||
self.rows[slot as usize] = row;
|
||||
}
|
||||
}
|
||||
|
||||
fn append(&mut self, rel: &str) -> Span {
|
||||
let span = Span::of(&self.text, rel);
|
||||
self.text.push_str(rel);
|
||||
span
|
||||
}
|
||||
|
||||
/// Updates the row of an existing slot (replace) in place.
|
||||
fn update(&mut self, slot: u32, e: &FileEntry, sym_mask: u64) {
|
||||
let idx = slot as usize;
|
||||
if self.rows[idx].rel.get(&self.text) != &*e.rel {
|
||||
self.dead_text += self.rows[idx].rel.len as usize;
|
||||
let span = self.append(&e.rel);
|
||||
self.rows[idx].rel = span;
|
||||
self.rows[idx].ascii = e.rel.is_ascii();
|
||||
self.rows[idx].dir_mask = char_mask(e.dir());
|
||||
}
|
||||
let row = &mut self.rows[idx];
|
||||
row.name_start = e.name_start;
|
||||
row.name_mask = e.name_mask;
|
||||
row.rel_mask = e.rel_mask;
|
||||
row.sym_start = e.sym_start;
|
||||
row.sym_len = e.sym_len;
|
||||
row.sym_mask = sym_mask;
|
||||
row.live = true;
|
||||
}
|
||||
|
||||
fn remove(&mut self, slot: u32) {
|
||||
let row = &mut self.rows[slot as usize];
|
||||
self.dead_text += row.rel.len as usize;
|
||||
row.rel = Span::NONE;
|
||||
row.sym_start = 0;
|
||||
row.sym_len = 0;
|
||||
row.sym_mask = 0;
|
||||
row.live = false;
|
||||
}
|
||||
|
||||
fn compact(&mut self) {
|
||||
let mut text = String::with_capacity(self.text.len() - self.dead_text);
|
||||
for row in &mut self.rows {
|
||||
if !row.live {
|
||||
continue;
|
||||
}
|
||||
let rel = row.rel.get(&self.text);
|
||||
row.rel = Span::of(&text, rel);
|
||||
text.push_str(rel);
|
||||
}
|
||||
self.text = text;
|
||||
self.dead_text = 0;
|
||||
}
|
||||
|
||||
fn shrink(&mut self) {
|
||||
self.compact();
|
||||
self.rows.shrink_to_fit();
|
||||
self.text.shrink_to_fit();
|
||||
}
|
||||
}
|
||||
|
||||
/// One folder holding indexed files, packed for the query scan.
|
||||
pub(crate) struct DirRow {
|
||||
/// `rel` in [`HotDirs`]' arena, including the trailing `/`.
|
||||
pub rel: Span,
|
||||
/// Byte offset of the last path segment inside the trimmed `rel`.
|
||||
pub name_start: u32,
|
||||
pub name_mask: u64,
|
||||
/// Mask of `rel` without the trailing `/`.
|
||||
pub rel_mask: u64,
|
||||
pub path: PathBuf,
|
||||
}
|
||||
|
||||
impl DirRow {
|
||||
#[inline]
|
||||
pub(crate) fn rel<'a>(&self, arena: &'a str) -> &'a str {
|
||||
self.rel.get(arena)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct HotDirs {
|
||||
pub rows: Vec<DirRow>,
|
||||
text: String,
|
||||
dead: usize,
|
||||
}
|
||||
|
||||
impl HotDirs {
|
||||
#[inline]
|
||||
pub(crate) fn text(&self) -> &str {
|
||||
&self.text
|
||||
}
|
||||
|
||||
fn push(&mut self, rel: &str, abs: &Path) -> u32 {
|
||||
let span = Span::of(&self.text, rel);
|
||||
self.text.push_str(rel);
|
||||
let trimmed = &rel[..rel.len() - 1];
|
||||
let name_start = trimmed.rfind('/').map_or(0, |i| i + 1);
|
||||
self.rows.push(DirRow {
|
||||
rel: span,
|
||||
name_start: name_start as u32,
|
||||
name_mask: char_mask(&trimmed[name_start..]),
|
||||
rel_mask: char_mask(trimmed),
|
||||
path: abs.to_owned(),
|
||||
});
|
||||
(self.rows.len() - 1) as u32
|
||||
}
|
||||
|
||||
fn remove(&mut self, row: u32, dirs: &mut HashMap<Box<str>, (PathBuf, u32, u32)>) {
|
||||
let idx = row as usize;
|
||||
let last = self.rows.len() - 1;
|
||||
self.dead += self.rows[idx].rel.len as usize;
|
||||
self.rows.swap_remove(idx);
|
||||
if idx != last {
|
||||
let moved = self.rows[idx].rel.get(&self.text);
|
||||
if let Some(dir) = dirs.get_mut(moved) {
|
||||
dir.2 = idx as u32;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn compact(&mut self) {
|
||||
let mut text = String::with_capacity(self.text.len() - self.dead);
|
||||
for row in &mut self.rows {
|
||||
let rel = row.rel.get(&self.text);
|
||||
row.rel = Span::of(&text, rel);
|
||||
text.push_str(rel);
|
||||
}
|
||||
self.text = text;
|
||||
self.dead = 0;
|
||||
}
|
||||
|
||||
fn shrink(&mut self) {
|
||||
self.compact();
|
||||
self.rows.shrink_to_fit();
|
||||
self.text.shrink_to_fit();
|
||||
}
|
||||
}
|
||||
|
||||
/// The scan-relevant fields of one symbol: its character mask and the name in the
|
||||
/// arena. Interleaved so a scan touches one cache line per candidate instead of three
|
||||
/// parallel arrays.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct SymHead {
|
||||
pub mask: u64,
|
||||
pub name: Span,
|
||||
}
|
||||
|
||||
/// Index-wide symbol storage: one row per symbol in parallel arrays, with names and
|
||||
/// containers interned in a single arena. Each file points at a contiguous range.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct SymTable {
|
||||
head: Vec<SymHead>,
|
||||
container: Vec<Span>,
|
||||
kind: Vec<SymbolKind>,
|
||||
range: Vec<Range>,
|
||||
text: String,
|
||||
dead_rows: usize,
|
||||
}
|
||||
|
||||
impl SymTable {
|
||||
#[inline]
|
||||
pub(crate) fn name(&self, i: u32) -> &str {
|
||||
self.head[i as usize].name.get(&self.text)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn mask(&self, i: u32) -> u64 {
|
||||
self.head[i as usize].mask
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn container(&self, i: u32) -> Option<&str> {
|
||||
let span = self.container[i as usize];
|
||||
(span.start != u32::MAX).then(|| span.get(&self.text))
|
||||
}
|
||||
|
||||
/// The mask + name rows of a file's contiguous symbol range.
|
||||
#[inline]
|
||||
pub(crate) fn heads(&self, start: u32, len: u32) -> &[SymHead] {
|
||||
let (start, end) = (start as usize, start as usize + len as usize);
|
||||
&self.head[start..end]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn kind(&self, i: u32) -> SymbolKind {
|
||||
self.kind[i as usize]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn range(&self, i: u32) -> Range {
|
||||
self.range[i as usize]
|
||||
}
|
||||
|
||||
fn intern(&mut self, s: &str) -> Span {
|
||||
let span = Span::of(&self.text, s);
|
||||
self.text.push_str(s);
|
||||
span
|
||||
}
|
||||
|
||||
/// Appends a file's symbols; they stay contiguous. Returns the start index
|
||||
/// and the union of their masks.
|
||||
fn push(&mut self, symbols: &[StoredSymbol]) -> (u32, u64) {
|
||||
let start = self.head.len() as u32;
|
||||
let mut agg_mask = 0u64;
|
||||
for s in symbols {
|
||||
let mask = char_mask(&s.name);
|
||||
agg_mask |= mask;
|
||||
let name = self.intern(&s.name);
|
||||
let container = match &s.container {
|
||||
Some(c) => self.intern(c),
|
||||
None => Span::NONE,
|
||||
};
|
||||
self.head.push(SymHead { mask, name });
|
||||
self.container.push(container);
|
||||
self.kind.push(s.kind);
|
||||
self.range.push(s.range);
|
||||
}
|
||||
(start, agg_mask)
|
||||
}
|
||||
|
||||
/// Whether `symbols` would flatten to exactly the range at `start`.
|
||||
fn same(&self, start: u32, len: u32, symbols: &[StoredSymbol]) -> bool {
|
||||
len as usize == symbols.len()
|
||||
&& symbols.iter().enumerate().all(|(k, s)| {
|
||||
let i = start + k as u32;
|
||||
self.name(i) == s.name
|
||||
&& self.container(i) == s.container.as_deref()
|
||||
&& self.kind(i) == s.kind
|
||||
&& self.range(i) == s.range
|
||||
})
|
||||
}
|
||||
|
||||
fn free(&mut self, _start: u32, len: u32) {
|
||||
self.dead_rows += len as usize;
|
||||
}
|
||||
|
||||
/// Rewrites the live rows in file order, reclaiming the space of replaced files.
|
||||
/// `files` entries keep their range in sync; queries read rows, but persistence
|
||||
/// and `FileEntry` accessors go through the entry.
|
||||
fn compact(&mut self, rows: &mut [FileRow], files: &mut [Option<FileEntry>]) {
|
||||
let mut text = String::with_capacity(self.text.len());
|
||||
let mut head = Vec::with_capacity(self.head.len() - self.dead_rows);
|
||||
let mut container = Vec::with_capacity(head.capacity());
|
||||
let mut kind = Vec::with_capacity(head.capacity());
|
||||
let mut range = Vec::with_capacity(head.capacity());
|
||||
let mut live = 0u32;
|
||||
for (slot, row) in rows.iter_mut().enumerate() {
|
||||
if !row.live {
|
||||
row.sym_start = 0;
|
||||
continue;
|
||||
}
|
||||
let (start, end) = (row.sym_start, row.sym_start + row.sym_len);
|
||||
row.sym_start = live;
|
||||
if let Some(e) = files.get_mut(slot).and_then(Option::as_mut) {
|
||||
e.sym_start = live;
|
||||
}
|
||||
for i in start..end {
|
||||
let name_span = self.head[i as usize].name;
|
||||
let name = name_span.get(&self.text);
|
||||
head.push(SymHead { mask: self.head[i as usize].mask, name: Span::of(&text, name) });
|
||||
text.push_str(name);
|
||||
let container_span = self.container[i as usize];
|
||||
if container_span.start == u32::MAX {
|
||||
container.push(Span::NONE);
|
||||
} else {
|
||||
let c = container_span.get(&self.text);
|
||||
container.push(Span::of(&text, c));
|
||||
text.push_str(c);
|
||||
}
|
||||
kind.push(self.kind[i as usize]);
|
||||
range.push(self.range[i as usize]);
|
||||
live += 1;
|
||||
}
|
||||
}
|
||||
self.head = head;
|
||||
self.container = container;
|
||||
self.kind = kind;
|
||||
self.range = range;
|
||||
self.text = text;
|
||||
self.dead_rows = 0;
|
||||
}
|
||||
|
||||
fn shrink(&mut self) {
|
||||
self.head.shrink_to_fit();
|
||||
self.container.shrink_to_fit();
|
||||
self.kind.shrink_to_fit();
|
||||
self.range.shrink_to_fit();
|
||||
self.text.shrink_to_fit();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct IndexData {
|
||||
pub files: Vec<Option<FileEntry>>,
|
||||
by_path: HashMap<PathBuf, u32>,
|
||||
/// Every folder holding an indexed file at any depth, keyed by its `rel` with a
|
||||
/// trailing `/`: its absolute path, the number of files below it, and its row in
|
||||
/// [`HotDirs`].
|
||||
pub dirs: HashMap<Box<str>, (PathBuf, u32, u32)>,
|
||||
/// Compact query-time view of `files`, kept in sync by `insert`/`remove`.
|
||||
pub hot: HotFiles,
|
||||
/// Compact query-time view of `dirs`, kept in sync by `insert`/`remove`.
|
||||
pub dirs_hot: HotDirs,
|
||||
/// Flattened symbols of every file, kept in sync by `insert`/`remove`.
|
||||
pub syms: SymTable,
|
||||
/// trailing `/`: its absolute path and the number of files below it.
|
||||
pub dirs: HashMap<Box<str>, (PathBuf, u32)>,
|
||||
free: Vec<u32>,
|
||||
pub file_count: u32,
|
||||
pub symbol_count: u32,
|
||||
@@ -553,124 +161,49 @@ impl IndexData {
|
||||
self.by_path.get(path).copied()
|
||||
}
|
||||
|
||||
/// The persisted form of a file, rebuilt from [`IndexData::syms`].
|
||||
pub(crate) fn record(&self, e: &FileEntry) -> FileRecord {
|
||||
FileRecord {
|
||||
mtime: e.mtime,
|
||||
size: e.size,
|
||||
hash: e.hash,
|
||||
symbols: self
|
||||
.symbols_of(e)
|
||||
.map(|s| StoredSymbol {
|
||||
name: s.name.to_owned(),
|
||||
kind: s.kind,
|
||||
container: s.container.map(str::to_owned),
|
||||
range: s.range,
|
||||
})
|
||||
.collect(),
|
||||
ignored: e.ignored,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn record_of(&self, path: &Path) -> Option<FileRecord> {
|
||||
self.get(path).map(|e| self.record(e))
|
||||
}
|
||||
|
||||
/// The symbols of one file, in declaration order.
|
||||
pub(crate) fn symbols_of<'a>(&'a self, e: &'a FileEntry) -> impl Iterator<Item = SymRef<'a>> + 'a {
|
||||
let syms = &self.syms;
|
||||
(e.sym_start..e.sym_start + e.sym_len).map(move |i| SymRef {
|
||||
name: syms.name(i),
|
||||
kind: syms.kind(i),
|
||||
container: syms.container(i),
|
||||
range: syms.range(i),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn insert(&mut self, mut entry: FileEntry, symbols: Vec<StoredSymbol>) {
|
||||
let sym_len = symbols.len() as u32;
|
||||
pub(crate) fn insert(&mut self, entry: FileEntry) {
|
||||
let symbols = entry.symbols.len() as u32;
|
||||
if let Some(&slot) = self.by_path.get(&entry.path) {
|
||||
let old = self.files[slot as usize].as_ref().expect("indexed slots are live");
|
||||
let old_len = old.sym_len;
|
||||
// Rescans and saves that re-parse to the same symbols reuse the range; a
|
||||
// same-path replacement then costs nothing in the symbol table.
|
||||
let (sym_start, sym_mask) = if self.syms.same(old.sym_start, old_len, &symbols) {
|
||||
(old.sym_start, self.hot.rows[slot as usize].sym_mask)
|
||||
} else {
|
||||
self.syms.free(old.sym_start, old_len);
|
||||
self.syms.push(&symbols)
|
||||
};
|
||||
entry.sym_start = sym_start;
|
||||
entry.sym_len = sym_len;
|
||||
self.symbol_count = self.symbol_count - old_len + sym_len;
|
||||
self.hot.update(slot, &entry, sym_mask);
|
||||
self.files[slot as usize] = Some(entry);
|
||||
self.compact_if_needed();
|
||||
let old = self.files[slot as usize].replace(entry);
|
||||
self.symbol_count -= old.map_or(0, |o| o.symbols.len() as u32);
|
||||
self.symbol_count += symbols;
|
||||
return;
|
||||
}
|
||||
let (sym_start, sym_mask) = self.syms.push(&symbols);
|
||||
entry.sym_start = sym_start;
|
||||
entry.sym_len = sym_len;
|
||||
let slot = match self.free.pop() {
|
||||
Some(slot) => slot,
|
||||
Some(slot) => {
|
||||
self.files[slot as usize] = Some(entry);
|
||||
slot
|
||||
}
|
||||
None => {
|
||||
self.files.push(None);
|
||||
self.files.push(Some(entry));
|
||||
(self.files.len() - 1) as u32
|
||||
}
|
||||
};
|
||||
let path = entry.path.clone();
|
||||
let (name_start, name_mask, rel_mask) = (entry.name_start, entry.name_mask, entry.rel_mask);
|
||||
let rel = self.hot.append(&entry.rel);
|
||||
self.hot.set(
|
||||
slot,
|
||||
FileRow {
|
||||
rel,
|
||||
name_start,
|
||||
sym_start: entry.sym_start,
|
||||
sym_len,
|
||||
sym_mask,
|
||||
rel_mask,
|
||||
name_mask,
|
||||
dir_mask: char_mask(&entry.rel[..name_start as usize]),
|
||||
ascii: entry.rel.is_ascii(),
|
||||
live: true,
|
||||
},
|
||||
);
|
||||
self.files[slot as usize] = Some(entry);
|
||||
let path = self.files[slot as usize].as_ref().map(|e| e.path.clone()).unwrap_or_default();
|
||||
if let Some(e) = &self.files[slot as usize] {
|
||||
for (rel, abs) in ancestors(e) {
|
||||
if let Some(dir) = self.dirs.get_mut(rel) {
|
||||
dir.1 += 1;
|
||||
} else {
|
||||
let row = self.dirs_hot.push(rel, abs);
|
||||
self.dirs.insert(rel.into(), (abs.to_owned(), 1, row));
|
||||
}
|
||||
self.dirs.entry(rel.into()).or_insert_with(|| (abs.to_owned(), 0)).1 += 1;
|
||||
}
|
||||
}
|
||||
self.by_path.insert(path, slot);
|
||||
self.file_count += 1;
|
||||
self.symbol_count += sym_len;
|
||||
self.compact_if_needed();
|
||||
self.symbol_count += symbols;
|
||||
}
|
||||
|
||||
pub(crate) fn remove(&mut self, path: &Path) -> Option<FileEntry> {
|
||||
let slot = self.by_path.remove(path)?;
|
||||
let old = self.files[slot as usize].take()?;
|
||||
self.free.push(slot);
|
||||
self.hot.remove(slot);
|
||||
self.syms.free(old.sym_start, old.sym_len);
|
||||
for (rel, _) in ancestors(&old) {
|
||||
let Some(dir) = self.dirs.get_mut(rel) else { continue };
|
||||
dir.1 -= 1;
|
||||
if dir.1 > 0 {
|
||||
continue;
|
||||
if let Some(d) = self.dirs.get_mut(rel) {
|
||||
d.1 -= 1;
|
||||
if d.1 == 0 {
|
||||
self.dirs.remove(rel);
|
||||
}
|
||||
}
|
||||
let Some((_, _, row)) = self.dirs.remove(rel) else { continue };
|
||||
self.dirs_hot.remove(row, &mut self.dirs);
|
||||
}
|
||||
self.file_count -= 1;
|
||||
self.symbol_count -= old.sym_len;
|
||||
self.compact_if_needed();
|
||||
self.symbol_count -= old.symbols.len() as u32;
|
||||
Some(old)
|
||||
}
|
||||
|
||||
@@ -680,19 +213,6 @@ impl IndexData {
|
||||
doomed.into_iter().filter(|p| self.remove(p).is_some()).collect()
|
||||
}
|
||||
|
||||
/// Reclaims the space of replaced/removed files once it dominates a table.
|
||||
fn compact_if_needed(&mut self) {
|
||||
if self.hot.dead_text > 1 << 16 && self.hot.dead_text * 2 > self.hot.text.len() {
|
||||
self.hot.compact();
|
||||
}
|
||||
if self.syms.dead_rows > 4096 && self.syms.dead_rows * 2 > self.syms.head.len() {
|
||||
self.syms.compact(&mut self.hot.rows, &mut self.files);
|
||||
}
|
||||
if self.dirs_hot.dead > 1 << 16 && self.dirs_hot.dead * 2 > self.dirs_hot.text.len() {
|
||||
self.dirs_hot.compact();
|
||||
}
|
||||
}
|
||||
|
||||
/// Releases spare capacity (after large deletions).
|
||||
pub(crate) fn shrink(&mut self) {
|
||||
while matches!(self.files.last(), Some(None)) {
|
||||
@@ -701,11 +221,6 @@ impl IndexData {
|
||||
self.free.retain(|&s| s != last);
|
||||
}
|
||||
self.files.shrink_to_fit();
|
||||
self.hot.rows.truncate(self.files.len());
|
||||
self.hot.shrink();
|
||||
self.dirs_hot.shrink();
|
||||
self.syms.compact(&mut self.hot.rows, &mut self.files);
|
||||
self.syms.shrink();
|
||||
self.free.shrink_to_fit();
|
||||
self.by_path.shrink_to_fit();
|
||||
self.dirs.shrink_to_fit();
|
||||
@@ -733,7 +248,7 @@ fn ancestors(e: &FileEntry) -> impl Iterator<Item = (&str, &Path)> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn entry(path: &str, symbols: usize) -> (FileEntry, Vec<StoredSymbol>) {
|
||||
fn entry(path: &str, symbols: usize) -> FileEntry {
|
||||
let record = FileRecord {
|
||||
symbols: (0..symbols)
|
||||
.map(|i| StoredSymbol {
|
||||
@@ -748,101 +263,48 @@ mod tests {
|
||||
FileEntry::new(PathBuf::from("/r").join(path), path.to_owned(), record)
|
||||
}
|
||||
|
||||
fn insert(d: &mut IndexData, path: &str, symbols: usize) {
|
||||
let (e, s) = entry(path, symbols);
|
||||
d.insert(e, s);
|
||||
}
|
||||
|
||||
/// The compact tables must always mirror the entries they were derived from.
|
||||
fn assert_consistent(d: &IndexData) {
|
||||
assert_eq!(d.hot.rows.len(), d.files.len(), "one hot row per slot");
|
||||
assert_eq!(d.hot.rows.iter().filter(|r| r.live).count(), d.file_count as usize, "live rows are files");
|
||||
for (slot, e) in d.files.iter().enumerate() {
|
||||
let Some(e) = e else {
|
||||
assert!(d.hot.row(slot).is_none(), "free slot {slot} has no row");
|
||||
continue;
|
||||
};
|
||||
let row = d.hot.row(slot).unwrap_or_else(|| panic!("slot {slot} has a row"));
|
||||
assert_eq!(row.rel(d.hot.text()), &*e.rel);
|
||||
assert_eq!(row.name(d.hot.text()), e.name());
|
||||
assert_eq!(row.dir(d.hot.text()), e.dir());
|
||||
assert_eq!(row.name_mask, char_mask(e.name()));
|
||||
assert_eq!(row.rel_mask, char_mask(&e.rel));
|
||||
assert_eq!(row.dir_mask, char_mask(e.dir()));
|
||||
assert_eq!(row.ascii, e.rel.is_ascii());
|
||||
assert_eq!(row.sym_start, e.sym_start);
|
||||
assert_eq!(row.sym_len, e.sym_len);
|
||||
assert_eq!(row.sym_mask, d.symbols_of(e).fold(0u64, |m, s| m | char_mask(s.name)));
|
||||
assert_eq!(d.syms.head.len(), d.syms.container.len());
|
||||
assert_eq!(d.syms.head.len(), d.syms.kind.len());
|
||||
assert_eq!(d.syms.head.len(), d.syms.range.len());
|
||||
assert!(e.sym_len == 0 || (e.sym_start as usize) < d.syms.head.len());
|
||||
assert!(e.sym_start + e.sym_len <= d.syms.head.len() as u32);
|
||||
}
|
||||
for (rel, (path, count, row)) in &d.dirs {
|
||||
let row = &d.dirs_hot.rows[*row as usize];
|
||||
assert_eq!(row.rel(d.dirs_hot.text()), &**rel);
|
||||
assert_eq!(&row.path, path);
|
||||
assert!(*count > 0);
|
||||
let trimmed = &rel[..rel.len() - 1];
|
||||
let name = &trimmed[row.name_start as usize..];
|
||||
assert_eq!(row.name_mask, char_mask(name));
|
||||
assert_eq!(row.rel_mask, char_mask(trimmed));
|
||||
}
|
||||
assert_eq!(d.dirs.len(), d.dirs_hot.rows.len());
|
||||
assert_eq!(d.symbol_count, d.files.iter().flatten().map(|e| e.sym_len).sum::<u32>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dirs_follow_inserts_and_removals() {
|
||||
let mut d = IndexData::default();
|
||||
insert(&mut d, "a/b/c.rs", 0);
|
||||
insert(&mut d, "a/d.rs", 0);
|
||||
insert(&mut d, "a/d.rs", 0);
|
||||
insert(&mut d, "top.rs", 0);
|
||||
d.insert(entry("a/b/c.rs", 0));
|
||||
d.insert(entry("a/d.rs", 0));
|
||||
d.insert(entry("a/d.rs", 0));
|
||||
d.insert(entry("top.rs", 0));
|
||||
let mut dirs: Vec<_> = d.dirs.iter().map(|(k, v)| (k.to_string(), v.1)).collect();
|
||||
dirs.sort();
|
||||
assert_eq!(dirs, [("a/".into(), 2), ("a/b/".into(), 1)]);
|
||||
assert_eq!(d.dirs["a/b/"].0, PathBuf::from("/r/a/b"));
|
||||
assert_consistent(&d);
|
||||
d.remove(Path::new("/r/a/b/c.rs"));
|
||||
assert!(!d.dirs.contains_key("a/b/"));
|
||||
assert_consistent(&d);
|
||||
d.remove_tree(Path::new("/r/a"));
|
||||
assert!(d.dirs.is_empty());
|
||||
assert_consistent(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_replace_remove_keep_counts() {
|
||||
let mut d = IndexData::default();
|
||||
insert(&mut d, "a/b.rs", 2);
|
||||
insert(&mut d, "c.rs", 1);
|
||||
d.insert(entry("a/b.rs", 2));
|
||||
d.insert(entry("c.rs", 1));
|
||||
assert_eq!((d.file_count, d.symbol_count), (2, 3));
|
||||
insert(&mut d, "a/b.rs", 5);
|
||||
d.insert(entry("a/b.rs", 5));
|
||||
assert_eq!((d.file_count, d.symbol_count), (2, 6));
|
||||
assert_consistent(&d);
|
||||
assert!(d.remove(Path::new("/r/c.rs")).is_some());
|
||||
assert_eq!((d.file_count, d.symbol_count), (1, 5));
|
||||
assert_consistent(&d);
|
||||
insert(&mut d, "d.rs", 0);
|
||||
d.insert(entry("d.rs", 0));
|
||||
assert_eq!(d.files.len(), 2, "slot reused");
|
||||
assert_consistent(&d);
|
||||
assert_eq!(d.remove_tree(Path::new("/r/a")), vec![PathBuf::from("/r/a/b.rs")]);
|
||||
assert_eq!((d.file_count, d.symbol_count), (1, 0));
|
||||
let e = d.get(Path::new("/r/d.rs")).unwrap();
|
||||
assert_eq!((e.name(), e.dir()), ("d.rs", ""));
|
||||
insert(&mut d, "e.rs", 1);
|
||||
insert(&mut d, "f.rs", 1);
|
||||
d.insert(entry("e.rs", 1));
|
||||
d.insert(entry("f.rs", 1));
|
||||
d.remove(Path::new("/r/e.rs"));
|
||||
d.remove(Path::new("/r/f.rs"));
|
||||
d.shrink();
|
||||
assert_consistent(&d);
|
||||
assert_eq!(d.files.len(), 2, "trailing free slot dropped");
|
||||
assert_eq!(d.free, vec![0]);
|
||||
insert(&mut d, "g.rs", 1);
|
||||
d.insert(entry("g.rs", 1));
|
||||
assert_eq!((d.file_count, d.files.len()), (2, 2));
|
||||
assert_consistent(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -850,65 +312,4 @@ mod tests {
|
||||
assert_eq!(char_mask("ab") & char_mask("Bad"), char_mask("ab"));
|
||||
assert_ne!(char_mask("z") & char_mask("abc"), char_mask("z"));
|
||||
}
|
||||
|
||||
fn insert_symbols(d: &mut IndexData, path: &str, symbols: Vec<StoredSymbol>) {
|
||||
let record = FileRecord { symbols, ..Default::default() };
|
||||
let (e, s) = FileEntry::new(PathBuf::from("/r").join(path), path.to_owned(), record);
|
||||
d.insert(e, s);
|
||||
}
|
||||
|
||||
fn symbol(n: &str) -> StoredSymbol {
|
||||
StoredSymbol { name: n.to_owned(), kind: SymbolKind::Function, container: None, range: Range::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compaction_keeps_entries_and_records_in_sync() {
|
||||
let mut d = IndexData::default();
|
||||
insert(&mut d, "a.rs", 3);
|
||||
insert(&mut d, "b/c.rs", 2);
|
||||
insert_symbols(&mut d, "a.rs", vec![symbol("fresh")]);
|
||||
d.shrink();
|
||||
assert_consistent(&d);
|
||||
assert_eq!(d.syms.head.len() as u32, d.symbol_count, "compaction drops dead symbol rows");
|
||||
let names = |d: &IndexData, p: &str| -> Vec<String> {
|
||||
let e = d.get(Path::new(p)).unwrap();
|
||||
d.record(e).symbols.into_iter().map(|s| s.name).collect()
|
||||
};
|
||||
assert_eq!(names(&d, "/r/a.rs"), ["fresh"]);
|
||||
assert_eq!(names(&d, "/r/b/c.rs"), ["s0", "s1"]);
|
||||
assert_eq!(d.symbol_count, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_replacements_reclaim_symbol_storage() {
|
||||
let mut d = IndexData::default();
|
||||
insert_symbols(&mut d, "a.rs", (0..5_000).map(|i| symbol(&format!("old{i}"))).collect());
|
||||
assert_eq!(d.syms.head.len(), 5_000);
|
||||
insert_symbols(&mut d, "a.rs", vec![symbol("fresh")]);
|
||||
assert_eq!(d.syms.head.len(), 1, "dead symbol rows are reclaimed");
|
||||
assert_eq!((d.symbol_count, d.file_count), (1, 1));
|
||||
assert_consistent(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tree_removal_leaves_no_hot_rows_or_dirs() {
|
||||
let mut d = IndexData::default();
|
||||
insert(&mut d, "a/b/one.rs", 2);
|
||||
insert(&mut d, "a/b/two.rs", 3);
|
||||
insert(&mut d, "a/three.rs", 1);
|
||||
insert(&mut d, "elsewhere/four.rs", 1);
|
||||
assert_eq!(d.remove_tree(Path::new("/r/a")).len(), 3);
|
||||
assert_consistent(&d);
|
||||
assert_eq!(d.hot.rows.iter().filter(|r| r.live).count(), 1);
|
||||
assert!(d.hot.row(0).is_none(), "removed slots have no live row");
|
||||
assert_eq!(d.dirs.len(), 1, "elsewhere/ only");
|
||||
assert_eq!(d.dirs_hot.rows.len(), 1);
|
||||
assert_eq!(d.symbol_count, 1);
|
||||
d.shrink();
|
||||
assert_eq!(d.syms.head.len() as u32, d.symbol_count);
|
||||
// Slots are reusable and the new row replaces the tombstone.
|
||||
insert(&mut d, "a/five.rs", 2);
|
||||
assert_consistent(&d);
|
||||
assert_eq!(d.file_count, 2);
|
||||
}
|
||||
}
|
||||
@@ -199,11 +199,12 @@ impl ProjectIndex {
|
||||
return None;
|
||||
}
|
||||
Some(
|
||||
data.symbols_of(file)
|
||||
file.symbols
|
||||
.iter()
|
||||
.map(|s| ide_language::SymbolTag {
|
||||
name: s.name.to_string(),
|
||||
kind: s.kind,
|
||||
container: s.container.map(ToString::to_string),
|
||||
container: s.container.as_ref().map(ToString::to_string),
|
||||
range: s.range,
|
||||
})
|
||||
.collect(),
|
||||
@@ -230,7 +231,7 @@ impl ProjectIndex {
|
||||
pub fn find_files(&self, query: &str, limit: usize) -> Vec<FileMatch> {
|
||||
let recent = self.shared.recent.lock().clone();
|
||||
let d = self.shared.data.read();
|
||||
matching::find_files(&d, &matching::Recents::new(&recent), query, limit)
|
||||
matching::find_files(&d, &matching::Recents { paths: &recent }, query, limit)
|
||||
}
|
||||
|
||||
/// All indexed files with this exact basename, for resolving printed source locations.
|
||||
@@ -273,7 +274,7 @@ impl ProjectIndex {
|
||||
pub fn find_symbols(&self, query: &str, filter: SymbolFilter, limit: usize) -> Vec<SymbolMatch> {
|
||||
let recent = self.shared.recent.lock().clone();
|
||||
let d = self.shared.data.read();
|
||||
matching::find_symbols(&d, &matching::Recents::new(&recent), query, filter, limit)
|
||||
matching::find_symbols(&d, &matching::Recents { paths: &recent }, query, filter, limit)
|
||||
}
|
||||
|
||||
/// Scoped symbol search with cooperative interruption, including lock waits.
|
||||
@@ -302,7 +303,15 @@ impl ProjectIndex {
|
||||
break data;
|
||||
}
|
||||
};
|
||||
matching::find_symbols_until(&data, &matching::Recents::new(&recent), query, filter, limit, include, stopped)
|
||||
matching::find_symbols_until(
|
||||
&data,
|
||||
&matching::Recents { paths: &recent },
|
||||
query,
|
||||
filter,
|
||||
limit,
|
||||
include,
|
||||
stopped,
|
||||
)
|
||||
}
|
||||
|
||||
/// Symbols named exactly `name` (of `kind`, if given): `.card` selectors for `class="card"`.
|
||||
@@ -514,8 +523,7 @@ pub mod bench_support {
|
||||
})
|
||||
.collect();
|
||||
let record = FileRecord { symbols, ..Default::default() };
|
||||
let (entry, symbols) = FileEntry::new(PathBuf::from("/bench").join(&rel), rel, record);
|
||||
data.insert(entry, symbols);
|
||||
data.insert(FileEntry::new(PathBuf::from("/bench").join(&rel), rel, record));
|
||||
}
|
||||
let recent = data.paths().take(MAX_RECENT).cloned().collect();
|
||||
Self { data, recent }
|
||||
@@ -530,7 +538,7 @@ pub mod bench_support {
|
||||
}
|
||||
|
||||
pub fn find_files(&self, query: &str, limit: usize) -> Vec<FileMatch> {
|
||||
matching::find_files(&self.data, &matching::Recents::new(&self.recent), query, limit)
|
||||
matching::find_files(&self.data, &matching::Recents { paths: &self.recent }, query, limit)
|
||||
}
|
||||
|
||||
pub fn find_dirs(&self, query: &str, limit: usize) -> Vec<FileMatch> {
|
||||
@@ -538,7 +546,7 @@ pub mod bench_support {
|
||||
}
|
||||
|
||||
pub fn find_symbols(&self, query: &str, filter: SymbolFilter, limit: usize) -> Vec<SymbolMatch> {
|
||||
matching::find_symbols(&self.data, &matching::Recents::new(&self.recent), query, filter, limit)
|
||||
matching::find_symbols(&self.data, &matching::Recents { paths: &self.recent }, query, filter, limit)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,19 +4,14 @@
|
||||
//! (bit-mask pre-filter, nucleo score, exact/prefix boosts) and keeps the best
|
||||
//! few; the survivors then get match indices, CamelHump and recency boosts and
|
||||
//! are re-sorted.
|
||||
//!
|
||||
//! The scan streams the compact tables in `data` (`HotFiles`/`HotDirs`/`SymTable`):
|
||||
//! only the hot fields per candidate and strings from contiguous arenas, with the
|
||||
//! thread-local matcher and one UTF-32 buffer per scan rather than per candidate.
|
||||
|
||||
use crate::data::{DirRow, FileEntry, FileRow, IndexData, SymTable, char_mask};
|
||||
use crate::data::{FileEntry, IndexData, char_mask};
|
||||
use crate::{FileMatch, SymbolFilter, SymbolMatch};
|
||||
use ide_core::SymbolKind;
|
||||
use nucleo_matcher::{Config, Matcher, Utf32Str, Utf32String};
|
||||
use rayon::prelude::*;
|
||||
use std::cell::RefCell;
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const TIER_NAME: u32 = 1 << 20;
|
||||
@@ -59,11 +54,6 @@ impl Needle {
|
||||
m.fuzzy_match(Utf32Str::new(hay, buf), self.utf32.slice(..)).map(u32::from)
|
||||
}
|
||||
|
||||
/// `hay` is pure ASCII: skip `Utf32Str::new`'s check and UTF-32 conversion.
|
||||
fn score_ascii(&self, m: &mut Matcher, hay: &str) -> Option<u32> {
|
||||
m.fuzzy_match(Utf32Str::Ascii(hay.as_bytes()), self.utf32.slice(..)).map(u32::from)
|
||||
}
|
||||
|
||||
fn indices(&self, m: &mut Matcher, hay: &str, buf: &mut Vec<char>, out: &mut Vec<u32>) -> Option<u32> {
|
||||
out.clear();
|
||||
let s = m.fuzzy_indices(Utf32Str::new(hay, buf), self.utf32.slice(..), out).map(u32::from);
|
||||
@@ -115,9 +105,6 @@ struct Cand {
|
||||
slot: u32,
|
||||
sym: u32,
|
||||
score: u32,
|
||||
/// Candidate name/rel length: the first tie-break key, cached so ranking a pool
|
||||
/// does not chase it through the tables.
|
||||
len: u32,
|
||||
}
|
||||
|
||||
fn keep_best(mut v: Vec<Cand>, k: usize, tiebreak: &impl Fn(&Cand, &Cand) -> Ordering) -> Vec<Cand> {
|
||||
@@ -132,7 +119,7 @@ fn scan(
|
||||
data: &IndexData,
|
||||
pool: usize,
|
||||
tiebreak: &(impl Fn(&Cand, &Cand) -> Ordering + Sync),
|
||||
per_file: impl Fn(u32, &FileRow, &mut Matcher, &mut Vec<Cand>) + Sync,
|
||||
per_file: impl Fn(u32, &FileEntry, &mut Vec<Cand>) + Sync,
|
||||
) -> Vec<Cand> {
|
||||
scan_until(data, pool, tiebreak, &|| false, per_file).unwrap_or_default()
|
||||
}
|
||||
@@ -142,22 +129,18 @@ fn scan_until(
|
||||
pool: usize,
|
||||
tiebreak: &(impl Fn(&Cand, &Cand) -> Ordering + Sync),
|
||||
stopped: &(impl Fn() -> bool + Sync),
|
||||
per_file: impl Fn(u32, &FileRow, &mut Matcher, &mut Vec<Cand>) + Sync,
|
||||
per_file: impl Fn(u32, &FileEntry, &mut Vec<Cand>) + Sync,
|
||||
) -> Option<Vec<Cand>> {
|
||||
// One row per slot, so this is exactly the old scan over `files`: same item
|
||||
// order and count, and free slots are skipped exactly like `None` was, keeping
|
||||
// the pruning boundaries (and therefore the candidate pool) unchanged.
|
||||
data.hot
|
||||
.rows
|
||||
data.files
|
||||
.par_iter()
|
||||
.enumerate()
|
||||
.with_min_len(256)
|
||||
.try_fold(Vec::new, |mut acc, (slot, row)| {
|
||||
.try_fold(Vec::new, |mut acc, (slot, e)| {
|
||||
if stopped() {
|
||||
return None;
|
||||
}
|
||||
if row.live {
|
||||
with_matcher(|m| per_file(slot as u32, row, m, &mut acc));
|
||||
if let Some(e) = e {
|
||||
per_file(slot as u32, e, &mut acc);
|
||||
if acc.len() >= pool * 2 {
|
||||
acc = keep_best(acc, pool, tiebreak);
|
||||
}
|
||||
@@ -172,22 +155,15 @@ fn scan_until(
|
||||
|
||||
pub(crate) struct Recents<'a> {
|
||||
pub paths: &'a [PathBuf],
|
||||
/// Position of each path, so ranking a survivor does not scan the list.
|
||||
/// Duplicates keep their first position, like `position`.
|
||||
ranks: HashMap<&'a Path, usize>,
|
||||
}
|
||||
|
||||
impl<'a> Recents<'a> {
|
||||
pub(crate) fn new(paths: &'a [PathBuf]) -> Self {
|
||||
let mut ranks = HashMap::with_capacity(paths.len());
|
||||
for (i, p) in paths.iter().enumerate() {
|
||||
ranks.entry(p.as_path()).or_insert(i);
|
||||
}
|
||||
Self { paths, ranks }
|
||||
impl Recents<'_> {
|
||||
fn rank(&self, path: &std::path::Path) -> Option<usize> {
|
||||
self.paths.iter().position(|p| p == path)
|
||||
}
|
||||
|
||||
fn bonus(&self, path: &Path) -> u32 {
|
||||
self.ranks.get(path).map_or(0, |&r| RECENT_MAX.saturating_sub(r as u32 * 12))
|
||||
fn bonus(&self, path: &std::path::Path) -> u32 {
|
||||
self.rank(path).map_or(0, |r| RECENT_MAX.saturating_sub(r as u32 * 12))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -233,31 +209,29 @@ pub(crate) fn find_files(data: &IndexData, recents: &Recents, query: &str, limit
|
||||
Some((dir, name)) => FileQuery::Path { dir: Needle::new(dir), name: Needle::new(name) },
|
||||
None => FileQuery::Name(Needle::new(&q)),
|
||||
};
|
||||
let tiebreak = |a: &Cand, b: &Cand| a.len.cmp(&b.len).then_with(|| data.hot.rel(a.slot).cmp(data.hot.rel(b.slot)));
|
||||
let tiebreak = |a: &Cand, b: &Cand| {
|
||||
let (ea, eb) = (file(data, a.slot), file(data, b.slot));
|
||||
ea.rel.len().cmp(&eb.rel.len()).then_with(|| ea.rel.cmp(&eb.rel))
|
||||
};
|
||||
let pool = limit * 4 + 64;
|
||||
let mut cands = scan(data, pool, &tiebreak, |slot, row, m, acc| {
|
||||
let mut cands = scan(data, pool, &tiebreak, |slot, e, acc| {
|
||||
let mut buf = Vec::new();
|
||||
if let Some(score) = base_file_score(m, &fq, row, data.hot.text(), &mut buf) {
|
||||
acc.push(Cand { slot, sym: u32::MAX, score, len: row.rel.len });
|
||||
if let Some(score) = with_matcher(|m| base_file_score(m, &fq, e, &mut buf)) {
|
||||
acc.push(Cand { slot, sym: u32::MAX, score });
|
||||
}
|
||||
});
|
||||
// Recent files always compete for the final ranking.
|
||||
with_matcher(|m| {
|
||||
let mut buf = Vec::new();
|
||||
for p in recents.paths {
|
||||
if data.get(p).is_none() {
|
||||
continue;
|
||||
}
|
||||
for p in recents.paths {
|
||||
if let Some(e) = data.get(p) {
|
||||
let Some(slot) = data.slot(p) else { continue };
|
||||
if cands.iter().any(|c| c.slot == slot) {
|
||||
continue;
|
||||
}
|
||||
let Some(row) = data.hot.row_of_slot(slot) else { continue };
|
||||
if let Some(score) = base_file_score(m, &fq, row, data.hot.text(), &mut buf) {
|
||||
cands.push(Cand { slot, sym: u32::MAX, score, len: row.rel.len });
|
||||
if !cands.iter().any(|c| c.slot == slot) {
|
||||
let mut buf = Vec::new();
|
||||
if let Some(score) = with_matcher(|m| base_file_score(m, &fq, e, &mut buf)) {
|
||||
cands.push(Cand { slot, sym: u32::MAX, score });
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
let mut out: Vec<(u32, &FileEntry, Vec<u32>)> = with_matcher(|m| {
|
||||
let mut buf = Vec::new();
|
||||
cands
|
||||
@@ -299,46 +273,30 @@ pub(crate) fn find_dirs(data: &IndexData, query: &str, limit: usize) -> Vec<File
|
||||
}
|
||||
let by_path = q.contains('/');
|
||||
let needle = Needle::new(q.trim_end_matches('/'));
|
||||
let text = data.dirs_hot.text();
|
||||
// (score, rel without the trailing `/`, char offset of the name when it matched by name)
|
||||
let (mut best, _): (Vec<_>, Vec<char>) = data
|
||||
.dirs_hot
|
||||
.rows
|
||||
let score = |m: &mut Matcher, buf: &mut Vec<char>, rel: &str| -> Option<(u32, Option<u32>)> {
|
||||
let trimmed = &rel[..rel.len() - 1];
|
||||
let start = trimmed.rfind('/').map_or(0, |i| i + 1);
|
||||
let name = &trimmed[start..];
|
||||
if !by_path
|
||||
&& needle.mask & char_mask(name) == needle.mask
|
||||
&& let Some(s) = needle.score(m, name, buf)
|
||||
{
|
||||
return Some((TIER_NAME + s * 4 + needle.name_boost(name), Some(trimmed[..start].chars().count() as u32)));
|
||||
}
|
||||
if needle.mask & char_mask(trimmed) != needle.mask {
|
||||
return None;
|
||||
}
|
||||
needle.score(m, trimmed, buf).map(|s| (s, None))
|
||||
};
|
||||
let mut best: Vec<(u32, &str, &Path, Option<u32>)> = data
|
||||
.dirs
|
||||
.par_iter()
|
||||
.fold(
|
||||
|| (Vec::new(), Vec::new()),
|
||||
|(mut found, mut buf), row: &DirRow| {
|
||||
let rel = row.rel(text);
|
||||
let trimmed = &rel[..rel.len() - 1];
|
||||
let name = &trimmed[row.name_start as usize..];
|
||||
with_matcher(|m| {
|
||||
let hit = if !by_path
|
||||
&& needle.mask & row.name_mask == needle.mask
|
||||
&& let Some(s) = needle.score(m, name, &mut buf)
|
||||
{
|
||||
Some((
|
||||
TIER_NAME + s * 4 + needle.name_boost(name),
|
||||
Some(trimmed[..row.name_start as usize].chars().count() as u32),
|
||||
))
|
||||
} else if needle.mask & row.rel_mask != needle.mask {
|
||||
None
|
||||
} else {
|
||||
needle.score(m, trimmed, &mut buf).map(|s| (s, None))
|
||||
};
|
||||
if let Some((s, at)) = hit {
|
||||
found.push((s, rel, row.path.as_path(), at));
|
||||
}
|
||||
});
|
||||
(found, buf)
|
||||
},
|
||||
)
|
||||
.reduce(
|
||||
|| (Vec::new(), Vec::new()),
|
||||
|mut a, b| {
|
||||
a.0.extend(b.0);
|
||||
a
|
||||
},
|
||||
);
|
||||
.filter_map(|(rel, (path, _))| {
|
||||
let mut buf = Vec::new();
|
||||
with_matcher(|m| score(m, &mut buf, rel)).map(|(s, at)| (s, &**rel, path.as_path(), at))
|
||||
})
|
||||
.collect();
|
||||
let order = |a: &(u32, &str, &Path, Option<u32>), b: &(u32, &str, &Path, Option<u32>)| {
|
||||
b.0.cmp(&a.0).then_with(|| a.1.len().cmp(&b.1.len())).then_with(|| a.1.cmp(b.1))
|
||||
};
|
||||
@@ -380,39 +338,33 @@ fn file(data: &IndexData, slot: u32) -> &FileEntry {
|
||||
data.files[slot as usize].as_ref().expect("candidate slots are live")
|
||||
}
|
||||
|
||||
fn base_file_score(m: &mut Matcher, q: &FileQuery, row: &FileRow, text: &str, buf: &mut Vec<char>) -> Option<u32> {
|
||||
// Strings are sliced only once their mask passes, so a rejected row costs two masks.
|
||||
fn base_file_score(m: &mut Matcher, q: &FileQuery, e: &FileEntry, buf: &mut Vec<char>) -> Option<u32> {
|
||||
match q {
|
||||
FileQuery::Name(n) => {
|
||||
if n.mask & row.name_mask == n.mask {
|
||||
let name = row.name(text);
|
||||
let s = if row.ascii { n.score_ascii(m, name) } else { n.score(m, name, buf) };
|
||||
if let Some(s) = s {
|
||||
return Some(TIER_NAME + s * 4 + n.name_boost(name));
|
||||
}
|
||||
if n.mask & e.name_mask == n.mask
|
||||
&& let Some(s) = n.score(m, e.name(), buf)
|
||||
{
|
||||
return Some(TIER_NAME + s * 4 + n.name_boost(e.name()));
|
||||
}
|
||||
if n.mask & row.rel_mask == n.mask {
|
||||
let rel = row.rel(text);
|
||||
return if row.ascii { n.score_ascii(m, rel) } else { n.score(m, rel, buf) };
|
||||
if n.mask & e.rel_mask == n.mask {
|
||||
return n.score(m, &e.rel, buf);
|
||||
}
|
||||
None
|
||||
}
|
||||
FileQuery::Path { dir, name: n } => {
|
||||
let name_score = if n.is_empty() {
|
||||
FileQuery::Path { dir, name } => {
|
||||
let name_score = if name.is_empty() {
|
||||
0
|
||||
} else {
|
||||
if n.mask & row.name_mask != n.mask {
|
||||
if name.mask & e.name_mask != name.mask {
|
||||
return None;
|
||||
}
|
||||
let name = row.name(text);
|
||||
let s = if row.ascii { n.score_ascii(m, name) } else { n.score(m, name, buf) }?;
|
||||
s * 4 + n.name_boost(name)
|
||||
name.score(m, e.name(), buf)? * 4 + name.name_boost(e.name())
|
||||
};
|
||||
if dir.mask & row.dir_mask != dir.mask {
|
||||
let dir_str = e.dir();
|
||||
if dir.mask & char_mask(dir_str) != dir.mask {
|
||||
return None;
|
||||
}
|
||||
let dir_str = row.dir(text);
|
||||
let dir_score = if row.ascii { dir.score_ascii(m, dir_str) } else { dir.score(m, dir_str, buf) }?;
|
||||
let dir_score = dir.score(m, dir_str, buf)?;
|
||||
Some(TIER_NAME + name_score + dir_score)
|
||||
}
|
||||
}
|
||||
@@ -444,21 +396,22 @@ fn symbol_score(
|
||||
m: &mut Matcher,
|
||||
name: &Needle,
|
||||
container: Option<&Needle>,
|
||||
syms: &SymTable,
|
||||
i: u32,
|
||||
s: &crate::data::Sym,
|
||||
buf: &mut Vec<char>,
|
||||
) -> Option<u32> {
|
||||
let symbol = syms.name(i);
|
||||
let mut score = if name.is_empty() { 0 } else { name.score(m, symbol, buf)? * 4 };
|
||||
score += name.name_boost(symbol);
|
||||
if name.mask & s.mask != name.mask {
|
||||
return None;
|
||||
}
|
||||
let mut score = if name.is_empty() { 0 } else { name.score(m, &s.name, buf)? * 4 };
|
||||
score += name.name_boost(&s.name);
|
||||
if let Some(cq) = container {
|
||||
let c = syms.container(i)?;
|
||||
let c = s.container.as_deref()?;
|
||||
if cq.mask & char_mask(c) != cq.mask {
|
||||
return None;
|
||||
}
|
||||
score += cq.score(m, c, buf)? + cq.name_boost(c) / 4;
|
||||
}
|
||||
if syms.kind(i).is_type_like() {
|
||||
if s.kind.is_type_like() {
|
||||
score += TYPE_LIKE;
|
||||
}
|
||||
Some(score)
|
||||
@@ -502,35 +455,30 @@ pub(crate) fn find_symbols_until(
|
||||
let (container_q, name_q) = split_symbol_query(&q);
|
||||
let name = Needle::new(name_q);
|
||||
let container = container_q.map(Needle::new);
|
||||
let syms = &data.syms;
|
||||
let tiebreak = |a: &Cand, b: &Cand| a.len.cmp(&b.len).then_with(|| data.hot.rel(a.slot).cmp(data.hot.rel(b.slot)));
|
||||
let sym = |c: &Cand| &file(data, c.slot).symbols[c.sym as usize];
|
||||
let tiebreak = |a: &Cand, b: &Cand| {
|
||||
let (sa, sb) = (sym(a), sym(b));
|
||||
sa.name.len().cmp(&sb.name.len()).then_with(|| file(data, a.slot).rel.cmp(&file(data, b.slot).rel))
|
||||
};
|
||||
let pool = limit * 4 + 64;
|
||||
let cands = scan_until(data, pool, &tiebreak, stopped, |slot, row, m, acc| {
|
||||
// Whole-file pre-filter: when the union of the file's symbol masks
|
||||
// already misses a query character, no symbol can match.
|
||||
if row.sym_len == 0 || name.mask & row.sym_mask != name.mask {
|
||||
let cands = scan_until(data, pool, &tiebreak, stopped, |slot, e, acc| {
|
||||
if e.symbols.is_empty() || !include(&e.path) {
|
||||
return;
|
||||
}
|
||||
let e = file(data, slot);
|
||||
if !include(&e.path) {
|
||||
return;
|
||||
}
|
||||
let mut buf = Vec::new();
|
||||
for (k, head) in syms.heads(row.sym_start, row.sym_len).iter().enumerate() {
|
||||
if stopped() {
|
||||
break;
|
||||
with_matcher(|m| {
|
||||
let mut buf = Vec::new();
|
||||
for (i, s) in e.symbols.iter().enumerate() {
|
||||
if stopped() {
|
||||
break;
|
||||
}
|
||||
if filter == SymbolFilter::Types && !s.kind.is_type_like() {
|
||||
continue;
|
||||
}
|
||||
if let Some(score) = symbol_score(m, &name, container.as_ref(), s, &mut buf) {
|
||||
acc.push(Cand { slot, sym: i as u32, score });
|
||||
}
|
||||
}
|
||||
if filter == SymbolFilter::Types && !syms.kind(row.sym_start + k as u32).is_type_like() {
|
||||
continue;
|
||||
}
|
||||
if name.mask & head.mask != name.mask {
|
||||
continue;
|
||||
}
|
||||
let i = row.sym_start + k as u32;
|
||||
if let Some(score) = symbol_score(m, &name, container.as_ref(), syms, i, &mut buf) {
|
||||
acc.push(Cand { slot, sym: i, score, len: head.name.len });
|
||||
}
|
||||
}
|
||||
});
|
||||
})?;
|
||||
if stopped() {
|
||||
return None;
|
||||
@@ -541,32 +489,33 @@ pub(crate) fn find_symbols_until(
|
||||
.into_iter()
|
||||
.take_while(|_| !stopped())
|
||||
.filter_map(|c| {
|
||||
let symbol = syms.name(c.sym);
|
||||
let s = sym(&c);
|
||||
let e = file(data, c.slot);
|
||||
let mut idx = Vec::new();
|
||||
if !name.is_empty() {
|
||||
name.indices(m, symbol, &mut buf, &mut idx)?;
|
||||
name.indices(m, &s.name, &mut buf, &mut idx)?;
|
||||
}
|
||||
let bonus = hump_bonus(symbol, &idx) + recents.bonus(&e.path) / 4;
|
||||
let bonus = hump_bonus(&s.name, &idx) + recents.bonus(&e.path) / 4;
|
||||
Some((c.score + bonus, c, idx))
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
out.sort_by(|a, b| {
|
||||
b.0.cmp(&a.0).then_with(|| tiebreak(&a.1, &b.1)).then_with(|| syms.range(a.1.sym).cmp(&syms.range(b.1.sym)))
|
||||
b.0.cmp(&a.0).then_with(|| tiebreak(&a.1, &b.1)).then_with(|| sym(&a.1).range.cmp(&sym(&b.1).range))
|
||||
});
|
||||
out.truncate(limit);
|
||||
let results = out
|
||||
.into_iter()
|
||||
.map(|(score, c, indices)| {
|
||||
let e = file(data, c.slot);
|
||||
let s = &e.symbols[c.sym as usize];
|
||||
SymbolMatch {
|
||||
name: syms.name(c.sym).to_string(),
|
||||
kind: syms.kind(c.sym),
|
||||
container: syms.container(c.sym).map(str::to_owned),
|
||||
name: s.name.to_string(),
|
||||
kind: s.kind,
|
||||
container: s.container.as_deref().map(str::to_owned),
|
||||
path: e.path.clone().into(),
|
||||
rel_path: e.rel.to_string(),
|
||||
range: syms.range(c.sym),
|
||||
range: s.range,
|
||||
score,
|
||||
indices,
|
||||
}
|
||||
@@ -592,25 +541,24 @@ pub(crate) fn symbols_named_within(
|
||||
) -> Vec<SymbolMatch> {
|
||||
let mask = char_mask(name);
|
||||
let within = |e: &FileEntry| roots.is_empty() || roots.iter().any(|root| e.path.starts_with(root));
|
||||
let syms = &data.syms;
|
||||
let mut out: Vec<SymbolMatch> = data
|
||||
.files
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|e| within(e))
|
||||
.flat_map(|e| {
|
||||
(e.sym_start..e.sym_start + e.sym_len)
|
||||
.filter(|&i| syms.mask(i) == mask && syms.name(i) == name && kind.is_none_or(|k| syms.kind(i) == k))
|
||||
.map(move |i| SymbolMatch {
|
||||
name: syms.name(i).to_string(),
|
||||
kind: syms.kind(i),
|
||||
container: syms.container(i).map(str::to_owned),
|
||||
e.symbols.iter().filter(|s| s.mask == mask && &*s.name == name && kind.is_none_or(|k| s.kind == k)).map(
|
||||
move |s| SymbolMatch {
|
||||
name: s.name.to_string(),
|
||||
kind: s.kind,
|
||||
container: s.container.as_deref().map(str::to_owned),
|
||||
path: e.path.clone().into(),
|
||||
rel_path: e.rel.to_string(),
|
||||
range: syms.range(i),
|
||||
range: s.range,
|
||||
score: 0,
|
||||
indices: Vec::new(),
|
||||
})
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
out.sort_by(|a, b| a.rel_path.cmp(&b.rel_path).then_with(|| a.range.cmp(&b.range)));
|
||||
|
||||
@@ -173,7 +173,7 @@ impl Shared {
|
||||
let root = filter.root().to_owned();
|
||||
match store.load() {
|
||||
Ok(records) => {
|
||||
let entries: Vec<(FileEntry, Vec<StoredSymbol>)> = records
|
||||
let entries: Vec<FileEntry> = records
|
||||
.into_par_iter()
|
||||
.filter(|(rel, _)| {
|
||||
let path = root.join(rel);
|
||||
@@ -182,8 +182,8 @@ impl Shared {
|
||||
.map(|(rel, rec)| FileEntry::new(root.join(&rel), rel, rec))
|
||||
.collect();
|
||||
let mut d = self.data.write();
|
||||
for (e, symbols) in entries {
|
||||
d.insert(e, symbols);
|
||||
for e in entries {
|
||||
d.insert(e);
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::warn!("index cache load failed: {e}"),
|
||||
@@ -321,7 +321,8 @@ impl Shared {
|
||||
match self.extract(f, prev_hash) {
|
||||
Extracted::Unchanged => {
|
||||
// Same content, new mtime: keep the symbols, refresh metadata.
|
||||
let mut rec = self.data.read().record_of(&f.path)?;
|
||||
let d = self.data.read();
|
||||
let mut rec = d.get(&f.path)?.record();
|
||||
rec.mtime = f.mtime;
|
||||
rec.size = f.size;
|
||||
rec.ignored = f.ignored;
|
||||
@@ -337,11 +338,11 @@ impl Shared {
|
||||
let puts: Vec<(String, FileRecord)> =
|
||||
extracted.iter().filter_map(|(_, rec, path)| Some((filter.store_key(path)?, rec.clone()))).collect();
|
||||
{
|
||||
let entries: Vec<(FileEntry, Vec<StoredSymbol>)> =
|
||||
let entries: Vec<FileEntry> =
|
||||
extracted.into_iter().map(|(rel, rec, path)| FileEntry::new(path, rel, rec)).collect();
|
||||
let mut d = self.data.write();
|
||||
for (e, symbols) in entries {
|
||||
d.insert(e, symbols);
|
||||
for e in entries {
|
||||
d.insert(e);
|
||||
}
|
||||
}
|
||||
self.persist(&puts, &[], false);
|
||||
|
||||
@@ -92,17 +92,4 @@ describe("development worktrees", () => {
|
||||
expect(args.slice(-5)).toEqual(["--", "--features", "test", "--", "/project"]);
|
||||
expect(JSON.parse(args[4]!)).toEqual({ build: { beforeDevCommand: "", devUrl: "http://localhost:54321/" } });
|
||||
});
|
||||
|
||||
it("puts the Vite URL before a project path, which tauri dev hands to the app with what follows", () => {
|
||||
const config = JSON.stringify({ build: { beforeDevCommand: "", devUrl: "http://localhost:54321/" } });
|
||||
expect(
|
||||
withDevConfig(["dev", "--config", "custom.json", "/project", "--verbose"], "http://localhost:54321/"),
|
||||
).toEqual(["dev", "--config", "custom.json", "--config", config, "/project", "--verbose"]);
|
||||
expect(withDevConfig(["dev", "--release"], "http://localhost:54321/")).toEqual([
|
||||
"dev",
|
||||
"--release",
|
||||
"--config",
|
||||
config,
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -79,20 +79,9 @@ export async function claimSession(
|
||||
throw new Error("No available development session port");
|
||||
}
|
||||
|
||||
/** `tauri dev` options that take a value as the next argument. */
|
||||
const VALUE_OPTIONS = new Set(["-c", "--config", "-t", "--target", "-f", "--features", "-r", "--runner", "--port"]);
|
||||
|
||||
/**
|
||||
* `args` with the session's Vite URL as the last `--config`, placed before the first
|
||||
* positional argument: `tauri dev` passes everything from there on to the app, so a config
|
||||
* after `pnpm dev:app <project path>` would be ignored.
|
||||
*/
|
||||
export function withDevConfig(args: string[], devUrl: string): string[] {
|
||||
let index = 1;
|
||||
while (index < args.length && args[index] !== "--" && args[index]!.startsWith("-")) {
|
||||
index += VALUE_OPTIONS.has(args[index]!) ? 2 : 1;
|
||||
}
|
||||
index = Math.min(index, args.length);
|
||||
const separator = args.indexOf("--");
|
||||
const index = separator < 0 ? args.length : separator;
|
||||
return [
|
||||
...args.slice(0, index),
|
||||
"--config",
|
||||
|
||||
@@ -1,146 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { Variable } from "@/platform/ipc";
|
||||
import {
|
||||
AmbiguousClassError,
|
||||
declaresInaccessible,
|
||||
evaluateWithImports,
|
||||
forgetImports,
|
||||
importingCompletion,
|
||||
qualify,
|
||||
qualifyIn,
|
||||
rememberImport,
|
||||
unresolvedNames,
|
||||
} from "../classImports";
|
||||
|
||||
const UNRESOLVED = "Cannot evaluate because of compilation error(s): JSON cannot be resolved.";
|
||||
const value = (v: string) => ({ value: v }) as Variable;
|
||||
|
||||
describe("unresolvedNames", () => {
|
||||
it("takes the types java-debug could not resolve, not variables", () => {
|
||||
expect(unresolvedNames(UNRESOLVED)).toEqual(["JSON"]);
|
||||
expect(unresolvedNames("List cannot be resolved to a type. Foo cannot be resolved to a variable.")).toEqual([
|
||||
"List",
|
||||
]);
|
||||
expect(unresolvedNames("x cannot be resolved")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("qualify", () => {
|
||||
const names = new Map([["JSON", "com.alibaba.fastjson2.JSON"]]);
|
||||
|
||||
it("qualifies a class name where it stands for the type", () => {
|
||||
expect(qualify("JSON.toJSONString(u)", names)).toBe("com.alibaba.fastjson2.JSON.toJSONString(u)");
|
||||
expect(qualify("(JSON) o", names)).toBe("(com.alibaba.fastjson2.JSON) o");
|
||||
expect(qualify("JSON::toJSONString", names)).toBe("com.alibaba.fastjson2.JSON::toJSONString");
|
||||
});
|
||||
|
||||
it("leaves members, methods, strings, chars and comments alone", () => {
|
||||
expect(qualify("a.JSON", names)).toBe("a.JSON");
|
||||
expect(qualify("JSON (1)", names)).toBe("JSON (1)");
|
||||
// A constructor call is a type.
|
||||
expect(qualify("new JSON()", names)).toBe("new com.alibaba.fastjson2.JSON()");
|
||||
expect(qualify("new JSON ()", names)).toBe("new com.alibaba.fastjson2.JSON ()");
|
||||
expect(qualify("renew JSON()", names)).toBe("renew JSON()");
|
||||
expect(qualify('"JSON \\" JSON"', names)).toBe('"JSON \\" JSON"');
|
||||
expect(qualify("/* JSON */ 1 // JSON", names)).toBe("/* JSON */ 1 // JSON");
|
||||
expect(qualify("JSONArray", names)).toBe("JSONArray");
|
||||
});
|
||||
});
|
||||
|
||||
describe("declaresInaccessible", () => {
|
||||
it("tells a class only its package sees from a public one", () => {
|
||||
expect(declaresInaccessible("package org.json;\n\nclass JSON {\n}", "JSON")).toBe(true);
|
||||
expect(declaresInaccessible("package org.json;\nfinal class JSON {}", "JSON")).toBe(true);
|
||||
expect(declaresInaccessible("package a;\npublic abstract class JSON {}", "JSON")).toBe(false);
|
||||
expect(declaresInaccessible("package a;\n@Deprecated public interface JSON {}", "JSON")).toBe(false);
|
||||
expect(declaresInaccessible("package a;\npublic class JSONArray {}", "JSON")).toBe(false);
|
||||
});
|
||||
|
||||
it("hides a private nested class but not one without modifiers", () => {
|
||||
const arrays = "public class Arrays {\n private static class ArrayList<E> extends AbstractList<E> {}\n}";
|
||||
expect(declaresInaccessible(arrays, "ArrayList", true)).toBe(true);
|
||||
const map = "public interface Map<K, V> {\n interface Entry<K, V> {}\n}";
|
||||
expect(declaresInaccessible(map, "Entry", true)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("importingCompletion", () => {
|
||||
const item = (text: string, kind: string | null = "class") => ({
|
||||
label: text,
|
||||
text,
|
||||
kind,
|
||||
detail: null,
|
||||
sortText: null,
|
||||
});
|
||||
|
||||
it("inserts a qualified class by its simple name and imports it", async () => {
|
||||
expect(importingCompletion(5, item("com.zhangdagou.fight.ai.chat.support.JSONUtil1")).text).toBe("JSONUtil1");
|
||||
const run = vi.fn(async (e: string) => value(e));
|
||||
await evaluateWithImports(5, "JSONUtil1.aaa(s)", run, async () => []);
|
||||
expect(run).toHaveBeenCalledWith("com.zhangdagou.fight.ai.chat.support.JSONUtil1.aaa(s)");
|
||||
forgetImports(5);
|
||||
});
|
||||
|
||||
it("a later choice of the same simple name replaces the earlier one", () => {
|
||||
importingCompletion(7, item("com.x.debug.controller.JSONUtil1"));
|
||||
importingCompletion(7, item("com.x.chat.support.JSONUtil1"));
|
||||
expect(qualifyIn(7, "JSONUtil1.")).toBe("com.x.chat.support.JSONUtil1.");
|
||||
forgetImports(7);
|
||||
expect(qualifyIn(7, "JSONUtil1.")).toBe("JSONUtil1.");
|
||||
});
|
||||
|
||||
it("leaves members and simple names as they are", () => {
|
||||
expect(importingCompletion(6, item("toString", "method")).text).toBe("toString");
|
||||
expect(importingCompletion(6, item("user.name", "field")).text).toBe("user.name");
|
||||
expect(importingCompletion(6, item("User")).text).toBe("User");
|
||||
forgetImports(6);
|
||||
});
|
||||
});
|
||||
|
||||
describe("evaluateWithImports", () => {
|
||||
it("imports the only class with the name and evaluates again, and keeps the import", async () => {
|
||||
const run = vi.fn(async (e: string) => {
|
||||
if (e.startsWith("JSON")) throw new Error(UNRESOLVED);
|
||||
return value(e);
|
||||
});
|
||||
const find = vi.fn(async () => ["com.alibaba.fastjson2.JSON"]);
|
||||
await expect(evaluateWithImports(1, "JSON.toJSONString(u)", run, find)).resolves.toEqual(
|
||||
value("com.alibaba.fastjson2.JSON.toJSONString(u)"),
|
||||
);
|
||||
await evaluateWithImports(1, "JSON.toJSONString(v)", run, find);
|
||||
expect(find).toHaveBeenCalledTimes(1);
|
||||
forgetImports(1);
|
||||
});
|
||||
|
||||
it("asks which one when several classes have the name, then uses the chosen one", async () => {
|
||||
const run = vi.fn(async (e: string) => {
|
||||
if (e.startsWith("JSON")) throw new Error(UNRESOLVED);
|
||||
return value(e);
|
||||
});
|
||||
const find = async () => ["com.alibaba.fastjson.JSON", "com.alibaba.fastjson2.JSON"];
|
||||
const error = await evaluateWithImports(2, "JSON.toJSONString(u)", run, find).catch((e: unknown) => e);
|
||||
expect(error).toBeInstanceOf(AmbiguousClassError);
|
||||
expect((error as AmbiguousClassError).candidates).toEqual([
|
||||
"com.alibaba.fastjson.JSON",
|
||||
"com.alibaba.fastjson2.JSON",
|
||||
]);
|
||||
rememberImport(2, "com.alibaba.fastjson2.JSON");
|
||||
await expect(evaluateWithImports(2, "JSON.toJSONString(u)", run, find)).resolves.toEqual(
|
||||
value("com.alibaba.fastjson2.JSON.toJSONString(u)"),
|
||||
);
|
||||
forgetImports(2);
|
||||
});
|
||||
|
||||
it("reports the original error when no class has the name or it is not about a class", async () => {
|
||||
const run = async () => {
|
||||
throw new Error(UNRESOLVED);
|
||||
};
|
||||
await expect(evaluateWithImports(3, "JSON.x", run, async () => [])).rejects.toThrow(UNRESOLVED);
|
||||
const other = async () => {
|
||||
throw new Error("Cannot evaluate because the thread is resumed");
|
||||
};
|
||||
const find = vi.fn(async () => ["a.JSON"]);
|
||||
await expect(evaluateWithImports(3, "x", other, find)).rejects.toThrow("thread is resumed");
|
||||
expect(find).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,202 +0,0 @@
|
||||
/**
|
||||
* Java Evaluate with classes the frame's file does not import, as IDEA's Evaluate does with
|
||||
* the imports of its code fragment. java-debug takes only the expression's text, resolved
|
||||
* against the frame's compilation unit, so a class it reports as unresolved is looked up by
|
||||
* name and written fully qualified; the field keeps the short name.
|
||||
*/
|
||||
import type { DebugCompletion } from "@/bindings";
|
||||
import { call, commands, nextRequestId, type DebugSessionId, type SymbolKind, type Variable } from "@/platform/ipc";
|
||||
import { isVirtualUri } from "@/platform/virtualDocs";
|
||||
|
||||
const TYPE_KINDS = new Set<SymbolKind>(["class", "interface", "enum"]);
|
||||
const MAX_ROUNDS = 3;
|
||||
|
||||
/** More than one class has the name: the user picks one ({@link rememberImport}). */
|
||||
export class AmbiguousClassError extends Error {
|
||||
constructor(
|
||||
readonly className: string,
|
||||
readonly candidates: readonly string[],
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Per session: simple name → qualified name, like the imports of IDEA's code fragment. */
|
||||
const imports = new Map<DebugSessionId, Map<string, string>>();
|
||||
|
||||
function importsOf(sessionId: DebugSessionId): Map<string, string> {
|
||||
let map = imports.get(sessionId);
|
||||
if (!map) imports.set(sessionId, (map = new Map()));
|
||||
return map;
|
||||
}
|
||||
|
||||
/** Evaluations in `sessionId` write `qualifiedName`'s simple name qualified. */
|
||||
export function rememberImport(sessionId: DebugSessionId, qualifiedName: string) {
|
||||
importsOf(sessionId).set(qualifiedName.slice(qualifiedName.lastIndexOf(".") + 1), qualifiedName);
|
||||
}
|
||||
|
||||
export function forgetImports(sessionId: DebugSessionId) {
|
||||
imports.delete(sessionId);
|
||||
}
|
||||
|
||||
/** `expression` with the session's imports written qualified (see {@link qualify}). */
|
||||
export function qualifyIn(sessionId: DebugSessionId, expression: string): string {
|
||||
const known = imports.get(sessionId);
|
||||
return known ? qualify(expression, known) : expression;
|
||||
}
|
||||
|
||||
/**
|
||||
* A class completion java-debug inserts qualified (`com.x.Foo`) inserts the simple name and
|
||||
* imports the class, as IDEA's completion in the Evaluate field does.
|
||||
*/
|
||||
export function importingCompletion(sessionId: DebugSessionId, item: DebugCompletion): DebugCompletion {
|
||||
const text = item.text ?? item.label;
|
||||
if (item.kind === "method" || item.kind === "field" || !/^[a-z_$][\w$]*(\.[\w$]+)*\.[A-Z][\w$]*$/.test(text))
|
||||
return item;
|
||||
rememberImport(sessionId, text);
|
||||
return { ...item, text: text.slice(text.lastIndexOf(".") + 1) };
|
||||
}
|
||||
|
||||
/** Type names a java-debug compile error could not resolve (`JSON cannot be resolved`, `… to a type`). */
|
||||
export function unresolvedNames(message: string): string[] {
|
||||
const names = new Set<string>();
|
||||
for (const m of message.matchAll(/\b([A-Z][\w$]*) cannot be resolved(?! to a variable)/g)) names.add(m[1]!);
|
||||
return [...names];
|
||||
}
|
||||
|
||||
/**
|
||||
* `expression` with each name in `names` written qualified where it stands for a type: not
|
||||
* after `.` (a member), not before `(` unless after `new` (a method, not a constructor), not
|
||||
* in a string, char or comment.
|
||||
*/
|
||||
export function qualify(expression: string, names: ReadonlyMap<string, string>): string {
|
||||
if (!names.size) return expression;
|
||||
let out = "";
|
||||
let prev = "";
|
||||
let prevWord = "";
|
||||
let i = 0;
|
||||
const n = expression.length;
|
||||
while (i < n) {
|
||||
const c = expression[i]!;
|
||||
let end = i + 1;
|
||||
if (expression.startsWith('"""', i)) {
|
||||
const close = expression.indexOf('"""', i + 3);
|
||||
end = close < 0 ? n : close + 3;
|
||||
} else if (c === '"' || c === "'") {
|
||||
while (end < n && expression[end] !== c) end += expression[end] === "\\" ? 2 : 1;
|
||||
end = Math.min(n, end + 1);
|
||||
} else if (expression.startsWith("//", i)) {
|
||||
const close = expression.indexOf("\n", i);
|
||||
end = close < 0 ? n : close;
|
||||
} else if (expression.startsWith("/*", i)) {
|
||||
const close = expression.indexOf("*/", i + 2);
|
||||
end = close < 0 ? n : close + 2;
|
||||
} else if (/[A-Za-z_$]/.test(c)) {
|
||||
while (end < n && /[\w$]/.test(expression[end]!)) end++;
|
||||
const name = expression.slice(i, end);
|
||||
const qualified = names.get(name);
|
||||
const next = expression.slice(end).match(/^\s*(\S?)/)![1];
|
||||
out += qualified && prev !== "." && (next !== "(" || prevWord === "new") ? qualified : name;
|
||||
prev = "a";
|
||||
prevWord = name;
|
||||
i = end;
|
||||
continue;
|
||||
}
|
||||
const token = expression.slice(i, end);
|
||||
out += token;
|
||||
if (token.trim()) {
|
||||
prev = token.length === 1 ? token : "a";
|
||||
prevWord = "";
|
||||
}
|
||||
i = end;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The package in a symbol's container; some servers put more before it (`app.jar com.x`). */
|
||||
function packageOf(container: string | null): string {
|
||||
const last = (container ?? "").trim().split(/\s+/).pop() ?? "";
|
||||
return /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*$/.test(last) ? last : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `source` declares type `simple` so that other packages can't use it: `private`
|
||||
* (`java.util.Arrays.ArrayList`), or top-level without `public` (android-json's `org.json.JSON`).
|
||||
* A nested type without modifiers counts as visible: it is public inside an interface.
|
||||
* `false` when the declaration is not found.
|
||||
*/
|
||||
export function declaresInaccessible(source: string, simple: string, nested = false): boolean {
|
||||
const declaration = new RegExp(
|
||||
String.raw`^[ \t]*((?:@[\w.]+(?:\([^)]*\))?\s+|[a-z-]+\s+)*)(?:class|interface|enum|record|@interface)\s+${simple.replaceAll("$", "\\$")}\b`,
|
||||
"m",
|
||||
).exec(source);
|
||||
if (!declaration) return false;
|
||||
const modifiers = declaration[1]!;
|
||||
return /\bprivate\b/.test(modifiers) || (!nested && !/\b(public|protected)\b/.test(modifiers));
|
||||
}
|
||||
|
||||
async function sourceOf(path: string): Promise<string> {
|
||||
return isVirtualUri(path) ? (await call(commands.lspVirtualDocument(path))).text : call(commands.fsReadText(path));
|
||||
}
|
||||
|
||||
/**
|
||||
* Qualified names of the classes called `simple` in the project and its dependencies that
|
||||
* other packages can use; IDEA's import offers only accessible classes too.
|
||||
*/
|
||||
export async function findClasses(simple: string): Promise<string[]> {
|
||||
const symbols = await call(commands.lspWorkspaceSymbols(nextRequestId(), simple));
|
||||
const found = new Map<string, string>();
|
||||
for (const s of symbols) {
|
||||
const pkg = s.name === simple && TYPE_KINDS.has(s.kind) ? packageOf(s.container) : "";
|
||||
if (pkg && !found.has(`${pkg}.${simple}`)) found.set(`${pkg}.${simple}`, s.location.path);
|
||||
}
|
||||
const names = [...found.keys()].sort();
|
||||
if (names.length < 2) return names;
|
||||
const hidden = await Promise.all(
|
||||
names.map((name) =>
|
||||
sourceOf(found.get(name)!).then(
|
||||
// Nested in a type: the container's last segment is a class name (`java.util.Map`).
|
||||
(source) => declaresInaccessible(source, simple, /(^|\.)[A-Z][\w$]*$/.test(name.slice(0, -simple.length - 1))),
|
||||
() => false,
|
||||
),
|
||||
),
|
||||
);
|
||||
return names.filter((_, i) => !hidden[i]);
|
||||
}
|
||||
|
||||
function messageOf(e: unknown): string {
|
||||
return e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
|
||||
/**
|
||||
* `run(expression)` with the session's imports applied; a class the evaluation could not
|
||||
* resolve and only one class has the name of is imported and the evaluation repeated.
|
||||
* Throws {@link AmbiguousClassError} when several have it.
|
||||
*/
|
||||
export async function evaluateWithImports(
|
||||
sessionId: DebugSessionId,
|
||||
expression: string,
|
||||
run: (expression: string) => Promise<Variable>,
|
||||
find: (simple: string) => Promise<string[]> = findClasses,
|
||||
): Promise<Variable> {
|
||||
const known = importsOf(sessionId);
|
||||
for (let round = 0; ; round++) {
|
||||
try {
|
||||
return await run(qualify(expression, known));
|
||||
} catch (e) {
|
||||
const names = unresolvedNames(messageOf(e)).filter((name) => !known.has(name));
|
||||
if (round >= MAX_ROUNDS || !names.length) throw e;
|
||||
let added = false;
|
||||
for (const name of names) {
|
||||
const candidates = await find(name).catch(() => []);
|
||||
if (candidates.length > 1) throw new AmbiguousClassError(name, candidates, messageOf(e));
|
||||
if (candidates.length === 1) {
|
||||
known.set(name, candidates[0]!);
|
||||
added = true;
|
||||
}
|
||||
}
|
||||
if (!added) throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,8 +40,6 @@ import { refreshExceptionFilters } from "./breakpoints/exceptions";
|
||||
import { flashTaskbarForBreakpoint, stopTaskbarFlash } from "./taskbarFlash";
|
||||
import { missingAdapter } from "./missingAdapter";
|
||||
import { startFailureMessage } from "./startFailure";
|
||||
import { evaluateWithImports, forgetImports } from "./classImports";
|
||||
import { JAVA_ADAPTER } from "./java";
|
||||
|
||||
export type SessionStatus = "starting" | "running" | "paused" | "stopping" | "terminated";
|
||||
|
||||
@@ -828,7 +826,6 @@ export function sessionSupports(cap: keyof DebugCapabilities, s: DebugSession |
|
||||
|
||||
function markTerminated(id: DebugSessionId) {
|
||||
stopTaskbarFlash();
|
||||
forgetImports(id);
|
||||
patch(id, { status: "terminated", endedAt: Date.now(), frames: [], selectedFrame: null, stoppedThread: null });
|
||||
const st = useDebug.getState();
|
||||
if (st.active === id) {
|
||||
@@ -1085,8 +1082,7 @@ export async function evaluate(
|
||||
session: DebugSession | null = activeSession(),
|
||||
): Promise<Variable> {
|
||||
if (!session || !isLive(session)) throw new Error("No active debug session");
|
||||
const run = (expr: string) => call(commands.debugEvaluateIn(session.id, session.selectedFrame, expr, context));
|
||||
return session.adapter === JAVA_ADAPTER ? evaluateWithImports(session.id, expression, run) : run(expression);
|
||||
return call(commands.debugEvaluateIn(session.id, session.selectedFrame, expression, context));
|
||||
}
|
||||
|
||||
/** Settings › Debugger › Focus application on breakpoint. */
|
||||
|
||||
@@ -11,8 +11,6 @@ import { isImeKey } from "@/platform/ime";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { badgeKind, Popup, SymbolBadge } from "@/ui";
|
||||
import { isLive, type DebugSession } from "../state";
|
||||
import { importingCompletion, qualifyIn } from "../classImports";
|
||||
import { JAVA_ADAPTER } from "../java";
|
||||
import styles from "./ExpressionCompletion.module.css";
|
||||
|
||||
type Field = HTMLInputElement | HTMLTextAreaElement;
|
||||
@@ -98,12 +96,8 @@ export function useExpressionCompletion(
|
||||
return;
|
||||
}
|
||||
const mine = ++seq.current;
|
||||
// The adapter resolves names against the frame's file: imported classes before the word
|
||||
// being typed go qualified (the word itself is what it completes).
|
||||
const head = text.slice(0, at - prefix.length);
|
||||
const before = (session.adapter === JAVA_ADAPTER ? qualifyIn(session.id, head) : head) + prefix;
|
||||
const { line, column } = position(before, before.length);
|
||||
call(commands.debugCompletions(session.id, session.selectedFrame, before + text.slice(at), line, column)).then(
|
||||
const { line, column } = position(text, at);
|
||||
call(commands.debugCompletions(session.id, session.selectedFrame, text, line, column)).then(
|
||||
(result) => {
|
||||
if (mine !== seq.current) return;
|
||||
setItems(result.length ? result : null);
|
||||
@@ -116,8 +110,7 @@ export function useExpressionCompletion(
|
||||
const accept = (item: DebugCompletion) => {
|
||||
const el = field.current;
|
||||
if (!el) return;
|
||||
const chosen = session?.adapter === JAVA_ADAPTER ? importingCompletion(session.id, item) : item;
|
||||
const next = applyCompletion(el.value, el.selectionStart ?? el.value.length, chosen);
|
||||
const next = applyCompletion(el.value, el.selectionStart ?? el.value.length, item);
|
||||
close();
|
||||
setValue(next.text);
|
||||
requestAnimationFrame(() => {
|
||||
|
||||
@@ -181,13 +181,6 @@
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.evalImport {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px 8px;
|
||||
}
|
||||
|
||||
/* Grows with the dialog when it is resized. */
|
||||
.evalResult {
|
||||
flex: 1;
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
useBreakpoints,
|
||||
} from "../breakpoints/store";
|
||||
import { activeSession, addWatch, evaluate, isLive, startSession, useDebug, resumeExecution } from "../state";
|
||||
import { AmbiguousClassError, rememberImport } from "../classImports";
|
||||
import {
|
||||
addMethodBreakpoint,
|
||||
removeAllSpecial,
|
||||
@@ -690,7 +689,6 @@ function EvaluateDialog() {
|
||||
function EvaluateDialogInner({ initial }: { initial: string }) {
|
||||
const [expression, setExpression] = useState(initial);
|
||||
const [result, setResult] = useState<VarRoot | null>(null);
|
||||
const [ambiguous, setAmbiguous] = useState<AmbiguousClassError | null>(null);
|
||||
const [history, setHistory] = useState(() => readHistory("evaluate"));
|
||||
const [historyMenu, setHistoryMenu] = useState(false);
|
||||
const historyPos = useRef(-1);
|
||||
@@ -707,19 +705,15 @@ function EvaluateDialogInner({ initial }: { initial: string }) {
|
||||
pushHistory("evaluate", e);
|
||||
setHistory(readHistory("evaluate"));
|
||||
historyPos.current = -1;
|
||||
setAmbiguous(null);
|
||||
try {
|
||||
const v: Variable = await evaluate(e, session?.adapter === "gdb" ? "watch" : "repl", session ?? null);
|
||||
setResult({ key: `eval:${e}:${Date.now()}`, kind: "eval", name: e, variable: v, error: null });
|
||||
} catch (err) {
|
||||
setResult({ key: `eval:${e}:${Date.now()}`, kind: "eval", name: e, variable: null, error: errorText(err) });
|
||||
if (err instanceof AmbiguousClassError) setAmbiguous(err);
|
||||
}
|
||||
};
|
||||
const className = ambiguous?.className ?? "";
|
||||
const recall = (text: string) => {
|
||||
setExpression(text);
|
||||
setAmbiguous(null);
|
||||
requestAnimationFrame(() => {
|
||||
const el = field.current;
|
||||
if (!el) return;
|
||||
@@ -786,7 +780,6 @@ function EvaluateDialogInner({ initial }: { initial: string }) {
|
||||
value={expression}
|
||||
onChange={(e) => {
|
||||
setExpression(e.target.value);
|
||||
setAmbiguous(null);
|
||||
historyPos.current = -1;
|
||||
completion.onInput();
|
||||
}}
|
||||
@@ -821,24 +814,6 @@ function EvaluateDialogInner({ initial }: { initial: string }) {
|
||||
.map((h) => ({ label: h.replace(/\s+/g, " "), verbatim: true, run: () => recall(h) }))}
|
||||
/>
|
||||
</div>
|
||||
{ambiguous && (
|
||||
<div className={styles.evalImport} role="group" aria-label={tx("Class to import")}>
|
||||
<span className={styles.label}>{tx`Choose the class to import for ${className}:`}</span>
|
||||
{ambiguous.candidates.map((c) => (
|
||||
<Button
|
||||
key={c}
|
||||
variant="ghost"
|
||||
size="small"
|
||||
onClick={() => {
|
||||
if (session) rememberImport(session.id, c);
|
||||
void run();
|
||||
}}
|
||||
>
|
||||
{c}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className={styles.evalResult}>
|
||||
{result ? (
|
||||
<VariablesView roots={[result]} session={session?.id ?? null} aria-label="Evaluation result" />
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
blockScopedNamespace,
|
||||
caretAfterReformat,
|
||||
csprojFileScoped,
|
||||
csprojRootNamespace,
|
||||
inferCsharpNamespace,
|
||||
expandIncludes,
|
||||
fragmentResolver,
|
||||
composerPsr4,
|
||||
@@ -184,43 +180,6 @@ describe("PHP namespaces", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("C# namespaces", () => {
|
||||
it("come from the project's root namespace and the folders below the .csproj", () => {
|
||||
expect(csprojRootNamespace('<Project Sdk="Microsoft.NET.Sdk"></Project>', "My.App.csproj")).toBe("My.App");
|
||||
expect(csprojRootNamespace("<RootNamespace>Acme.Shop</RootNamespace>", "Web.csproj")).toBe("Acme.Shop");
|
||||
expect(csprojRootNamespace("", "my-app.csproj")).toBe("my_app");
|
||||
expect(inferCsharpNamespace("/Services/Billing", "Acme.Shop")).toBe("Acme.Shop.Services.Billing");
|
||||
expect(inferCsharpNamespace("", "Acme.Shop")).toBe("Acme.Shop");
|
||||
expect(inferCsharpNamespace("/2024-data", "App")).toBe("App._2024_data");
|
||||
});
|
||||
|
||||
it("are file-scoped from C# 10 and blocks before it (.NET Framework and Unity projects)", () => {
|
||||
const sdk = (tf: string) => `<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup>${tf}</PropertyGroup></Project>`;
|
||||
expect(csprojFileScoped(sdk("<TargetFramework>net8.0</TargetFramework>"))).toBe(true);
|
||||
expect(csprojFileScoped(sdk("<TargetFrameworks>net6.0;net8.0</TargetFrameworks>"))).toBe(true);
|
||||
expect(csprojFileScoped(sdk("<TargetFrameworks>netstandard2.0;net8.0</TargetFrameworks>"))).toBe(false);
|
||||
expect(csprojFileScoped(sdk("<TargetFramework>net48</TargetFramework>"))).toBe(false);
|
||||
expect(csprojFileScoped(sdk("<TargetFramework>net5.0</TargetFramework>"))).toBe(false);
|
||||
expect(
|
||||
csprojFileScoped(sdk("<TargetFramework>netstandard2.1</TargetFramework><LangVersion>latest</LangVersion>")),
|
||||
).toBe(true);
|
||||
expect(
|
||||
csprojFileScoped("<TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion><LangVersion>9.0</LangVersion>"),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("render C# classes with a file-scoped namespace, a block, or none", () => {
|
||||
const cls = tpl("csharp").kinds[0]!.body;
|
||||
const vars = { name: "OrderService", fileName: "OrderService.cs", packageName: "Acme.Shop" };
|
||||
expect(renderFileTemplate(cls, vars).text).toBe("namespace Acme.Shop;\n\npublic class OrderService\n{\n \n}\n");
|
||||
expect(renderFileTemplate(blockScopedNamespace(cls), vars).text).toBe(
|
||||
"namespace Acme.Shop\n{\n public class OrderService\n {\n \n }\n}\n",
|
||||
);
|
||||
expect(renderFileTemplate(cls, { name: "Foo", fileName: "Foo.cs" }).text).toBe("public class Foo\n{\n \n}\n");
|
||||
expect(tpl("csharp").kinds.map((k) => k.label)).toEqual(["Class", "Interface", "Struct", "Enum", "Record"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("rendering", () => {
|
||||
it("substitutes variables and places the caret", () => {
|
||||
const kind = tpl("java").kinds[0]!;
|
||||
|
||||
@@ -53,22 +53,6 @@ describe("plugin package inference uses built-in rules", () => {
|
||||
);
|
||||
expect(await packageFor({ ...plugin("java"), fileName: ".dockerignore" }, "/p/src/main/java/com/acme")).toBe("");
|
||||
});
|
||||
it("uses the nearest .csproj for C#", async () => {
|
||||
useProject.setState({ project: { root: "/p", name: "p" } as never });
|
||||
const csproj = { kind: "file", name: "Shop.csproj", path: "/p/src/Shop/Shop.csproj" };
|
||||
const readDir = vi
|
||||
.mocked(commands.fsReadDir)
|
||||
.mockImplementation((async (dir: string) => (dir === "/p/src/Shop" ? [csproj] : [])) as never);
|
||||
mocks.read.mockResolvedValue(
|
||||
"<Project><PropertyGroup><RootNamespace>Acme.Shop</RootNamespace></PropertyGroup></Project>",
|
||||
);
|
||||
try {
|
||||
expect(await packageFor(plugin("cs"), "/p/src/Shop/Orders/Api")).toBe("Acme.Shop.Orders.Api");
|
||||
expect(await packageFor(plugin("cs"), "/p/tools")).toBe("");
|
||||
} finally {
|
||||
readDir.mockReset();
|
||||
}
|
||||
});
|
||||
it("uses an existing Go package", async () => {
|
||||
useProject.setState({ project: { root: "/p", name: "p" } as never });
|
||||
mocks.read.mockResolvedValue("package service\n");
|
||||
|
||||
@@ -302,11 +302,7 @@ function NameStep({
|
||||
{error ?? (
|
||||
<>
|
||||
{where}
|
||||
{packageStyle && pkg
|
||||
? packageStyle === "php" || packageStyle === "csharp"
|
||||
? ` · namespace ${pkg}`
|
||||
: ` · package ${pkg}`
|
||||
: ""}
|
||||
{packageStyle && pkg ? (packageStyle === "php" ? ` · namespace ${pkg}` : ` · package ${pkg}`) : ""}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -294,27 +294,6 @@ export const BUILTIN_FILE_TEMPLATES: readonly FileTemplate[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "csharp",
|
||||
name: "C# Class",
|
||||
icon: "class",
|
||||
extension: "cs",
|
||||
nameStyle: "pascal",
|
||||
packageStyle: "csharp",
|
||||
kinds: (
|
||||
[
|
||||
["class", "Class", "class"],
|
||||
["interface", "Interface", "interface"],
|
||||
["struct", "Struct", "struct"],
|
||||
["enum", "Enum", "enum"],
|
||||
["record", "Record", "record"],
|
||||
] as const
|
||||
).map(([id, label, keyword]) => ({
|
||||
id,
|
||||
label,
|
||||
body: `namespace $PACKAGE$;\n\n#parse("File Header")\npublic ${keyword} $NAME$\n{\n $END$\n}\n`,
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "kotlin",
|
||||
name: "Kotlin Class/File",
|
||||
|
||||
@@ -10,12 +10,8 @@ import { activeEditor, editorsFor, type TextEditorHandle } from "@/editor/api";
|
||||
import { editorService, maybeEditorService, notifications, resolveFileEditor } from "@/workbench/contributions";
|
||||
import {
|
||||
GO_PACKAGE_RE,
|
||||
blockScopedNamespace,
|
||||
caretAfterReformat,
|
||||
composerPsr4,
|
||||
csprojFileScoped,
|
||||
csprojRootNamespace,
|
||||
inferCsharpNamespace,
|
||||
inferGoPackage,
|
||||
inferJvmPackage,
|
||||
inferPhpNamespace,
|
||||
@@ -72,26 +68,6 @@ async function composerNamespace(directory: string, root: string | null): Promis
|
||||
}
|
||||
}
|
||||
|
||||
/** C# namespace from the nearest .csproj between `directory` and the project root. */
|
||||
async function csharpNamespace(directory: string, root: string | null): Promise<{ name: string; fileScoped: boolean }> {
|
||||
const none = { name: "", fileScoped: true };
|
||||
if (!isTauri()) return none;
|
||||
const start = directory.replace(/\/+$/, "");
|
||||
const top = root?.replace(/\/+$/, "") ?? null;
|
||||
for (let dir = start; ; dir = dirname(dir)) {
|
||||
const csproj = await call(commands.fsReadDir(dir)).then(
|
||||
(entries) => entries.find((e) => e.kind === "file" && /\.csproj$/i.test(e.name)),
|
||||
() => undefined,
|
||||
);
|
||||
if (csproj) {
|
||||
const text = await call(commands.fsReadText(csproj.path)).catch(() => "");
|
||||
const rootNamespace = csprojRootNamespace(text, csproj.name);
|
||||
return { name: inferCsharpNamespace(start.slice(dir.length), rootNamespace), fileScoped: csprojFileScoped(text) };
|
||||
}
|
||||
if (!top || dir === top || !dir.startsWith(`${top}/`)) return none;
|
||||
}
|
||||
}
|
||||
|
||||
export function packageStyleFor(t: FileTemplate): FileTemplate["packageStyle"] {
|
||||
const dot = t.fileName?.lastIndexOf(".") ?? -1;
|
||||
const extension = t.fileName === undefined ? t.extension : dot > 0 ? t.fileName.slice(dot + 1) : "";
|
||||
@@ -110,7 +86,6 @@ export async function packageFor(t: FileTemplate, directory: string): Promise<st
|
||||
if (style === "jvm") return inferJvmPackage(directory, root, packageRoots());
|
||||
if (style === "go") return inferGoPackage(directory, root, await siblingGoPackage(directory));
|
||||
if (style === "php") return composerNamespace(directory, root);
|
||||
if (style === "csharp") return (await csharpNamespace(directory, root)).name;
|
||||
return "";
|
||||
}
|
||||
|
||||
@@ -168,15 +143,9 @@ export async function createFromTemplate(
|
||||
const plan = planFile(withKind(t, kind), directory, input);
|
||||
if (!plan) throw new Error(tx("Invalid file name"));
|
||||
const project = useProject.getState().project;
|
||||
let body = kind.body;
|
||||
let packageName: string;
|
||||
if (packageStyleFor(withKind(t, kind)) === "csharp") {
|
||||
const ns = await csharpNamespace(plan.directory, project?.root ?? null);
|
||||
packageName = ns.name;
|
||||
if (ns.name && !ns.fileScoped) body = blockScopedNamespace(body);
|
||||
} else packageName = await packageFor(withKind(t, kind), plan.directory);
|
||||
const packageName = await packageFor(withKind(t, kind), plan.directory);
|
||||
const { text, caret } = renderFileTemplate(
|
||||
body,
|
||||
kind.body,
|
||||
{
|
||||
variables,
|
||||
name: plan.name,
|
||||
|
||||
@@ -254,56 +254,6 @@ export function inferPhpNamespace(directory: string, psr4: ReadonlyArray<readonl
|
||||
return parts.every((p) => /^[A-Za-z_\x80-\uffff][\w\x80-\uffff]*$/.test(p)) ? parts.join("\\") : "";
|
||||
}
|
||||
|
||||
/** A folder or project name as a C# identifier: other characters become `_`, as Rider does. */
|
||||
function csharpIdentifier(s: string): string {
|
||||
const id = s.replace(/[^\p{L}\p{N}_]/gu, "_");
|
||||
return /^\p{N}/u.test(id) ? `_${id}` : id;
|
||||
}
|
||||
|
||||
/** A .csproj's `<RootNamespace>`, else its file name (`My.App.csproj` → `My.App`). */
|
||||
export function csprojRootNamespace(text: string, fileName: string): string {
|
||||
const explicit = /<RootNamespace>\s*([^<]*?)\s*<\/RootNamespace>/i.exec(text)?.[1];
|
||||
const base = explicit || fileName.replace(/\.csproj$/i, "");
|
||||
return base.split(".").filter(Boolean).map(csharpIdentifier).join(".");
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a .csproj's C# version has file-scoped namespaces (C# 10): its `<LangVersion>`,
|
||||
* else every target framework is .NET 6 or later. .NET Framework (Unity), .NET Standard and
|
||||
* .NET Core projects stay on C# 9 or earlier.
|
||||
*/
|
||||
export function csprojFileScoped(text: string): boolean {
|
||||
const lang = /<LangVersion>\s*([^<]*?)\s*<\/LangVersion>/i.exec(text)?.[1]?.toLowerCase();
|
||||
if (lang && /^(latest|latestmajor|preview)$/.test(lang)) return true;
|
||||
if (lang && /^\d+(\.\d+)?$/.test(lang)) return Number(lang) >= 10;
|
||||
if (/<TargetFrameworkVersion>/i.test(text)) return false;
|
||||
const frameworks = /<TargetFrameworks?>\s*([^<]*?)\s*<\/TargetFrameworks?>/i.exec(text)?.[1];
|
||||
if (!frameworks) return true;
|
||||
return frameworks
|
||||
.split(";")
|
||||
.map((f) => f.trim())
|
||||
.filter(Boolean)
|
||||
.every((f) => Number(/^net(\d+)\.\d/.exec(f)?.[1] ?? 0) >= 6);
|
||||
}
|
||||
|
||||
/** The namespace of a folder `relDir` below the .csproj: the root namespace plus each folder. */
|
||||
export function inferCsharpNamespace(relDir: string, rootNamespace: string): string {
|
||||
const folders = relDir.split("/").filter(Boolean).map(csharpIdentifier);
|
||||
return [...rootNamespace.split(".").filter(Boolean), ...folders].join(".");
|
||||
}
|
||||
|
||||
/** A body with `namespace $PACKAGE$;` rewritten as a namespace block, for C# before 10. */
|
||||
export function blockScopedNamespace(body: string): string {
|
||||
const m = /^namespace \$PACKAGE\$;\n\n?/m.exec(body);
|
||||
if (!m) return body;
|
||||
const rest = body.slice(m.index + m[0].length).replace(/\n+$/, "");
|
||||
const indented = rest
|
||||
.split("\n")
|
||||
.map((l) => (l ? ` ${l}` : l))
|
||||
.join("\n");
|
||||
return `${body.slice(0, m.index)}namespace $PACKAGE$\n{\n${indented}\n}\n`;
|
||||
}
|
||||
|
||||
export interface FileTemplateVars {
|
||||
name: string;
|
||||
fileName: string;
|
||||
|
||||
@@ -1284,8 +1284,7 @@ function CommitList() {
|
||||
{
|
||||
id: "date",
|
||||
title: "Date",
|
||||
// Fits a 12-hour date and time ("11/05/2026 02:30 PM", "Yesterday 09:07 AM").
|
||||
width: 140,
|
||||
width: 120,
|
||||
render: (c: Commit) => formatTime(opts.commitTimestamp ? (c.commitTimeMs ?? c.timeMs) : c.timeMs),
|
||||
},
|
||||
]
|
||||
|
||||
@@ -1,12 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
DEFAULT_DATE_FORMAT,
|
||||
formatClock,
|
||||
formatDateTime,
|
||||
formatDay,
|
||||
formatPattern,
|
||||
formatTimestamp,
|
||||
} from "./dateFormat";
|
||||
import { DEFAULT_DATE_FORMAT, formatClock, formatDay, formatPattern } from "./dateFormat";
|
||||
|
||||
describe("dateFormat", () => {
|
||||
const d = new Date(2026, 10, 5, 9, 7);
|
||||
@@ -22,17 +15,6 @@ describe("dateFormat", () => {
|
||||
expect(formatPattern(d, "MMMM MMM dd.MM.yyyy")).toBe("November Nov 05.11.2026");
|
||||
});
|
||||
|
||||
it("keeps the time of dates before yesterday, as IDEA's pretty date-time does", () => {
|
||||
const now = new Date(2026, 10, 13, 12, 0).getTime();
|
||||
const pretty = { ...system, pretty: true };
|
||||
const numeric = d.toLocaleDateString(undefined, { year: "numeric", month: "2-digit", day: "2-digit" });
|
||||
expect(formatTimestamp(d.getTime(), now, pretty)).toBe(`${numeric} ${formatClock(d, system)}`);
|
||||
expect(formatTimestamp(d.getTime(), now, { ...system, pretty: false })).toBe(formatDateTime(d, system));
|
||||
expect(formatTimestamp(new Date(2026, 10, 13, 9, 7).getTime(), now, pretty)).toMatch(/09:07|9:07/);
|
||||
const custom = { ...pretty, overrideSystem: true, pattern: "dd.MM.yyyy", use24Hour: true };
|
||||
expect(formatTimestamp(d.getTime(), now, custom)).toBe("05.11.2026 09:07");
|
||||
});
|
||||
|
||||
it("formats another date with the same cached formatter", () => {
|
||||
const e = new Date(2025, 0, 31);
|
||||
formatDay(d, system);
|
||||
|
||||
@@ -74,18 +74,7 @@ export function formatDay(d: Date, o: DateFormatOptions = dateFormatOptions(), s
|
||||
: formatter(undefined, { year: "numeric", month: "short", day: "numeric" }).format(d);
|
||||
}
|
||||
|
||||
/** Numeric date and time (`2026/11/11 22:43`), IDEA's `formatDateTime`. */
|
||||
export function formatDateTime(d: Date, o: DateFormatOptions = dateFormatOptions()): string {
|
||||
const day = o.overrideSystem
|
||||
? formatPattern(d, o.pattern)
|
||||
: formatter(undefined, { year: "numeric", month: "2-digit", day: "2-digit" }).format(d);
|
||||
return `${day} ${formatClock(d, o)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Timestamp for lists: pretty ("Today 10:42", "5 min ago") when enabled, else date + time;
|
||||
* older dates keep their time, as IDEA's `formatPrettyDateTime` does.
|
||||
*/
|
||||
/** Timestamp for lists: pretty ("Today 10:42", "5 min ago") when enabled, else date + time. */
|
||||
export function formatTimestamp(ms: number, now = Date.now(), o: DateFormatOptions = dateFormatOptions()): string {
|
||||
const d = new Date(ms);
|
||||
if (o.pretty) {
|
||||
@@ -96,6 +85,7 @@ export function formatTimestamp(ms: number, now = Date.now(), o: DateFormatOptio
|
||||
const today = new Date(now);
|
||||
if (d.toDateString() === today.toDateString()) return tx`Today ${formatClock(d, o)}`;
|
||||
if (d.toDateString() === new Date(now - 86_400_000).toDateString()) return tx`Yesterday ${formatClock(d, o)}`;
|
||||
return formatDay(d, o);
|
||||
}
|
||||
return formatDateTime(d, o);
|
||||
return `${formatDay(d, o)} ${formatClock(d, o)}`;
|
||||
}
|
||||
@@ -16,11 +16,8 @@ export interface FileTemplate {
|
||||
/** Without the dot; empty for "File…" (the name carries the extension). */
|
||||
extension: string;
|
||||
nameStyle: NameStyle;
|
||||
/**
|
||||
* Package inference: `jvm` (Java/Kotlin source roots), `go` (directory), `php` (composer.json
|
||||
* PSR-4) or `csharp` (the nearest .csproj's root namespace and the folders below it).
|
||||
*/
|
||||
packageStyle?: "jvm" | "go" | "php" | "csharp";
|
||||
/** Package inference: `jvm` (Java/Kotlin source roots) or `go` (directory). */
|
||||
packageStyle?: "jvm" | "go" | "php";
|
||||
/** Dotted names (`com.acme.Foo`) create package directories. */
|
||||
dottedPackages?: boolean;
|
||||
kinds: FileTemplateKind[];
|
||||
|
||||
@@ -176,8 +176,6 @@
|
||||
"The debugger link stopped reading the JVM. Debugging continues.": "The debugger link stopped reading the JVM. Debugging continues.",
|
||||
"No referrers": "No referrers",
|
||||
"Could not find the source of {name}.": "Could not find the source of {name}.",
|
||||
"Class to import": "Class to import",
|
||||
"Choose the class to import for {className}:": "Choose the class to import for {className}:",
|
||||
"Memory view needs a JVM on this computer started with -XX:+StartAttachListener. Programs the IDE debugs get it automatically.": "Memory view needs a JVM on this computer started with -XX:+StartAttachListener. Programs the IDE debugs get it automatically.",
|
||||
"Memory view is not available when the IDE listens for the JVM to connect.": "Memory view is not available when the IDE listens for the JVM to connect.",
|
||||
"Memory view is not available on this platform yet.": "Memory view is not available on this platform yet.",
|
||||
|
||||
@@ -165,8 +165,6 @@
|
||||
"The debugger link stopped reading the JVM. Debugging continues.": "调试器链接已停止读取 JVM。调试仍在继续。",
|
||||
"No referrers": "没有引用者",
|
||||
"Could not find the source of {name}.": "找不到 {name} 的源代码。",
|
||||
"Class to import": "要导入的类",
|
||||
"Choose the class to import for {className}:": "选择 {className} 要导入的类:",
|
||||
"Memory view needs a JVM on this computer started with -XX:+StartAttachListener. Programs the IDE debugs get it automatically.": "内存视图需要本机上以 -XX:+StartAttachListener 启动的 JVM。由 IDE 调试的程序会自动添加该选项。",
|
||||
"Memory view is not available when the IDE listens for the JVM to connect.": "IDE 监听 JVM 连接时,内存视图不可用。",
|
||||
"Memory view is not available on this platform yet.": "此平台暂不支持内存视图。",
|
||||
|
||||
Reference in new issue
Заблокувати користувача