rustledger-parser 0.16.1

Beancount parser with error recovery and full syntax support
Documentation
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
//! CST baseline gate for `#1262`, switched to `parse_structured` at
//! phase 2.1a.
//!
//! For every `.beancount` file in `tests/compatibility/files/`,
//! hash:
//!
//! 1. The byte-identical round-trip of
//!    `parse_structured(source).text()` — must equal the source.
//!    Primary CST invariant.
//! 2. `token_seq_blake3` — ordered `(kind, len)` of LEAF tokens
//!    only. Stable across phase 2+ structural PRs — adding parent
//!    nodes around token runs doesn't change the token sequence.
//!    Only token-classification changes move this hash.
//! 3. `node_shape_blake3` — preorder node-ENTER sequence (kinds,
//!    no tokens). Phase 1 produced one entry per file
//!    (`SOURCE_FILE`). Phase 2.0 added the `DIRECTIVE` umbrella
//!    kind but didn't emit it from the parser. Phase 2.1a emits
//!    specific `*_DIRECTIVE` kinds for 14 single-line directives,
//!    so this column churns on every file that contains any
//!    recognized directive.
//!
//! Manifest format (one line per file, sorted lexically):
//!
//! ```text
//! relative/path<TAB>source_blake3<TAB>token_seq_blake3<TAB>node_shape_blake3
//! ```
//!
//! The split keeps phase-2 review surface honest: a structural PR
//! diffs the node column (expected, every file), and reviewers can
//! verify the token column is unchanged (any drift there is a real
//! regression).

mod baseline_common;

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

use baseline_common::is_in_tree_fixture;
use rustledger_parser::parse_structured;

const CORPUS_ROOT: &str = "tests/compatibility/files";
const MIN_FULL_CORPUS_SIZE: usize = 100;
const MANIFEST_PATH: &str = "tests/baselines/cst-corpus.manifest";

const MANIFEST_HEADER: &[&str] = &[
    "# CST baseline (#1262 phase 2.4, parse_structured). See crates/rustledger-parser/tests/cst_baseline.rs.",
    "# Format: path<TAB>source_blake3<TAB>token_seq_blake3<TAB>node_shape_blake3",
    "# Regenerate: BASELINE_UPDATE=1 cargo test -p rustledger-parser --test cst_baseline",
];

#[derive(Debug, Clone, PartialEq, Eq)]
struct Fingerprint {
    source: String,
    tokens: String,
    nodes: String,
}

fn repo_root() -> &'static Path {
    static ROOT: OnceLock<PathBuf> = OnceLock::new();
    ROOT.get_or_init(|| {
        let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        loop {
            if p.join(CORPUS_ROOT).is_dir() && has_workspace_table(&p) {
                return p;
            }
            assert!(
                p.pop(),
                "could not locate repo root from {}",
                env!("CARGO_MANIFEST_DIR"),
            );
        }
    })
}

fn has_workspace_table(dir: &Path) -> bool {
    let Ok(toml) = std::fs::read_to_string(dir.join("Cargo.toml")) else {
        return false;
    };
    toml.lines()
        .any(|line| line.trim_start().starts_with("[workspace]"))
}

fn discover_corpus_files() -> Vec<PathBuf> {
    let corpus_dir = repo_root().join(CORPUS_ROOT);
    let mut out = Vec::new();
    if !corpus_dir.is_dir() {
        return out;
    }
    walk(&corpus_dir, &mut out);
    out.sort();
    out
}

fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
    let entries = std::fs::read_dir(dir)
        .unwrap_or_else(|e| panic!("read_dir({}) failed: {e}", dir.display()));
    for entry in entries {
        let entry =
            entry.unwrap_or_else(|e| panic!("read_dir entry under {} failed: {e}", dir.display()));
        let path = entry.path();
        if path.is_dir() {
            walk(&path, out);
        } else if path.extension().and_then(|s| s.to_str()) == Some("beancount") {
            let rel = path
                .strip_prefix(repo_root())
                .expect("corpus paths under repo_root")
                .to_path_buf();
            out.push(rel);
        }
    }
}

/// Compute the fingerprint triple for a single corpus file. Files
/// that can't be UTF-8-decoded (e.g.,
/// `fava/tests_data_invalid-unicode.beancount`) get a
/// `read-error:<kind>` sentinel in every column matching the AST
/// baseline.
fn fingerprint(rel: &Path) -> Fingerprint {
    let abs = repo_root().join(rel);
    let source = match std::fs::read_to_string(&abs) {
        Ok(s) => s,
        Err(e) => {
            let tag = format!("read-error:{:?}", e.kind());
            return Fingerprint {
                source: tag.clone(),
                tokens: tag.clone(),
                nodes: tag,
            };
        }
    };
    let source_hash = blake3::hash(source.as_bytes()).to_hex().to_string();

    // Round-trip is part of the contract: a divergence here is a hard
    // failure of the CST builder, recorded as a sentinel so the
    // manifest diff is visible.
    let tree = parse_structured(&source);
    let reconstructed = tree.text().to_string();
    if reconstructed != source {
        return Fingerprint {
            source: source_hash,
            tokens: "round-trip-failure".to_string(),
            nodes: "round-trip-failure".to_string(),
        };
    }

    Fingerprint {
        source: source_hash,
        tokens: hash_token_sequence(&tree),
        nodes: hash_node_shape(&tree),
    }
}

/// Hash the ordered `(kind, len)` sequence of LEAF tokens. Stable
/// across phase 2+ structural changes because wrapping tokens in
/// parent nodes doesn't change the token sequence itself. The gate
/// for token-classification bugs (BOM misread as `ERROR_TOKEN`, Comment
/// vs Hash confusion, etc.).
fn hash_token_sequence(tree: &rustledger_parser::SyntaxNode) -> String {
    let mut hasher = blake3::Hasher::new();
    for elem in tree.preorder_with_tokens() {
        if let rowan::WalkEvent::Enter(rowan::NodeOrToken::Token(tok)) = elem {
            let kind = tok.kind() as u16;
            let len = u32::try_from(usize::from(tok.text_range().len())).unwrap_or(u32::MAX);
            hasher.update(&kind.to_le_bytes());
            hasher.update(&len.to_le_bytes());
        }
    }
    hasher.finalize().to_hex().to_string()
}

/// Hash the preorder sequence of node ENTER events (kinds only, no
/// tokens). Phase 1 emits exactly one entry per file (the root
/// `SOURCE_FILE`). Phase 2 PRs that wrap token runs in
/// `DIRECTIVE`/`POSTING`/etc. nodes change this column on every file
/// — that's the expected churn. The split lets reviewers verify
/// `token_seq_blake3` stays put while `node_shape_blake3` moves.
fn hash_node_shape(tree: &rustledger_parser::SyntaxNode) -> String {
    let mut hasher = blake3::Hasher::new();
    for elem in tree.preorder_with_tokens() {
        if let rowan::WalkEvent::Enter(rowan::NodeOrToken::Node(node)) = elem {
            let kind = node.kind() as u16;
            hasher.update(&kind.to_le_bytes());
        }
    }
    hasher.finalize().to_hex().to_string()
}

fn read_committed_manifest() -> BTreeMap<PathBuf, Fingerprint> {
    let path = repo_root().join(MANIFEST_PATH);
    let contents = match std::fs::read_to_string(&path) {
        Ok(s) => s,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => panic!("failed to read {}: {e}", path.display()),
    };
    let mut out = BTreeMap::new();
    for (lineno, line) in contents.lines().enumerate() {
        let lineno = lineno + 1;
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let mut parts = line.split('\t');
        let (Some(path_str), Some(source), Some(tokens), Some(nodes), None) = (
            parts.next(),
            parts.next(),
            parts.next(),
            parts.next(),
            parts.next(),
        ) else {
            panic!(
                "{}:{lineno}: malformed manifest line: {line:?}",
                path.display(),
            );
        };
        out.insert(
            PathBuf::from(path_str),
            Fingerprint {
                source: source.to_string(),
                tokens: tokens.to_string(),
                nodes: nodes.to_string(),
            },
        );
    }
    out
}

fn write_manifest(manifest: &BTreeMap<PathBuf, Fingerprint>) {
    let path = repo_root().join(MANIFEST_PATH);
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).expect("create baseline dir");
    }
    let mut out = String::new();
    for line in MANIFEST_HEADER {
        out.push_str(line);
        out.push('\n');
    }
    for (rel, fp) in manifest {
        use std::fmt::Write;
        let _ = writeln!(
            &mut out,
            "{}\t{}\t{}\t{}",
            rel.to_string_lossy(),
            fp.source,
            fp.tokens,
            fp.nodes,
        );
    }
    std::fs::write(&path, out).expect("write manifest");
    eprintln!("wrote {} entries to {}", manifest.len(), path.display());
}

/// The baseline test.
///
/// Modes (mirrors `corpus_baseline.rs`):
///
/// - **Default**: compare against the committed manifest. Token or
///   node drift on an unchanged-source file fails. A corpus smaller
///   than `MIN_FULL_CORPUS_SIZE` is skipped (warn).
/// - `BASELINE_UPDATE=1`: regenerate the manifest from current output.
/// - `STRICT_BASELINE=1`: turn the corpus-too-small skip into a hard
///   failure, AND escalate two in-tree-fixture conditions into drift:
///   (a) in-tree fixture present without a manifest entry; (b) in-
///   tree fixture with edited source whose manifest entry was not
///   regenerated. Downloaded-corpus equivalents stay warn-only (race
///   with upstream pushes is not the PR author's fault).
#[test]
fn cst_output_matches_baseline() {
    let strict = std::env::var_os("STRICT_BASELINE").is_some();
    let update = std::env::var_os("BASELINE_UPDATE").is_some();

    let files = discover_corpus_files();

    if files.len() < MIN_FULL_CORPUS_SIZE {
        assert!(
            !strict,
            "STRICT_BASELINE: corpus has {} files (need at least \
             {MIN_FULL_CORPUS_SIZE}). Did `fetch-compat-test-files.sh` run?",
            files.len(),
        );
        assert!(
            !update,
            "BASELINE_UPDATE=1 refusing to write manifest from only {} \
             files. Run `./scripts/fetch-compat-test-files.sh` first.",
            files.len(),
        );
        eprintln!(
            "corpus at `{CORPUS_ROOT}` has only {} files; skipping. \
             CI uses STRICT_BASELINE=1.",
            files.len(),
        );
        return;
    }

    let current: BTreeMap<PathBuf, Fingerprint> = files
        .iter()
        .map(|rel| (rel.clone(), fingerprint(rel)))
        .collect();

    if update {
        write_manifest(&current);
        return;
    }

    let committed = read_committed_manifest();

    let mut token_drift: Vec<(PathBuf, String, String)> = Vec::new();
    let mut node_drift: Vec<(PathBuf, String, String)> = Vec::new();
    let mut source_drift: Vec<PathBuf> = Vec::new();
    let mut round_trip_failures: Vec<PathBuf> = Vec::new();
    let mut missing_from_corpus: Vec<PathBuf> = Vec::new();
    let mut missing_from_manifest: Vec<PathBuf> = Vec::new();

    for (path, expected) in &committed {
        match current.get(path) {
            None => missing_from_corpus.push(path.clone()),
            Some(c) if c.source != expected.source => source_drift.push(path.clone()),
            Some(c) if c.tokens == "round-trip-failure" => {
                round_trip_failures.push(path.clone());
            }
            Some(c) => {
                if c.tokens != expected.tokens {
                    token_drift.push((path.clone(), expected.tokens.clone(), c.tokens.clone()));
                }
                if c.nodes != expected.nodes {
                    node_drift.push((path.clone(), expected.nodes.clone(), c.nodes.clone()));
                }
            }
        }
    }
    for path in current.keys() {
        if !committed.contains_key(path) {
            missing_from_manifest.push(path.clone());
        }
    }

    // Mirror corpus_baseline.rs: only ESCALATE in-tree-fixture problems
    // to strict-mode failure. Downloaded-corpus appearances are subject
    // to upstream race; an unmanifested-or-edited downloaded fixture
    // shouldn't fail CI on PRs that don't touch it. But edits under
    // `tests/compatibility/files/plugins/` ARE PR-author actions
    // (committed in-tree), and a missing manifest entry or source
    // drift there means the contributor forgot to regenerate
    // — exactly the silent-manifest-desync class of bug strict mode
    // exists to catch.
    let unmanifested_in_tree: Vec<&PathBuf> = missing_from_manifest
        .iter()
        .filter(|p| is_in_tree_fixture(p))
        .collect();
    let source_drift_in_tree: Vec<&PathBuf> = source_drift
        .iter()
        .filter(|p| is_in_tree_fixture(p))
        .collect();
    let unprotected_in_strict =
        strict && (!unmanifested_in_tree.is_empty() || !source_drift_in_tree.is_empty());

    if token_drift.is_empty()
        && node_drift.is_empty()
        && round_trip_failures.is_empty()
        && !unprotected_in_strict
    {
        if !source_drift.is_empty() {
            eprintln!(
                "info: {} corpus file(s) have new source hashes; CST \
                 kind hash NOT checked for those. Regenerate when \
                 convenient: BASELINE_UPDATE=1 cargo test -p \
                 rustledger-parser --test cst_baseline",
                source_drift.len(),
            );
        }
        if !missing_from_manifest.is_empty() {
            eprintln!(
                "warning: {} corpus file(s) have no manifest entry.",
                missing_from_manifest.len(),
            );
        }
        if !missing_from_corpus.is_empty() {
            eprintln!(
                "warning: {} manifest entry/entries refer to files no \
                 longer present in the corpus.",
                missing_from_corpus.len(),
            );
        }
        return;
    }

    let mut report = String::new();
    if !round_trip_failures.is_empty() {
        use std::fmt::Write;
        let _ = writeln!(
            &mut report,
            "Round-trip failed on {} file(s):",
            round_trip_failures.len(),
        );
        for path in round_trip_failures.iter().take(10) {
            let _ = writeln!(&mut report, "  {}", path.display());
        }
    }
    if !token_drift.is_empty() {
        use std::fmt::Write;
        let _ = writeln!(
            &mut report,
            "Token-sequence drift on {} file(s) with unchanged source (first 10):",
            token_drift.len(),
        );
        for (path, expected, current) in token_drift.iter().take(10) {
            let _ = writeln!(
                &mut report,
                "  {}\n    expected: {}\n    current:  {}",
                path.display(),
                &expected[..16.min(expected.len())],
                &current[..16.min(current.len())],
            );
        }
    }
    if !node_drift.is_empty() {
        use std::fmt::Write;
        let _ = writeln!(
            &mut report,
            "Node-shape drift on {} file(s) with unchanged source (first 10):",
            node_drift.len(),
        );
        for (path, expected, current) in node_drift.iter().take(10) {
            let _ = writeln!(
                &mut report,
                "  {}\n    expected: {}\n    current:  {}",
                path.display(),
                &expected[..16.min(expected.len())],
                &current[..16.min(current.len())],
            );
        }
    }
    if strict && !unmanifested_in_tree.is_empty() {
        use std::fmt::Write;
        let _ = writeln!(
            &mut report,
            "\n{} in-tree fixture(s) have no manifest entry (first 10):",
            unmanifested_in_tree.len(),
        );
        for path in unmanifested_in_tree.iter().take(10) {
            let _ = writeln!(&mut report, "  {}", path.display());
        }
    }
    if strict && !source_drift_in_tree.is_empty() {
        use std::fmt::Write;
        let _ = writeln!(
            &mut report,
            "\n{} in-tree fixture(s) have edited source without a manifest regen (first 10):",
            source_drift_in_tree.len(),
        );
        for path in source_drift_in_tree.iter().take(10) {
            let _ = writeln!(&mut report, "  {}", path.display());
        }
    }
    panic!(
        "CST baseline drift:\n\n{report}\nIf this drift is intentional, \
         regenerate:\n  BASELINE_UPDATE=1 cargo test -p rustledger-parser \
         --test cst_baseline\n\nReview the diff against `{MANIFEST_PATH}` \
         and commit.",
    );
}