#![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");
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"];
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum ProfileError {
UnknownClass { class: String },
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 {}
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"))
}
#[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())
}
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))
}
pub(crate) fn class_profile(class: &str) -> Option<Value> {
parse_yaml(profile_source(class)?).ok()
}
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(())
}
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")
}
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"));
}
}
#[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");
}
}
#[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(()));
}
}