use std::collections::{HashMap, VecDeque};
use std::fmt::Write as _;
use proptest::prelude::*;
use stratum_node_config::{preview, Change, Value};
const PATH: &str = "backup.age_recipients";
const PREFIX: &str = "schema_version = 1\n[backup]\nage_recipients = ";
fn alphabet() -> impl Strategy<Value = String> {
(0u8..5).prop_map(|i| format!("v{i}"))
}
#[derive(Debug, Clone)]
struct GenElement {
value: String,
heads: usize,
tail: bool,
same_line: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Layout {
SingleLine,
Multiline,
}
#[derive(Debug, Clone)]
struct GenArray {
layout: Layout,
indent: &'static str,
opening: bool,
elements: Vec<GenElement>,
closing: usize,
trailing_comma: bool,
outer: bool,
endings: Endings,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Endings {
Lf,
CrLf,
}
fn gen_element() -> impl Strategy<Value = GenElement> {
(alphabet(), 0usize..3, any::<bool>(), any::<bool>()).prop_map(
|(value, heads, tail, same_line)| GenElement {
value,
heads,
tail,
same_line,
},
)
}
fn gen_array() -> impl Strategy<Value = GenArray> {
(
any::<bool>(),
prop_oneof![Just(" "), Just(" "), Just("\t")],
any::<bool>(),
prop_oneof![
1 => Just(0usize..1),
4 => Just(1usize..6),
]
.prop_flat_map(|n| proptest::collection::vec(gen_element(), n)),
0usize..3,
any::<bool>(),
any::<bool>(),
prop_oneof![Just(Endings::Lf), Just(Endings::CrLf)],
)
.prop_map(
|(
single_line,
indent,
opening,
mut elements,
closing,
trailing_comma,
outer,
endings,
)| {
for i in 0..elements.len() {
let previous_ends_line = if i == 0 {
opening
} else {
elements[i - 1].tail
};
let e = &mut elements[i];
if single_line {
e.heads = 0;
e.tail = false;
e.same_line = true;
} else if e.heads > 0 || previous_ends_line {
e.same_line = false;
}
}
GenArray {
layout: if single_line {
Layout::SingleLine
} else {
Layout::Multiline
},
indent,
opening: opening && !single_line,
elements,
closing: if single_line { 0 } else { closing },
trailing_comma,
outer,
endings,
}
},
)
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Owned {
value: String,
heads: Vec<String>,
tail: Option<String>,
}
#[derive(Debug, Clone)]
struct Model {
opening: Option<String>,
elements: Vec<Owned>,
closing: Vec<String>,
outer: Option<String>,
}
impl Model {
fn edit(&self, list: &[String]) -> Self {
let mut queues: HashMap<&str, VecDeque<&Owned>> = HashMap::new();
for e in &self.elements {
queues.entry(e.value.as_str()).or_default().push_back(e);
}
let elements = list
.iter()
.map(|v| {
queues
.get_mut(v.as_str())
.and_then(VecDeque::pop_front)
.cloned()
.unwrap_or_else(|| Owned {
value: v.clone(),
heads: Vec::new(),
tail: None,
})
})
.collect();
Self {
elements,
..self.clone()
}
}
fn values(&self) -> Vec<String> {
self.elements.iter().map(|e| e.value.clone()).collect()
}
fn tokens(&self) -> Vec<&str> {
let mut all: Vec<&str> = self.opening.iter().map(String::as_str).collect();
for e in &self.elements {
all.extend(e.heads.iter().map(String::as_str));
all.extend(e.tail.iter().map(String::as_str));
}
all.extend(self.closing.iter().map(String::as_str));
all.extend(self.outer.iter().map(String::as_str));
all
}
}
fn render(g: &GenArray) -> (String, Model) {
let mut next = 0;
let mut token = || {
next += 1;
format!("c{next}")
};
let mut out = String::from(PREFIX);
out.push('[');
let opening = g.opening.then(&mut token);
if let Some(t) = &opening {
let _ = write!(out, " # {t}");
}
let first_same_line = g.elements.first().is_some_and(|e| e.same_line);
if !(g.layout == Layout::SingleLine) && !first_same_line {
out.push('\n');
}
let mut elements = Vec::new();
let n = g.elements.len();
for (i, e) in g.elements.iter().enumerate() {
let heads: Vec<String> = (0..e.heads).map(|_| token()).collect();
if e.same_line {
if i > 0 {
out.push(' ');
}
} else {
for h in &heads {
let _ = writeln!(out, "{}# {h}", g.indent);
}
out.push_str(g.indent);
}
let _ = write!(out, "{:?}", e.value);
if i + 1 < n || g.trailing_comma {
out.push(',');
}
let tail = e.tail.then(&mut token);
if let Some(t) = &tail {
let _ = write!(out, " # {t}");
}
let next_shares = g.elements.get(i + 1).is_some_and(|x| x.same_line);
if !(g.layout == Layout::SingleLine) && !next_shares {
out.push('\n');
}
elements.push(Owned {
value: e.value.clone(),
heads,
tail,
});
}
let closing: Vec<String> = (0..g.closing).map(|_| token()).collect();
for c in &closing {
let _ = writeln!(out, "{}# {c}", g.indent);
}
out.push(']');
let outer = g.outer.then(&mut token);
if let Some(t) = &outer {
let _ = write!(out, " # {t}");
}
out.push('\n');
(
out,
Model {
opening,
elements,
closing,
outer,
},
)
}
#[derive(Debug)]
struct Line {
values: Vec<String>,
open: bool,
close: bool,
comment: Option<String>,
}
impl Line {
fn comment_only(&self) -> bool {
self.values.is_empty() && !self.open && !self.close && self.comment.is_some()
}
}
fn scan(array_text: &str) -> Result<Vec<Line>, TestCaseError> {
let mut lines = Vec::new();
for raw in array_text.lines() {
let (code, comment) = match raw.find('#') {
Some(i) => (&raw[..i], Some(raw[i + 1..].trim().to_owned())),
None => (raw, None),
};
if let Some(c) = &comment {
prop_assert!(
c.starts_with('c') && c[1..].chars().all(|ch| ch.is_ascii_digit()),
"merged or malformed comment {c:?} in line {raw:?}"
);
}
let parts: Vec<&str> = code.split('"').collect();
prop_assert!(parts.len() % 2 == 1, "unbalanced quotes in {raw:?}");
let values = parts
.iter()
.skip(1)
.step_by(2)
.map(|s| (*s).to_owned())
.collect();
let outside: String = parts.iter().step_by(2).copied().collect();
lines.push(Line {
values,
open: outside.contains('['),
close: outside.contains(']'),
comment,
});
}
Ok(lines)
}
fn comments_above(lines: &[Line], at: usize) -> Vec<String> {
let mut run = Vec::new();
let mut i = at;
while i > 0 && lines[i - 1].comment_only() {
i -= 1;
run.push(lines[i].comment.clone().unwrap_or_default());
}
run.reverse();
run
}
fn check_with_endings(text: &str, model: &Model, endings: Endings) -> Result<(), TestCaseError> {
if endings == Endings::CrLf {
prop_assert!(
!text.replace("\r\n", "").contains('\n'),
"a line break of a CRLF document is not CRLF: {text:?}"
);
check(&text.replace("\r\n", "\n"), model)
} else {
prop_assert!(
!text.contains('\r'),
"an LF document gained a carriage return: {text:?}"
);
check(text, model)
}
}
fn check(text: &str, model: &Model) -> Result<(), TestCaseError> {
prop_assert!(
text.starts_with(PREFIX),
"text before the array changed: {text:?}"
);
let doc: toml_edit::DocumentMut = text
.parse()
.map_err(|e| TestCaseError::fail(format!("does not parse: {e}\n{text}")))?;
let parsed: Vec<String> = doc["backup"]["age_recipients"]
.as_array()
.ok_or_else(|| TestCaseError::fail("not an array"))?
.iter()
.map(|v| v.as_str().unwrap_or("<non-string>").to_owned())
.collect();
prop_assert_eq!(&parsed, &model.values(), "parsed values\n{}", text);
let array_text = &text[PREFIX.len()..];
let lines = scan(array_text)?;
let mut seen: Vec<&str> = lines.iter().filter_map(|l| l.comment.as_deref()).collect();
let mut want = model.tokens();
seen.sort_unstable();
want.sort_unstable();
prop_assert_eq!(seen, want, "comment set\n{}", text);
check_elements(text, &lines, model)?;
check_array_comments(text, &lines, model)
}
fn check_elements(text: &str, lines: &[Line], model: &Model) -> Result<(), TestCaseError> {
let positions: Vec<(usize, usize, usize)> = lines
.iter()
.enumerate()
.flat_map(|(li, l)| (0..l.values.len()).map(move |k| (li, k, l.values.len())))
.collect();
prop_assert_eq!(
positions.len(),
model.elements.len(),
"value count\n{}",
text
);
for (e, &(li, k, on_line)) in model.elements.iter().zip(&positions) {
let line = &lines[li];
prop_assert_eq!(&line.values[k], &e.value, "value order\n{}", text);
let last_on_line = k + 1 == on_line;
let line_comment = line
.comment
.as_deref()
.filter(|c| Some(*c) != model.outer.as_deref());
match &e.tail {
Some(t) => {
prop_assert!(
last_on_line,
"{} is not last on the line of {t}\n{text}",
e.value
);
prop_assert_eq!(
line_comment,
Some(t.as_str()),
"tail of {}\n{}",
e.value,
text
);
}
None if last_on_line => {
prop_assert_eq!(line_comment, None, "{} gained a comment\n{}", e.value, text);
}
None => {}
}
let first_on_line = k == 0;
if first_on_line {
prop_assert_eq!(
&comments_above(lines, li),
&e.heads,
"heads of {}\n{}",
e.value,
text
);
} else {
prop_assert!(
e.heads.is_empty(),
"{} has heads but shares a line\n{text}",
e.value
);
}
}
Ok(())
}
fn check_array_comments(text: &str, lines: &[Line], model: &Model) -> Result<(), TestCaseError> {
let open_line = lines.iter().position(|l| l.open);
prop_assert_eq!(open_line, Some(0), "[ line\n{}", text);
if let Some(t) = &model.opening {
prop_assert_eq!(
lines[0].comment.as_deref(),
Some(t.as_str()),
"opening\n{}",
text
);
prop_assert!(
lines[0].values.is_empty(),
"value on the opening line\n{text}"
);
}
let close_line = lines
.iter()
.position(|l| l.close)
.ok_or_else(|| TestCaseError::fail("no ]"))?;
prop_assert_eq!(
&comments_above(lines, close_line),
&model.closing,
"closing\n{}",
text
);
if let Some(t) = &model.outer {
prop_assert_eq!(
lines[close_line].comment.as_deref(),
Some(t.as_str()),
"outer\n{}",
text
);
}
Ok(())
}
fn edit_of(old: Vec<String>) -> BoxedStrategy<Vec<String>> {
let n = old.len();
let mut arms: Vec<BoxedStrategy<Vec<String>>> = vec![
Just(old.clone()).prop_shuffle().boxed(),
Just(Vec::new()).boxed(),
proptest::collection::vec(alphabet(), 0..7).boxed(),
{
let old = old.clone();
(0..=n, alphabet())
.prop_map(move |(i, v)| {
let mut l = old.clone();
l.insert(i, v);
l
})
.boxed()
},
Just(old.clone()).boxed(),
];
if n > 0 {
let o = old.clone();
arms.push(
(0..n)
.prop_map(move |i| {
let mut l = o.clone();
l.remove(i);
l
})
.boxed(),
);
let o = old.clone();
arms.push(
(0..n, alphabet())
.prop_map(move |(i, v)| {
let mut l = o.clone();
l[i] = v;
l
})
.boxed(),
);
let o = old;
arms.push(
proptest::sample::subsequence((0..n).collect::<Vec<_>>(), 0..=n)
.prop_shuffle()
.prop_map(move |idx| idx.iter().map(|&i| o[i].clone()).collect())
.boxed(),
);
}
proptest::strategy::Union::new(arms).boxed()
}
fn case() -> impl Strategy<Value = (GenArray, Vec<String>, Vec<String>)> {
gen_array().prop_flat_map(|g| {
let old: Vec<String> = g.elements.iter().map(|e| e.value.clone()).collect();
(Just(g), edit_of(old)).prop_flat_map(|(g, first)| {
let second = edit_of(first.clone());
(Just(g), Just(first), second)
})
})
}
fn apply(text: &str, list: &[String]) -> Result<String, TestCaseError> {
let p = preview(text, &[Change::new(PATH, Value::from(list.to_vec()))])
.map_err(|e| TestCaseError::fail(format!("preview failed: {e}\n{text}")))?;
Ok(p.text().to_owned())
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(2048))]
#[test]
fn list_edits_keep_every_comment_with_its_owner((g, first, second) in case()) {
let (lf_base, model) = render(&g);
let base = if g.endings == Endings::CrLf { lf_base.replace('\n', "\r\n") } else { lf_base };
check_with_endings(&base, &model, g.endings)?;
let text1 = apply(&base, &first)?;
let model1 = model.edit(&first);
check_with_endings(&text1, &model1, g.endings)?;
if first == model.values() {
prop_assert_eq!(&text1, &base, "unchanged list must be byte-identical");
}
let text2 = apply(&text1, &second)?;
let model2 = model1.edit(&second);
check_with_endings(&text2, &model2, g.endings)?;
if second == first {
prop_assert_eq!(&text2, &text1, "unchanged list must be byte-identical");
}
}
}