Skip to main content

capnpc_embedded/
lib.rs

1//! Compile Cap'n Proto schemas from a `build.rs` with **no system `capnp`** and
2//! **no C/C++ toolchain**.
3//!
4//! The Cap'n Proto schema compiler is embedded as a single, architecture-
5//! independent WebAssembly module (`capnp.wasm`) and executed *in-process* by a
6//! pure-Rust WASM engine. [`CompileCommand::compile`] returns the raw
7//! `CodeGeneratorRequest` the compiler produces — no subprocess, no native
8//! binary, no network.
9//!
10//! This crate deliberately does **not** depend on `capnpc`/`capnp`. You feed the
11//! returned request to your own chosen `capnpc` version, so nothing here couples
12//! you to a particular `capnp` runtime:
13//!
14//! ```no_run
15//! // build.rs
16//! let request = capnpc_embedded::CompileCommand::new()
17//!     .src_prefix("schema")
18//!     .file("schema/foo.capnp")
19//!     .compile()
20//!     .expect("capnp compile failed");
21//!
22//! capnpc::codegen::CodeGenerationCommand::new()
23//!     .output_directory(std::env::var("OUT_DIR").unwrap())
24//!     .run(&request[..])
25//!     .expect("capnp codegen failed");
26//! ```
27
28use std::path::{Path, PathBuf};
29
30mod runner;
31
32/// The embedded standard Cap'n Proto import schemas (importable as
33/// `/capnp/<name>.capnp`), including `rust.capnp` for the capnpc-rust
34/// annotations (`$Rust.parentModule`, `$Rust.name`, ...).
35const STD_SCHEMAS: &[(&str, &[u8])] = &[
36    (
37        "capnp/c++.capnp",
38        include_bytes!("../assets/capnp-include/capnp/c++.capnp"),
39    ),
40    (
41        "capnp/schema.capnp",
42        include_bytes!("../assets/capnp-include/capnp/schema.capnp"),
43    ),
44    (
45        "capnp/stream.capnp",
46        include_bytes!("../assets/capnp-include/capnp/stream.capnp"),
47    ),
48    (
49        "capnp/persistent.capnp",
50        include_bytes!("../assets/capnp-include/capnp/persistent.capnp"),
51    ),
52    (
53        "capnp/rpc.capnp",
54        include_bytes!("../assets/capnp-include/capnp/rpc.capnp"),
55    ),
56    (
57        "capnp/rpc-twoparty.capnp",
58        include_bytes!("../assets/capnp-include/capnp/rpc-twoparty.capnp"),
59    ),
60    (
61        "capnp/rust.capnp",
62        include_bytes!("../assets/capnp-include/capnp/rust.capnp"),
63    ),
64];
65
66/// An error produced while compiling schemas.
67#[derive(Debug)]
68pub struct Error {
69    message: String,
70}
71
72impl std::fmt::Display for Error {
73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74        f.write_str(&self.message)
75    }
76}
77
78impl std::error::Error for Error {}
79
80impl Error {
81    fn new(message: impl Into<String>) -> Self {
82        Self {
83            message: message.into(),
84        }
85    }
86}
87
88/// Result alias for schema compilation.
89pub type Result<T> = std::result::Result<T, Error>;
90
91/// A builder for compiling Cap'n Proto schemas into a `CodeGeneratorRequest`.
92///
93/// The builder options mirror the corresponding `capnp compile` flags. Options
94/// that concern code *generation* (output directory, parent module, ...) live on
95/// your `capnpc` code generator, not here — this type only runs the compiler.
96#[derive(Default)]
97pub struct CompileCommand {
98    files: Vec<PathBuf>,
99    src_prefixes: Vec<PathBuf>,
100    import_paths: Vec<PathBuf>,
101    no_standard_import: bool,
102}
103
104impl CompileCommand {
105    /// Creates a new, empty command.
106    pub fn new() -> Self {
107        Self::default()
108    }
109
110    /// Adds a schema file to compile. Paths are resolved relative to the current
111    /// working directory (typically the crate root during a build script).
112    pub fn file<P: AsRef<Path>>(&mut self, path: P) -> &mut Self {
113        self.files.push(path.as_ref().to_path_buf());
114        self
115    }
116
117    /// Adds a `--src-prefix`: a prefix stripped from schema paths when the
118    /// compiler computes each file's display name (which in turn drives the
119    /// generated file names).
120    pub fn src_prefix<P: AsRef<Path>>(&mut self, prefix: P) -> &mut Self {
121        self.src_prefixes.push(prefix.as_ref().to_path_buf());
122        self
123    }
124
125    /// Adds an `--import-path` directory searched for absolute (`/foo.capnp`)
126    /// imports.
127    pub fn import_path<P: AsRef<Path>>(&mut self, dir: P) -> &mut Self {
128        self.import_paths.push(dir.as_ref().to_path_buf());
129        self
130    }
131
132    /// Disables the embedded standard import schemas. Only set this if you are
133    /// providing your own copies of `capnp/*.capnp` via [`Self::import_path`].
134    pub fn no_standard_import(&mut self) -> &mut Self {
135        self.no_standard_import = true;
136        self
137    }
138
139    /// Runs the embedded `capnp` compiler and returns the raw serialized
140    /// `CodeGeneratorRequest` message.
141    ///
142    /// Feed the returned bytes to your code generator, e.g.
143    /// `capnpc::codegen::CodeGenerationCommand::run(&request[..])`.
144    pub fn compile(&self) -> Result<Vec<u8>> {
145        // Validate inputs up front for friendly errors (the wasm sees them via a
146        // preopened directory).
147        for file in &self.files {
148            std::fs::metadata(file).map_err(|e| {
149                Error::new(format!(
150                    "unable to read capnp input file `{}`: {e}",
151                    file.display()
152                ))
153            })?;
154        }
155
156        runner::run_capnp(self)
157            .map_err(|e| Error::new(format!("error running embedded capnp compiler: {e:#}")))
158    }
159
160    // --- accessors for the runner module ---
161    pub(crate) fn files(&self) -> &[PathBuf] {
162        &self.files
163    }
164    pub(crate) fn src_prefixes(&self) -> &[PathBuf] {
165        &self.src_prefixes
166    }
167    pub(crate) fn import_paths(&self) -> &[PathBuf] {
168        &self.import_paths
169    }
170    pub(crate) fn use_standard_import(&self) -> bool {
171        !self.no_standard_import
172    }
173}