visi-core 0.2.2

Embeddable spreadsheet engine: Excel formula compilation and evaluation, dependency-tracked recalculation, and .xlsx import/export
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
//! VBA macro project data model.
//!
//! A `VbaProject` is workbook-level (like `Chart`/`PivotTable`), not
//! sheet-scoped like `ExcelTable`, since it's a single `vbaProject.bin` part
//! per workbook holding potentially many modules, some of which (document
//! modules) happen to bind to individual sheets.
//!
//! Unlike tables/pivots, round-tripping this through xlsx doesn't mean
//! re-deriving every byte from these fields on export: `raw_donor` holds the
//! `vbaProject.bin` bytes export (`vba_xlsx.rs`) patches only what changed
//! into, rather than synthesizing a full CFB container from scratch every
//! time. For a project imported from a real file, that's the file's own
//! original bytes (preserving whatever PROJECTREFERENCES it already had --
//! e.g. MSForms, Office -- which this codebase doesn't yet synthesize). For
//! a brand-new project, `VbaProject::new_empty` builds `raw_donor` (and the
//! per-module `prefix_bytes` new modules borrow) entirely synthetically via
//! `vba_synth.rs`, with no real Excel-authored file involved. See
//! `vba_xlsx.rs` and `vba_synth.rs` for why that used to require one, and
//! the design notes in this crate's VBA feature plan for the full rationale
//! (proven via a scratchpad proof-of-concept against real Excel).

// The syntax layer. These are `#[doc(hidden)] pub` for the same reason
// `ovba` and `vba_xlsx` are: `visi-core/fuzz`'s `vba_parse` target needs to
// reach `parse_module` from outside the crate. The supported surface is
// [`check_syntax`] and [`ModuleSyntax`] below, which is what `core`'s
// `pub use` list carries -- the AST is an implementation detail until the
// interpreter phases need it, and pinning its shape now would be a semver
// commitment made a phase too early.
#[doc(hidden)]
pub mod ast;
pub(crate) mod builtin_names;
#[doc(hidden)]
pub mod builtins;
pub(crate) mod color;
#[doc(hidden)]
pub mod host;
#[doc(hidden)]
pub mod interp;
#[doc(hidden)]
pub mod lexer;
#[doc(hidden)]
pub mod parser;
pub(crate) mod resolve;
#[doc(hidden)]
pub mod value;

use crate::{Error, ObjectKind};
use serde::{Deserialize, Serialize};

/// What [`check_syntax`] found in a module that parsed.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct ModuleSyntax {
    /// The names of every `Sub`, `Function` and `Property` declared, in source
    /// order. Procedures inside a `#If` branch are all included: which branch
    /// is live depends on `#Const` values, which parsing alone cannot decide.
    pub procedures: Vec<String>,
}

/// Checks a VBA module's source for syntax errors.
///
/// Phase 0 of the plan in `docs/vba-macro-support.md`, plus the narrow
/// name-resolution pass in [`resolve`] that issue #78 called for: it answers
/// whether the source *compiles*, as far as parsing and resolving the names
/// it can see will show. It does not check types or evaluate anything, so it
/// will still accept a module that fails at run time -- and, being an
/// independent implementation, may differ from Excel's compiler at the edges.
///
/// **`source` is treated as a self-contained project.** A name used with
/// call syntax that resolves nowhere -- not in this module, not a VBA or
/// Excel built-in -- is reported, which is right for a standalone `.bas` and
/// for the single generated module the differential harness compiles, but
/// would be wrong for one module of a larger project, where the name may
/// live in a sibling. Use [`VbaProject::check_modules`] for that case -- it
/// supplies each module the others' names -- or [`check_syntax_partial`]
/// when the siblings are not available at all.
///
/// ```
/// use visi_core::core::check_syntax;
/// assert!(check_syntax("Sub Hello()\n    MsgBox \"hi\"\nEnd Sub\n").is_ok());
/// assert!(check_syntax("Sub Hello()\n").is_err());
/// ```
pub fn check_syntax(source: &str) -> Result<ModuleSyntax, Error> {
    let empty = std::collections::HashSet::new();
    check_source(source, None, &resolve::Scope::self_contained(&empty))
}

/// [`check_syntax`] for source that is **one module of a larger project**
/// whose other modules are not available.
///
/// Same parse and the same rules, with one exception: a name that resolves
/// nowhere is accepted rather than reported, since a sibling module this
/// call cannot see may well declare it. Everything the module's own text
/// disproves -- a syntax error, a duplicate declaration, a plain local used
/// as a call target -- is still reported.
///
/// This is strictly the weaker check, and is the scope
/// [`VbaModule::check_syntax`] already uses. Prefer
/// [`VbaProject::check_modules`] wherever the whole project is in hand;
/// reach for this only when it genuinely is not, as for a `.bas` file cut
/// out of a project that lives elsewhere.
///
/// ```
/// use visi_core::core::{check_syntax, check_syntax_partial};
/// // `DoWork` is declared by some other module of the project.
/// let src = "Sub Caller()\n    DoWork 1\nEnd Sub\n";
/// assert!(check_syntax(src).is_err());
/// assert!(check_syntax_partial(src).is_ok());
/// // A fragment is still held to what its own text shows.
/// assert!(check_syntax_partial("Sub Caller()\n").is_err());
/// ```
pub fn check_syntax_partial(source: &str) -> Result<ModuleSyntax, Error> {
    let empty = std::collections::HashSet::new();
    check_source(source, None, &resolve::Scope::partial(&empty))
}

/// [`check_syntax`]'s body, with the resolution scope chosen by the caller.
fn check_source(
    source: &str,
    module_name: Option<&str>,
    scope: &resolve::Scope<'_>,
) -> Result<ModuleSyntax, Error> {
    let to_err = |e: parser::ParseError| Error::VbaSyntax {
        message: e.message,
        module: module_name.map(str::to_string),
        line: e.pos.line,
        column: e.pos.col,
    };
    let module = parser::parse_module(source).map_err(to_err)?;
    resolve::check_module(&module, scope).map_err(to_err)?;
    Ok(ModuleSyntax {
        procedures: module.procedures().iter().map(|p| p.name.clone()).collect(),
    })
}

/// The outcome of running a VBA procedure: its return value, rendered the way
/// VBA would render it, plus the subtype name `TypeName()` reports.
///
/// Both halves matter. An interpreter that computes the right number with the
/// wrong subtype has a real bug -- `1 + 1` is an `Integer` and `1 / 1` is a
/// `Double` -- so the differential fuzzer compares the type as well as the
/// value.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct RunOutcome {
    /// `TypeName()` of the returned value.
    pub type_name: String,
    /// `CStr()` of the returned value, or `None` where VBA itself cannot
    /// stringify it (`Null`).
    pub value: Option<String>,
    /// Whether the run changed the workbook.
    ///
    /// Always `false` from [`run_macro`], which has no workbook to change.
    /// From [`crate::core::WorkbookManager::run_macro`] this is what tells a caller
    /// whether it has something worth saving -- and, for the `visi` CLI,
    /// whether discarding the result silently would be a data loss rather
    /// than a no-op.
    pub mutated: bool,
}

/// Turns command-line argument text into the `Variant`s a procedure receives.
///
/// Arguments arrive as text -- they come from a CLI or a fuzz harness -- and
/// are given the type VBA would give the same literal, so `-a 1` is an
/// `Integer` and `-a 1.5` a `Double`.
fn parse_args(args: &[&str]) -> Vec<value::Variant> {
    args.iter()
        .map(|a| match value::parse_vba_number(a) {
            Ok(n) if !a.trim().is_empty() => {
                value::Variant::from_literal(n, a.contains('.') || a.contains(['e', 'E']))
            }
            _ => value::Variant::Str((*a).to_string()),
        })
        .collect()
}

fn to_outcome(result: value::Variant, mutated: bool, interp: &interp::Interpreter) -> RunOutcome {
    RunOutcome {
        type_name: interp.type_name_of(&result),
        value: result.to_vba_string().ok(),
        mutated,
    }
}

fn parse_or_error(source: &str, module: Option<&str>) -> Result<ast::Module, Error> {
    parser::parse_module(source).map_err(|e| Error::VbaSyntax {
        message: e.message,
        module: module.map(str::to_string),
        line: e.pos.line,
        column: e.pos.col,
    })
}

fn to_runtime_error(e: value::VbaError) -> Error {
    Error::VbaRuntime {
        message: e.description,
        number: e.number,
    }
}

impl crate::core::WorkbookManager {
    /// Runs one of this workbook's own VBA procedures **against** this
    /// workbook.
    ///
    /// Phase 2 of `docs/vba-macro-support.md`, and the entry point that
    /// separates it from Phase 1: the interpreter borrows the workbook for
    /// the duration, so a macro can read and write cells, walk the sheets,
    /// and call worksheet functions. [`run_macro`] stays as the text-only
    /// form -- it is what `visi_core.run_macro` and `fuzz/fuzz_vba.py` drive,
    /// and a macro that touches no workbook has no reason to need one.
    ///
    /// `module` picks which module to take the procedure from; `None`
    /// searches every module for one that declares it, which is the common
    /// single-module case. Resolving it here rather than in each caller is
    /// Runs a VBA procedure in the workbook's project.
    ///
    /// The workbook is left recalculated, so a caller that saves afterwards
    /// writes the values the macro itself would have read.
    pub fn run_macro(
        &mut self,
        module: Option<&str>,
        procedure: &str,
        args: &[&str],
    ) -> Result<RunOutcome, Error> {
        let args = parse_args(args);

        let interp = if let Some(project) = &self.vba_project {
            if let Some(name) = module
                && project.find_module(name).is_none()
            {
                let available = project.modules.iter().map(|m| m.name.clone()).collect();
                return Err(Error::not_found_among(
                    ObjectKind::VbaModule,
                    name,
                    available,
                ));
            }
            interp::Interpreter::from_project(project, module).map_err(to_runtime_error)?
        } else {
            let source = self.macro_source_for(module, procedure)?;
            let parsed = parse_or_error(&source, module)?;
            interp::Interpreter::new(parsed)
        };

        let host = host::Host::new(self).map_err(to_runtime_error)?;
        let mut interp = interp.with_host(host);

        let result = interp.run(procedure, args);
        // The recalculation runs whether or not the procedure succeeded: a
        // macro that wrote three cells and then raised has still written
        // them, and leaving the workbook holding stale computed values would
        // make the failure look like corruption.
        interp.finish();
        let mutated = interp.mutated();
        let result = result.map_err(to_runtime_error)?;
        Ok(to_outcome(result, mutated, &interp))
    }

    /// Runs startup macro events (`Workbook_Open` in `ThisWorkbook` then `Auto_Open` in standard modules).
    pub fn run_open_events(&mut self) -> Result<RunOutcome, Error> {
        let interp = if let Some(project) = &self.vba_project {
            interp::Interpreter::from_project(project, None).map_err(to_runtime_error)?
        } else {
            return Err(Error::not_found(
                ObjectKind::VbaModule,
                "Workbook_Open or Auto_Open",
            ));
        };

        let host = host::Host::new(self).map_err(to_runtime_error)?;
        let mut interp = interp.with_host(host);

        interp.run_open_events().map_err(to_runtime_error)?;
        interp.finish();
        let mutated = interp.mutated();
        Ok(RunOutcome {
            type_name: "Empty".to_string(),
            value: Some(String::new()),
            mutated,
        })
    }

    /// The source text to run, resolving `module` the way
    /// [`WorkbookManager::run_macro`] documents.
    fn macro_source_for(&self, module: Option<&str>, procedure: &str) -> Result<String, Error> {
        let project = self
            .vba_project
            .as_ref()
            .ok_or_else(|| Error::not_found(ObjectKind::VbaModule, module.unwrap_or(procedure)))?;
        let available = || project.modules.iter().map(|m| m.name.clone()).collect();
        if let Some(name) = module {
            return project
                .find_module(name)
                .map(|m| m.source.clone())
                .ok_or_else(|| Error::not_found_among(ObjectKind::VbaModule, name, available()));
        }
        project
            .modules
            .iter()
            // A module that does not parse is skipped rather than fatal: it
            // cannot be the one declaring the procedure, and reporting its
            // syntax error here would blame the wrong module entirely.
            //
            // Deliberately `parse_module` rather than `check_syntax`: the
            // only question is which module *declares* this procedure, which
            // is answered by parsing alone. Going through the name-resolution
            // pass as well would let an unrelated unresolved name elsewhere
            // in the module hide a procedure that is really there.
            .find(|m| {
                parser::parse_module(&m.source).is_ok_and(|module| {
                    module
                        .procedures()
                        .iter()
                        .any(|p| p.name.eq_ignore_ascii_case(procedure))
                })
            })
            .map(|m| m.source.clone())
            .ok_or_else(|| {
                Error::not_found_among(
                    ObjectKind::VbaModule,
                    format!("a module declaring '{procedure}'"),
                    available(),
                )
            })
    }
}

/// Parses `source` and runs one of its procedures.
///
/// Phase 1 of `docs/vba-macro-support.md`: expressions, control flow,
/// `Sub`/`Function` calls and `On Error`. There is **no host object model**,
/// so anything touching a workbook raises a run-time error naming what it
/// was rather than silently doing nothing.
///
/// Execution is bounded -- a statement budget stops a runaway loop and a
/// depth limit stops unbounded recursion -- because this runs source the
/// caller did not necessarily write.
///
/// ```
/// use visi_core::core::run_macro;
/// let src = "Function Add2(a, b)\n    Add2 = a + b\nEnd Function\n";
/// let out = run_macro(src, "Add2", &["1", "2"]).unwrap();
/// assert_eq!(out.type_name, "Integer");
/// assert_eq!(out.value.as_deref(), Some("3"));
/// ```
pub fn run_macro(source: &str, procedure: &str, args: &[&str]) -> Result<RunOutcome, Error> {
    let module = parser::parse_module(source).map_err(|e| Error::VbaSyntax {
        message: e.message,
        module: None,
        line: e.pos.line,
        column: e.pos.col,
    })?;
    let mut interp = interp::Interpreter::new(module);
    let result = interp
        .run(procedure, parse_args(args))
        .map_err(to_runtime_error)?;

    Ok(to_outcome(result, false, &interp))
}

impl VbaModule {
    /// Checks this module's source, naming it in any error.
    ///
    /// The name matters more than it looks: a workbook can hold many modules
    /// and `visi macro check` reports on all of them, so an error that does
    /// not say which one it came from is close to useless.
    ///
    /// A `VbaModule` does not know its project, so unlike the free
    /// [`check_syntax`] this **cannot** conclude anything from a name it
    /// fails to resolve -- a sibling module may well declare it. Reach for
    /// [`VbaProject::check_modules`] when the project is available; it is
    /// strictly the better check.
    pub fn check_syntax(&self) -> Result<ModuleSyntax, Error> {
        let empty = std::collections::HashSet::new();
        check_source(
            &self.source,
            Some(&self.name),
            &resolve::Scope::partial(&empty),
        )
    }
}

/// What kind of VBA module a [`VbaModule`] is, which decides how it binds to
/// the workbook.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum VbaModuleKind {
    /// A `.bas`-equivalent module with no host object binding.
    Standard,
    /// A `.cls`-equivalent module (not validated end-to-end against real
    /// Excel yet -- see the feature plan's open-risk notes).
    Class,
    /// `ThisWorkbook` or a worksheet's code-behind module. Must correspond
    /// 1:1 with an existing sheet (or the workbook itself) via
    /// `bound_sheet_id`, mirroring Excel's own codeName wiring.
    Document,
}

/// A single VBA module's editable content plus the opaque bytes needed to
/// keep Excel happy on export.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct VbaModule {
    /// VB_Name -- must satisfy `validate_vba_module_name`.
    pub name: String,
    /// What kind of module this is, and so how it binds to the workbook.
    pub kind: VbaModuleKind,
    /// Plain VBA source text (no compression, no Attribute-line management
    /// beyond what the caller writes -- callers are expected to include the
    /// `Attribute VB_Name = "..."` line themselves, matching how real
    /// Excel-authored module streams are shaped).
    pub source: String,
    /// Required iff `kind == Document`: the sheet this module's code
    /// belongs to (or `None`/ignored for `ThisWorkbook`, which isn't tied to
    /// a specific sheet). Kept as a stable id (not a name) so sheet renames
    /// don't silently orphan the binding -- deliberately NOT cascaded the
    /// other direction (renaming this module does not rename the sheet, and
    /// vice versa; Excel allows the two names to diverge).
    pub bound_sheet_id: Option<u64>,
    /// Opaque bytes forming the pre-TextOffset "p-code prefix" of this
    /// module's stream. Never reparsed or validated by this codebase --
    /// proven (via the POC) that its *content* doesn't need to correspond
    /// to this module's actual source, only its presence matters, as long
    /// as it's shaped the way real Excel's module loader expects (a
    /// naively zero-filled placeholder of the same length is NOT enough).
    /// For an imported module these are the real bytes read back from the
    /// original file; for a module created in this codebase they're
    /// `vba_synth::synthetic_module_prefix()`'s from-scratch, self-consistent
    /// zero-procedure cache -- see that module's doc comment.
    #[serde(default)]
    pub prefix_bytes: Vec<u8>,
    /// The module stream's MODULECOOKIE record (`0x002C`) value. MS-OVBA
    /// documents this as implementation-specific and ignorable on read, but
    /// this codebase used to blindly overwrite every module's (including
    /// untouched, imported ones') cookie with a hardcoded `0xFFFF` on every
    /// export -- discovered while investigating why every workbook this
    /// codebase produces failed `has vb project` in real Excel, by diffing
    /// a re-exported real donor project's `dir` stream against the
    /// original's record-by-record and finding this was the one place real
    /// data was being discarded and replaced rather than round-tripped
    /// verbatim. Preserved here instead so an imported module's original
    /// value survives re-export.
    #[serde(default = "default_module_cookie")]
    pub module_cookie: u16,
    /// This module stream's already-compressed source, as read back
    /// verbatim from an imported file -- `None` for a module created fresh
    /// in this session (nothing to cache yet). `set_vba_module_source`
    /// clears this whenever `source` is replaced. Export reuses the cached
    /// bytes instead of recompressing `source` from scratch for every
    /// module untouched by the CRUD operation that triggered the save.
    #[serde(default)]
    pub cached_compressed_source: Option<Vec<u8>>,
}

fn default_module_cookie() -> u16 {
    0xFFFF
}

impl VbaModule {
    /// Whether this is a document module -- `ThisWorkbook` or a worksheet's
    /// code-behind -- as opposed to a standard or class module.
    pub fn is_document(&self) -> bool {
        self.kind == VbaModuleKind::Document
    }
}

/// A workbook's VBA project: its modules plus the raw material needed to
/// patch (not rebuild from scratch) a `vbaProject.bin` on export.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct VbaProject {
    /// Project ID GUID, e.g. `"{7B4E3A2C-1F5D-4A6B-9C8E-2D3F4A5B6C7D}"`.
    /// Must stay internally consistent with `protection_lines` -- never
    /// mutated after import/creation, so it always is. If `CMG`/`DPB`/`GC`
    /// protection-state lines are ever made independently settable, they
    /// must correspond to this exact ID or Excel reports the whole project
    /// "unviewable" (a real finding from the POC, not a hypothetical).
    pub project_id: String,
    /// The project's modules, in no particular order. Names are unique
    /// case-insensitively.
    pub modules: Vec<VbaModule>,
    /// The full original `vbaProject.bin` bytes this project was imported
    /// from, or (for a project created fresh in this session)
    /// `vba_synth::synthetic_raw_donor()`'s from-scratch bytes -- export's
    /// patch base. See `vba_xlsx.rs`.
    #[serde(default)]
    pub raw_donor: Vec<u8>,
    /// P-code prefix bytes to donate to the first module ever added to a
    /// project that started with none -- kept separate from `modules`
    /// rather than as a phantom placeholder module, so it never shows up in
    /// `list_vba_modules`/export. Once a project has at least one real
    /// module, new modules instead borrow prefix bytes from an existing
    /// one, and this field goes unused.
    #[serde(default)]
    pub seed_prefix_bytes: Vec<u8>,
    /// `VbaModule::module_cookie` to donate to the first module ever added
    /// to a project that started with none -- same donation scheme as
    /// `seed_prefix_bytes`, see there for why.
    #[serde(default = "default_module_cookie")]
    pub seed_module_cookie: u16,
    /// The donor's original `PROJECT` stream `CMG=`/`DPB=`/`GC=` lines
    /// (joined with `\r\n`), reproduced verbatim on export -- `None` for a
    /// project created fresh in this session, which never had any. See
    /// `vba_xlsx::build_project_stream` for why these must be preserved
    /// rather than dropped.
    #[serde(default)]
    pub protection_lines: Option<String>,
}

impl VbaProject {
    /// A brand-new, empty VBA project with no real Excel-authored file
    /// behind it anywhere -- `raw_donor` and `seed_prefix_bytes` are built
    /// by `vba_synth` entirely from scratch. See `vba_synth`'s doc comment
    /// for why that's now possible.
    pub fn new_empty() -> Self {
        VbaProject {
            project_id: new_project_guid(),
            modules: Vec::new(),
            raw_donor: crate::core::vba_synth::synthetic_raw_donor(),
            seed_prefix_bytes: crate::core::vba_synth::synthetic_module_prefix(),
            seed_module_cookie: default_module_cookie(),
            protection_lines: None,
        }
    }

    /// Finds a module by name, matched case-insensitively as VBA does.
    pub fn find_module(&self, name: &str) -> Option<&VbaModule> {
        self.modules
            .iter()
            .find(|m| m.name.eq_ignore_ascii_case(name))
    }

    /// [`VbaProject::find_module`], mutably.
    pub fn find_module_mut(&mut self, name: &str) -> Option<&mut VbaModule> {
        self.modules
            .iter_mut()
            .find(|m| m.name.eq_ignore_ascii_case(name))
    }

    /// Whether a module of this name already exists, matched
    /// case-insensitively.
    pub fn module_name_taken(&self, name: &str) -> bool {
        self.find_module(name).is_some()
    }

    /// Checks every module, resolving names against the **whole project**.
    ///
    /// This is the check to prefer wherever the project is in hand.
    /// [`VbaModule::check_syntax`] sees one module and so has to accept any
    /// name it cannot resolve, since a sibling may declare it; here the
    /// siblings are known, so `x = arr(1)` with no `arr` anywhere is
    /// reported the way Excel reports it -- Excel compiles a project, not a
    /// file.
    ///
    /// Returns one entry per module, in `modules` order, pairing the
    /// module's name with its result. A module whose *source* does not parse
    /// still contributes whatever names it declares to the others, since a
    /// parse failure in one module is not evidence about another.
    pub fn check_modules(&self) -> Vec<(String, Result<ModuleSyntax, Error>)> {
        self.check_modules_scoped(true)
    }

    /// [`check_modules`](Self::check_modules) for a project that is **not**
    /// the whole story -- one whose procedures may live in a referenced
    /// project this `VbaProject` does not model.
    ///
    /// Modules still resolve against each other; the only thing that
    /// changes is that a name resolving nowhere is accepted rather than
    /// reported, as in [`check_syntax_partial`]. Nothing in a workbook
    /// records whether such a reference exists, so this is a caller's
    /// assertion, not something to infer.
    pub fn check_modules_partial(&self) -> Vec<(String, Result<ModuleSyntax, Error>)> {
        self.check_modules_scoped(false)
    }

    /// The body both of the above share, `complete` being
    /// [`resolve::Scope::complete_project`].
    fn check_modules_scoped(&self, complete: bool) -> Vec<(String, Result<ModuleSyntax, Error>)> {
        let mut declared: std::collections::HashSet<String> = std::collections::HashSet::new();
        let parsed: Vec<_> = self
            .modules
            .iter()
            .map(|m| (m, parser::parse_module(&m.source).ok()))
            .collect();
        for (_, module) in &parsed {
            if let Some(module) = module {
                declared.extend(resolve::declared_names(module));
            }
        }

        parsed
            .iter()
            .map(|(m, _)| {
                let scope = resolve::Scope {
                    external: &declared,
                    complete_project: complete,
                };
                (
                    m.name.clone(),
                    check_source(&m.source, Some(&m.name), &scope),
                )
            })
            .collect()
    }
}

/// A GUID-shaped project id (`{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}`) for
/// a brand-new project, built from two `generate_unique_id()` draws rather
/// than duplicating its getrandom/fallback logic.
fn new_project_guid() -> String {
    let hi = crate::core::engine::generate_unique_id();
    let lo = crate::core::engine::generate_unique_id();
    format!(
        "{{{:08X}-{:04X}-{:04X}-{:04X}-{:012X}}}",
        (hi >> 32) as u32,
        (hi >> 16) as u16,
        hi as u16,
        (lo >> 48) as u16,
        lo & 0xFFFF_FFFF_FFFF,
    )
}

/// VBA identifiers: must start with a letter, contain only letters/digits/
/// underscore, and be at most 31 characters (the real VBE module-name
/// limit).
pub fn validate_vba_module_name(name: &str) -> Result<(), String> {
    let trimmed = name.trim();
    if trimmed.is_empty() {
        return Err("Module name cannot be empty".to_string());
    }
    if trimmed.chars().count() > 31 {
        return Err(format!(
            "Module name '{}' exceeds VBA's 31-character limit",
            name
        ));
    }
    let first = trimmed.chars().next().unwrap();
    if !first.is_alphabetic() {
        return Err(format!("Module name '{}' must start with a letter", name));
    }
    if !trimmed.chars().all(|c| c.is_alphanumeric() || c == '_') {
        return Err(format!(
            "Module name '{}' may only contain letters, digits, and underscores",
            name
        ));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_project() -> VbaProject {
        VbaProject {
            project_id: "{00000000-0000-0000-0000-000000000000}".to_string(),
            modules: vec![
                VbaModule {
                    name: "ThisWorkbook".to_string(),
                    kind: VbaModuleKind::Document,
                    source: "Attribute VB_Name = \"ThisWorkbook\"\r\n".to_string(),
                    bound_sheet_id: None,
                    prefix_bytes: vec![0xAA; 16],
                    module_cookie: 0xFFFF,
                    cached_compressed_source: None,
                },
                VbaModule {
                    name: "Module1".to_string(),
                    kind: VbaModuleKind::Standard,
                    source: "Attribute VB_Name = \"Module1\"\r\nSub Foo()\r\nEnd Sub\r\n"
                        .to_string(),
                    bound_sheet_id: None,
                    prefix_bytes: vec![0xBB; 16],
                    module_cookie: 0xFFFF,
                    cached_compressed_source: None,
                },
            ],
            raw_donor: Vec::new(),
            seed_prefix_bytes: Vec::new(),
            seed_module_cookie: 0xFFFF,
            protection_lines: None,
        }
    }

    #[test]
    fn validate_name_rules() {
        assert!(validate_vba_module_name("Module1").is_ok());
        assert!(validate_vba_module_name("_Bad").is_err());
        assert!(validate_vba_module_name("1Bad").is_err());
        assert!(validate_vba_module_name("").is_err());
        assert!(validate_vba_module_name("Has Space").is_err());
        assert!(validate_vba_module_name("Has-Dash").is_err());
        assert!(validate_vba_module_name(&"A".repeat(32)).is_err());
        assert!(validate_vba_module_name(&"A".repeat(31)).is_ok());
    }

    #[test]
    fn find_module_case_insensitive() {
        let project = sample_project();
        assert!(project.find_module("module1").is_some());
        assert!(project.find_module("MODULE1").is_some());
        assert!(project.find_module("Module2").is_none());
    }

    #[test]
    fn module_name_taken_case_insensitive() {
        let project = sample_project();
        assert!(project.module_name_taken("module1"));
        assert!(!project.module_name_taken("Module2"));
    }

    /// `sample_project()`'s shape with the sources the caller cares about,
    /// one standard module per `(name, source)` pair.
    fn project_of(sources: &[(&str, &str)]) -> VbaProject {
        let mut project = sample_project();
        project.modules = sources
            .iter()
            .map(|(name, source)| VbaModule {
                name: (*name).to_string(),
                kind: VbaModuleKind::Standard,
                source: (*source).to_string(),
                bound_sheet_id: None,
                prefix_bytes: vec![0xBB; 16],
                module_cookie: 0xFFFF,
                cached_compressed_source: None,
            })
            .collect();
        project
    }

    const CALLER: &str = "Public Sub Caller()\n    DoWork 1\nEnd Sub\n";
    const CALLEE: &str = "Public Sub DoWork(n As Long)\nEnd Sub\n";

    /// The two scopes differ on exactly one thing, and only on it: a name
    /// no supplied module declares. Issue #82.
    #[test]
    fn partial_scope_accepts_a_call_into_source_not_supplied() {
        // A fragment on its own: reported by default, accepted as partial.
        assert!(check_syntax(CALLER).is_err());
        assert!(check_syntax_partial(CALLER).is_ok());

        // Nothing else moves. A duplicate declaration is disproved by the
        // module's own text, so the partial scope still reports it.
        let dup = "Sub Test()\n    Dim x As Long\n    Dim x As Long\nEnd Sub\n";
        assert!(check_syntax(dup).is_err());
        assert!(check_syntax_partial(dup).is_err());
    }

    #[test]
    fn check_modules_resolves_across_siblings() {
        let project = project_of(&[("Module1", CALLER), ("Module2", CALLEE)]);
        for (name, result) in project.check_modules() {
            assert!(result.is_ok(), "{name} should be clean: {result:?}");
        }

        // Drop the sibling and the same call is a whole-project error.
        let alone = project_of(&[("Module1", CALLER)]);
        let results = alone.check_modules();
        assert_eq!(results.len(), 1);
        match &results[0].1 {
            Err(Error::VbaSyntax {
                message, module, ..
            }) => {
                assert!(message.contains("DoWork"), "{message}");
                assert_eq!(module.as_deref(), Some("Module1"));
            }
            other => panic!("expected a syntax error, got {other:?}"),
        }

        // ...and clean again under `--partial`, where the missing declaration
        // may be in a project this one merely references.
        assert!(alone.check_modules_partial()[0].1.is_ok());
    }

    #[test]
    fn set_source_leaves_prefix_bytes_untouched() {
        let mut project = sample_project();
        let original_prefix = project.find_module("Module1").unwrap().prefix_bytes.clone();
        project.find_module_mut("Module1").unwrap().source =
            "Attribute VB_Name = \"Module1\"\r\nSub Bar()\r\nEnd Sub\r\n".to_string();
        assert_eq!(
            project.find_module("Module1").unwrap().prefix_bytes,
            original_prefix
        );
    }
}