daml_codegen/generator/
code_generator.rs

1use daml_lf::DarFile;
2
3use crate::error::{DamlCodeGenError, DamlCodeGenResult};
4use crate::generator::combined::generate_archive_combined;
5use crate::generator::generator_options::RenderMethod;
6use crate::generator::module_matcher::ModuleMatcher;
7use crate::generator::separate::generate_archive_separate;
8use crate::generator::ModuleOutputMode;
9
10/// Code generator which is designed to be called from `build.rs` files.
11///
12/// To use the [`daml_codegen`] function you must first import the `daml` crate and specify feature `codegen`:
13///
14/// ```toml
15/// [dependencies]
16/// daml = { version = "0.2.2", features = [ "codegen" ] }
17/// ```
18///
19/// In your `build.rs` main function invoke the [`daml_codegen`] function for a `dar` file and specify where the
20/// generated src code should be created:
21///
22/// ```no_run
23/// use daml_codegen::generator::{daml_codegen, ModuleOutputMode, RenderMethod};
24/// let method = RenderMethod::Full;
25/// let mode = ModuleOutputMode::Combined;
26/// daml_codegen("MyModel.dar", "src/autogen", &[], method, mode).unwrap();
27/// ```
28///
29/// In the example above we used [`RenderMethod::Full`] to indicate that we want to render Rust types without
30/// intermediate annotations (such as [`DamlTemplate`]) and [`ModuleOutputMode::Combined`] to combine all Daml modules
31/// in a single Rust src file.
32///
33/// [`DamlTemplate`]: https://docs.rs/daml-derive/0.2.2/daml_derive/attr.DamlTemplate.html
34pub fn daml_codegen(
35    dar_file: &str,
36    output_path: &str,
37    module_filter_regex: &[&str],
38    quote_method: RenderMethod,
39    module_output_mode: ModuleOutputMode,
40) -> DamlCodeGenResult<()> {
41    println!("cargo:rerun-if-changed={}", dar_file);
42    daml_codegen_internal(dar_file, output_path, module_filter_regex, quote_method, module_output_mode)
43}
44
45#[doc(hidden)]
46pub fn daml_codegen_internal(
47    dar_file: &str,
48    output_path: &str,
49    module_filter_regex: &[&str],
50    render_method: RenderMethod,
51    module_output_mode: ModuleOutputMode,
52) -> DamlCodeGenResult<()> {
53    let dar = DarFile::from_file(dar_file).map_err(DamlCodeGenError::DamlLfError)?;
54    dar.apply(|archive| {
55        let module_matcher = ModuleMatcher::new(module_filter_regex)?;
56        match module_output_mode {
57            ModuleOutputMode::Separate =>
58                generate_archive_separate(archive, output_path.as_ref(), &module_matcher, &render_method)
59                    .map_err(DamlCodeGenError::IoError)?,
60            ModuleOutputMode::Combined =>
61                generate_archive_combined(archive, output_path.as_ref(), &module_matcher, &render_method)
62                    .map_err(DamlCodeGenError::IoError)?,
63        }
64        Ok(())
65    })
66    .map_err(DamlCodeGenError::DamlLfError)?
67}