Skip to main content

htl_core/
build_target.rs

1//! [`BuildTarget`]: what runs the output of an htl project.
2//!
3//! One enum, four entries, and everything else about a target derived from it: the crate
4//! types cargo is told to build ([`BuildTarget::crate_types`]), whether the project has an
5//! entry script ([`BuildTarget::entry`]), and the sentence that names the thing on the far
6//! end ([`BuildTarget::runs_it`]). `htl.toml` records the choice as `[build] target`, and
7//! the scaffolder in `htl-cli` is a consumer of this type rather than the place it is
8//! defined.
9
10use serde::{Deserialize, Deserializer};
11use std::fmt;
12use std::str::FromStr;
13
14/// **A build target is what runs htl's output.** The `htl` binary runs a `.hb` bundle; the
15/// OS runs a native binary; a caller written in C, Python or C# loads a `cdylib`. That is
16/// the axis, and it is the only thing the entries below differ about:
17///
18/// | target | what runs the output | output | Rust in the project |
19/// |---|---|---|---|
20/// | `hb` (the default) — plain `htl new`, then `htl build` | the `htl` binary, `htl run app.hb` | a `.hb` bundle | no |
21/// | `bin` | the OS, as a binary | a binary (library + a thin `main.rs`) | the user's crate |
22/// | `cdylib` | a C / Python / Unity caller | `cdylib` + `staticlib` + a header | the user's crate |
23/// | `window` | the OS, as a window | a binary that opens a window (library + `main.rs` calling `htl_mq::run`) | the user's crate, plus `htl-mq` |
24///
25/// *Host* is the other axis: the Rust side that embeds the Lua state, what `[build] host`
26/// and `htl build --host` name the modules of. `htl.toml` records the target as `[build]
27/// target` (absent means `hb`), `htl new --target <name>` writes it, `htl init --target
28/// <name>` adds the Rust side to a project that predates it, and `htl build` refuses a
29/// project whose target is not `hb`, naming the command that does build it.
30///
31/// # What is in the enum, and what is derived from it
32///
33/// The enum is over *what runs the output*, and nothing else. Cargo's `[lib] crate-type`
34/// and the entry-script rule are answers derived from an entry ([`crate_types`],
35/// [`entry`]), not fields stored beside it, so adding a target is adding one arm and the
36/// answers it gives rather than a row of parallel data that can disagree with itself. A
37/// platform or a target triple is deliberately not in here: `bin` on Linux and `bin` on
38/// Windows are the same build target, and if a platform ever has to be named it is an
39/// attribute of one target, not a fourth entry.
40///
41/// [`crate_types`]: BuildTarget::crate_types
42/// [`entry`]: BuildTarget::entry
43///
44/// # Why it is not called a host
45///
46/// Three of the four entries happen to be Rust crates, which is why this used to be called
47/// a host; an output nothing Rust runs — a `.love` bundle, say — is the entry that makes
48/// that word plainly wrong.
49///
50/// *Host* keeps its own meaning throughout htl and is not this: it is the Rust side that
51/// embeds the Lua state — `#[host_module]`, the `src/host.d.tl` generated from it, and
52/// `[build] host` / `htl build --host x,y`, which name the modules that side provides at
53/// run time. A project can have a host and the default target (`htl build` alone), and two
54/// targets can share one host, so they are two axes rather than two words for one.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
56pub enum BuildTarget {
57    /// A `.hb` bundle, run by the `htl` binary. What plain `htl build` produces, and what
58    /// every project without Rust in it is.
59    Hb,
60    /// A native binary, run by the OS: a library crate holding the host module and the
61    /// embedded scripts, with a thin binary on top.
62    Bin,
63    /// A C ABI library, loaded by a caller that is not written in Rust.
64    Cdylib,
65    /// A native binary the OS runs as a windowed app: the same library-plus-thin-binary
66    /// shape as [`Bin`](BuildTarget::Bin), with the window and the frame loop coming from
67    /// `htl-mq`. That crate is the backend today and the target does not name it: a second
68    /// backend would be a second crate behind this entry, because what runs the output —
69    /// the OS, as a window — is what the enum is over, and that does not change with the
70    /// crate that opens the window.
71    Window,
72}
73
74impl BuildTarget {
75    /// Every target there is, in the order they are offered and reported.
76    pub const ALL: &'static [BuildTarget] = &[
77        BuildTarget::Hb,
78        BuildTarget::Bin,
79        BuildTarget::Cdylib,
80        BuildTarget::Window,
81    ];
82
83    /// How it is spelled on the command line (`--target <name>`) and in `htl.toml`.
84    pub fn name(&self) -> &'static str {
85        match self {
86            BuildTarget::Hb => "hb",
87            BuildTarget::Bin => "bin",
88            BuildTarget::Cdylib => "cdylib",
89            BuildTarget::Window => "window",
90        }
91    }
92
93    /// Every name, in [`ALL`](BuildTarget::ALL) order: what a flag offers and what a typo
94    /// is answered with.
95    pub fn names() -> Vec<&'static str> {
96        BuildTarget::ALL.iter().map(BuildTarget::name).collect()
97    }
98
99    /// `[lib] crate-type = [...]` beyond the default `rlib`, which needs no section at all.
100    /// Derived rather than stored: the crate shape is a consequence of what loads the
101    /// output, so it is answered here and `Cargo.toml` has nothing else to know about it.
102    pub fn crate_types(&self) -> &'static [&'static str] {
103        match self {
104            // No Rust crate at all; `htl build` writes the bundle.
105            BuildTarget::Hb => &[],
106            // The default `rlib`, plus the binary cargo builds from `src/main.rs`.
107            BuildTarget::Bin => &[],
108            // The shared object a caller loads, and the static library Unity on iOS links;
109            // the second costs one more artefact and nothing else.
110            BuildTarget::Cdylib => &["rlib", "cdylib", "staticlib"],
111            // The default `rlib` and the binary from `src/main.rs`, as `Bin`: the window
112            // is a dependency's doing, not a crate shape.
113            BuildTarget::Window => &[],
114        }
115    }
116
117    /// What this target has to say about `src/main.tl`.
118    pub fn entry(&self) -> Script {
119        match self {
120            BuildTarget::Hb => Script::Either,
121            BuildTarget::Bin => Script::Either,
122            // A `cdylib` has no entry point of its own, and the caller that loads it brings
123            // its own `main`.
124            BuildTarget::Cdylib => Script::Forbids,
125            // The frame loop is handed a game table, and that table is what `src/main.tl`
126            // returns; without the script there is nothing for the loop to drive.
127            BuildTarget::Window => Script::Requires,
128        }
129    }
130
131    /// Who is on the far end, in the words the README's table and `htl new`'s refusals use.
132    pub fn runs_it(&self) -> &'static str {
133        match self {
134            BuildTarget::Hb => "the htl binary",
135            BuildTarget::Bin => "the OS, as a binary",
136            BuildTarget::Cdylib => "a C / Python / Unity caller",
137            BuildTarget::Window => "the OS, as a window",
138        }
139    }
140}
141
142impl fmt::Display for BuildTarget {
143    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144        f.write_str(self.name())
145    }
146}
147
148impl FromStr for BuildTarget {
149    type Err = String;
150
151    fn from_str(s: &str) -> Result<Self, Self::Err> {
152        BuildTarget::ALL
153            .iter()
154            .copied()
155            .find(|t| t.name() == s)
156            .ok_or_else(|| {
157                format!(
158                    "unknown target `{s}`; registered targets: {}",
159                    BuildTarget::names().join(", ")
160                )
161            })
162    }
163}
164
165/// The string form is the only form: `target = "cdylib"` in `htl.toml` goes through
166/// [`FromStr`], so a name that is not one is refused with the same sentence the command
167/// line answers a typo with, rather than with serde's list of variant spellings.
168impl<'de> Deserialize<'de> for BuildTarget {
169    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
170        let s = String::deserialize(d)?;
171        s.parse().map_err(serde::de::Error::custom)
172    }
173}
174
175/// What a target has to say about `src/main.tl`. `--lib` is the user's side of the same
176/// question, and the two are reconciled once, where the scaffold resolves a target, before
177/// anything is written.
178#[derive(Debug, PartialEq, Eq, Clone, Copy)]
179pub enum Script {
180    /// The target runs an entry script and cannot be built without one (a window loop).
181    Requires,
182    /// The target is a library for someone else to call and has no entry point (a C ABI).
183    Forbids,
184    /// Either shape works; `--lib` decides.
185    Either,
186}
187
188impl Script {
189    /// Does this rule accept a project built with `--lib` (`lib = true`), or without one?
190    pub fn accepts(self, lib: bool) -> bool {
191        match self {
192            Script::Requires => !lib,
193            Script::Forbids => lib,
194            Script::Either => true,
195        }
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use super::{BuildTarget, Script};
202
203    /// The name is the only spelling there is, and it round-trips: what `htl.toml` records
204    /// is what `--target` takes, for every entry, with nothing spelled twice.
205    #[test]
206    fn every_target_round_trips_through_its_name() {
207        for t in BuildTarget::ALL {
208            assert_eq!(t.name().parse::<BuildTarget>().unwrap(), *t);
209            assert_eq!(t.to_string(), t.name());
210        }
211        assert_eq!(BuildTarget::names(), vec!["hb", "bin", "cdylib", "window"]);
212    }
213
214    /// A name that is not one is answered with the ones that are — the same sentence
215    /// whether it arrived on the command line or in `htl.toml`.
216    #[test]
217    fn an_unknown_name_is_refused_with_every_registered_one() {
218        let e = "rust".parse::<BuildTarget>().unwrap_err();
219        assert!(e.contains("unknown target `rust`"), "{e}");
220        for n in BuildTarget::names() {
221            assert!(e.contains(n), "{e}");
222        }
223    }
224
225    /// The crate shape follows from what loads the output: only the C ABI target needs a
226    /// `[lib]` section, and it needs all three of those types. A window is a binary like
227    /// any other — what opens it is a dependency, not a crate type.
228    #[test]
229    fn crate_types_are_derived_from_the_target() {
230        assert!(BuildTarget::Hb.crate_types().is_empty());
231        assert!(BuildTarget::Bin.crate_types().is_empty());
232        assert!(BuildTarget::Window.crate_types().is_empty());
233        assert_eq!(
234            BuildTarget::Cdylib.crate_types(),
235            ["rlib", "cdylib", "staticlib"]
236        );
237    }
238
239    /// So does the entry-script rule: a `cdylib` refuses one, a `window` cannot run without
240    /// one, and the other two leave the question to `--lib`.
241    #[test]
242    fn the_entry_rule_is_derived_from_the_target() {
243        assert_eq!(BuildTarget::Hb.entry(), Script::Either);
244        assert_eq!(BuildTarget::Bin.entry(), Script::Either);
245        assert_eq!(BuildTarget::Cdylib.entry(), Script::Forbids);
246        assert_eq!(BuildTarget::Window.entry(), Script::Requires);
247
248        assert!(Script::Requires.accepts(false) && !Script::Requires.accepts(true));
249        assert!(Script::Forbids.accepts(true) && !Script::Forbids.accepts(false));
250        assert!(Script::Either.accepts(true) && Script::Either.accepts(false));
251    }
252}