cargo-tops 0.4.0

init / check / gate for the Rust-TOPS protocol. Orchestrates existing Cargo tools; does not replace them.
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
//! Class profiles merged onto the init template as data.
//!
//! Every file in the crate's `templates/profiles/` is embedded with
//! `include_str!`. That directory is the source and the repo-root `profiles/`
//! its synced copy, so the published package holds them. [`merge_profile`]
//! parses the base template and the class file and writes the profile's
//! numbers into the template tree. It does not search-and-replace template
//! text. An unknown class is an error, not a library-core document.
//!
//! `profiles.rs` is the caller. This allow holds until that call lands.
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used))]
#![allow(dead_code, reason = "profiles.rs calls merge_profile")]

use serde_json::{Map, Number, Value};

use crate::init_meta::{resolve_unsafe_policy, Settings};

const TEMPLATE: &str = include_str!("../templates/rust-tops.example.yaml");

/// Every `templates/profiles/*.yaml`, keyed by the class id in the file.
const PROFILES: &[(&str, &str)] = &[
    (
        "binary-cli",
        include_str!("../templates/profiles/binary-cli.yaml"),
    ),
    (
        "ffi-bridge",
        include_str!("../templates/profiles/ffi-bridge.yaml"),
    ),
    (
        "library-core",
        include_str!("../templates/profiles/library-core.yaml"),
    ),
    (
        "library-util",
        include_str!("../templates/profiles/library-util.yaml"),
    ),
    (
        "no-std-embedded",
        include_str!("../templates/profiles/no-std-embedded.yaml"),
    ),
    (
        "parser-codec",
        include_str!("../templates/profiles/parser-codec.yaml"),
    ),
    (
        "unsafe-kernel",
        include_str!("../templates/profiles/unsafe-kernel.yaml"),
    ),
    (
        "workspace-root",
        include_str!("../templates/profiles/workspace-root.yaml"),
    ),
];

const COVERAGE_FLOORS: &[&str] = &[
    "line_min_pct",
    "region_min_pct",
    "per_file_line_min_pct",
    "branch_min_pct",
];
const CRAP_FLOORS: &[&str] = &["threshold_agent", "threshold_human", "threshold_production"];
const MUTATION_FLOORS: &[&str] = &["kill_rate_min_pct"];

/// Why [`merge_profile`] produced no document.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum ProfileError {
    /// No embedded profile for this class. Library-core is not a fallback.
    UnknownClass { class: String },
    /// The profile or the template could not be merged.
    Invalid { class: String, detail: String },
}

impl std::fmt::Display for ProfileError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::UnknownClass { class } => write!(f, "no profile for class {class}"),
            Self::Invalid { class, detail } => write!(f, "profile {class} is invalid: {detail}"),
        }
    }
}

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

/// Whether clippy should lint changes that break this class's exported API.
///
/// Binary classes say false. Clippy reads that from `clippy.toml`, not from
/// the `gates.lint` copy in `rust-tops.yaml`.
pub(crate) fn avoid_breaking_exported_api(class: &str) -> Result<bool, ProfileError> {
    let source = profile_source(class).ok_or_else(|| ProfileError::UnknownClass {
        class: class.to_string(),
    })?;
    let profile = parse_yaml(source).map_err(|detail| ProfileError::Invalid {
        class: class.to_string(),
        detail,
    })?;
    profile
        .pointer("/strict/avoid_breaking_exported_api")
        .and_then(Value::as_bool)
        .ok_or_else(|| invalid(class, "strict.avoid_breaking_exported_api is not a bool"))
}

/// `rust-tops.yaml` for `class`, with `crate.name` set to `crate_name`.
///
/// Coverage, CRAP, and mutation numbers come from the profile file and land
/// on `gates`. `inherits: per-package` drops the template's package floors,
/// so a workspace root does not keep library-core's agent CRAP or line floor.
/// Call this from `init` and `check`. Do not fall back when it returns
/// [`ProfileError::UnknownClass`].
#[must_use = "an unknown class is an error and must not be written as library-core"]
pub(crate) fn merge_profile(class: &str, crate_name: &str) -> Result<String, ProfileError> {
    merge_profile_with(class, crate_name, &Settings::default())
}

/// [`merge_profile`] with what `init` read from the crate: its edition and
/// `rust-version`, whether its lint table forbids unsafe code, and `--laws`.
/// `hot_paths` is always empty: an adopter names their own.
pub(crate) fn merge_profile_with(
    class: &str,
    crate_name: &str,
    settings: &Settings,
) -> Result<String, ProfileError> {
    let source = profile_source(class).ok_or_else(|| ProfileError::UnknownClass {
        class: class.to_string(),
    })?;
    let mut doc = parse_yaml(TEMPLATE).map_err(|detail| ProfileError::Invalid {
        class: class.to_string(),
        detail,
    })?;
    let profile = parse_yaml(source).map_err(|detail| ProfileError::Invalid {
        class: class.to_string(),
        detail,
    })?;
    apply_profile(&mut doc, &profile, class, crate_name)?;
    apply_settings(&mut doc, &profile, settings, class)?;
    Ok(emit_yaml(&doc))
}

fn profile_source(class: &str) -> Option<&'static str> {
    PROFILES
        .iter()
        .find(|(name, _)| *name == class)
        .map(|(_, body)| *body)
}

fn apply_profile(
    doc: &mut Value,
    profile: &Value,
    class: &str,
    crate_name: &str,
) -> Result<(), ProfileError> {
    let declared = profile.get("class").and_then(Value::as_str).unwrap_or("");
    if declared != class {
        return Err(invalid(class, format!("file says class {declared}")));
    }
    set_crate(doc, class, crate_name, profile)?;
    for (key, pointer) in [
        ("coverage", "/gates/coverage"),
        ("crap", "/gates/crap"),
        ("mutation", "/gates/mutation"),
        ("strict", "/gates/lint"),
    ] {
        if let Some(src) = profile.get(key) {
            overlay(doc, pointer, src, class)?;
        }
    }
    if inherits_per_package(profile) {
        drop_unset_floors(doc, profile);
    }
    reject_tighter_agent(doc, class)
}

fn set_crate(
    doc: &mut Value,
    class: &str,
    crate_name: &str,
    profile: &Value,
) -> Result<(), ProfileError> {
    let Some(slot) = doc.pointer_mut("/crate").and_then(Value::as_object_mut) else {
        return Err(invalid(class, "template has no crate"));
    };
    slot.insert("name".to_string(), Value::String(crate_name.to_string()));
    slot.insert("class".to_string(), Value::String(class.to_string()));
    if let Some(policy) = profile.get("unsafe_policy").and_then(Value::as_str) {
        slot.insert(
            "unsafe_policy".to_string(),
            Value::String(policy.to_string()),
        );
    }
    Ok(())
}

/// The crate facts onto the merged document. `unsafe_policy` comes from
/// [`resolve_unsafe_policy`], the P0-R7 rule.
fn apply_settings(
    doc: &mut Value,
    profile: &Value,
    settings: &Settings,
    class: &str,
) -> Result<(), ProfileError> {
    let Some(slot) = doc.pointer_mut("/crate").and_then(Value::as_object_mut) else {
        return Err(invalid(class, "template has no crate"));
    };
    if let Some(edition) = &settings.edition {
        slot.insert("edition".to_string(), Value::String(edition.clone()));
    }
    if let Some(msrv) = &settings.msrv {
        slot.insert("msrv".to_string(), Value::String(msrv.clone()));
    }
    slot.insert("hot_paths".to_string(), Value::Array(Vec::new()));
    let class_policy = profile.get("unsafe_policy").and_then(Value::as_str);
    let unsafe_policy = resolve_unsafe_policy(settings.unsafe_lint.as_deref(), class_policy).policy;
    slot.insert("unsafe_policy".to_string(), Value::String(unsafe_policy));
    if settings.laws {
        enable_layer(doc, "laws", class)?;
    }
    Ok(())
}

fn enable_layer(doc: &mut Value, id: &str, class: &str) -> Result<(), ProfileError> {
    let layer = doc
        .pointer_mut("/layers")
        .and_then(Value::as_array_mut)
        .and_then(|layers| {
            layers
                .iter_mut()
                .find(|l| l.get("id").and_then(Value::as_str) == Some(id))
        })
        .and_then(Value::as_object_mut)
        .ok_or_else(|| invalid(class, format!("template has no {id} layer")))?;
    layer.insert("enabled".to_string(), Value::Bool(true));
    Ok(())
}

fn overlay(doc: &mut Value, pointer: &str, src: &Value, class: &str) -> Result<(), ProfileError> {
    let Some(src_map) = src.as_object() else {
        return Err(invalid(
            class,
            format!("{pointer} profile value is not a map"),
        ));
    };
    let Some(slot) = doc.pointer_mut(pointer).and_then(Value::as_object_mut) else {
        return Err(invalid(class, format!("template has no {pointer}")));
    };
    for (key, value) in src_map {
        slot.insert(key.clone(), value.clone());
    }
    Ok(())
}

fn inherits_per_package(profile: &Value) -> bool {
    profile.get("inherits").and_then(Value::as_str) == Some("per-package")
}

/// A workspace root sets no coverage, CRAP, or mutation floors of its own.
/// Keys the profile did not supply are removed so the template's library-core
/// numbers do not remain.
fn drop_unset_floors(doc: &mut Value, profile: &Value) {
    if profile.get("coverage").is_none() {
        remove_keys(doc, "/gates/coverage", COVERAGE_FLOORS);
    }
    if profile.get("crap").is_none() {
        remove_keys(doc, "/gates/crap", CRAP_FLOORS);
    }
    if profile.get("mutation").is_none() {
        remove_keys(doc, "/gates/mutation", MUTATION_FLOORS);
    }
}

fn remove_keys(doc: &mut Value, pointer: &str, keys: &[&str]) {
    let Some(slot) = doc.pointer_mut(pointer).and_then(Value::as_object_mut) else {
        return;
    };
    for key in keys {
        slot.remove(*key);
    }
}

fn reject_tighter_agent(doc: &Value, class: &str) -> Result<(), ProfileError> {
    let Some(crap) = doc.pointer("/gates/crap") else {
        return Ok(());
    };
    let (Some(agent), Some(human)) = (
        crap.get("threshold_agent").and_then(Value::as_f64),
        crap.get("threshold_human").and_then(Value::as_f64),
    ) else {
        return Ok(());
    };
    if agent < human {
        return Err(invalid(
            class,
            format!("agent CRAP {agent} is tighter than human {human}"),
        ));
    }
    Ok(())
}

fn invalid(class: &str, detail: impl Into<String>) -> ProfileError {
    ProfileError::Invalid {
        class: class.to_string(),
        detail: detail.into(),
    }
}

fn parse_yaml(raw: &str) -> Result<Value, String> {
    serde_saphyr::from_str_with_options(
        raw,
        serde_saphyr::options! {
            strict_booleans: true,
        },
    )
    .map_err(|err| err.to_string())
}

fn emit_yaml(value: &Value) -> String {
    let mut out = String::new();
    match value {
        Value::Object(map) => write_map(&mut out, map, 0),
        other => {
            write_scalar(&mut out, other);
            out.push('\n');
        }
    }
    if !out.ends_with('\n') {
        out.push('\n');
    }
    out
}

fn write_map(out: &mut String, map: &Map<String, Value>, indent: usize) {
    for (key, value) in map {
        write_entry(out, key, value, indent);
    }
}

fn write_entry(out: &mut String, key: &str, value: &Value, indent: usize) {
    pad(out, indent);
    out.push_str(&plain_key(key));
    match value {
        Value::Object(map) if !map.is_empty() => {
            out.push_str(":\n");
            write_map(out, map, indent + 2);
        }
        Value::Array(items) if !items.is_empty() => {
            out.push_str(":\n");
            write_array(out, items, indent + 2);
        }
        Value::Object(_) => out.push_str(": {}\n"),
        Value::Array(_) => out.push_str(": []\n"),
        other => {
            out.push_str(": ");
            write_scalar(out, other);
            out.push('\n');
        }
    }
}

fn write_array(out: &mut String, items: &[Value], indent: usize) {
    for item in items {
        pad(out, indent);
        out.push('-');
        match item {
            Value::Object(map) if !map.is_empty() => {
                out.push('\n');
                write_map(out, map, indent + 2);
            }
            Value::Array(nested) if !nested.is_empty() => {
                out.push('\n');
                write_array(out, nested, indent + 2);
            }
            other => {
                out.push(' ');
                write_scalar(out, other);
                out.push('\n');
            }
        }
    }
}

fn write_scalar(out: &mut String, value: &Value) {
    match value {
        Value::Null => out.push_str("null"),
        Value::Bool(true) => out.push_str("true"),
        Value::Bool(false) => out.push_str("false"),
        Value::Number(number) => out.push_str(&emit_number(number)),
        Value::String(text) => write_string(out, text),
        Value::Array(_) | Value::Object(_) => out.push_str("null"),
    }
}

fn emit_number(number: &Number) -> String {
    if let Some(value) = number.as_i64() {
        return value.to_string();
    }
    if let Some(value) = number.as_u64() {
        return value.to_string();
    }
    if let Some(value) = number.as_f64() {
        if value.is_finite() && value.fract() == 0.0 && value.abs() < i64::MAX as f64 {
            #[expect(
                clippy::cast_possible_truncation,
                reason = "already in this crate when the strict table was turned on"
            )]
            return (value as i64).to_string();
        }
        return value.to_string();
    }
    number.to_string()
}

fn write_string(out: &mut String, text: &str) {
    out.push('"');
    for c in text.chars() {
        match c {
            '\\' | '"' => {
                out.push('\\');
                out.push(c);
            }
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c => out.push(c),
        }
    }
    out.push('"');
}

fn plain_key(key: &str) -> String {
    let plain = !key.is_empty()
        && key
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
    if plain {
        key.to_string()
    } else {
        let mut quoted = String::new();
        write_string(&mut quoted, key);
        quoted
    }
}

fn pad(out: &mut String, indent: usize) {
    out.push_str(&" ".repeat(indent));
}

#[cfg(test)]
mod strict_profile {
    use super::merge_profile;

    #[test]
    fn library_classes_keep_lib_lints_and_binaries_do_not() {
        let lib = merge_profile("library-util", "demo").unwrap();
        assert!(lib.contains("library_only: true"));
        assert!(lib.contains("avoid_breaking_exported_api: true"));
        let bin = merge_profile("binary-cli", "demo").unwrap();
        assert!(bin.contains("library_only: false"));
        assert!(bin.contains("avoid_breaking_exported_api: false"));
    }
}

/// `init` writes the merged profile with [`emit_yaml`]; what it writes must
/// read back as the tree it was given.
#[cfg(test)]
mod emit {
    use super::{emit_number, emit_yaml, parse_yaml};
    use serde_json::{json, Number};

    #[test]
    fn emitted_yaml_reads_back_as_the_same_tree() {
        let tree = json!({
            "plain_key": "text",
            "needs quotes": "a \"quoted\" \\ back\nslash\r\t",
            "": null,
            "flags": [true, false],
            "numbers": [0, -7, 18_446_744_073_709_551_615_u64, 0.5, -2.25],
            "empty_map": {},
            "empty_list": [],
            "nested": [[1, [2]], {"k": [{"deep": "v"}]}],
        });
        assert_eq!(parse_yaml(&emit_yaml(&tree)), Ok(tree));
    }

    #[test]
    fn a_whole_float_is_written_as_an_integer() {
        let cases: [(f64, &str); 4] = [(2.0, "2"), (-3.0, "-3"), (0.5, "0.5"), (-2.25, "-2.25")];
        for (value, want) in cases {
            let number = Number::from_f64(value).expect("finite");
            assert_eq!(emit_number(&number), want, "{value}");
        }
    }

    #[test]
    fn a_scalar_document_is_one_line() {
        assert_eq!(emit_yaml(&json!("x")), "\"x\"\n");
        assert_eq!(emit_yaml(&json!(null)), "null\n");
        assert_eq!(emit_yaml(&json!(7)), "7\n");
    }
}

/// A profile that cannot be merged is an error that names the class and
/// the reason, never a document.
#[cfg(test)]
mod errors {
    use super::{
        avoid_breaking_exported_api, overlay, reject_tighter_agent, remove_keys, set_crate,
        ProfileError,
    };
    use serde_json::json;

    fn invalid(detail: &str) -> ProfileError {
        ProfileError::Invalid {
            class: "x".to_string(),
            detail: detail.to_string(),
        }
    }

    #[test]
    fn an_unknown_class_has_no_lint_scope() {
        let err = avoid_breaking_exported_api("no-such-class").unwrap_err();
        assert_eq!(
            err,
            ProfileError::UnknownClass {
                class: "no-such-class".to_string()
            }
        );
        assert_eq!(err.to_string(), "no profile for class no-such-class");
        assert_eq!(invalid("why").to_string(), "profile x is invalid: why");
    }

    #[test]
    fn a_profile_value_must_land_on_a_template_map() {
        let mut doc = json!({"gates": {"coverage": {}}});
        assert_eq!(
            overlay(&mut doc, "/gates/coverage", &json!(5), "x"),
            Err(invalid("/gates/coverage profile value is not a map"))
        );
        assert_eq!(
            overlay(&mut doc, "/gates/crap", &json!({}), "x"),
            Err(invalid("template has no /gates/crap"))
        );
        assert_eq!(
            set_crate(&mut doc, "x", "demo", &json!({})),
            Err(invalid("template has no crate"))
        );
        remove_keys(&mut doc, "/gates/crap", &["threshold_agent"]);
        assert_eq!(doc, json!({"gates": {"coverage": {}}}));
    }

    #[test]
    fn an_agent_threshold_tighter_than_the_human_one_is_refused() {
        let doc = json!({"gates": {"crap": {"threshold_agent": 4, "threshold_human": 6}}});
        assert_eq!(
            reject_tighter_agent(&doc, "x"),
            Err(invalid("agent CRAP 4 is tighter than human 6"))
        );
        let equal = json!({"gates": {"crap": {"threshold_agent": 6, "threshold_human": 6}}});
        assert_eq!(reject_tighter_agent(&equal, "x"), Ok(()));
        assert_eq!(reject_tighter_agent(&json!({}), "x"), Ok(()));
    }
}