starmap-cli 0.3.0

The starmap command, which checks, explains, compares and runs an application's declared environment
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
//! The scan of an application's `src` directory for the environment
//! variables that its code reads, which `starmap init` guesses from and
//! `starmap check` compares with the spec.
//!
//! The scan splits each `.rs` file into Rust tokens with proc-macro2 and
//! looks for one shape: the word `var`, `var_os` or `starmap` followed by
//! parentheses that hold only a string literal, such as
//! `std::env::var("SHELF_PORT")` or the derive's field attribute
//! `#[starmap("SHELF_PORT")]`. After `starmap`, the literal may be followed
//! by `, check = <path>`, as in `#[starmap("SHELF_PORT", check = unprivileged)]`,
//! and the scan records that the field names a check.
//!
//! After `var` or `var_os`, the parentheses may instead hold a `format!`
//! call, with or without a leading `&` and a path such as `std::format!`,
//! whose first argument is a string literal. The scan reads the literal as
//! `format!` does: `{{` and `}}` are braces, and any other `{...}` is a
//! placeholder. A literal that is a variable name, an underscore and one
//! placeholder at the end, such as `"SHELF_DB_URL_{region}"`, reads a
//! member of the family with that prefix. A literal without a placeholder
//! reads the name it holds. Any other literal, such as one that starts with
//! a placeholder, has one in the middle or has two, is unresolved, and the
//! scan records only its place. A field attribute's `format!` is not a
//! read.
//!
//! The scan also counts a variable that clap reads for the application. In
//! an attribute `#[arg(...)]` or `#[clap(...)]`, an argument `env = "NAME"`
//! with a string literal reads `NAME`, as in
//! `#[arg(long, env = "SHELF_PORT")]`. A bare `env`, as in
//! `#[arg(long, env)]`, reads the upper-case form of the name of the field
//! that follows the attribute, after any other attribute and a visibility,
//! so the field `shelf_port` reads `SHELF_PORT`. clap names the variable
//! the same way for a field name in lower case with single underscores
//! between its words. The place of either read is the line of the word
//! `env`.
//!
//! It looks inside every bracket, so a read
//! inside a macro call counts, and comments are not tokens, so a name in a
//! comment does not. A word after a `.` is a method of some other type, so
//! `ctx.var("X")` does not count. A full parse with syn would add nothing
//! that this shape needs, because the scan never asks what an expression
//! means.
//!
//! The scan leaves out test code, because a test may read a variable that
//! the application never reads. It skips each file named `tests.rs` or
//! ending in `_tests.rs`, where the Rust standards put unit tests, the
//! item that follows `#[cfg(test)]`, up to its closing brace, a semicolon
//! or a comma, and the rest of a module after `#![cfg(test)]`, so a file
//! that begins with `#![cfg(test)]` is skipped whole. The comma ends a
//! test-only field, variant, match arm or argument. Angle brackets are not
//! token groups, so any comma outside brackets in a test-only item's header
//! ends the skip too: in a function's generics such as `fn f<A, B>()`, in
//! a return type such as `-> Result<(), E>`, in `impl<A, B>`, in a `where`
//! clause, or in a `static` whose type is generic. The reads in the rest of
//! that item then count, so the scan over-counts them, and `check` reports
//! each one that the spec does not declare. The skip knows only the exact
//! attribute `cfg(test)`, so code under `cfg(all(test, unix))` counts.
//!
//! The scan misses a read whose name is not a literal or a `format!` at the
//! call, such as `env::var(NAME)` with a constant, a name built with
//! `concat!`, `+` or `push_str`, and every lookup in the map that
//! `std::env::vars_os` returns. It misses a clap `env` whose value is not
//! a string literal, such as `#[arg(env = NAME)]` with a constant, and one
//! inside `cfg_attr`. It misses a clap `env` whose literal is not a valid
//! starmap name, such as `env = "lower_case"`, although clap reads that
//! variable. It reads a bare clap `env` under the wrong name when
//! clap does not name the variable after the field in upper case: when the
//! attribute sets `id`, when the struct sets `rename_all_env`, and when
//! the field name has a leading, trailing or doubled underscore or an
//! upper-case letter, which clap's word splitting changes. It also misses
//! a variable that any other library reads for the application, and a
//! reader that matches names by prefix. It counts any call of a function
//! named `var` or `var_os` with a literal name, including one from another
//! crate, and any attribute named `arg` or `clap` with an `env` argument.
//! `starmap check` then reports a missed variable as declared and
//! unread, and a miscounted one as undeclared. The application's own
//! `starmap_test::check` test still compares the derived struct with the
//! spec.

use std::collections::BTreeMap;
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use std::str::FromStr as _;

use crumbkit::{Failure, Recovery};
use proc_macro2::{Delimiter, Group, TokenStream, TokenTree};
use starmap::Name;

use crate::codes::SOURCE_UNREADABLE;
use crate::files;

#[cfg(test)]
mod tests;

/// The most bytes of one source file that the scan reads. A larger file,
/// such as generated bindings, fails with `starmap::source::unreadable`,
/// so it costs at most this much memory (BASE-34). The scan does not skip
/// such a file, because a skipped file could hide a read.
const MAX_SOURCE_BYTES: usize = 1024 * 1024;

/// The words that read a variable when a string literal in parentheses
/// follows them: the two functions of `std::env` and the field attribute of
/// `#[derive(starmap::Env)]`.
const READERS: &[&str] = &["var", "var_os", "starmap"];

/// Each variable that the source reads, with the places that read it, such
/// as `src/serve.rs:22`, in the order of the files and their lines.
pub(crate) type Reads = BTreeMap<Name, Vec<String>>;

/// What a scan finds: the reads, each variable whose field attribute names
/// a check, with the first place that names it, the family reads and the
/// unresolved reads.
#[derive(Debug, Default)]
pub(crate) struct Scanned {
    /// Each variable that the source reads.
    pub(crate) reads: Reads,
    /// Each variable that a `#[starmap("NAME", check = <path>)]` field
    /// attribute reads, with its first place.
    pub(crate) checks: BTreeMap<Name, String>,
    /// Each family prefix whose members the source reads through a
    /// `format!` name, with the places that read it.
    pub(crate) families: Reads,
    /// The place of each read whose `format!` name the scan cannot
    /// resolve, in the order of the files and their lines.
    pub(crate) unresolved: Vec<String>,
}

/// What one read names.
#[derive(Debug)]
enum Target {
    /// The variable that a literal names.
    Variable(Name),
    /// A member of the family with this prefix, which a `format!` name
    /// with one trailing placeholder reads.
    Family(Name),
    /// A `format!` name that the scan cannot resolve.
    Unresolved,
}

/// One read in a file: what it names, the line of the word that reads it,
/// and whether it is a field attribute that names a check.
#[derive(Debug)]
struct Read {
    /// What the read names.
    target: Target,
    /// The line of the word that reads it.
    line: usize,
    /// Whether a `check = <path>` follows the name.
    checked: bool,
}

/// Reads every `.rs` file under each directory of `dirs`, as [`scan`]
/// does, and returns the reads of all of them. A variable that several
/// directories read lists the places of each directory in turn.
///
/// # Errors
///
/// Returns [`SourceFailure`] as [`scan`] does for any of the directories.
pub(crate) fn scan_all(dirs: &[PathBuf]) -> Result<Scanned, SourceFailure> {
    let mut all = Scanned::default();
    for dir in dirs {
        let scanned = scan(dir)?;
        for (name, places) in scanned.reads {
            all.reads.entry(name).or_default().extend(places);
        }
        for (name, at) in scanned.checks {
            all.checks.entry(name).or_insert(at);
        }
        for (prefix, places) in scanned.families {
            all.families.entry(prefix).or_default().extend(places);
        }
        all.unresolved.extend(scanned.unresolved);
    }
    Ok(all)
}

/// The source directories of a scan, which print as `src`, as `src and
/// bin` when there are several, and as `no source directory` when a
/// pointer lists none.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Dirs<'a>(pub(crate) &'a [PathBuf]);

impl Dirs<'_> {
    /// Returns whether there is no directory, so the scan reads nothing.
    pub(crate) fn is_empty(self) -> bool {
        self.0.is_empty()
    }

    /// Returns `one` when there is one directory, and `several` otherwise,
    /// so a sentence agrees with the directories it names.
    pub(crate) fn verb(self, one: &'static str, several: &'static str) -> &'static str {
        if self.0.len() == 1 { one } else { several }
    }
}

impl fmt::Display for Dirs<'_> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let names: Vec<String> = self.0.iter().map(|dir| dir.display().to_string()).collect();
        match names.split_last() {
            None => formatter.write_str("no source directory"),
            Some((last, [])) => formatter.write_str(last),
            Some((last, rest)) => write!(formatter, "{} and {last}", rest.join(", ")),
        }
    }
}

/// Reads every `.rs` file under `src` and returns the variables that they
/// read. A missing `src` has no reads. Each place names its file by `src`
/// joined with the file's path below it.
///
/// # Errors
///
/// Returns [`SourceFailure`] for a directory or file that cannot be read,
/// a file over 1 MiB, and a file that is not UTF-8 text or not Rust tokens.
pub(crate) fn scan(src: &Path) -> Result<Scanned, SourceFailure> {
    let paths = match files::rust_files(src) {
        Ok(paths) => paths,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Scanned::default()),
        Err(error) => return Err(SourceFailure::new(src, format!("cannot be read: {error}"))),
    };
    let mut scanned = Scanned::default();
    for path in paths.into_iter().filter(|path| !is_test_file(path)) {
        let bytes = files::read_capped(&path, MAX_SOURCE_BYTES + 1)
            .map_err(|error| SourceFailure::new(&path, format!("cannot be read: {error}")))?;
        if bytes.len() > MAX_SOURCE_BYTES {
            return Err(SourceFailure::too_large(&path));
        }
        let text = String::from_utf8(bytes)
            .map_err(|_| SourceFailure::new(&path, "is not UTF-8 text".to_owned()))?;
        let lines = lines_of_reads(&text).map_err(|error| {
            let line = error.span().start().line;
            SourceFailure::new(&path, format!("is not valid Rust at line {line}"))
        })?;
        for Read {
            target,
            line,
            checked,
        } in lines
        {
            let place = format!("{}:{line}", path.display());
            match target {
                Target::Variable(name) => {
                    if checked {
                        scanned
                            .checks
                            .entry(name.clone())
                            .or_insert_with(|| place.clone());
                    }
                    scanned.reads.entry(name).or_default().push(place);
                }
                Target::Family(prefix) => {
                    scanned.families.entry(prefix).or_default().push(place);
                }
                Target::Unresolved => scanned.unresolved.push(place),
            }
        }
    }
    Ok(scanned)
}

/// Returns each read in the Rust source `text`, in the order of the text.
///
/// # Errors
///
/// Returns proc-macro2's error for text that is not Rust tokens, such as an
/// unclosed bracket or string.
fn lines_of_reads(text: &str) -> Result<Vec<Read>, proc_macro2::LexError> {
    let mut reads = Vec::new();
    collect(TokenStream::from_str(text)?, &mut reads);
    Ok(reads)
}

/// Reports whether `path` names a file of unit tests: `tests.rs`, or a
/// name that ends in `_tests.rs`.
fn is_test_file(path: &Path) -> bool {
    path.file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| name == "tests.rs" || name.ends_with("_tests.rs"))
}

/// Adds each read in `tokens`, and in every bracket inside them, to
/// `reads`. It skips the item that follows `#[cfg(test)]`, and the rest of
/// the stream after an inner `#![cfg(test)]`.
fn collect(tokens: TokenStream, reads: &mut Vec<Read>) {
    let mut before_previous: Option<TokenTree> = None;
    let mut previous: Option<TokenTree> = None;
    let mut reader = None;
    let mut bare_env = None;
    let mut in_test_item = false;
    for token in tokens {
        if in_test_item {
            in_test_item = !ends_item(&token);
            continue;
        }
        if let TokenTree::Group(group) = &token
            && is_cfg_test(group)
        {
            if is_punct(previous.as_ref(), '#') {
                in_test_item = true;
                previous = None;
                bare_env = None;
                continue;
            }
            // An inner `#![cfg(test)]` makes the rest of its module test
            // code.
            if is_punct(previous.as_ref(), '!') && is_punct(before_previous.as_ref(), '#') {
                return;
            }
        }
        if let TokenTree::Group(group) = &token {
            if let Some((line, attribute)) = reader
                && group.delimiter() == Delimiter::Parenthesis
                && let Some((target, checked)) = read_in(group.stream(), attribute)
            {
                reads.push(Read {
                    target,
                    line,
                    checked,
                });
            }
            if group.delimiter() == Delimiter::Bracket
                && is_punct(previous.as_ref(), '#')
                && let Some((env, line)) = clap_env(group.stream())
            {
                match env {
                    ClapEnv::Named(name) => reads.push(Read {
                        target: Target::Variable(name),
                        line,
                        checked: false,
                    }),
                    ClapEnv::Field => bare_env = Some(line),
                }
            }
            collect(group.stream(), reads);
        }
        // A bare `env` reads the name of the field that follows its
        // attribute, after any other attribute and a visibility.
        if let Some(line) = bare_env {
            match &token {
                TokenTree::Ident(word) if word != "pub" => {
                    bare_env = None;
                    if let Some(name) = field_env(&word.to_string()) {
                        reads.push(Read {
                            target: Target::Variable(name),
                            line,
                            checked: false,
                        });
                    }
                }
                TokenTree::Ident(_) | TokenTree::Group(_) => {}
                TokenTree::Punct(punct) if punct.as_char() == '#' => {}
                TokenTree::Punct(_) | TokenTree::Literal(_) => bare_env = None,
            }
        }
        reader = match &token {
            TokenTree::Ident(word)
                if READERS.iter().any(|reader| word == reader)
                    && !is_punct(previous.as_ref(), '.') =>
            {
                Some((word.span().start().line, word == "starmap"))
            }
            _ => None,
        };
        before_previous = previous.replace(token);
    }
}

/// What the `env` argument of a clap attribute names.
enum ClapEnv {
    /// The variable that a string literal names, as in `env = "SHELF_PORT"`.
    Named(Name),
    /// The variable that clap names after the field, as in a bare `env`.
    Field,
}

/// Returns what the `env` argument reads, and the line of the word `env`,
/// when `attribute` is the inside of the brackets of `#[arg(...)]` or
/// `#[clap(...)]` and one of its arguments is a bare `env` or `env` with a
/// string literal that is a valid name. Any other value of `env`, such as a
/// constant, is nothing the scan can resolve.
fn clap_env(attribute: TokenStream) -> Option<(ClapEnv, usize)> {
    let mut attribute = attribute.into_iter();
    let (Some(TokenTree::Ident(word)), Some(TokenTree::Group(arguments)), None) =
        (attribute.next(), attribute.next(), attribute.next())
    else {
        return None;
    };
    if !(word == "arg" || word == "clap") || arguments.delimiter() != Delimiter::Parenthesis {
        return None;
    }
    let mut tokens = arguments.stream().into_iter().peekable();
    let mut starts_argument = true;
    while let Some(token) = tokens.next() {
        if starts_argument
            && let TokenTree::Ident(key) = &token
            && key == "env"
        {
            let line = key.span().start().line;
            if tokens.peek().is_none() || is_punct(tokens.peek(), ',') {
                return Some((ClapEnv::Field, line));
            }
            let (Some(TokenTree::Punct(equals)), Some(TokenTree::Literal(literal))) =
                (tokens.next(), tokens.next())
            else {
                return None;
            };
            if equals.as_char() != '=' || !(tokens.peek().is_none() || is_punct(tokens.peek(), ','))
            {
                return None;
            }
            let written = literal.to_string();
            return Name::from_str(string_text(&written)?)
                .ok()
                .map(|name| (ClapEnv::Named(name), line));
        }
        starts_argument = is_punct(Some(&token), ',');
    }
    None
}

/// Returns the variable that a bare clap `env` reads for the field named
/// `field`: the field's name in upper case, without the `r#` of a raw
/// identifier, when that is a valid name.
fn field_env(field: &str) -> Option<Name> {
    let field = field.strip_prefix("r#").unwrap_or(field);
    Name::from_str(&field.to_uppercase()).ok()
}

/// Reports whether `token` is the punctuation `character`.
fn is_punct(token: Option<&TokenTree>, character: char) -> bool {
    matches!(token, Some(TokenTree::Punct(punct)) if punct.as_char() == character)
}

/// Reports whether an attribute's brackets hold `cfg(test)`.
fn is_cfg_test(group: &Group) -> bool {
    group.delimiter() == Delimiter::Bracket
        && group.stream().to_string().replace(' ', "") == "cfg(test)"
}

/// Reports whether `token` ends an item: its braces, a semicolon, or the
/// comma after a field, a variant, a match arm or an argument. The end of
/// the enclosing bracket ends the item too, because the stream ends there.
fn ends_item(token: &TokenTree) -> bool {
    match token {
        TokenTree::Group(group) => group.delimiter() == Delimiter::Brace,
        TokenTree::Punct(punct) => matches!(punct.as_char(), ';' | ','),
        TokenTree::Ident(_) | TokenTree::Literal(_) => false,
    }
}

/// Returns what the parentheses after a reader read: the name of a string
/// literal, or, outside a field attribute, the target of a `format!` call.
/// The flag says whether a field attribute names a check.
fn read_in(tokens: TokenStream, attribute: bool) -> Option<(Target, bool)> {
    if let Some((name, checked)) = literal_name(tokens.clone(), attribute) {
        return Some((Target::Variable(name), checked));
    }
    if attribute {
        return None;
    }
    formatted(tokens).map(|target| (target, false))
}

/// Returns the target of a read when `tokens` are one `format!` call, with
/// or without a leading `&`, a path such as `std::format!` and a trailing
/// comma, whose first argument is a string literal.
fn formatted(tokens: TokenStream) -> Option<Target> {
    let mut tokens = tokens.into_iter().peekable();
    if is_punct(tokens.peek(), '&') {
        tokens.next();
    }
    let mut last = None;
    loop {
        match tokens.next()? {
            TokenTree::Ident(word) => last = Some(word),
            TokenTree::Punct(punct) if punct.as_char() == ':' => {}
            TokenTree::Punct(punct) if punct.as_char() == '!' => break,
            _ => return None,
        }
    }
    if !last.is_some_and(|word| word == "format") {
        return None;
    }
    let Some(TokenTree::Group(arguments)) = tokens.next() else {
        return None;
    };
    match (tokens.next(), tokens.next()) {
        (None, _) => {}
        (Some(TokenTree::Punct(comma)), None) if comma.as_char() == ',' => {}
        _ => return None,
    }
    let Some(TokenTree::Literal(literal)) = arguments.stream().into_iter().next() else {
        return None;
    };
    let text = string_text(&literal.to_string())?.to_owned();
    Some(target_of(&text))
}

/// Returns what a `format!` literal whose text is `text` reads: a family
/// when it is a name, an underscore and one trailing placeholder, the name
/// itself when it has no placeholder, and nothing the scan can resolve
/// otherwise.
fn target_of(text: &str) -> Target {
    let Some((literal, placeholders)) = pattern(text) else {
        return Target::Unresolved;
    };
    let resolved = match placeholders.as_slice() {
        [] => Name::from_str(&literal).ok().map(Target::Variable),
        [at] if *at == literal.len() => literal
            .strip_suffix('_')
            .and_then(|prefix| Name::from_str(prefix).ok())
            .map(Target::Family),
        _ => None,
    };
    resolved.unwrap_or(Target::Unresolved)
}

/// Splits a `format!` literal's `text` as `format!` reads it: the literal
/// text, with `{{` and `}}` as single braces, and the byte offset in that
/// text of each placeholder. Returns `None` for a lone `}` or an unclosed
/// `{`, which `format!` refuses.
fn pattern(text: &str) -> Option<(String, Vec<usize>)> {
    let mut literal = String::new();
    let mut placeholders = Vec::new();
    let mut chars = text.chars().peekable();
    while let Some(character) = chars.next() {
        match character {
            '{' if chars.peek() == Some(&'{') => {
                chars.next();
                literal.push('{');
            }
            '{' => {
                chars.by_ref().find(|&inner| inner == '}')?;
                placeholders.push(literal.len());
            }
            '}' if chars.next_if_eq(&'}').is_some() => literal.push('}'),
            '}' => return None,
            other => literal.push(other),
        }
    }
    Some((literal, placeholders))
}

/// Returns the text between the quotes of a string literal as Rust writes
/// it, `"..."` or a raw string's `r#"..."#`, or `None` for any other
/// literal. Escapes stay as written, so a text with one is no name.
fn string_text(written: &str) -> Option<&str> {
    let text = written
        .strip_prefix('r')
        .unwrap_or(written)
        .trim_matches('#');
    text.strip_prefix('"')?.strip_suffix('"')
}

/// Returns the variable name that `tokens` hold when they are one string
/// literal, with or without a trailing comma, whose text is a valid name.
/// When `attribute` is set, the tokens are a field attribute's, and the
/// literal may be followed by `, check = <path>`; the returned flag says
/// whether it is.
fn literal_name(tokens: TokenStream, attribute: bool) -> Option<(Name, bool)> {
    let mut tokens = tokens.into_iter();
    let Some(TokenTree::Literal(literal)) = tokens.next() else {
        return None;
    };
    let checked = match (tokens.next(), tokens.next()) {
        (None, _) => false,
        (Some(TokenTree::Punct(comma)), None) if comma.as_char() == ',' => false,
        (Some(TokenTree::Punct(comma)), Some(TokenTree::Ident(key)))
            if attribute && comma.as_char() == ',' && key == "check" =>
        {
            true
        }
        _ => return None,
    };
    // A name holds no quote and no backslash, so its literal is the name
    // between quotes, or between a raw string's `r`, hashes and quotes.
    let name = string_text(&literal.to_string())?.to_owned();
    Name::from_str(&name).ok().map(|name| (name, checked))
}

/// A source file or directory that the scan cannot read.
#[derive(Debug, Failure)]
pub(crate) enum SourceFailure {
    /// The path cannot be read, or is not UTF-8 text or valid Rust.
    #[failure(
        code = SOURCE_UNREADABLE,
        hint = "fix {file} so that cargo builds it",
        alternative = Recovery::Hint(format!("move {file} out of src")),
        field(file = file.as_str()),
    )]
    Unbuildable {
        /// The path, as the scan found it.
        file: String,
        /// What is wrong with it, such as `is not valid Rust at line 3`.
        problem: String,
    },
    /// The file is over 1 MiB. Such a file is usually generated and
    /// builds, so its one repair is to move it.
    #[failure(
        code = SOURCE_UNREADABLE,
        hint = "move generated code out of src",
        field(file = file.as_str()),
    )]
    TooLarge {
        /// The path, as the scan found it.
        file: String,
    },
}

impl SourceFailure {
    /// Returns the failure of the file at `path`, which `problem` states.
    fn new(path: &Path, problem: String) -> Self {
        Self::Unbuildable {
            file: path.display().to_string(),
            problem,
        }
    }

    /// Returns the failure of the file at `path`, which is over 1 MiB.
    fn too_large(path: &Path) -> Self {
        Self::TooLarge {
            file: path.display().to_string(),
        }
    }
}

impl fmt::Display for SourceFailure {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unbuildable { file, problem } => write!(formatter, "{file} {problem}"),
            Self::TooLarge { file } => {
                write!(
                    formatter,
                    "{file} is over 1 MiB, so the scan does not read it"
                )
            }
        }
    }
}

impl std::error::Error for SourceFailure {}