canton-codegen 0.2.3

Type-safe Rust code generation from Daml packages (DAR to Rust).
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
//! The end-to-end pipeline: a `.dar` in, a self-contained bindings **crate**
//! out (`Cargo.toml` + `src/lib.rs`).
//!
//! This is what the `dpm-codegen-rust` binary runs, and what a build script
//! should call. For finer control (emit a single module, post-process the IR
//! first), use [`lower_dar`](crate::lower_dar) and
//! [`generate_crate`](crate::generate_crate) directly.

use std::fs;
use std::path::{Path, PathBuf};

use canton_lf::{Dar, DarError, DecodeError, decode_main_package, package_version};

use crate::{CodegenError, SkippedType, generate_crate};

/// The marker written into a generated `Cargo.toml`, and looked for before
/// overwriting one: a file without it was not written by this tool.
const CARGO_TOML_MARKER: &str = "# generated by dpm-codegen-rust — do not edit by hand";

/// The marker in a generated `lib.rs` (the first line of its crate docs), used
/// to recognize this tool's own output before overwriting. Kept in sync with
/// `crate_docs` — the test below fails if the emitted header stops carrying it.
const LIB_RS_MARKER: &str = "Typed Rust bindings generated from a Daml archive";

/// Writing a bindings crate failed.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum GenerateError {
    /// The `.dar` could not be read.
    #[error("reading {path}")]
    ReadDar {
        /// The DAR that could not be read.
        path: PathBuf,
        /// The underlying container error.
        #[source]
        source: DarError,
    },
    /// The `.dar` could not be decoded.
    #[error("decoding {path}")]
    DecodeDar {
        /// The DAR that could not be decoded.
        path: PathBuf,
        /// The underlying decode error.
        #[source]
        source: DecodeError,
    },
    /// The archive held no Daml-LF packages to generate from.
    #[error("{path} contains no Daml-LF packages — is it a DAR built with `daml build`?")]
    EmptyDar {
        /// The offending archive.
        path: PathBuf,
    },
    /// The requested crate name is not a valid Cargo package name.
    #[error(
        "`{name}` is not a valid Cargo package name (ASCII letters, digits, `-`/`_`; \
         must not start with a digit)"
    )]
    InvalidCrateName {
        /// The rejected name.
        name: String,
    },
    /// The DAR's package version is not usable as a Cargo version.
    ///
    /// It is refused rather than sanitised because the version reaches the
    /// generated `Cargo.toml`, and a DAR is not necessarily something the
    /// caller wrote.
    #[error(
        "the DAR declares the package version `{version}`, which is not a semantic \
         version Cargo will accept (`MAJOR.MINOR.PATCH`, optionally `-pre` and \
         `+build`). Rebuild the DAR with a plain version"
    )]
    InvalidCrateVersion {
        /// The rejected version, as the DAR declared it.
        version: String,
    },
    /// The `canton-daml` version requirement is not one Cargo can parse.
    #[error(
        "`{requirement}` is not a Cargo version requirement (e.g. `0.2`, `^0.2`, \
         `>=0.2, <0.4`)"
    )]
    InvalidRuntimeRequirement {
        /// The rejected requirement.
        requirement: String,
    },
    /// An output file exists and was not written by this tool.
    #[error(
        "{path} already exists and was not generated by this tool; \
         choose an empty output directory or force the overwrite"
    )]
    WouldClobber {
        /// The file that would have been overwritten.
        path: PathBuf,
    },
    /// The generated tokens were not valid Rust — a bug in this crate.
    #[error(transparent)]
    Codegen(#[from] CodegenError),
    /// Writing the output crate failed.
    #[error("writing {path}")]
    Write {
        /// The path being written.
        path: PathBuf,
        /// The underlying I/O error.
        #[source]
        source: std::io::Error,
    },
}

/// How the generated crate depends on the `canton-daml` runtime.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Runtime {
    /// A published version requirement (e.g. `0.2`).
    Version(String),
    /// A local path — for a monorepo, or to try bindings before publishing.
    Path(PathBuf),
}

/// What to generate and where. Build with [`Options::new`], then the
/// `with_*` methods.
///
/// ```no_run
/// use canton_codegen::{Options, Runtime};
///
/// let options = Options::new("my-app-0.1.0.dar", "my-app-bindings")
///     .with_crate_name("my-app-bindings")
///     .with_runtime(Runtime::Version("0.2".to_string()));
/// ```
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Options {
    dar: PathBuf,
    out: PathBuf,
    crate_name: Option<String>,
    runtime: Runtime,
    force: bool,
    external: crate::lower::ExternalPackages,
}

impl Options {
    /// Generate bindings for `dar` into the crate directory `out` (created if
    /// absent). The crate name defaults to one derived from the DAR file name
    /// and the runtime to the matching published `canton-daml`.
    #[must_use]
    pub fn new(dar: impl Into<PathBuf>, out: impl Into<PathBuf>) -> Self {
        Self {
            dar: dar.into(),
            out: out.into(),
            crate_name: None,
            runtime: Runtime::Version(DEFAULT_RUNTIME_REQ.to_string()),
            force: false,
            external: crate::lower::ExternalPackages::new(),
        }
    }

    /// Set the generated crate's package name (default: derived from the DAR
    /// file name — see [`default_crate_name`]).
    #[must_use]
    pub fn with_crate_name(mut self, name: impl Into<String>) -> Self {
        self.crate_name = Some(name.into());
        self
    }

    /// Set how the generated crate depends on the `canton-daml` runtime.
    #[must_use]
    pub fn with_runtime(mut self, runtime: Runtime) -> Self {
        self.runtime = runtime;
        self
    }

    /// Reference a package that is **already published as its own crate**
    /// instead of generating it, keyed by package name (preferred) or id.
    ///
    /// A DAR's dependency closure is shared — `splice-api-token-holding-v1`
    /// sits under amulet, wallet and wallet-payments alike — and generating it
    /// into each crate gives each its own `Holding`, which Rust treats as
    /// unrelated types. A `ContractId<Holding>` from one then does not
    /// typecheck against the other, though both name the same interface in the
    /// same package.
    ///
    /// ```no_run
    /// # use canton_codegen::Options;
    /// let options = Options::new("splice-amulet.dar", "amulet-bindings")
    ///     .with_external_package("splice-api-token-holding-v1", "canton_splice_api_token_holding_v1");
    /// ```
    #[must_use]
    pub fn with_external_package(
        mut self,
        package: impl Into<String>,
        crate_name: impl Into<String>,
    ) -> Self {
        self.external = self.external.with(package, crate_name);
        self
    }

    /// Overwrite output files even if they were not generated by this tool.
    #[must_use]
    pub fn with_force(mut self, force: bool) -> Self {
        self.force = force;
        self
    }

    /// The crate name that will be used: the explicit one, or the default
    /// derived from the DAR path.
    #[must_use]
    pub fn crate_name(&self) -> String {
        self.crate_name
            .clone()
            .unwrap_or_else(|| default_crate_name(&self.dar))
    }
}

/// The `canton-daml` version requirement written into a generated crate when
/// the caller does not choose one. Kept in lockstep with this crate's own
/// version, since the SDK crates release together.
const DEFAULT_RUNTIME_REQ: &str = concat!(
    env!("CARGO_PKG_VERSION_MAJOR"),
    ".",
    env!("CARGO_PKG_VERSION_MINOR")
);

/// A summary of a successful generation.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Stats {
    /// Packages in the DAR closure that produced modules.
    pub packages: usize,
    /// Generated Rust submodules.
    pub modules: usize,
    /// Generated named items (data types + templates + interfaces).
    pub items: usize,
    /// Size of the generated `lib.rs`, in bytes.
    pub bytes: usize,
    /// Declarations that could not be lowered (best-effort; surface these as
    /// warnings).
    pub skipped: Vec<SkippedType>,
}

/// Decode `opts.dar`, lower its whole closure, and write a bindings crate
/// (`Cargo.toml` + `src/lib.rs`) into the output directory.
///
/// Refuses to overwrite an existing `Cargo.toml` / `src/lib.rs` that this tool
/// did not generate, unless [`Options::with_force`] is set — a wrong output
/// directory must not clobber a hand-written crate.
///
/// # Errors
/// See [`GenerateError`].
pub fn generate(opts: &Options) -> Result<Stats, GenerateError> {
    let crate_name = opts.crate_name();
    validate_crate_name(&crate_name)?;

    let dar = Dar::open(&opts.dar).map_err(|source| GenerateError::ReadDar {
        path: opts.dar.clone(),
        source,
    })?;
    let (krate, skipped) =
        crate::lower::lower_dar_with(&dar, &opts.external).map_err(|source| {
            GenerateError::DecodeDar {
                path: opts.dar.clone(),
                source,
            }
        })?;
    if krate.packages.is_empty() {
        return Err(GenerateError::EmptyDar {
            path: opts.dar.clone(),
        });
    }
    let source = generate_crate(&krate)?;

    let modules = krate.packages.iter().map(|p| p.modules.len()).sum();
    let items = krate
        .packages
        .iter()
        .flat_map(|p| &p.modules)
        .map(|m| m.module.data_types.len() + m.module.templates.len() + m.module.interfaces.len())
        .sum();

    let cargo_toml_path = opts.out.join("Cargo.toml");
    let lib_rs_path = opts.out.join("src").join("lib.rs");
    if !opts.force {
        refuse_foreign(&cargo_toml_path, CARGO_TOML_MARKER)?;
        refuse_foreign(&lib_rs_path, LIB_RS_MARKER)?;
    }

    let src_dir = opts.out.join("src");
    fs::create_dir_all(&src_dir).map_err(|source| GenerateError::Write {
        path: src_dir,
        source,
    })?;
    let version = crate_version(&dar);
    validate_crate_version(&version)?;
    if let Runtime::Version(requirement) = &opts.runtime {
        validate_runtime_requirement(requirement)?;
    }
    let manifest = cargo_toml(opts, &crate_name, &version);
    fs::write(&cargo_toml_path, manifest).map_err(|source| GenerateError::Write {
        path: cargo_toml_path,
        source,
    })?;
    fs::write(&lib_rs_path, &source).map_err(|source| GenerateError::Write {
        path: lib_rs_path,
        source,
    })?;

    Ok(Stats {
        packages: krate.packages.len(),
        modules,
        items,
        bytes: source.len(),
        skipped,
    })
}

/// Error if `path` exists but does not carry `marker` in its first lines —
/// i.e. it is someone's own file, not a previous run's output.
fn refuse_foreign(path: &Path, marker: &str) -> Result<(), GenerateError> {
    match fs::read_to_string(path) {
        Ok(existing) => {
            let head: String = existing.lines().take(5).collect::<Vec<_>>().join("\n");
            if head.contains(marker) {
                Ok(()) // ours from a previous run — safe to regenerate over
            } else {
                Err(GenerateError::WouldClobber {
                    path: path.to_path_buf(),
                })
            }
        }
        Err(_) => Ok(()), // absent (or unreadable, in which case the write errors)
    }
}

/// The generated crate's version: the DAR main package's version (so
/// `splice-amulet 0.1.14` yields a `0.1.14` crate), or `0.0.0` when the
/// package carries none.
fn crate_version(dar: &Dar) -> String {
    decode_main_package(dar)
        .ok()
        .and_then(|(package, _)| package_version(&package).map(str::to_string))
        .map_or_else(|| "0.0.0".to_string(), |version| pad_to_semver(&version))
}

/// Complete a short but otherwise numeric version: `2.0` becomes `2.0.0`.
///
/// Cargo requires all three components — it rejects `2.0`, `0.1` and `1` — and
/// Daml does not. Refusing the whole DAR over that would leave the caller
/// stuck, since the version belongs to somebody else's package and they cannot
/// change it. Anything that is not simply *short* is left exactly as it is, for
/// [`validate_crate_version`] to refuse.
fn pad_to_semver(version: &str) -> String {
    let parts: Vec<&str> = version.split('.').collect();
    let numeric = parts.len() < 3
        && !parts.is_empty()
        && parts
            .iter()
            .all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()));
    if numeric {
        let mut padded = parts.join(".");
        for _ in parts.len()..3 {
            padded.push_str(".0");
        }
        padded
    } else {
        version.to_string()
    }
}

/// The `Cargo.toml` for the generated crate: a publishable manifest depending
/// on the `canton-daml` runtime.
fn cargo_toml(opts: &Options, crate_name: &str, version: &str) -> String {
    let dependency = match &opts.runtime {
        // Escaped for the same reason the path below is: both are interpolated
        // into a quoted TOML string, and only one of them used to be.
        Runtime::Version(requirement) => {
            format!("canton-daml = \"{}\"", toml_escape(requirement))
        }
        Runtime::Path(path) => {
            // A relative path would silently re-anchor at the *output* crate;
            // resolve it against the invoking directory instead. Escaped as a
            // TOML basic string (Windows separators, quotes).
            let absolute = std::path::absolute(path).unwrap_or_else(|_| path.clone());
            format!(
                "canton-daml = {{ path = \"{}\" }}",
                toml_escape(&absolute.display().to_string())
            )
        }
    };
    // A referenced crate has to be a dependency, or the paths the emitter wrote
    // do not resolve. The version is left to the caller to pin: this tool knows
    // the crate's name, not which release of it matches the DAR.
    let externals = opts
        .external
        .crate_names()
        .iter()
        .fold(String::new(), |mut out, name| {
            use std::fmt::Write as _;
            let _ = writeln!(out, "{} = \"*\"  # pin this", name.replace('_', "-"));
            out
        });
    format!(
        "{CARGO_TOML_MARKER}\n\
         [package]\n\
         name = \"{crate_name}\"\n\
         version = \"{version}\"\n\
         edition = \"2021\"\n\
         description = \"Typed Rust bindings generated from a Daml archive (DAR).\"\n\
         # Fill these in before publishing the generated crate.\n\
         # license = \"Apache-2.0\"\n\
         # repository = \"\"\n\
         \n\
         [dependencies]\n{dependency}\n{externals}"
    )
}

/// Escape a string for a double-quoted TOML basic string.
fn toml_escape(raw: &str) -> String {
    // A quote is not the only way out of a basic string. A raw newline ends it
    // too — TOML forbids one inside — so escaping only `"` left an input able
    // to put its own text on the next line of the manifest. Control characters
    // are escaped as TOML spells them.
    raw.chars()
        .fold(String::with_capacity(raw.len()), |mut out, c| {
            match c {
                '\\' => out.push_str("\\\\"),
                '"' => out.push_str("\\\""),
                '\n' => out.push_str("\\n"),
                '\r' => out.push_str("\\r"),
                '\t' => out.push_str("\\t"),
                c if c.is_control() => {
                    use std::fmt::Write as _;
                    let _ = write!(out, "\\u{:04X}", c as u32);
                }
                c => out.push(c),
            }
            out
        })
}

/// Error unless `name` is a valid Cargo package name: non-empty ASCII
/// alphanumerics, `-` or `_`, not starting with a digit.
/// Refuse a package version that cannot go into a `Cargo.toml` verbatim.
///
/// The version comes out of the DAR, and a DAR is not necessarily something the
/// caller wrote — the package id is the hash of whatever payload its author
/// chose, so every integrity guard upstream still passes one that was authored
/// rather than built. Interpolated raw, a version of the form
/// `0.1.0"` + newline + `[dependencies.evil]` + `git = "…` closed the string
/// and opened a table: an arbitrary dependency in a manifest the caller then
/// compiles.
///
/// The name beside it was already validated and the runtime path beside it
/// already escaped, for this reason. This is the third field in the same
/// manifest and the one that was missed.
///
/// Parsed as a semantic version rather than screened by charset, because
/// blocking the injection is only half the job: a charset wide enough to admit
/// every real version also admits `hello`, `1..2` and `1.0_bad`, and those
/// write a manifest that generation calls a success and every later `cargo`
/// command fails to parse. `semver` is the crate Cargo itself uses, so this
/// accepts exactly what a `package.version` may be.
fn validate_crate_version(version: &str) -> Result<(), GenerateError> {
    semver::Version::parse(version)
        .map(|_| ())
        .map_err(|_| GenerateError::InvalidCrateVersion {
            version: version.to_string(),
        })
}

/// The `canton-daml` version requirement, checked the same way and for the same
/// two reasons.
///
/// It reaches the manifest through the identical `format!`, so a quote or a
/// newline in it opens a table exactly as the package version did. And a
/// requirement that is merely mistyped — `--runtime-version 0..2` — otherwise
/// produces a crate that generates cleanly and cannot be built.
///
/// Unlike a version, a *requirement* may carry an operator (`^0.2`, `>=0.2,
/// <0.4`), so it parses as `VersionReq`.
fn validate_runtime_requirement(requirement: &str) -> Result<(), GenerateError> {
    semver::VersionReq::parse(requirement)
        .map(|_| ())
        .map_err(|_| GenerateError::InvalidRuntimeRequirement {
            requirement: requirement.to_string(),
        })
}

fn validate_crate_name(name: &str) -> Result<(), GenerateError> {
    let valid = !name.is_empty()
        && !name.starts_with(|c: char| c.is_ascii_digit())
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
    if valid {
        Ok(())
    } else {
        Err(GenerateError::InvalidCrateName {
            name: name.to_string(),
        })
    }
}

/// Derive a crate name from a DAR path: its file stem with the trailing
/// version dropped, sanitised to a valid Cargo package name
/// (`splice-amulet-0.1.14.dar` → `splice-amulet`).
///
/// The version is left out on purpose: a DAR version bump should not rename the
/// crate a caller depends on (the *crate version* carries it instead).
#[must_use]
pub fn default_crate_name(dar: &Path) -> String {
    let stem = dar
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("bindings");
    let stem = strip_trailing_version(stem);
    let name: String = stem
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' {
                c
            } else {
                '-'
            }
        })
        .collect();
    let name = name.trim_matches('-').to_string();
    // A Cargo package name cannot be empty or start with a digit.
    if name.is_empty() || name.starts_with(|c: char| c.is_ascii_digit()) {
        format!("bindings-{name}").trim_end_matches('-').to_string()
    } else {
        name
    }
}

/// Drop a trailing `-<version>` (dot-separated digits) from a DAR file stem.
fn strip_trailing_version(stem: &str) -> &str {
    match stem.rsplit_once('-') {
        Some((head, tail))
            if !tail.is_empty()
                && tail
                    .split('.')
                    .all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit())) =>
        {
            head
        }
        _ => stem,
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    #[test]
    fn default_crate_names_drop_the_dar_version_and_stay_valid() {
        let cases = [
            // A DAR version bump must not rename the crate.
            ("splice-amulet-0.1.14.dar", "splice-amulet"),
            ("splice-amulet-0.1.15.dar", "splice-amulet"),
            ("quickstart-licensing-0.0.1.dar", "quickstart-licensing"),
            ("quickstart licensing.dar", "quickstart-licensing"),
            // Not a version suffix — kept.
            ("my-app-v2.dar", "my-app-v2"),
            // Degenerate: a name that is only a version keeps its digits
            // behind the `bindings-` prefix (a Cargo name cannot lead with one).
            ("0.1.14.dar", "bindings-0-1-14"),
        ];
        for (input, expected) in cases {
            let name = default_crate_name(Path::new(input));
            assert_eq!(name, expected, "for {input}");
            assert!(validate_crate_name(&name).is_ok(), "{name}");
        }
    }

    #[test]
    fn invalid_crate_names_are_rejected_with_a_typed_error() {
        for bad in ["", "1abc", "has space", "naïve"] {
            assert!(matches!(
                validate_crate_name(bad),
                Err(GenerateError::InvalidCrateName { .. })
            ));
        }
        assert!(validate_crate_name("fine-name_2").is_ok());
    }

    #[test]
    fn cargo_toml_is_publishable_and_escapes_windows_paths() {
        let options = Options::new("x.dar", "out")
            .with_runtime(Runtime::Path(PathBuf::from(r"C:\Users\dev\canton-daml")));
        let toml = cargo_toml(&options, "x", "0.0.0");
        // Backslashes must be escaped or the TOML string is invalid.
        assert!(toml.contains(r"C:\\Users\\dev\\canton-daml"), "{toml}");
        assert!(toml.starts_with(CARGO_TOML_MARKER), "{toml}");
        // A description is present, and no `[workspace]` stanza is forced on
        // the caller's layout.
        assert!(toml.contains("description = "), "{toml}");
        assert!(!toml.contains("[workspace]"), "{toml}");
    }

    #[test]
    fn the_default_runtime_requirement_tracks_this_crate() {
        // Lockstep: a generated crate asks for the runtime that matches the
        // codegen that wrote it.
        assert_eq!(
            DEFAULT_RUNTIME_REQ,
            concat!(
                env!("CARGO_PKG_VERSION_MAJOR"),
                ".",
                env!("CARGO_PKG_VERSION_MINOR")
            )
        );
        assert!(matches!(
            Options::new("x.dar", "o").runtime,
            Runtime::Version(_)
        ));
    }

    /// The clobber guard recognises this tool's own output only if the emitted
    /// header actually contains the marker — so assert against a real emission,
    /// not against the constant.
    #[test]
    fn the_lib_rs_marker_matches_what_the_generator_emits() {
        let emitted = crate::generate_crate(&crate::ir::Crate::default()).unwrap();
        assert!(
            emitted.contains(LIB_RS_MARKER),
            "generated header must carry the marker, got:\n{emitted}"
        );
    }

    #[test]
    fn refuses_to_overwrite_a_foreign_file() {
        let dir = std::env::temp_dir().join(format!("codegen-clobber-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("Cargo.toml");

        std::fs::write(&file, "[package]\nname = \"users-own-crate\"\n").unwrap();
        assert!(matches!(
            refuse_foreign(&file, CARGO_TOML_MARKER),
            Err(GenerateError::WouldClobber { .. })
        ));

        // Our own previous output is fine to regenerate over, as is an absent file.
        std::fs::write(&file, format!("{CARGO_TOML_MARKER}\n[package]\n")).unwrap();
        assert!(refuse_foreign(&file, CARGO_TOML_MARKER).is_ok());
        assert!(refuse_foreign(&dir.join("absent.toml"), CARGO_TOML_MARKER).is_ok());

        std::fs::remove_dir_all(&dir).ok();
    }
    /// The version reaches `Cargo.toml`, and it comes out of the DAR — which
    /// the caller did not necessarily write. Every integrity guard upstream
    /// still passes an *authored* archive, because the package id is the hash
    /// of whatever payload its author chose.
    ///
    /// Interpolated raw, this closed the string and opened a table: an
    /// arbitrary git dependency in a manifest the caller then compiles. The
    /// name beside it was already validated and the runtime path beside it
    /// already escaped; this was the third field in the same manifest.
    #[test]
    fn a_package_version_cannot_inject_into_the_manifest() {
        let hostile = "0.1.0\"\n[dependencies.evil]\ngit = \"https://example.invalid/repo";
        let error = validate_crate_version(hostile).expect_err("must be refused");
        assert!(
            matches!(error, GenerateError::InvalidCrateVersion { .. }),
            "{error}"
        );
        // The message shows what was rejected, so the reader can go and look at
        // the DAR rather than guess.
        assert!(error.to_string().contains("0.1.0"), "{error}");

        // Neither can a newline on its own, which is all it takes to start a
        // new key once the quote is out.
        assert!(validate_crate_version("0.1.0\nx = 1").is_err());
        assert!(validate_crate_version("").is_err());

        // Cargo itself rejects a two-component version, so this must too —
        // `2.0` is completed to `2.0.0` upstream, in `crate_version`, not
        // waved through here.
        assert!(validate_crate_version("2.0").is_err());
        assert_eq!(pad_to_semver("2.0"), "2.0.0");
        assert_eq!(pad_to_semver("1"), "1.0.0");
        assert_eq!(
            pad_to_semver("0.1.14"),
            "0.1.14",
            "a complete version is untouched"
        );
        assert_eq!(
            pad_to_semver("hello"),
            "hello",
            "padding never rescues a non-version"
        );

        // Everything a real package carries still passes.
        for good in [
            "0.0.0",
            "1.2.3",
            "0.1.14",
            "1.0.0-SNAPSHOT",
            "1.0.0-rc.1+build.5",
        ] {
            assert!(
                validate_crate_version(good).is_ok(),
                "{good} should be accepted"
            );
        }
    }
    /// Both fields that reach the manifest as text, checked the way Cargo
    /// checks them.
    ///
    /// A charset was enough to stop the injection and not enough to stop a
    /// broken manifest: it admitted `hello` and `1..2`, which generate cleanly
    /// and then fail every later `cargo` command with a parse error nowhere
    /// near its cause.
    #[test]
    fn a_manifest_is_never_written_with_a_version_cargo_cannot_read() {
        // Rejected: not versions at all.
        for bad in ["hello", "1..2", "1.0_bad", "", "1.0", "v1.0.0"] {
            assert!(
                validate_crate_version(bad).is_err(),
                "`{bad}` is not a Cargo package version"
            );
        }
        // Accepted: every shape a real DAR carries, plus the semver extras.
        for good in [
            "0.0.1",
            "0.1.14",
            "1.0.0",
            "1.0.6",
            "1.0.0-SNAPSHOT",
            "1.0.0-rc.1+build.5",
        ] {
            assert!(validate_crate_version(good).is_ok(), "{good}");
        }

        // The requirement is a *requirement*, so operators are legal here and
        // a bare `0.2` — what this crate emits by default — must pass.
        for good in [DEFAULT_RUNTIME_REQ, "0.2", "^0.2", ">=0.2, <0.4", "*"] {
            assert!(validate_runtime_requirement(good).is_ok(), "{good}");
        }
        for bad in ["0..2", "hello", "", ">>0.2"] {
            assert!(validate_runtime_requirement(bad).is_err(), "`{bad}`");
        }
    }

    /// The two arms of one `match` disagreed: the path was escaped, the version
    /// requirement three lines above it was not. Both reach the same quoted
    /// TOML string.
    #[test]
    fn a_runtime_requirement_cannot_inject_into_the_manifest() {
        let hostile = "0.2\"\n[dependencies.evil]\ngit = \"https://example.invalid/repo";
        assert!(
            validate_runtime_requirement(hostile).is_err(),
            "must be refused before it reaches the manifest"
        );

        // And if it somehow did, the escape is now there too — no unescaped
        // quote survives into the file.
        let opts = Options::new("x.dar", "out").with_runtime(Runtime::Version(hostile.to_string()));
        let manifest = cargo_toml(&opts, "bindings", "1.0.0");
        // The text may survive as *content* of the escaped string — harmless.
        // What must not happen is a line of the manifest starting with it,
        // which is what a table header is.
        assert!(
            !manifest
                .lines()
                .any(|l| l.trim_start().starts_with('[') && l.contains("evil")),
            "escaped output opened a table:\n{manifest}"
        );
        // And nothing may break out of the dependency line at all.
        let dependency = manifest
            .lines()
            .find(|l| l.starts_with("canton-daml"))
            .expect("the dependency line");
        assert!(!dependency.contains('\n'));
    }
}