use proptest::prelude::*;
use std::collections::BTreeSet;
use crate::hash;
const WORDS: &[&str] = &[
"alpha", "beta", "river", "stone", "cloud", "ember", "north", "quiet",
];
#[derive(Clone, Debug)]
pub struct GenClause {
words: Vec<&'static str>,
struck: bool,
base_struck: bool,
published: bool,
tight: bool,
flat: bool,
cont: bool,
table: bool,
fence: bool,
children: Vec<GenClause>,
}
#[derive(Clone, Debug)]
pub struct GenLaw {
words: Vec<&'static str>,
struck: bool,
base_struck: bool,
published: bool,
provisional: bool,
bold: bool,
table: bool,
fence: bool,
context: bool,
clauses: Vec<GenClause>,
}
#[derive(Clone, Copy, Debug)]
pub enum Place {
Code,
Text(usize),
Cont(usize),
}
#[derive(Clone, Debug)]
pub struct GenPointer {
target: usize,
place: Place,
}
#[derive(Clone, Debug)]
pub struct GenNote {
sections: Vec<Vec<GenLaw>>,
pointers: Vec<GenPointer>,
}
#[derive(Clone, Debug)]
pub struct CodePointer {
pub line: usize,
pub id: String,
pub letter: Option<String>,
}
#[derive(Clone, Debug)]
pub struct Rendered {
pub text: String,
pub base: String,
pub published: BTreeSet<String>,
pub code_pointers: Vec<CodePointer>,
pub expect_refusal: bool,
}
fn gen_words() -> impl Strategy<Value = Vec<&'static str>> {
prop::collection::vec(prop::sample::select(WORDS), 1..4)
}
fn gen_clause_leaf() -> impl Strategy<Value = GenClause> {
(gen_words(), any::<[bool; 8]>()).prop_map(|(words, b)| GenClause {
words,
struck: b[0],
base_struck: b[1],
published: b[2],
tight: b[3],
flat: b[4],
cont: b[5],
table: b[6],
fence: b[7],
children: Vec::new(),
})
}
fn gen_clause() -> impl Strategy<Value = GenClause> {
(
gen_clause_leaf(),
prop::collection::vec(gen_clause_leaf(), 0..3),
)
.prop_map(|(mut al, kids)| {
al.children = kids;
al
})
}
fn gen_law() -> impl Strategy<Value = GenLaw> {
(
gen_words(),
any::<[bool; 8]>(),
prop::collection::vec(gen_clause(), 0..4),
)
.prop_map(|(words, b, clauses)| GenLaw {
words,
struck: b[0],
base_struck: b[1],
published: b[2],
provisional: b[3],
bold: b[4],
table: b[5],
fence: b[6],
context: b[7],
clauses,
})
}
fn gen_place() -> impl Strategy<Value = Place> {
prop_oneof![
Just(Place::Code),
any::<usize>().prop_map(Place::Text),
any::<usize>().prop_map(Place::Cont),
]
}
pub fn gen_note(provisional: bool, pointers: bool) -> impl Strategy<Value = GenNote> {
let max = if pointers { 6 } else { 0 };
(
prop::collection::vec(prop::collection::vec(gen_law(), 1..4), 1..4),
prop::collection::vec(
(any::<usize>(), gen_place()).prop_map(|(target, place)| GenPointer { target, place }),
0..=max,
),
)
.prop_map(move |(mut sections, pointers)| {
for law in sections.iter_mut().flatten() {
gen_normalise_law(law, provisional);
}
GenNote { sections, pointers }
})
}
fn gen_normalise_law(law: &mut GenLaw, provisional: bool) {
law.provisional &= provisional && !law.published;
law.base_struck &= law.published;
law.struck |= law.base_struck;
for al in &mut law.clauses {
gen_normalise_clause(al, law.published);
}
}
fn gen_normalise_clause(al: &mut GenClause, parent_published: bool) {
al.published &= parent_published;
al.base_struck &= al.published;
al.struck |= al.base_struck;
let published = al.published;
for kid in &mut al.children {
gen_normalise_clause(kid, published);
}
}
#[derive(Clone, Copy, PartialEq)]
enum Fate {
Keep,
Tombstone,
Delete,
}
struct Flat<'a> {
al: &'a GenClause,
depth: usize,
letter: String,
tag: usize,
fate: Fate,
}
fn gen_letter(n: usize) -> char {
(b'a' + n as u8) as char
}
impl GenNote {
pub fn render(&self) -> Rendered {
let mut tag = 0usize;
let mut laws = Vec::new();
let mut flats: Vec<Flat> = Vec::new();
for (s, section) in self.sections.iter().enumerate() {
for law in section {
tag += 1;
let law_tag = tag;
let sentence = format!("{} law{tag}.", law.words.join(" "));
let id = if law.provisional {
format!("+p{tag}")
} else {
hash::mint_id(&sentence)
};
let law_deleted = law.struck && !law.published;
let law_fate = match (law.struck, law.published) {
(true, false) => Some(Fate::Delete),
(true, true) => Some(Fate::Keep),
_ => None,
};
let first = flats.len();
for (i, al) in law.clauses.iter().enumerate() {
let letter = gen_letter(i).to_string();
tag += 1;
flats.push(gen_flat(al, 0, letter.clone(), tag, law_fate));
for (k, kid) in al.children.iter().enumerate() {
tag += 1;
let letter = format!("{letter}{}", gen_letter(k));
flats.push(gen_flat(kid, 1, letter, tag, law_fate));
}
}
laws.push((
s,
law,
law_tag,
sentence,
id,
law_deleted,
first..flats.len(),
));
}
}
let keys: Vec<(String, Option<String>, bool)> = laws
.iter()
.filter(|(_, law, ..)| !law.provisional)
.flat_map(|(_, _, _, _, id, deleted, range)| {
std::iter::once((id.clone(), None, *deleted)).chain(
flats[range.clone()]
.iter()
.map(|f| (id.clone(), Some(f.letter.clone()), f.fate != Fate::Keep)),
)
})
.collect();
let mut text_links: Vec<Vec<String>> = vec![Vec::new(); flats.len()];
let mut cont_links: Vec<Vec<String>> = vec![Vec::new(); flats.len()];
let mut code_pointers = Vec::new();
let mut expect_refusal = false;
for ptr in &self.pointers {
if keys.is_empty() {
break;
}
let (id, letter, removed) = &keys[ptr.target % keys.len()];
let link = match letter {
Some(l) => format!("[{id}.{l}](#{id})"),
None => format!("[{id}](#{id})"),
};
let place = if flats.is_empty() {
Place::Code
} else {
ptr.place
};
let on_removed_line = match place {
Place::Code => {
code_pointers.push(CodePointer {
line: code_pointers.len() + 1,
id: id.clone(),
letter: letter.clone(),
});
false
}
Place::Text(k) => {
let k = k % flats.len();
text_links[k].push(link);
flats[k].fate != Fate::Keep
}
Place::Cont(k) => {
let k = k % flats.len();
cont_links[k].push(link);
flats[k].fate != Fate::Keep
}
};
expect_refusal |= *removed && !on_removed_line;
}
let mut now = Vec::new();
let mut base = Vec::new();
let mut published = BTreeSet::new();
let mut section = usize::MAX;
for (s, law, law_tag, sentence, id, _, range) in &laws {
if *s != section {
section = *s;
now.push(format!("## Section {s}"));
base.push(format!("## Section {s}"));
}
gen_push_law(&mut now, law, sentence, id, law.struck, *law_tag);
if law.published {
published.insert(id.clone());
gen_push_law(&mut base, law, sentence, id, law.base_struck, *law_tag);
}
for (k, f) in flats[range.clone()].iter().enumerate() {
let k = range.start + k;
gen_push_clause(&mut now, f, f.al.struck, &text_links[k], &cont_links[k]);
if f.al.published {
published.insert(format!("{id}.{}", f.letter));
gen_push_clause(
&mut base,
f,
f.al.base_struck,
&text_links[k],
&cont_links[k],
);
}
}
if law.context {
now.push(String::new());
now.push(format!("Context words ctx{law_tag}."));
if law.published {
base.push(String::new());
base.push(format!("Context words ctx{law_tag}."));
}
}
}
Rendered {
text: now.join("\n") + "\n",
base: base.join("\n") + "\n",
published,
code_pointers,
expect_refusal,
}
}
}
fn gen_flat(
al: &GenClause,
depth: usize,
letter: String,
tag: usize,
law_fate: Option<Fate>,
) -> Flat<'_> {
let fate = if let Some(fate) = law_fate {
fate
} else if !al.struck || (!al.published && al.children.iter().any(|k| !k.struck)) {
Fate::Keep
} else if al.published {
Fate::Tombstone
} else {
Fate::Delete
};
Flat {
al,
depth,
letter,
tag,
fate,
}
}
fn gen_push_law(
out: &mut Vec<String>,
law: &GenLaw,
sentence: &str,
id: &str,
struck: bool,
tag: usize,
) {
let inner = if struck {
format!("§ {id} ~~{sentence}~~")
} else {
format!("§ {id} {sentence}")
};
out.push(String::new());
out.push(if law.bold {
format!("**{inner}**")
} else {
inner
});
if law.table {
out.push(String::new());
out.push(format!("| hcol{tag} | hval{tag} |"));
out.push("| --- | --- |".to_string());
}
if law.fence {
out.push(String::new());
out.push("```text".to_string());
out.push(format!("head{tag} --> x"));
out.push("```".to_string());
}
}
fn gen_push_clause(
out: &mut Vec<String>,
f: &Flat,
struck: bool,
text_links: &[String],
cont_links: &[String],
) {
let al = f.al;
let tag = f.tag;
let indent = if al.flat { 0 } else { 2 * f.depth };
let pad = " ".repeat(indent);
let body = " ".repeat(indent + 2);
let mut text = format!("{} al{tag}", al.words.join(" "));
for link in text_links {
text.push_str(&format!(" see {link}"));
}
let text = if struck { format!("~~{text}~~") } else { text };
if !al.tight {
out.push(String::new());
}
out.push(format!("{pad}- ({}) {text}", f.letter));
if al.cont || !cont_links.is_empty() {
let mut line = format!("{body}More words cont{tag}.");
for link in cont_links {
line.push_str(&format!(" See {link}."));
}
out.push(String::new());
out.push(line);
}
if al.table {
out.push(String::new());
out.push(format!("{body}| col{tag} | val{tag} |"));
out.push(format!("{body}| --- | --- |"));
out.push(format!("{body}| x{tag} | y{tag} |"));
}
if al.fence {
out.push(String::new());
out.push(format!("{body}```text"));
out.push(format!("{body}code{tag} --> x"));
out.push(format!("{body}```"));
}
}