panicgraph 0.2.1

Reports which functions can panic, why, and through what call path.
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
//! Rendering of analysis results.

use std::fmt::Write as _;

use anyhow::Result;

use crate::{
    Body, Category, CategorySet, FuncId, Graph, Solution, Terminal,
    args::{Args, Format},
    select::Selection,
    util::Map,
    verify::{Missed, Verdict, Verdicts},
    witness,
};

/// One reported function.
pub(crate) struct Finding<'a> {
    /// The crate the function is defined in.
    pub krate: &'a str,
    /// The name it reports under.
    pub name: &'a str,
    /// Every node that renders under this name. A generic function has one
    /// per instantiation, and they share a source location, so reporting
    /// them separately would print the same line several times.
    pub ids: Vec<FuncId>,
    pub categories: CategorySet,
}

impl Finding<'_> {
    /// The node the report describes the function through.
    fn id(&self) -> FuncId {
        self.ids.first().copied().unwrap_or(FuncId(0))
    }
}

/// Renders the result of an analysis.
///
/// # Errors
///
/// Returns an error if JSON serialisation fails.
pub fn analysis(
    graph: &Graph,
    solution: &Solution,
    args: &Args,
    verdicts: Option<&Verdicts>,
    out: &mut String,
) -> Result<()> {
    let findings = collect(graph, solution, args);
    match args.format {
        Format::Human => {
            human(graph, solution, args, &findings, verdicts, out);
        }
        Format::Json => {
            json(graph, solution, &findings, args, verdicts, out)?;
        }
        Format::Github => github(graph, &findings, args, out),
        // Handled before the report is built, because it draws the tree
        // rather than the list of findings.
        #[cfg(feature = "svg")]
        Format::Svg => {}
    }
    Ok(())
}

/// The artifact's verdict on one finding and category.
///
/// A finding can merge several instantiations of one function; whichever
/// the artifact confirms decides, and only unanimity can call it absent.
fn verdict_of(
    graph: &Graph,
    verdicts: &Verdicts,
    finding: &Finding<'_>,
    category: Category,
) -> Verdict {
    let mut all_absent = true;
    for &id in &finding.ids {
        match verdicts.of(&graph.body(id).key, category) {
            Verdict::Confirmed => return Verdict::Confirmed,
            Verdict::Absent => {}
            Verdict::Unverified => all_absent = false,
        }
    }
    if all_absent {
        Verdict::Absent
    } else {
        Verdict::Unverified
    }
}

/// Every function the report considers, with what it reports under, which
/// may be nothing at all.
///
/// Which functions those are, and under what names, is the selection's
/// call, made once for every rendering so the report and the drawing
/// agree.
fn considered<'a>(
    graph: &'a Graph,
    solution: &'a Solution,
    args: &'a Args,
) -> impl Iterator<Item = (FuncId, &'a Body, CategorySet)> {
    let selection = args.selection();
    selection.functions(graph).map(move |(id, body)| {
        (id, body, selection.shown(solution.enabled(id)))
    })
}

/// The name a body reports under.
pub(crate) fn reported_name<'a>(body: &'a Body, args: &Args) -> &'a str {
    args.selection().name(body)
}

/// Whether anything at all would be reported under these settings.
///
/// The exit code is what a continuous integration run reads, so it has to
/// agree with what the report prints rather than with the unfiltered
/// solution: a run that names no finding has nothing to report.
#[must_use]
pub fn any_finding(graph: &Graph, solution: &Solution, args: &Args) -> bool {
    !collect(graph, solution, args).is_empty()
}

/// Selects the functions worth reporting, one entry per name.
///
/// The report and the gate both group here, so a function that reports
/// under one name cannot be gated under another. Every body the selection
/// keeps under a name contributes what it raises, so a generic function
/// reports what its written body and its instantiations raise together,
/// or what the instantiations alone do, as the selection decides.
pub(crate) fn collect<'a>(
    graph: &'a Graph,
    solution: &'a Solution,
    args: &'a Args,
) -> Vec<Finding<'a>> {
    let mut findings: Vec<Finding<'a>> = Vec::new();
    let mut index: Map<(&str, &str), usize> = Map::default();
    for (id, body, categories) in considered(graph, solution, args) {
        let name = reported_name(body, args);
        let key = (body.krate.as_str(), name);
        let at = if let Some(&at) = index.get(&key) {
            at
        } else {
            index.insert(key, findings.len());
            findings.push(Finding {
                krate: &body.krate,
                name,
                ids: Vec::new(),
                categories: CategorySet::EMPTY,
            });
            findings.len().saturating_sub(1)
        };
        let Some(finding) = findings.get_mut(at) else {
            continue;
        };
        // The first body stands for the name, so the body that bears the
        // name itself takes that place ahead of the closures folded into it.
        let bears_name = body.display == name;
        let first_does_not = finding
            .ids
            .first()
            .is_some_and(|&first| graph.body(first).display != name);
        if bears_name && first_does_not {
            finding.ids.insert(0, id);
        } else {
            finding.ids.push(id);
        }
        finding.categories = finding.categories.union(categories);
    }
    findings.retain(|finding| !finding.categories.is_empty());
    findings.sort_by(|a, b| a.name.cmp(b.name));
    findings
}

/// Writes the functions the artifact reaches a panic from that the report
/// does not name them with.
fn missed_prose(graph: &Graph, missed: &[Missed], out: &mut String) {
    if missed.is_empty() {
        return;
    }
    out.push_str(
        "The compiled artifact reaches panics the analysis did not report:\n\n",
    );
    for entry in missed {
        let body = graph.body(entry.id);
        let _ = writeln!(out, "{}", body.display);
        if let Some(loc) = &body.loc {
            let _ = writeln!(out, "    defined at {loc}");
        }
        for set in &entry.reaches {
            let _ = writeln!(out, "    {}", set.names().join(", or "));
        }
        out.push('\n');
    }
}

/// Writes the human readable report.
fn human(
    graph: &Graph,
    solution: &Solution,
    args: &Args,
    findings: &[Finding<'_>],
    verdicts: Option<&Verdicts>,
    out: &mut String,
) {
    header(graph, args, findings.len(), out);

    if findings.is_empty() {
        out.push_str("\nNo function can panic under this policy.\n");
        return;
    }

    out.push('\n');
    for finding in findings {
        let body = graph.body(finding.id());
        let _ = writeln!(out, "{}", reported_name(body, args));
        if let Some(loc) = &body.loc {
            let _ = writeln!(out, "    defined at {loc}");
        }
        for category in finding.categories.iter() {
            match direct_site(graph, solution, finding, category) {
                Some(site) => {
                    let _ = write!(out, "    {category:<18} {}", site.0);
                    if let Some(loc) = site.1 {
                        let _ = write!(out, " at {loc}");
                    }
                    if always(graph, solution, finding, category) {
                        out.push_str(" (always)");
                    }
                }
                None => {
                    let _ = write!(
                        out,
                        "    {category:<18} reached through a call"
                    );
                }
            }
            if let Some(verdicts) = verdicts {
                let word = match verdict_of(graph, verdicts, finding, category)
                {
                    Verdict::Confirmed => "confirmed in",
                    Verdict::Absent => "absent from",
                    Verdict::Unverified => "unverified in",
                };
                let _ = write!(out, " ({word} the compiled artifact)");
            }
            out.push('\n');
        }
        out.push('\n');
    }

    if let Some(verdicts) = verdicts {
        missed_prose(graph, &verdicts.missed(graph, solution), out);
    }

    let _ =
        writeln!(out, "Run `panicgraph why <function>` to see a call path.");
}

/// Whether every execution of the function raises this category itself.
///
/// A site the body cannot get round is a bug that shows on every call,
/// where one behind a guard shows only for some argument, so the report
/// says which it is.
fn always(
    graph: &Graph,
    solution: &Solution,
    finding: &Finding<'_>,
    category: Category,
) -> bool {
    finding.ids.iter().any(|&id| {
        let body = graph.body(id);
        let activity = solution.activity(graph, id);
        body.sites.iter().enumerate().any(|(i, site)| {
            site.certain && site.category == category && activity.site(i)
        })
    })
}

/// The reason and place of a panic this function raises itself.
///
/// Returns nothing when the category is only reached through a call.
fn direct_site<'a>(
    graph: &'a Graph,
    solution: &Solution,
    finding: &Finding<'_>,
    category: Category,
) -> Option<(&'a str, Option<String>)> {
    for &id in &finding.ids {
        let body = graph.body(id);
        let activity = solution.activity(graph, id);
        let hit =
            body.sites.iter().enumerate().find(|(i, site)| {
                site.category == category && activity.site(*i)
            });
        if let Some((_, site)) = hit {
            return Some((
                site.reason.as_str(),
                site.loc.as_ref().map(ToString::to_string),
            ));
        }
    }
    None
}

/// Writes the analysis preamble.
fn header(graph: &Graph, args: &Args, found: usize, out: &mut String) {
    out.push_str("Analysis\n");
    if let Some(config) = graph.config() {
        let _ = writeln!(out, "    rustc              {}", config.rustc);
        let _ = writeln!(
            out,
            "    profile            {} (debug assertions {}, overflow \
             checks {})",
            config.profile,
            on_off(config.debug_assertions),
            on_off(config.overflow_checks),
        );
        let _ =
            writeln!(out, "    standard library   {}", config.std_mode.name());
        if let Some(level) = config.mir_opt_level {
            let _ = writeln!(out, "    mir opt level      {level}");
        }
    }
    if !args.features.is_default() {
        let _ = writeln!(
            out,
            "    features           {}",
            args.features.describe()
        );
    }
    let suppressed = if args.suppress.is_empty() {
        "nothing".to_owned()
    } else {
        args.suppress.to_string()
    };
    let _ = writeln!(out, "    suppressed         {suppressed}");
    let _ = writeln!(
        out,
        "    functions          {} analysed, {found} can panic",
        graph.len()
    );
}

/// Writes the machine readable report.
fn json(
    graph: &Graph,
    solution: &Solution,
    findings: &[Finding<'_>],
    args: &Args,
    verdicts: Option<&Verdicts>,
    out: &mut String,
) -> Result<()> {
    let items: Vec<serde_json::Value> = findings
        .iter()
        .map(|f| {
            let body = graph.body(f.id());
            let mut item = serde_json::json!({
                "function": reported_name(body, args),
                "crate": body.krate,
                "location": body.loc.as_ref().map(ToString::to_string),
                "categories": f
                    .categories.names(),
            });
            let certain: Vec<&str> = f
                .categories
                .iter()
                .filter(|category| always(graph, solution, f, *category))
                .map(Category::name)
                .collect();
            if !certain.is_empty() {
                item["always"] = certain.into();
            }
            if let Some(verdicts) = verdicts {
                let verified: serde_json::Map<String, serde_json::Value> = f
                    .categories
                    .iter()
                    .map(|category| {
                        (
                            category.name().to_owned(),
                            verdict_of(graph, verdicts, f, category)
                                .name()
                                .into(),
                        )
                    })
                    .collect();
                item["verified"] = verified.into();
            }
            item
        })
        .collect();
    let mut doc = serde_json::json!({
        "config": graph.config(),
        "analysed": graph.len(),
        "findings": items,
    });
    if let Some(verdicts) = verdicts {
        let missed: Vec<serde_json::Value> = verdicts
            .missed(graph, solution)
            .iter()
            .map(|entry| {
                let body = graph.body(entry.id);
                serde_json::json!({
                    "function": reported_name(body, args),
                    "crate": body.krate,
                    "location": body.loc.as_ref().map(ToString::to_string),
                    "reaches": entry
                        .reaches
                        .iter()
                        .map(|set| set.names())
                        .collect::<Vec<_>>(),
                })
            })
            .collect();
        doc["missed"] = missed.into();
    }
    out.push_str(&serde_json::to_string_pretty(&doc)?);
    out.push('\n');
    Ok(())
}

/// Splits a `file:line:col` location into the fields a workflow command
/// wants, or nothing at all when there is no location to name.
pub(crate) fn workflow_location(loc: Option<&str>) -> String {
    fn split(loc: &str) -> Option<String> {
        let mut parts = loc.rsplitn(3, ':');
        let col = parts.next()?;
        let line = parts.next()?;
        let file = parts.next()?;
        Some(format!("file={file},line={line},col={col},"))
    }
    loc.and_then(split).unwrap_or_default()
}

/// Writes one workflow command per finding, which a continuous integration
/// log turns into an annotation against the source.
fn github(
    graph: &Graph,
    findings: &[Finding<'_>],
    args: &Args,
    out: &mut String,
) {
    for finding in findings {
        let body = graph.body(finding.id());
        let loc = body.loc.as_ref().map(ToString::to_string);
        let where_at = workflow_location(loc.as_deref());
        let _ = writeln!(
            out,
            "::warning {where_at}title=Function can panic::{} can panic \
             with {}",
            reported_name(body, args),
            finding.categories.names().join(", ")
        );
    }
}

/// What `why` says about one function.
struct Explanation<'a> {
    /// The body the query matched first, which names the function.
    body: &'a Body,
    /// How many bodies the query matched.
    matched: usize,
    /// Whether the query matched more than one function.
    ambiguous: bool,
    /// How many bodies report together under the function's name.
    bodies: usize,
    /// What those bodies raise between them under the policy.
    categories: CategorySet,
    /// A shortest path to each, from a body that reaches it.
    paths: Vec<(Category, witness::Witness)>,
}

/// Finds the function a query names and a path to each of its panics.
///
/// The closest match names the function, and every body the report shows
/// under that name is searched, so each panic the report lists is explained.
fn explain<'a>(
    graph: &'a Graph,
    solution: &Solution,
    selection: Selection,
    name: &str,
) -> Option<Explanation<'a>> {
    let matches = graph.find_by_display(name);
    let &first = matches.first()?;
    let body = graph.body(first);
    let ids = selection.namesakes(graph, first);
    let categories = ids.iter().fold(CategorySet::EMPTY, |set, id| {
        set.union(solution.enabled(*id))
    });
    let paths = categories
        .iter()
        .filter_map(|category| {
            witness::find_any(graph, solution, &ids, category)
                .map(|path| (category, path))
        })
        .collect();
    Some(Explanation {
        body,
        matched: matches.len(),
        ambiguous: matches
            .iter()
            .any(|&other| graph.body(other).display != body.display),
        bodies: ids.len(),
        categories,
        paths,
    })
}

/// Explains how one function reaches each panic it can raise.
///
/// # Errors
///
/// Returns an error if the JSON document cannot be serialized.
pub fn why(
    graph: &Graph,
    solution: &Solution,
    args: &Args,
    name: &str,
    out: &mut String,
) -> Result<()> {
    let selection = args.selection();
    let found = explain(graph, solution, selection, name);
    if args.format == Format::Json {
        return why_json(graph, selection, name, found, out);
    }
    why_prose(graph, selection, name, found, out);
    Ok(())
}

/// Explains one function's panics for a machine.
///
/// The same walk the prose takes, written as the path itself: every path
/// names the body it starts in, every hop names the callee it reaches and
/// the edge it was resolved through, and the ending says what raises.
fn why_json(
    graph: &Graph,
    selection: Selection,
    name: &str,
    found: Option<Explanation<'_>>,
    out: &mut String,
) -> Result<()> {
    let doc = match found {
        None => serde_json::json!({ "query": name, "matched": 0 }),
        Some(found) => {
            let paths: Vec<serde_json::Value> = found
                .paths
                .iter()
                .map(|(category, path)| {
                    serde_json::json!({
                        "category": category.name(),
                        "from": graph.body(path.root).display,
                        "hops": path
                            .hops
                            .iter()
                            .map(|hop| serde_json::json!({
                                "function": graph.body(hop.callee).display,
                                "kind": hop.kind.name(),
                                "location": hop
                                    .loc
                                    .as_ref()
                                    .map(ToString::to_string),
                            }))
                            .collect::<Vec<_>>(),
                        "ending": ending(graph, path),
                    })
                })
                .collect();
            serde_json::json!({
                "query": name,
                "matched": found.matched,
                "function": selection.name(found.body),
                "crate": found.body.krate,
                "location": found.body.loc.as_ref().map(ToString::to_string),
                "bodies": found.bodies,
                "categories": found.categories.names(),
                "paths": paths,
            })
        }
    };
    out.push_str(&serde_json::to_string_pretty(&doc)?);
    out.push('\n');
    Ok(())
}

/// What the end of a witness path raises, as a document.
fn ending(graph: &Graph, path: &witness::Witness) -> serde_json::Value {
    let body = graph.body(path.func);
    match path.terminal {
        Terminal::Site(i) => body.sites.get(i).map_or_else(
            || serde_json::json!({ "kind": "site" }),
            |site| {
                serde_json::json!({
                    "kind": "site",
                    "reason": site.reason,
                    "location": site.loc.as_ref().map(ToString::to_string),
                })
            },
        ),
        Terminal::Opaque => serde_json::json!({
            "kind": if body.foreign { "foreign" } else { "opaque" },
        }),
        Terminal::Unresolved(i) => body.calls.get(i).map_or_else(
            || serde_json::json!({ "kind": "unresolved" }),
            |call| {
                serde_json::json!({
                    "kind": "unresolved",
                    "callee": call.callee_display,
                    "edge": call.kind.name(),
                    "location": call.loc.as_ref().map(ToString::to_string),
                })
            },
        ),
    }
}

/// Explains how one function reaches each panic it can raise, in prose.
fn why_prose(
    graph: &Graph,
    selection: Selection,
    name: &str,
    found: Option<Explanation<'_>>,
    out: &mut String,
) {
    let Some(found) = found else {
        let _ = writeln!(out, "No function matching `{name}` was analysed.");
        return;
    };
    let function = selection.name(found.body);
    if found.ambiguous {
        let _ = writeln!(
            out,
            "`{name}` matched {} functions; explaining `{function}`.\n",
            found.matched
        );
    }
    if found.bodies > 1 {
        let _ = writeln!(
            out,
            "`{function}` has {} bodies; each panic below is shown from one \
             that reaches it.\n",
            found.bodies
        );
    }

    if found.categories.is_empty() {
        let _ = writeln!(out, "{function} cannot panic under this policy.");
        return;
    }

    for (category, path) in &found.paths {
        let _ = writeln!(out, "{function} can panic with `{category}`:\n");
        let _ = writeln!(out, "  {}", graph.body(path.root).display);
        for hop in &path.hops {
            if let Some(loc) = &hop.loc {
                let _ = writeln!(out, "      at {loc}  [{}]", hop.kind.name());
            }
            let _ = writeln!(out, "  -> {}", graph.body(hop.callee).display);
        }
        describe_terminal(graph, path, out);
        out.push('\n');
    }
}

/// Writes the last line of a witness path.
fn describe_terminal(graph: &Graph, path: &witness::Witness, out: &mut String) {
    let body = graph.body(path.func);
    match path.terminal {
        Terminal::Site(i) => {
            let Some(site) = body.sites.get(i) else {
                return;
            };
            let _ = write!(out, "      {}", site.reason);
            if let Some(loc) = &site.loc {
                let _ = write!(out, " at {loc}");
            }
            out.push('\n');
        }
        Terminal::Opaque if body.foreign => {
            let _ = writeln!(
                out,
                "      foreign code, which has no Rust body to read"
            );
        }
        Terminal::Opaque => {
            let _ = writeln!(
                out,
                "      no MIR available for this function, so its panics \
                 are unknown"
            );
            let _ = writeln!(
                out,
                "      re-run with `--std full` to see inside the standard \
                 library"
            );
        }
        Terminal::Unresolved(i) => {
            let Some(call) = body.calls.get(i) else {
                return;
            };
            let _ = write!(
                out,
                "      calls {} through a {} edge, target unknown",
                call.callee_display,
                call.kind.name()
            );
            if let Some(loc) = &call.loc {
                let _ = write!(out, " at {loc}");
            }
            out.push('\n');
        }
    }
}

/// Lists the categories and what each means, for a machine.
///
/// # Errors
///
/// Returns an error if the document cannot be serialized.
pub fn kinds_json(out: &mut String) -> Result<()> {
    let doc = serde_json::json!({
        "categories": crate::category::ALL
            .iter()
            .map(|category| serde_json::json!({
                "name": category.name(),
                "describe": category.describe(),
                // Whether the name stands for a panic or for a place the
                // analysis could not read.
                "assumed": CategorySet::assumed().contains(*category),
            }))
            .collect::<Vec<_>>(),
        "aliases": serde_json::json!({
            "oom": CategorySet::oom().names(),
            "default": CategorySet::default_suppressed().names(),
            "assumed": CategorySet::assumed().names(),
            "all": crate::category::ALL
                .iter()
                .map(|category| category.name())
                .collect::<Vec<_>>(),
        }),
    });
    out.push_str(&serde_json::to_string_pretty(&doc)?);
    out.push('\n');
    Ok(())
}

/// Writes the taxonomy as prose.
pub fn kinds(out: &mut String) {
    out.push_str("Panic categories\n\n");
    for category in crate::category::ALL {
        let _ =
            writeln!(out, "  {:<18} {}", category.name(), category.describe());
    }
    out.push_str(
        "\nGroup aliases: `oom` covers capacity-overflow and alloc-failure, \
         `default` adds ub-check, `assumed` covers what the analysis could \
         not read, `all` covers everything.\n",
    );
}

/// Renders a flag as text.
const fn on_off(value: bool) -> &'static str {
    if value { "on" } else { "off" }
}

/// Suppressed categories that were nonetheless observed, for the hint line.
///
/// # Errors
///
/// Returns an error if the graph cannot be solved without the suppression,
/// which is what the count is measured against.
pub fn suppressed_hint(
    graph: &Graph,
    solution: &Solution,
    args: &Args,
) -> Result<Option<String>> {
    if args.suppress.is_empty() {
        return Ok(None);
    }
    let hidden = solution.cleared_by_suppression(graph, args.selection())?;
    Ok((hidden > 0).then(|| {
        format!(
            "{hidden} local functions panic only through suppressed \
             categories ({}).",
            args.suppress
        )
    }))
}