Unnamed repository; edit this file 'description' to name the repository.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
//! Partitions a list of files into disjoint subsets.
//!
//! Files which do not belong to any explicitly configured `FileSet` belong to
//! the default `FileSet`.
use std::fmt;

use fst::{IntoStreamer, Streamer};
use nohash_hasher::IntMap;
use rustc_hash::FxHashMap;

use crate::{AnchoredPath, FileId, Vfs, VfsPath};

/// A set of [`VfsPath`]s identified by [`FileId`]s.
#[derive(Default, Clone, Eq, PartialEq)]
pub struct FileSet {
    files: FxHashMap<VfsPath, FileId>,
    paths: IntMap<FileId, VfsPath>,
}

impl FileSet {
    /// Returns the number of stored paths.
    pub fn len(&self) -> usize {
        self.files.len()
    }

    /// Get the id of the file corresponding to `path`.
    ///
    /// If either `path`'s [`anchor`](AnchoredPath::anchor) or the resolved path is not in
    /// the set, returns [`None`].
    pub fn resolve_path(&self, path: AnchoredPath<'_>) -> Option<FileId> {
        let mut base = self.paths[&path.anchor].clone();
        base.pop();
        let path = base.join(path.path)?;
        self.files.get(&path).copied()
    }

    /// Get the id corresponding to `path` if it exists in the set.
    pub fn file_for_path(&self, path: &VfsPath) -> Option<&FileId> {
        self.files.get(path)
    }

    /// Get the path corresponding to `file` if it exists in the set.
    pub fn path_for_file(&self, file: &FileId) -> Option<&VfsPath> {
        self.paths.get(file)
    }

    /// Insert the `file_id, path` pair into the set.
    ///
    /// # Note
    /// Multiple [`FileId`] can be mapped to the same [`VfsPath`], and vice-versa.
    pub fn insert(&mut self, file_id: FileId, path: VfsPath) {
        self.files.insert(path.clone(), file_id);
        self.paths.insert(file_id, path);
    }

    /// Iterate over this set's ids.
    pub fn iter(&self) -> impl Iterator<Item = FileId> + '_ {
        self.paths.keys().copied()
    }
}

impl fmt::Debug for FileSet {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FileSet").field("n_files", &self.files.len()).finish()
    }
}

/// This contains path prefixes to partition a [`Vfs`] into [`FileSet`]s.
///
/// # Example
/// ```rust
/// # use vfs::{file_set::FileSetConfigBuilder, VfsPath, Vfs};
/// let mut builder = FileSetConfigBuilder::default();
/// builder.add_file_set(vec![VfsPath::new_virtual_path("/src".to_string())]);
/// let config = builder.build();
/// let mut file_system = Vfs::default();
/// file_system.set_file_contents(VfsPath::new_virtual_path("/src/main.rs".to_string()), Some(vec![]));
/// file_system.set_file_contents(VfsPath::new_virtual_path("/src/lib.rs".to_string()), Some(vec![]));
/// file_system.set_file_contents(VfsPath::new_virtual_path("/build.rs".to_string()), Some(vec![]));
/// // contains the sets :
/// // { "/src/main.rs", "/src/lib.rs" }
/// // { "build.rs" }
/// let sets = config.partition(&file_system);
/// ```
#[derive(Debug)]
pub struct FileSetConfig {
    /// Number of sets that `self` can partition a [`Vfs`] into.
    ///
    /// This should be the number of sets in `self.map` + 1 for files that don't fit in any
    /// defined set.
    n_file_sets: usize,
    /// Map from encoded paths to the set they belong to.
    map: fst::Map<Vec<u8>>,
}

impl Default for FileSetConfig {
    fn default() -> Self {
        FileSetConfig::builder().build()
    }
}

impl FileSetConfig {
    /// Returns a builder for `FileSetConfig`.
    pub fn builder() -> FileSetConfigBuilder {
        FileSetConfigBuilder::default()
    }

    /// Partition `vfs` into `FileSet`s.
    ///
    /// Creates a new [`FileSet`] for every set of prefixes in `self`.
    pub fn partition(&self, vfs: &Vfs) -> Vec<FileSet> {
        let mut scratch_space = Vec::new();
        let mut res = vec![FileSet::default(); self.len()];
        for (file_id, path) in vfs.iter() {
            let root = self.classify(path, &mut scratch_space);
            res[root].insert(file_id, path.clone());
        }
        res
    }

    /// Number of sets that `self` can partition a [`Vfs`] into.
    fn len(&self) -> usize {
        self.n_file_sets
    }

    /// Get the lexicographically ordered vector of the underlying map.
    pub fn roots(&self) -> Vec<(Vec<u8>, u64)> {
        self.map.stream().into_byte_vec()
    }

    /// Returns the set index for the given `path`.
    ///
    /// `scratch_space` is used as a buffer and will be entirely replaced.
    fn classify(&self, path: &VfsPath, scratch_space: &mut Vec<u8>) -> usize {
        // `path` is a file, but r-a only cares about the containing directory. We don't
        // want `/foo/bar_baz.rs` to be attributed to source root directory `/foo/bar`.
        let path = path.parent().unwrap_or_else(|| path.clone());

        scratch_space.clear();
        path.encode(scratch_space);
        let automaton = PrefixOf::new(scratch_space.as_slice());
        let mut longest_prefix = self.len() - 1;
        let mut stream = self.map.search(automaton).into_stream();
        while let Some((_, v)) = stream.next() {
            longest_prefix = v as usize;
        }
        longest_prefix
    }
}

/// Builder for [`FileSetConfig`].
#[derive(Default)]
pub struct FileSetConfigBuilder {
    roots: Vec<Vec<VfsPath>>,
}

impl FileSetConfigBuilder {
    /// Returns the number of sets currently held.
    pub fn len(&self) -> usize {
        self.roots.len()
    }

    /// Add a new set of paths prefixes.
    pub fn add_file_set(&mut self, roots: Vec<VfsPath>) {
        self.roots.push(roots);
    }

    /// Build the `FileSetConfig`.
    pub fn build(self) -> FileSetConfig {
        let n_file_sets = self.roots.len() + 1;
        let map = {
            let mut entries = Vec::new();
            for (i, paths) in self.roots.into_iter().enumerate() {
                for p in paths {
                    let mut buf = Vec::new();
                    p.encode(&mut buf);
                    entries.push((buf, i as u64));
                }
            }
            entries.sort();
            entries.dedup_by(|(a, _), (b, _)| a == b);
            fst::Map::from_iter(entries).unwrap()
        };
        FileSetConfig { n_file_sets, map }
    }
}

/// Implements [`fst::Automaton`]
///
/// It will match if `prefix_of` is a prefix of the given data.
struct PrefixOf<'a> {
    prefix_of: &'a [u8],
}

impl<'a> PrefixOf<'a> {
    /// Creates a new `PrefixOf` from the given slice.
    fn new(prefix_of: &'a [u8]) -> Self {
        Self { prefix_of }
    }
}

impl fst::Automaton for PrefixOf<'_> {
    type State = usize;
    fn start(&self) -> usize {
        0
    }
    fn is_match(&self, &state: &usize) -> bool {
        state != !0
    }
    fn can_match(&self, &state: &usize) -> bool {
        state != !0
    }
    fn accept(&self, &state: &usize, byte: u8) -> usize {
        if self.prefix_of.get(state) == Some(&byte) {
            state + 1
        } else {
            !0
        }
    }
}

#[cfg(test)]
mod tests;
ug)] pub struct SsrPattern { parsed_rules: Vec<parsing::ParsedRule>, } #[derive(Debug, Default)] pub struct SsrMatches { pub matches: Vec<Match>, } /// Searches a crate for pattern matches and possibly replaces them with something else. pub struct MatchFinder<'db> { /// Our source of information about the user's code. sema: Semantics<'db, ide_db::RootDatabase>, rules: Vec<ResolvedRule<'db>>, resolution_scope: resolving::ResolutionScope<'db>, restrict_ranges: Vec<ide_db::FileRange>, } impl<'db> MatchFinder<'db> { /// Constructs a new instance where names will be looked up as if they appeared at /// `lookup_context`. pub fn in_context( db: &'db RootDatabase, lookup_context: ide_db::FilePosition, mut restrict_ranges: Vec<ide_db::FileRange>, ) -> Result<MatchFinder<'db>, SsrError> { restrict_ranges.retain(|range| !range.range.is_empty()); let sema = Semantics::new(db); let file_id = sema .attach_first_edition(lookup_context.file_id) .unwrap_or_else(|| EditionedFileId::current_edition(db, lookup_context.file_id)); let resolution_scope = resolving::ResolutionScope::new( &sema, hir::FilePosition { file_id, offset: lookup_context.offset }, ) .ok_or_else(|| SsrError("no resolution scope for file".into()))?; Ok(MatchFinder { sema, rules: Vec::new(), resolution_scope, restrict_ranges }) } /// Constructs an instance using the start of the first file in `db` as the lookup context. pub fn at_first_file(db: &'db ide_db::RootDatabase) -> Result<MatchFinder<'db>, SsrError> { if let Some(first_file_id) = db .local_roots() .iter() .next() .and_then(|root| db.source_root(*root).source_root(db).iter().next()) { MatchFinder::in_context( db, ide_db::FilePosition { file_id: first_file_id, offset: 0.into() }, vec![], ) } else { bail!("No files to search"); } } /// Adds a rule to be applied. The order in which rules are added matters. Earlier rules take /// precedence. If a node is matched by an earlier rule, then later rules won't be permitted to /// match to it. pub fn add_rule(&mut self, rule: SsrRule) -> Result<(), SsrError> { for parsed_rule in rule.parsed_rules { self.rules.push(ResolvedRule::new( parsed_rule, &self.resolution_scope, self.rules.len(), )?); } Ok(()) } /// Finds matches for all added rules and returns edits for all found matches. pub fn edits(&self) -> FxHashMap<FileId, TextEdit> { let mut matches_by_file = FxHashMap::default(); for m in self.matches().matches { matches_by_file .entry(m.range.file_id.file_id(self.sema.db)) .or_insert_with(SsrMatches::default) .matches .push(m); } matches_by_file .into_iter() .map(|(file_id, matches)| { ( file_id, replacing::matches_to_edit( self.sema.db, &matches, self.sema.db.file_text(file_id).text(self.sema.db), &self.rules, ), ) }) .collect() } /// Adds a search pattern. For use if you intend to only call `find_matches_in_file`. If you /// intend to do replacement, use `add_rule` instead. pub fn add_search_pattern(&mut self, pattern: SsrPattern) -> Result<(), SsrError> { for parsed_rule in pattern.parsed_rules { self.rules.push(ResolvedRule::new( parsed_rule, &self.resolution_scope, self.rules.len(), )?); } Ok(()) } /// Returns matches for all added rules. pub fn matches(&self) -> SsrMatches { let mut matches = Vec::new(); let mut usage_cache = search::UsageCache::default(); for rule in &self.rules { self.find_matches_for_rule(rule, &mut usage_cache, &mut matches); } nester::nest_and_remove_collisions(matches, &self.sema) } /// Finds all nodes in `file_id` whose text is exactly equal to `snippet` and attempts to match /// them, while recording reasons why they don't match. This API is useful for command /// line-based debugging where providing a range is difficult. pub fn debug_where_text_equal( &self, file_id: EditionedFileId, snippet: &str, ) -> Vec<MatchDebugInfo> { let file = self.sema.parse(file_id); let mut res = Vec::new(); let file_text = self.sema.db.file_text(file_id.file_id(self.sema.db)).text(self.sema.db); let mut remaining_text = &**file_text; let mut base = 0; let len = snippet.len() as u32; while let Some(offset) = remaining_text.find(snippet) { let start = base + offset as u32; let end = start + len; self.output_debug_for_nodes_at_range( file.syntax(), FileRange { file_id, range: TextRange::new(start.into(), end.into()) }, &None, &mut res, ); remaining_text = &remaining_text[offset + snippet.len()..]; base = end; } res } fn output_debug_for_nodes_at_range( &self, node: &SyntaxNode, range: FileRange, restrict_range: &Option<FileRange>, out: &mut Vec<MatchDebugInfo>, ) { for node in node.children() { let node_range = self.sema.original_range(&node); if node_range.file_id != range.file_id || !node_range.range.contains_range(range.range) { continue; } if node_range.range == range.range { for rule in &self.rules { // For now we ignore rules that have a different kind than our node, otherwise // we get lots of noise. If at some point we add support for restricting rules // to a particular kind of thing (e.g. only match type references), then we can // relax this. We special-case expressions, since function calls can match // method calls. if rule.pattern.node.kind() != node.kind() && !(ast::Expr::can_cast(rule.pattern.node.kind()) && ast::Expr::can_cast(node.kind())) { continue; } out.push(MatchDebugInfo { matched: matching::get_match(true, rule, &node, restrict_range, &self.sema) .map_err(|e| MatchFailureReason { reason: e.reason.unwrap_or_else(|| { "Match failed, but no reason was given".to_owned() }), }), pattern: rule.pattern.node.clone(), node: node.clone(), }); } } else if let Some(macro_call) = ast::MacroCall::cast(node.clone()) && let Some(expanded) = self.sema.expand_macro_call(&macro_call) && let Some(tt) = macro_call.token_tree() { self.output_debug_for_nodes_at_range( &expanded.value, range, &Some(self.sema.original_range(tt.syntax())), out, ); } self.output_debug_for_nodes_at_range(&node, range, restrict_range, out); } } } pub struct MatchDebugInfo { node: SyntaxNode, /// Our search pattern parsed as an expression or item, etc pattern: SyntaxNode, matched: Result<Match, MatchFailureReason>, } impl std::fmt::Debug for MatchDebugInfo { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.matched { Ok(_) => writeln!(f, "Node matched")?, Err(reason) => writeln!(f, "Node failed to match because: {}", reason.reason)?, } writeln!( f, "============ AST ===========\n\ {:#?}", self.node )?; writeln!(f, "========= PATTERN ==========")?; writeln!(f, "{:#?}", self.pattern)?; writeln!(f, "============================")?; Ok(()) } } impl SsrMatches { /// Returns `self` with any nested matches removed and made into top-level matches. pub fn flattened(self) -> SsrMatches { let mut out = SsrMatches::default(); self.flatten_into(&mut out); out } fn flatten_into(self, out: &mut SsrMatches) { for mut m in self.matches { for p in m.placeholder_values.values_mut() { std::mem::take(&mut p.inner_matches).flatten_into(out); } out.matches.push(m); } } } impl Match { pub fn matched_text(&self) -> String { self.matched_node.text().to_string() } } impl std::error::Error for SsrError {} #[cfg(test)] impl MatchDebugInfo { pub fn match_failure_reason(&self) -> Option<&str> { self.matched.as_ref().err().map(|r| r.reason.as_str()) } }