silcrow 0.2.0

Deterministic CLI for a citable, checkable graph of laws in a git tree.
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
//! Decision notes for the property tests: `##` sections, laws, clauses and compound
//! clauses, each with or without an attached table, fence or continuation, struck or not,
//! published or not. ASCII only: canonicalisation outside ASCII is an open question.

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>,
}

/// Where a pointer sits: a code file outside every note, the lettered line of the k-th
/// clause in document order, or that clause's continuation line.
#[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>,
}

/// A code marker the renderer placed outside the note.
#[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,
    /// The same note at the base: published clauses only, struck as they were there.
    pub base: String,
    /// `id` and `id.letter` keys present at the base.
    pub published: BTreeSet<String>,
    pub code_pointers: Vec<CodePointer>,
    /// Whether a pointer outside the lines `squash` removes targets a clause it removes
    /// or tombstones.
    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),
    ]
}

/// A note with minted ids only. `provisional` lets laws carry `§ +name`; `pointers`
/// adds cites and code markers aimed at its own clauses.
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 }
        })
}

/// What a real history allows: nothing unpublished under an unpublished parent, and
/// nothing struck at the base that is live now.
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;
                // A struck law the base published stays as it is, its clauses with it.
                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}```"));
    }
}