echoes 0.10.2

Find duplicated Rust doctests, functions and contexts
Documentation
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! Persistent dependency indexes partitioned by source privacy.

use crate::context_index::IndexedContext;
use alloc::collections::BTreeMap;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use std::io::Write;
use std::path::{Path, PathBuf};

/// Bumped when the stored entry layout changes.
pub(crate) const SCHEMA: u32 = 3;

/// A package index loaded from the store.
#[derive(Debug, serde::Deserialize)]
pub(crate) struct Stored {
    pub(crate) schema: u32,
    pub(crate) canonicalization: String,
    /// Content blake3 of each source input, keyed by package-relative path.
    /// Mutable entries include the package manifest under `Cargo.toml`.
    pub(crate) files: BTreeMap<String, String>,
    pub(crate) records: Vec<IndexedContext>,
}

#[derive(serde::Serialize)]
struct Entry<'a> {
    schema: u32,
    canonicalization: &'a str,
    files: &'a BTreeMap<String, String>,
    records: &'a [IndexedContext],
}

/// The outcome of a cache lookup.
#[derive(Debug)]
pub(crate) enum Load {
    /// An intact entry, validated by the caller.
    Stored(Stored),
    /// No entry yet.
    Missing,
    /// An unreadable or unparseable entry, safe to rebuild over.
    Corrupt,
    /// An I/O problem, the entry may be intact.
    Io(std::io::Error),
}

/// Package indexes under one cache directory.
pub(crate) struct Store {
    root: PathBuf,
}

impl Store {
    /// The per-user cache directory, honoring `XDG_CACHE_HOME`.
    pub(crate) fn default_root() -> PathBuf {
        match std::env::var_os("XDG_CACHE_HOME") {
            Some(dir) if !dir.is_empty() => PathBuf::from(dir).join("echoes"),
            _ => {
                let home = std::env::var_os("HOME").map_or_else(PathBuf::new, PathBuf::from);
                home.join(".cache").join("echoes")
            }
        }
    }

    /// Open `root`, creating it when absent.
    pub(crate) fn open(root: &Path) -> std::io::Result<Self> {
        std::fs::create_dir_all(root)?;
        Ok(Self {
            root: root.to_path_buf(),
        })
    }

    /// Load the entry under `dir`/`name.json`.
    pub(crate) fn load(&self, dir: &str, name: &str) -> Load {
        let path = self.root.join(dir).join(format!("{name}.json"));
        match std::fs::read(&path) {
            Ok(bytes) => match serde_json::from_slice::<Stored>(&bytes) {
                Ok(stored) => Load::Stored(stored),
                Err(_) => Load::Corrupt,
            },
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Load::Missing,
            Err(err) => Load::Io(err),
        }
    }

    /// Write `records` to `dir`/`name.json`, replacing any entry atomically.
    pub(crate) fn save(
        &self,
        dir: &str,
        name: &str,
        canonicalization: &str,
        files: &BTreeMap<String, String>,
        records: &[IndexedContext],
    ) -> std::io::Result<()> {
        let dir = self.root.join(dir);
        std::fs::create_dir_all(&dir)?;
        let payload = Entry {
            schema: SCHEMA,
            canonicalization,
            files,
            records,
        };
        let target = dir.join(format!("{name}.json"));
        let mut temp = tempfile::NamedTempFile::new_in(dir)?;
        {
            let mut writer = std::io::BufWriter::new(temp.as_file_mut());
            serde_json::to_writer(&mut writer, &payload)?;
            writer.flush()?;
        }
        temp.persist(target).map_err(|error| error.error)?;
        Ok(())
    }
}

/// A file exercising the canonicalizer's rename, drift and context paths.
const SENTINEL: &str = r#"
pub mod alpha {
    use core::mem;
    pub struct Beta {
        pub gamma: u32,
    }
    impl Beta {
        pub fn delta(&self, input: u32) -> u32 {
            let value = input + 1u32;
            match value {
                0 => self.gamma,
                _ => mem::swap(value, 2u32),
            }
        }
    }
    pub fn epsilon(value: u32) -> u32 {
        let zeta: u8 = 0;
        if value > 1u32 { value - 1u32 } else { u32::from(zeta) }
    }
    pub fn reflexive(value: u32) -> bool {
        value == value
    }
    pub fn xor(value: u32) -> u32 {
        value ^ value
    }
    pub fn xor_literal(value: u32) -> u32 {
        value ^ 7 ^ value
    }
    pub fn wrapping(value: u32, other: u32) -> u32 {
        other.wrapping_add(value)
    }
    pub fn selected(flag: bool, value: u32, other: u32) -> u32 {
        match flag {
            false => other,
            true => value,
        }
    }
    pub fn joined() -> &'static str {
        concat!("al", "pha")
    }
    pub fn unset(flag: bool) -> bool {
        flag == false
    }
    pub fn both(flag: bool, other: bool) -> bool {
        if other { flag } else { false }
    }
    pub fn accumulated(mut total: u32, step: u32) -> u32 {
        total += step;
        total
    }
    pub fn counted() -> u32 {
        let start: u32 = 1;
        start
    }
    pub fn scaled(value: u32, other: u32) -> u32 {
        other.saturating_mul(value) * value
    }
    pub fn padded(value: u32) -> u32 {
        (value | 0) * 1
    }
    pub fn armed(flag: bool, other: bool) -> u32 {
        if flag { if other { 1u32 } else { 0u32 } } else { 0u32 }
    }
    pub fn guarded(flag: bool, value: u32) -> u32 {
        if flag { return value; }
        0u32
    }
    pub fn slot(slot: Option<u32>) -> u32 {
        let Some(value) = slot else { return 0u32; };
        match value { 0 => 1u32, 1 => 1u32, _ => value }
    }
    pub fn label() -> String {
        String::from("sentinel")
    }
    pub fn widened(value: u32, flag: bool) -> u64 {
        u64::from(value) + flag as u64
    }
    pub fn picked<'a, T>(values: &'a [T]) -> Option<&'a T> where T: Ord + Copy {
        values.iter().max()
    }
    pub fn copied(value: u32, other: u32) -> bool {
        &value == &other
    }
    pub fn checked(value: u32) -> Option<u32> {
        if value == 0 { return None; }
        Some(value)
    }
    pub fn skipped(values: &[u32], quiet: bool) {
        if quiet { return; }
        for value in values { if *value == 0 { continue; } epsilon(*value); }
        epsilon(0u32);
    }
    pub fn ranked(value: Option<u32>, digit: u8) -> u32 {
        let first = if let Some(found) = value { found } else { 0 };
        match digit { 2 => first, 0 => 1, 1 => first, _ => 9 }
    }
    pub fn trimmed(values: &mut Vec<u32>) {
        let _ = values.pop();
    }
    pub fn bounded(value: u32) -> bool {
        value >= 1 && value <= 9
    }
    pub fn chosen(value: u32, other: u32, flag: bool) -> u32 {
        let bit: u32 = if flag { 1 } else { 0 };
        bit + std::cmp::max(value, other)
    }
    pub fn summed(values: &[u32]) -> u32 {
        let mut sum = 0;
        for value in values.iter() { sum += value; }
        if values.len() == 0 { 1 } else { sum }
    }
    pub fn worded(value: u32) -> String {
        println!("{} {}", "value", value);
        if value == 0 { String::from("") } else { format!("set") }
    }
    pub fn boxed(value: u32) -> Box<dyn core::fmt::Debug + Send + Sync> {
        Box::new(value)
    }
    pub struct Held<'a>(pub &'a u32);
    impl<'a> Held<'a> {
        pub fn get(&self) -> u32 { *self.0 }
    }
    pub fn bucket(id: u32) -> u32 {
        (id / 16 % 8) as u32 + (b'a' as u32) - u8::MAX as u32
    }
    pub fn small(value: u32) -> bool {
        matches!(value, 1 | 3..=5) || (7..=9).contains(&value)
    }
    pub fn coded(flag: bool) -> u8 {
        if flag { return 2 + 3; }
        if flag { 1 } else { 0 }
    }
    pub fn shifted(value: u32) -> u32 {
        let width = 2u32 * 4u32;
        return value << width;
    }
}
mod custom {
    macro_rules! vec {
        (1) => { 10u32 };
        (1,) => { 20u32 };
    }
    pub(crate) use vec;
}
fn tail_scope() -> u32 {
    let value = std::cell::RefCell::new(7u32);
    return *value.borrow();
}
fn main() {
    let beta = alpha::Beta { gamma: 3u32 };
    beta.delta(1u32);
    alpha::epsilon(2u32);
    custom::vec!(1,);
}
"#;

/// A fingerprint of canonicalization output and the crate version.
pub(crate) fn canonicalization_fingerprint() -> String {
    let file = syn::parse_file(SENTINEL).expect("the sentinel source parses");
    let tokens = syn_canon::canonicalize(file).to_string();
    format!(
        "{}:{}",
        blake3::hash(tokens.as_bytes()).to_hex(),
        env!("CARGO_PKG_VERSION")
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::borrow::ToOwned;

    fn records(n: usize) -> Vec<IndexedContext> {
        (0..n)
            .map(|i| IndexedContext {
                form: format!("form-{i}"),
                tokens: i + 1,
                site: crate::ContextSite {
                    file: "src/lib.rs".to_owned(),
                    line: u32::try_from(i).unwrap_or(u32::MAX) + 1,
                    column: 1,
                    end: u32::try_from(i).unwrap_or(u32::MAX) + 2,
                    end_column: 2,
                    item: format!("pkg::f{i}"),
                    kind: crate::ContextKind::FunctionBody,
                },
                module: format!("pkg::f{i}"),
                crate_name: "pkg".to_owned(),
                crate_root: "/tmp/pkg/src/lib.rs".to_owned(),
                access: crate::ContextAccess::PublicFunction,
                conditions: Vec::new(),
                extraction_notes: Vec::new(),
                api_path: None,
            })
            .collect()
    }

    fn map(n: usize) -> BTreeMap<String, String> {
        (0..n)
            .map(|i| (format!("src/f{i}.rs"), format!("hash-{i}")))
            .collect()
    }

    #[test]
    fn save_then_load_round_trips() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).unwrap();
        let records = records(3);
        store
            .save(
                "public/crates.io",
                "alpha-1.0.0",
                &canonicalization_fingerprint(),
                &map(3),
                &records,
            )
            .unwrap();
        let load = store.load("public/crates.io", "alpha-1.0.0");
        assert!(
            matches!(&load, Load::Stored(stored) if stored.schema == SCHEMA
                && stored.canonicalization == canonicalization_fingerprint()
                && stored.files == map(3)
                && stored.records.len() == 3),
            "{load:?}"
        );
        assert!(matches!(
            store.load("public/crates.io", "alpha-1.0.1"),
            Load::Missing
        ));
        let raw = dir.path().join("public/crates.io/alpha-1.0.0.json");
        assert!(raw.is_file());
        let temp = dir.path().join("public/crates.io/.alpha-1.0.0.json.tmp");
        assert!(!temp.exists(), "temp file must not survive a save");
    }

    #[test]
    fn corrupt_entry_reports_corrupt_and_rebuilds() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).unwrap();
        std::fs::create_dir_all(dir.path().join("private/path-a")).unwrap();
        std::fs::write(dir.path().join("private/path-a/beta.json"), "not json").unwrap();
        let records = records(1);
        store
            .save(
                "private/path-a",
                "beta",
                &canonicalization_fingerprint(),
                &map(1),
                &records,
            )
            .unwrap();
        assert!(matches!(
            store.load("private/path-a", "beta"),
            Load::Stored(stored) if stored.schema == SCHEMA
        ));
    }

    #[test]
    fn truncated_entry_reports_corrupt() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).unwrap();
        let records = records(1);
        store
            .save(
                "private/path-a",
                "beta",
                &canonicalization_fingerprint(),
                &map(1),
                &records,
            )
            .unwrap();
        let path = dir.path().join("private/path-a/beta.json");
        let bytes = std::fs::read(&path).unwrap();
        std::fs::write(&path, &bytes[..bytes.len() / 2]).unwrap();
        assert!(matches!(
            store.load("private/path-a", "beta"),
            Load::Corrupt
        ));
    }

    #[test]
    fn save_replaces_an_existing_entry() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).unwrap();
        let one = records(1);
        store
            .save("public/crates.io", "alpha-1.0.0", "c1", &map(1), &one)
            .unwrap();
        let two = records(2);
        store
            .save("public/crates.io", "alpha-1.0.0", "c2", &map(2), &two)
            .unwrap();
        let load = store.load("public/crates.io", "alpha-1.0.0");
        assert!(
            matches!(&load, Load::Stored(stored) if stored.canonicalization == "c2"
                && stored.records.len() == 2),
            "{load:?}"
        );
    }
    #[test]
    fn a_directory_where_the_entry_lives_reports_io() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(dir.path()).unwrap();
        std::fs::create_dir_all(dir.path().join("public/crates.io/alpha.json")).unwrap();
        assert!(matches!(
            store.load("public/crates.io", "alpha"),
            Load::Io(err) if matches!(err.kind(), std::io::ErrorKind::IsADirectory)
        ));
    }

    #[test]
    fn the_sentinel_source_parses() {
        assert!(syn::parse_file(SENTINEL).is_ok());
    }

    #[test]
    fn default_root_honors_the_xdg_cache_home() {
        if std::env::var_os("ECHOES_COV_XDG_PROBE").is_some() {
            let home = std::env::var_os("XDG_CACHE_HOME").expect("the probe run sets the variable");
            assert_eq!(Store::default_root(), PathBuf::from(home).join("echoes"));
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let output =
            std::process::Command::new(std::env::current_exe().expect("the test binary path"))
                .env("ECHOES_COV_XDG_PROBE", "1")
                .env("XDG_CACHE_HOME", dir.path())
                .arg("context_cache::tests::default_root_honors_the_xdg_cache_home")
                .arg("--exact")
                .output()
                .expect("the test binary runs itself");
        assert!(
            output.status.success(),
            "the probe run failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    /// An empty `XDG_CACHE_HOME` falls back to the home cache directory.
    #[test]
    fn default_root_ignores_an_empty_xdg_cache_home() {
        if std::env::var_os("ECHOES_COV_XDG_EMPTY_PROBE").is_some() {
            let home = std::env::var_os("HOME").expect("the probe run sets the variable");
            assert_eq!(
                Store::default_root(),
                PathBuf::from(home).join(".cache").join("echoes")
            );
            return;
        }
        let home = tempfile::tempdir().unwrap();
        let output =
            std::process::Command::new(std::env::current_exe().expect("the test binary path"))
                .env("ECHOES_COV_XDG_EMPTY_PROBE", "1")
                .env("XDG_CACHE_HOME", "")
                .env("HOME", home.path())
                .arg("context_cache::tests::default_root_ignores_an_empty_xdg_cache_home")
                .arg("--exact")
                .output()
                .expect("the test binary runs itself");
        let text = format!(
            "{}{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(output.status.success(), "the probe run failed: {text}");
    }
}