rllvm-query 0.10.0

Source-level queries over LLVM bitcode captured by rllvm
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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
use std::{
    io::{IsTerminal, Read},
    path::{Path, PathBuf},
    process::ExitCode,
};

use clap::{CommandFactory, Parser};
use rllvm_core::{
    config::try_rllvm_config,
    error::Error,
    utils::{print_stdout, split_response_arguments},
};
use rllvm_query::{
    AnchorParts, AnchorSurface, Color, FactsCache, Overlay, OverlaySummary, Query, Record, Session,
    TextMode, Verification, anchor_from_parts, check_anchor_parts,
    cli::{CacheAction, ClosureDirection, OverlayAction, QueryArgs, QueryCommand, QueryModifiers},
    default_overlay_path, emit_guards_module, emit_slice,
    index::Direction,
    llvm_version, mcp, open_with_cache,
    overlay::verdict_label,
    run_with_overlay,
};
use tracing_subscriber::FmtSubscriber;

/// Converts a parsed subcommand into the [`Query`] it names, or `None` for
/// the four variants that name a mode rather than a query: `Mcp` (serve
/// over MCP stdio), `Completions` (print a completion script), `Cache`
/// (inspect or prune the facts cache) and `Overlay` (keep agent-authored
/// edges), all of which this binary has already handled by the time a query
/// would run.
///
/// Exhaustive over `QueryCommand`, so a new `QueryCommand` variant with no
/// arm here fails to compile. That alone does not catch the opposite drift --
/// a new [`Query`] variant added without a matching `QueryCommand` --
/// which compiles cleanly on its own, and `Query` is non-exhaustive, so no
/// match here can fail to compile over it. This file's tests close that gap:
/// `every_query_tool_has_a_cli_subcommand` fails for a query the MCP server
/// lists with no subcommand to drive it from the command line.
fn to_query(command: QueryCommand, modifiers: QueryModifiers) -> Option<Planned> {
    let QueryModifiers {
        heuristics,
        include_overlay,
        include_annotations,
        min_confidence,
    } = modifiers;
    // `guards` is the one query whose arguments need the catalog: a
    // `file:line` is resolved to a call site against it. It is carried as
    // its flags until the session exists.
    if let QueryCommand::Guards {
        at,
        operand,
        ret,
        function,
        local,
        from,
        emit_module,
    } = command
    {
        return Some(Planned::Guards(GuardsRequest {
            parts: AnchorParts {
                at,
                operand,
                ret,
                function,
                local,
            },
            from,
            emit_module,
        }));
    }
    Some(Planned::Ready(match command {
        QueryCommand::Defs { name } => Query::Defs { name },
        QueryCommand::At { file, line } => Query::At { file, line },
        QueryCommand::Callers { name } => Query::Callers { name },
        QueryCommand::Callees { name } => Query::Callees { name },
        QueryCommand::Uses { name } => Query::Uses { name },
        QueryCommand::Reach { from, to } => Query::Reach {
            from,
            to,
            include_overlay,
            min_confidence,
            include_annotations,
        },
        // `--emit-module` acts on the answer rather than shaping the query,
        // so `run_query` reads it before the command is consumed here.
        QueryCommand::Slice { from, to, .. } => Query::Slice {
            from,
            to,
            include_overlay,
            min_confidence,
            include_annotations,
        },
        QueryCommand::Closure { name, direction } => Query::Closure {
            name,
            direction: match direction {
                ClosureDirection::In => Direction::In,
                ClosureDirection::Out => Direction::Out,
            },
            include_overlay,
            min_confidence,
        },
        QueryCommand::Externals => Query::Externals,
        QueryCommand::FfiExports => Query::FfiExports,
        QueryCommand::IndirectTargets { at } => Query::IndirectTargets { at, heuristics },
        QueryCommand::ResolutionCandidates => Query::ResolutionCandidates,
        // Returned above.
        QueryCommand::Guards { .. } => return None,
        QueryCommand::Mcp => return None,
        // `main` answers this one before `run_query` is ever called; the arm
        // is here so adding a mode variant cannot compile without a decision.
        QueryCommand::Completions { .. } => return None,
        QueryCommand::Cache { .. } => return None,
        QueryCommand::Overlay { .. } => return None,
    }))
}

/// A parsed query, ready to run or waiting on the catalog.
#[derive(Debug)]
enum Planned {
    Ready(Query),
    Guards(GuardsRequest),
}

/// The flags of a `guards` query, kept as written until the catalog can
/// resolve the call site they name.
#[derive(Debug, PartialEq)]
struct GuardsRequest {
    parts: AnchorParts,
    from: Option<String>,
    emit_module: Option<PathBuf>,
}

impl Planned {
    /// What can be rejected before any bitcode is read.
    fn validate(&self) -> Result<(), Error> {
        match self {
            Planned::Ready(query) => query.validate(),
            Planned::Guards(request) => check_anchor_parts(&request.parts, AnchorSurface::Cli)
                .map_err(Error::InvalidArguments),
        }
    }

    /// The query to run against `session`, whose call sites resolve a
    /// `guards` anchor.
    fn into_query(self, session: &Session) -> Result<Query, Error> {
        match self {
            Planned::Ready(query) => Ok(query),
            Planned::Guards(request) => Ok(Query::Guards {
                anchor: anchor_from_parts(session, &request.parts, AnchorSurface::Cli)
                    .map_err(Error::InvalidArguments)?,
                at: request.parts.use_site().map(str::to_string),
                from: request.from,
                emit_module: request.emit_module,
            }),
        }
    }
}

/// One line of stdin: a query subcommand, written as it would follow
/// `rllvm-query --catalog <catalog>`. Only the [`QueryModifiers`] flags may
/// accompany it; the output format, the catalog and the overlay file belong
/// to the whole run.
#[derive(Parser)]
#[command(name = "rllvm-query", no_binary_name = true)]
struct QueryLine {
    #[command(flatten)]
    modifiers: QueryModifiers,

    #[command(subcommand)]
    command: QueryCommand,
}

/// Parses and validates every query on stdin, before any catalog is read,
/// so a typo on the last line costs a diagnostic rather than a full load.
/// Each query is returned with its line as written, which heads its answer.
fn parse_queries(input: &str, modifiers: QueryModifiers) -> Result<Vec<(String, Planned)>, Error> {
    let mut queries = Vec::new();
    for (index, line) in input.lines().enumerate() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        // One line per diagnostic: clap's message runs to a usage block,
        // which here would describe a command line the reader never typed.
        let at_line = |reason: String| {
            let reason = reason.split("\n\n").next().unwrap_or_default();
            let reason = reason.strip_prefix("error: ").unwrap_or(reason);
            let reason = reason.split_whitespace().collect::<Vec<_>>().join(" ");
            Error::InvalidArguments(format!("line {}: {reason}", index + 1))
        };
        let arguments = split_response_arguments(line);
        let parsed =
            QueryLine::try_parse_from(&arguments).map_err(|error| at_line(error.to_string()))?;
        if let QueryCommand::Slice {
            emit_module: Some(_),
            ..
        }
        | QueryCommand::Guards {
            emit_module: Some(_),
            ..
        } = parsed.command
        {
            return Err(at_line(
                "`--emit-module` writes a file for one slice: run it on the command line"
                    .to_string(),
            ));
        }
        let query = to_query(parsed.command, modifiers.with(parsed.modifiers))
            .ok_or_else(|| at_line(format!("`{}` names a mode, not a query", arguments[0])))?;
        query.validate().map_err(|error| match error {
            Error::InvalidArguments(reason) => at_line(reason),
            other => at_line(other.to_string()),
        })?;
        queries.push((line.to_string(), query));
    }
    Ok(queries)
}

/// A bindir that cannot be found fails only a query that runs `opt`.
fn set_llvm_bindir(session: &mut Session) {
    session.set_llvm_bindir(
        try_rllvm_config()
            .and_then(|config| config.llvm_bindir().cloned())
            .map_err(|error| error.to_string()),
    );
}

/// The facts cache the configuration asks for, or `None` when disabled.
fn facts_cache() -> Result<Option<FactsCache>, Error> {
    Ok(FactsCache::from_config(try_rllvm_config()?))
}

/// `rllvm-query cache [clear [--stale]]`: needs no catalog.
fn run_cache(action: Option<&CacheAction>, format: Format) -> Result<(), Error> {
    let config = try_rllvm_config()?;
    let cache = FactsCache::configured(config)?;
    match action {
        Some(CacheAction::Clear { stale }) => {
            let cleared = cache.clear(*stale);
            match format {
                Format::Json => print_stdout(&format!(
                    "{}\n",
                    serde_json::to_string(&cleared)
                        .map_err(|error| Error::InvalidArguments(error.to_string()))?
                )),
                Format::Text(_) => {
                    let orphans = if cleared.orphans > 0 {
                        format!(" and {} orphaned temp file(s)", cleared.orphans)
                    } else {
                        String::new()
                    };
                    print_stdout(&format!(
                        "removed {} entries{orphans}, {}\n",
                        cleared.entries,
                        rllvm_query::render::human_bytes(cleared.bytes)
                    ))
                }
            }
        }
        None => {
            let usage = cache.usage(config.query_cache_enabled());
            match format {
                Format::Json => print_stdout(&format!(
                    "{}\n",
                    serde_json::to_string_pretty(&usage)
                        .map_err(|error| Error::InvalidArguments(error.to_string()))?
                )),
                Format::Text(_) => print_stdout(&rllvm_query::render_usage(&usage)),
            }
        }
    }
}

/// Parses the overlay records piped on stdin, one JSON object per line,
/// each kept with its 1-based line so a record that fails validation later
/// is named by its line too. Blank lines are skipped.
fn parse_records(input: &str) -> Result<Vec<(usize, Record)>, Error> {
    let mut records = Vec::new();
    for (index, line) in input.lines().enumerate() {
        if line.trim().is_empty() {
            continue;
        }
        let record = Record::parse_labeled(line, format_args!("line {}", index + 1))?;
        records.push((index + 1, record));
    }
    Ok(records)
}

/// The overlay file: `--overlay`, or the default beside the catalog.
fn overlay_path(catalog: &Path, overlay: Option<&Path>) -> PathBuf {
    overlay.map_or_else(|| default_overlay_path(catalog), Path::to_path_buf)
}

/// The overlay `query` walks, opened against `session` when it asks for one
/// and `opened` holds none yet: at most once per run. A file that cannot be
/// read is an error, never a silent direct-only answer. A missing file is an
/// empty overlay at the default path, where nothing may be recorded yet, but
/// an error when `--overlay` named it, which is a mistyped path, or when the
/// query asks for annotations, which a missing file cannot hold.
fn overlay_for<'o>(
    opened: &'o mut Option<Overlay>,
    session: &Session,
    catalog: &Path,
    named: Option<&Path>,
    query: &Query,
) -> Result<Option<&'o Overlay>, Error> {
    if query.walks_overlay() && opened.is_none() {
        let path = overlay_path(catalog, named);
        if (named.is_some() || query.includes_annotations())
            && let Err(error) = std::fs::metadata(&path)
            && error.kind() == std::io::ErrorKind::NotFound
        {
            return Err(Error::InvalidArguments(if named.is_some() {
                format!(
                    "{}: no such overlay; --overlay names an existing file for a walk to read",
                    path.display()
                )
            } else {
                format!(
                    "{}: no such overlay; --annotations needs one holding annotations",
                    path.display()
                )
            }));
        }
        *opened = Some(Overlay::open(session, &path)?);
    }
    Ok(opened.as_ref())
}

/// `rllvm-query --catalog <catalog> overlay record|list|compact`. The
/// overlay file defaults to one beside the catalog.
fn run_overlay(
    action: &OverlayAction,
    catalog: Option<&Path>,
    overlay: Option<&Path>,
    format: Format,
) -> Result<(), Error> {
    let catalog = catalog.ok_or_else(|| {
        Error::InvalidArguments("--catalog is required for the overlay command".to_string())
    })?;
    let path = overlay_path(catalog, overlay);
    // Before the catalog loads, as with piped queries, so a malformed line
    // costs a diagnostic rather than a full load.
    let records = match action {
        OverlayAction::Record => {
            let mut stdin = std::io::stdin();
            if stdin.is_terminal() {
                return Err(Error::InvalidArguments(
                    "no records given: pipe them on stdin, one JSON object per line".to_string(),
                ));
            }
            let mut input = String::new();
            stdin.read_to_string(&mut input)?;
            parse_records(&input)?
        }
        OverlayAction::List | OverlayAction::Compact => Vec::new(),
    };

    let mut session = open_with_cache(catalog, facts_cache()?.as_ref())?;
    // An `annotate` is grounded in its function's promoted module.
    set_llvm_bindir(&mut session);
    let mut overlay = Overlay::open(&session, &path)?;
    let text = match action {
        OverlayAction::Record => {
            let recorded = records.len();
            overlay.record_lines(&session, records)?;
            let saved = overlay.save()?;
            format!("recorded {recorded}, saved {saved} to {}\n", path.display())
        }
        OverlayAction::List => overlay_table(&overlay.summary(&session)),
        OverlayAction::Compact => {
            overlay.compact()?;
            format!(
                "compacted {}: {} edges, {} annotations\n",
                path.display(),
                overlay.edges().count(),
                overlay.annotations().len()
            )
        }
    };
    match format {
        Format::Json => print_stdout(&format!(
            "{}\n",
            serde_json::to_string_pretty(&overlay.summary(&session))
                .map_err(|error| Error::InvalidArguments(error.to_string()))?
        )),
        Format::Text(_) => print_stdout(&text),
    }
}

/// One line per edge: `<key>  <confidence>  <verdict|unverified>  <n> site(s)`,
/// then one per annotation: `<key>  <verdict>  <confidence>  <verification|unverified>`.
fn overlay_table(summary: &OverlaySummary) -> String {
    let verdict = |verification: Option<&Verification>| {
        verdict_label(verification.map(|verification| verification.verdict))
    };
    let edges = summary.edges.iter().map(|entry| {
        format!(
            "{}  {}  {}  {} site(s)\n",
            entry.edge.key,
            entry.edge.confidence,
            verdict(entry.edge.verification.as_ref()),
            entry.sites
        )
    });
    let annotations = summary.annotations.iter().map(|annotation| {
        format!(
            "{}  {}  {}  {}\n",
            annotation.key,
            annotation.verdict,
            annotation.confidence,
            verdict(annotation.verification.as_ref())
        )
    });
    edges.chain(annotations).collect()
}

/// Answers the queries piped on stdin from one load of `catalog`. Reading
/// a terminal would wait for input nobody knows to type, so that is an
/// error; empty stdin answers nothing.
fn run_stdin_queries(
    catalog: &Path,
    overlay: Option<&Path>,
    modifiers: QueryModifiers,
    format: Format,
) -> Result<(), Error> {
    let mut stdin = std::io::stdin();
    if stdin.is_terminal() {
        return Err(Error::InvalidArguments(
            "no query given: name one, or pipe queries on stdin".to_string(),
        ));
    }
    let mut input = String::new();
    stdin.read_to_string(&mut input)?;
    let queries = parse_queries(&input, modifiers)?;
    if queries.is_empty() {
        return Ok(());
    }
    init_logging()?;
    let mut session = open_with_cache(catalog, facts_cache()?.as_ref())?;
    set_llvm_bindir(&mut session);
    let named = overlay;
    let mut opened = None;
    for (line, query) in queries {
        let query = query.into_query(&session)?;
        let overlay = overlay_for(&mut opened, &session, catalog, named, &query)?;
        let result = run_with_overlay(&session, overlay, &query)?;
        let answer = match format {
            Format::Json => serde_json::to_string(&result)
                .map(|json| format!("{json}\n"))
                .map_err(|error| Error::InvalidArguments(error.to_string()))?,
            Format::Text(mode) => format!(
                "== {line}\n{}",
                rllvm_query::render(&result, mode, stdout_color())
            ),
        };
        print_stdout(&answer)?;
    }
    Ok(())
}

/// How answers are printed, chosen once for the whole run.
#[derive(Clone, Copy)]
enum Format {
    Json,
    Text(TextMode),
}

impl Format {
    fn of(args: &QueryArgs) -> Format {
        if args.json {
            Format::Json
        } else if args.full {
            Format::Text(TextMode::Full)
        } else {
            Format::Text(TextMode::Adaptive)
        }
    }
}

/// Matches the wrapper binaries' own convention (`rllvm_cc.rs`,
/// `rllvm_get_bc.rs`, `rllvm_rustc.rs`): the configured log level, on
/// stderr, so `tracing::warn!` (a module that failed to extract) actually
/// reaches a reader instead of being silently dropped by the default no-op
/// subscriber. Called only once a query is certain to run, so
/// `--llvm-version` alone never touches the configuration file.
fn init_logging() -> Result<(), Error> {
    FmtSubscriber::builder()
        .with_max_level(try_rllvm_config()?.log_level())
        .with_writer(std::io::stderr)
        .init();
    Ok(())
}

fn run_query(args: QueryArgs) -> Result<(), Error> {
    let format = Format::of(&args);
    let Some(command) = args.command else {
        // With a catalog and no query, the queries arrive on stdin.
        return match &args.catalog {
            Some(catalog) => {
                run_stdin_queries(catalog, args.overlay.as_deref(), args.modifiers, format)
            }
            None => Ok(()),
        };
    };

    init_logging()?;

    // The dispatch, named rather than inferred from `to_query`'s `None`.
    // Two commands answer `None` now -- `Mcp` and `Completions` -- so `None`
    // no longer identifies which mode was asked for, and reading it as "serve
    // MCP" would make the next mode-shaped variant silently do that: the one
    // outcome nobody would think to test for. Exhaustive and wildcard-free,
    // so such a variant has to fail to compile here too, not only in
    // `to_query`, where its `None` arm would otherwise be the whole story.
    match &command {
        QueryCommand::Mcp => return serve_mcp(args.catalog.as_deref()),
        // `main` answers this one before `run_query` is reached, so arriving
        // here means that early return was dropped --
        // `completions_name_the_query_binary` fails when it is, because
        // nothing reaches stdout.
        QueryCommand::Completions { .. } => return Ok(()),
        QueryCommand::Cache { action } => {
            if args.catalog.is_some() {
                return Err(Error::InvalidArguments(
                    "the cache command reads no catalog; drop --catalog".into(),
                ));
            }
            return run_cache(action.as_ref(), format);
        }
        QueryCommand::Overlay { action } => {
            return run_overlay(
                action,
                args.catalog.as_deref(),
                args.overlay.as_deref(),
                format,
            );
        }
        QueryCommand::Defs { .. }
        | QueryCommand::At { .. }
        | QueryCommand::Callers { .. }
        | QueryCommand::Callees { .. }
        | QueryCommand::Uses { .. }
        | QueryCommand::Reach { .. }
        | QueryCommand::Slice { .. }
        | QueryCommand::Closure { .. }
        | QueryCommand::Externals
        | QueryCommand::FfiExports
        | QueryCommand::IndirectTargets { .. }
        | QueryCommand::ResolutionCandidates
        | QueryCommand::Guards { .. } => {}
    }

    let emit_module = match &command {
        QueryCommand::Slice { emit_module, .. } | QueryCommand::Guards { emit_module, .. } => {
            emit_module.clone()
        }
        _ => None,
    };
    // Unreachable through the match above, which returns for every command
    // `to_query` answers `None` for. An error rather than a panic: a binary
    // that mis-dispatches should say so, not abort.
    let Some(query) = to_query(command, args.modifiers) else {
        return Err(Error::InvalidArguments(
            "this command names a mode, not a query".to_string(),
        ));
    };

    // Before `open`, so a mistyped location costs a diagnostic rather than a
    // full read and extraction of the catalog.
    query.validate()?;
    let catalog = args.catalog.ok_or_else(|| {
        Error::InvalidArguments("--catalog is required to run a query".to_string())
    })?;
    let mut session = open_with_cache(&catalog, facts_cache()?.as_ref())?;
    set_llvm_bindir(&mut session);
    let query = query.into_query(&session)?;
    let mut opened = None;
    let overlay = overlay_for(
        &mut opened,
        &session,
        &catalog,
        args.overlay.as_deref(),
        &query,
    )?;
    let result = run_with_overlay(&session, overlay, &query)?;
    // Before anything is printed, so a failed emit leaves no answer that
    // reads as though the module were written.
    let emitted = match &emit_module {
        Some(out) => {
            let config = try_rllvm_config()?;
            Some(match &query {
                // The analysis read one module; this is the slice a scoped
                // re-read would use.
                Query::Guards { anchor, from, .. } => emit_guards_module(
                    &session,
                    &catalog,
                    anchor,
                    from.as_deref(),
                    config.llvm_link_filepath(),
                    config.llvm_bindir()?,
                    out,
                )?,
                _ => emit_slice(
                    &session,
                    &catalog,
                    &result,
                    config.llvm_link_filepath(),
                    config.llvm_bindir()?,
                    out,
                )?,
            })
        }
        None => None,
    };

    match format {
        Format::Json => {
            let mut answer = serde_json::to_value(&result)
                .map_err(|error| Error::InvalidArguments(error.to_string()))?;
            if let Some(emitted) = &emitted {
                answer["emitted"] = serde_json::json!(emitted);
            }
            let json = serde_json::to_string_pretty(&answer)
                .map_err(|error| Error::InvalidArguments(error.to_string()))?;
            print_stdout(&format!("{json}\n"))?;
        }
        Format::Text(mode) => {
            // First, so the answer's own last line -- `not proven`, when an
            // agent edge was walked -- stays last.
            let mut text = emitted.map_or_else(String::new, |emitted| {
                format!(
                    "wrote {}: {} functions from {} modules\n",
                    emitted.path.display(),
                    emitted.functions,
                    emitted.modules
                )
            });
            text.push_str(&rllvm_query::render(&result, mode, stdout_color()));
            print_stdout(&text)?;
        }
    }
    Ok(())
}

/// Whether stdout should be coloured. `supports_color::on` honours
/// `NO_COLOR`, `FORCE_COLOR`, `CLICOLOR`, `CLICOLOR_FORCE`, `TERM=dumb`,
/// `COLORTERM` and `TERM_PROGRAM`, none of which a bare `is_terminal()`
/// check reads. Its CI detection cannot change a piped run's answer: the
/// terminal test short-circuits to "no colour" before `is_ci` is reached,
/// so CI only raises the level of a stream that is already a terminal.
///
/// Sensed here and passed to `render` rather than called inside it: `on`
/// reads the real environment, so an inline `if_supports_color` would make
/// the renderer's unit tests depend on whether the suite ran under
/// `--nocapture` on a terminal.
fn stdout_color() -> Color {
    match supports_color::on(supports_color::Stream::Stdout) {
        Some(_) => Color::Always,
        None => Color::Never,
    }
}

/// Serves MCP over stdio. `--catalog` is optional here and only preloads:
/// the point of the server is that a client chooses what to analyze, through
/// `load_catalog` and `inventory`, and keeps several catalogs loaded at once.
/// A preload failure is still fatal -- a client that asked for a catalog on
/// the command line should hear that it could not be read, not discover it
/// one query later.
fn serve_mcp(catalog: Option<&std::path::Path>) -> Result<(), Error> {
    let config = try_rllvm_config()?;
    // Only emitting a module, `guards` and grounding an `annotate` need the
    // bindir, so failing to find it fails only those.
    let mut registry = mcp::Registry::with_cache(facts_cache()?).with_llvm_tools(
        config.llvm_link_filepath().clone(),
        config.llvm_bindir().cloned(),
    );
    if let Some(catalog) = catalog {
        registry.load(catalog)?;
    }
    let stdin = std::io::stdin();
    let stdout = std::io::stdout();
    mcp::serve(&mut registry, stdin.lock(), stdout.lock())
}

fn main() -> ExitCode {
    let args = QueryArgs::parse();
    if args.llvm_version {
        // Documented as "print ... and exit": must return here rather than
        // falling into `run_query`, or `--llvm-version --catalog c mcp`
        // would print a bare version line onto stdout ahead of the
        // JSON-RPC frames, corrupting the protocol stream.
        return rllvm_core::error::report(print_stdout(&format!("{}\n", llvm_version())));
    }
    // Also before any configuration is read: generating a completion script
    // is a property of the CLI definition alone, and must not fail on a
    // machine that has no usable LLVM configuration yet.
    if let Some(QueryCommand::Completions { shell }) = args.command {
        let mut command = QueryArgs::command();
        let name = command.get_name().to_string();
        clap_complete::generate(shell, &mut command, name, &mut std::io::stdout());
        return ExitCode::SUCCESS;
    }
    match run_query(args) {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) => {
            eprintln!("{error}");
            ExitCode::FAILURE
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rllvm_query::{Confidence, GuardAnchor};

    /// The query a parsed line names, for one that needs nothing from the
    /// catalog.
    fn ready(planned: &Planned) -> &Query {
        match planned {
            Planned::Ready(query) => query,
            Planned::Guards(_) => panic!("a guards line waits on the catalog"),
        }
    }

    /// The reverse of `to_query`: the `QueryCommand` that drives `query`.
    /// `Query` is non-exhaustive, so the wildcard arm is required; a query
    /// with no arm here panics, and `every_query_tool_has_a_cli_subcommand`
    /// fails for one with no subcommand at all.
    fn cli_command_for(query: &Query) -> QueryCommand {
        match query {
            Query::Defs { name } => QueryCommand::Defs { name: name.clone() },
            Query::At { file, line } => QueryCommand::At {
                file: file.clone(),
                line: *line,
            },
            Query::Callers { name } => QueryCommand::Callers { name: name.clone() },
            Query::Callees { name } => QueryCommand::Callees { name: name.clone() },
            Query::Uses { name } => QueryCommand::Uses { name: name.clone() },
            Query::Reach { from, to, .. } => QueryCommand::Reach {
                from: from.clone(),
                to: to.clone(),
            },
            Query::Slice { from, to, .. } => QueryCommand::Slice {
                from: from.clone(),
                to: to.clone(),
                emit_module: None,
            },
            Query::Closure {
                name, direction, ..
            } => QueryCommand::Closure {
                name: name.clone(),
                direction: match direction {
                    Direction::In => ClosureDirection::In,
                    Direction::Out => ClosureDirection::Out,
                },
            },
            Query::Externals => QueryCommand::Externals,
            Query::FfiExports => QueryCommand::FfiExports,
            Query::IndirectTargets { at, .. } => QueryCommand::IndirectTargets { at: at.clone() },
            Query::ResolutionCandidates => QueryCommand::ResolutionCandidates,
            Query::Guards {
                anchor,
                at: use_site,
                from,
                emit_module,
            } => {
                let (mut operand, mut ret, mut function, mut local) = (None, false, None, None);
                let at = match anchor {
                    GuardAnchor::Argument { site, operand: n } => {
                        operand = Some(*n);
                        Some(serde_json::to_string(site).unwrap())
                    }
                    GuardAnchor::Return { site } => {
                        ret = true;
                        Some(serde_json::to_string(site).unwrap())
                    }
                    GuardAnchor::Local { function: f, name } => {
                        function = Some(f.clone());
                        local = Some(name.clone());
                        use_site.clone()
                    }
                };
                QueryCommand::Guards {
                    at,
                    operand,
                    ret,
                    function,
                    local,
                    from: from.clone(),
                    emit_module: emit_module.clone(),
                }
            }
            other => panic!("{other:?} has no CLI command"),
        }
    }

    /// The tools `tools/list` reports that decide which catalogs are loaded
    /// or keep the overlay, rather than ask a question: none is a query
    /// subcommand.
    const MANAGEMENT_TOOLS: [&str; 8] = [
        "load_catalog",
        "inventory",
        "list_catalogs",
        "unload_catalog",
        "load_overlay",
        "record_edges",
        "save_overlay",
        "list_overlay",
    ];

    /// The fence `Query`'s non-exhaustiveness takes from `cli_command_for`:
    /// every query the MCP server lists, which it lists from every `Query`
    /// variant, has a subcommand that drives it from the command line.
    #[test]
    fn every_query_tool_has_a_cli_subcommand() {
        let mut output = Vec::new();
        mcp::serve(
            &mut mcp::Registry::new(),
            "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}\n".as_bytes(),
            &mut output,
        )
        .unwrap();
        let reply: serde_json::Value = serde_json::from_slice(&output).unwrap();
        let tools: Vec<&str> = reply["result"]["tools"]
            .as_array()
            .unwrap()
            .iter()
            .map(|tool| tool["name"].as_str().unwrap())
            .filter(|name| !MANAGEMENT_TOOLS.contains(name))
            .collect();
        assert_eq!(tools.len(), 13, "{tools:?}");
        let command = QueryArgs::command();
        for tool in tools {
            assert!(
                command.find_subcommand(tool.replace('_', "-")).is_some(),
                "the `{tool}` tool has no `rllvm-query` subcommand"
            );
        }
    }

    #[test]
    fn each_line_of_stdin_is_one_query_in_command_line_syntax() {
        let queries = parse_queries(
            "callees quiche_accept\n\n  defs 'int twice<int>(int)'\nindirect-targets t.c:4 --heuristics\n",
            QueryModifiers::default(),
        )
        .unwrap();
        let lines: Vec<&str> = queries.iter().map(|(line, _)| line.as_str()).collect();
        assert_eq!(
            lines,
            [
                "callees quiche_accept",
                "defs 'int twice<int>(int)'",
                "indirect-targets t.c:4 --heuristics"
            ]
        );
        assert_eq!(
            format!("{:?}", ready(&queries[1].1)),
            format!(
                "{:?}",
                Query::Defs {
                    name: "int twice<int>(int)".into()
                }
            )
        );
        assert!(matches!(
            ready(&queries[2].1),
            Query::IndirectTargets {
                heuristics: true,
                ..
            }
        ));
    }

    #[test]
    fn heuristics_on_the_command_line_reach_every_stdin_query() {
        let heuristics = QueryModifiers {
            heuristics: true,
            ..QueryModifiers::default()
        };
        let queries = parse_queries("indirect-targets t.c:4\n", heuristics).unwrap();
        assert!(matches!(
            ready(&queries[0].1),
            Query::IndirectTargets {
                heuristics: true,
                ..
            }
        ));
    }

    #[test]
    fn a_stdin_line_may_ask_for_the_overlay() {
        let queries = parse_queries(
            "reach main handler --include-overlay --min-confidence medium\nreach main handler\n",
            QueryModifiers::default(),
        )
        .unwrap();
        assert!(matches!(
            ready(&queries[0].1),
            Query::Reach {
                include_overlay: true,
                min_confidence: Some(Confidence::Medium),
                ..
            }
        ));
        assert!(ready(&queries[0].1).walks_overlay());
        assert!(
            !ready(&queries[1].1).walks_overlay(),
            "each line asks for itself"
        );

        let error = parse_queries(
            "reach main handler --min-confidence high\n",
            QueryModifiers::default(),
        )
        .map(|_| ())
        .unwrap_err()
        .to_string();
        assert!(error.contains("line 1:"), "{error}");
    }

    #[test]
    fn a_stdin_slice_may_not_emit_a_module() {
        let queries = parse_queries(
            "slice main handler --include-overlay\n",
            QueryModifiers::default(),
        )
        .unwrap();
        assert!(matches!(
            ready(&queries[0].1),
            Query::Slice {
                include_overlay: true,
                ..
            }
        ));
        assert!(ready(&queries[0].1).walks_overlay());

        let error = parse_queries(
            "callees a\nslice main handler --emit-module out.bc\n",
            QueryModifiers::default(),
        )
        .map(|_| ())
        .unwrap_err()
        .to_string();
        assert!(
            error.contains("line 2:") && error.contains("--emit-module"),
            "{error}"
        );
    }

    #[test]
    fn a_bad_stdin_line_is_reported_by_its_number() {
        for (input, expected) in [
            ("callees a\nfrobnicate b\n", "line 2:"),
            ("\ncallees a --json\n", "line 2:"),
            ("callees a\n--catalog c.json callees b\n", "line 2:"),
            ("mcp\n", "line 1:"),
            ("completions bash\n", "line 1:"),
            ("callees a\ncallees b\nindirect-targets main.c\n", "line 3:"),
        ] {
            let error = parse_queries(input, QueryModifiers::default())
                .map(|_| ())
                .expect_err(input)
                .to_string();
            assert!(error.contains(expected), "{input:?} gave {error:?}");
            assert_eq!(error.lines().count(), 1, "{input:?} gave {error:?}");
        }
    }

    #[test]
    fn empty_stdin_names_no_query() {
        assert!(
            parse_queries("", QueryModifiers::default())
                .unwrap()
                .is_empty()
        );
        assert!(
            parse_queries("\n  \n", QueryModifiers::default())
                .unwrap()
                .is_empty()
        );
    }

    /// `to_query` maps `QueryCommand::Mcp` to `None`, since it selects a
    /// mode rather than naming a query.
    #[test]
    fn the_mcp_command_has_no_query() {
        assert!(to_query(QueryCommand::Mcp, QueryModifiers::default()).is_none());
    }

    /// Same for `Completions`: the binary answers it before a query could
    /// run, so reaching `to_query` with it must not name one.
    #[test]
    fn the_completions_command_has_no_query() {
        let command = QueryCommand::Completions {
            shell: clap_complete::Shell::Bash,
        };
        assert!(to_query(command, QueryModifiers::default()).is_none());
    }

    #[test]
    fn the_overlay_command_has_no_query() {
        let command = QueryCommand::Overlay {
            action: OverlayAction::List,
        };
        assert!(to_query(command, QueryModifiers::default()).is_none());
    }

    #[test]
    fn a_bad_record_on_stdin_is_reported_by_its_number() {
        let good = r#"{"op":"retract","edge":{"via_field":{"record":"ops","offset":8},"to":{"module_id":"m","symbol":"h3"}},"reason":"r"}"#;
        let lines: Vec<usize> = parse_records(&format!("\n{good}\n\n{good}\n"))
            .unwrap()
            .into_iter()
            .map(|(line, _)| line)
            .collect();
        assert_eq!(lines, [2, 4], "each record keeps its line for validation");
        for (input, expected) in [
            (format!("{good}\n{{\n"), "line 2:"),
            (format!("\n{good}\n{{\"op\":\"annotate\"}}\n"), "line 3:"),
        ] {
            let error = parse_records(&input).map(|_| ()).unwrap_err().to_string();
            assert!(error.contains(expected), "{input:?} gave {error:?}");
        }
    }

    /// Not just a compile-time fence: proves `to_query` and `cli_command_for`
    /// actually agree on every field, for every variant, not merely that
    /// both happen to be exhaustive.
    #[test]
    fn every_query_variant_round_trips_through_the_cli_command_mapping() {
        let modifiers = QueryModifiers {
            heuristics: true,
            include_overlay: true,
            include_annotations: true,
            min_confidence: Some(Confidence::High),
        };
        let queries = [
            Query::Defs { name: "f".into() },
            Query::At {
                file: "t.c".into(),
                line: 1,
            },
            Query::Callers { name: "f".into() },
            Query::Callees { name: "f".into() },
            Query::Uses { name: "f".into() },
            Query::Reach {
                from: "a".into(),
                to: "b".into(),
                include_overlay: true,
                min_confidence: Some(Confidence::High),
                include_annotations: true,
            },
            Query::Slice {
                from: "a".into(),
                to: "b".into(),
                include_overlay: true,
                min_confidence: Some(Confidence::High),
                include_annotations: true,
            },
            Query::Closure {
                name: "f".into(),
                direction: Direction::In,
                include_overlay: true,
                min_confidence: Some(Confidence::High),
            },
            Query::Closure {
                name: "f".into(),
                direction: Direction::Out,
                include_overlay: true,
                min_confidence: Some(Confidence::High),
            },
            Query::Externals,
            Query::FfiExports,
            Query::IndirectTargets {
                at: "t.c:4".into(),
                heuristics: true,
            },
        ];
        for query in queries {
            let command = cli_command_for(&query);
            let Some(Planned::Ready(round_tripped)) = to_query(command, modifiers) else {
                panic!("{query:?} should be ready to run");
            };
            assert_eq!(
                format!("{round_tripped:?}"),
                format!("{query:?}"),
                "CLI round-trip must preserve every field"
            );
        }
    }

    /// `guards` waits on the catalog, so its round trip is through the
    /// flags it was written with rather than through a `Query`.
    #[test]
    fn a_guards_query_round_trips_through_its_flags() {
        let site = rllvm_query::CallSiteId {
            function: rllvm_query::FunctionId {
                module_id: "m".into(),
                symbol: "f".into(),
            },
            block_index: 1,
            instruction_index: 2,
        };
        let parse_len = GuardAnchor::Local {
            function: "parse".into(),
            name: "len".into(),
        };
        for (anchor, at, from) in [
            (
                GuardAnchor::Argument {
                    site: site.clone(),
                    operand: 3,
                },
                None,
                Some("main".to_string()),
            ),
            (GuardAnchor::Return { site: site.clone() }, None, None),
            (parse_len.clone(), None, None),
            (parse_len, Some("t.c:9".to_string()), None),
        ] {
            let query = Query::Guards {
                anchor: anchor.clone(),
                at: at.clone(),
                from: from.clone(),
                emit_module: Some("out.bc".into()),
            };
            let command = cli_command_for(&query);
            let Some(Planned::Guards(request)) = to_query(command, QueryModifiers::default())
            else {
                panic!("{query:?} should wait on the catalog");
            };
            let site_json = serde_json::to_string(&site).unwrap();
            let expected = match &anchor {
                GuardAnchor::Argument { operand, .. } => GuardsRequest {
                    parts: AnchorParts {
                        at: Some(site_json),
                        operand: Some(*operand),
                        ret: false,
                        function: None,
                        local: None,
                    },
                    from,
                    emit_module: Some("out.bc".into()),
                },
                GuardAnchor::Return { .. } => GuardsRequest {
                    parts: AnchorParts {
                        at: Some(site_json),
                        operand: None,
                        ret: true,
                        function: None,
                        local: None,
                    },
                    from,
                    emit_module: Some("out.bc".into()),
                },
                GuardAnchor::Local { function, name } => GuardsRequest {
                    parts: AnchorParts {
                        at,
                        operand: None,
                        ret: false,
                        function: Some(function.clone()),
                        local: Some(name.clone()),
                    },
                    from,
                    emit_module: Some("out.bc".into()),
                },
            };
            assert_eq!(request, expected);
        }
    }

    #[test]
    fn guards_flags_parse_into_a_request() {
        let queries = parse_queries(
            "guards --at t.c:4 --operand 0 --from main\nguards --at t.c:4 --return\nguards --function parse --local len\nguards --function parse --local len --at t.c:9\n",
            QueryModifiers::default(),
        )
        .unwrap();
        let requests: Vec<&GuardsRequest> = queries
            .iter()
            .map(|(_, planned)| match planned {
                Planned::Guards(request) => request,
                Planned::Ready(query) => panic!("{query:?}"),
            })
            .collect();
        assert_eq!(requests[0].parts.at.as_deref(), Some("t.c:4"));
        assert_eq!(requests[0].parts.operand, Some(0));
        assert_eq!(requests[0].from.as_deref(), Some("main"));
        assert!(requests[1].parts.ret && requests[1].parts.operand.is_none());
        assert_eq!(requests[2].parts.function.as_deref(), Some("parse"));
        assert_eq!(requests[2].parts.local.as_deref(), Some("len"));
        assert_eq!(requests[3].parts.at.as_deref(), Some("t.c:9"));
        assert_eq!(requests[3].parts.local.as_deref(), Some("len"));
    }

    #[test]
    fn a_guards_line_naming_no_value_is_rejected_by_its_number() {
        for (input, expected) in [
            ("guards\n", "name a value"),
            ("guards --operand 0\n", "need --at"),
            ("guards --at t.c:4\n", "needs --operand"),
            ("guards --at t.c:4 --operand 0 --return\n", "give one"),
            ("guards --local n\n", "needs --function"),
            ("guards --function f\n", "needs --local"),
            (
                "guards --at t.c:4 --return --local n --function f\n",
                "give one",
            ),
            (
                "callees a\nguards --at t.c:4 --return --emit-module o.bc\n",
                "--emit-module",
            ),
        ] {
            let error = parse_queries(input, QueryModifiers::default())
                .map(|_| ())
                .expect_err(input)
                .to_string();
            assert!(
                error.contains("line") && error.contains(expected),
                "{input:?} gave {error:?}"
            );
        }
    }

    /// `--json` picks the envelope, `--full` the full text, and neither the
    /// adaptive text: the only check that `--full` reaches the renderer.
    #[test]
    fn the_output_flags_select_the_renderer() {
        // `None` for the JSON envelope; an exhaustive match, not `matches!`,
        // so a renderer added later must be placed here too.
        let selected = [
            &["rllvm-query", "--full", "callers", "add"][..],
            &["rllvm-query", "--json", "callers", "add"],
            &["rllvm-query", "callers", "add"],
        ]
        .map(
            |argv| match Format::of(&QueryArgs::try_parse_from(argv).unwrap()) {
                Format::Json => None,
                Format::Text(mode) => Some(mode),
            },
        );
        assert_eq!(
            selected,
            [Some(TextMode::Full), None, Some(TextMode::Adaptive)]
        );
    }
}