Skip to main content

lua_types/
version.rs

1//! `LuaVersion` — the single source of truth for which Lua language version a
2//! runtime instance speaks.
3//!
4//! This lives in `lua-types`, the lowest shared crate, so every layer above
5//! (parser, compiler, VM, stdlib, runtime) can name the version without a
6//! dependency cycle. Per the multi-version architecture decision
7//! (`specs/MULTIVERSION_ARCHITECTURE_DECISION.md` §4, §5), the version is a
8//! *backend selector* threaded from construction; it never appears in a public
9//! embedding-API type.
10
11/// The numeric model a version uses for Lua numbers.
12///
13/// This is the single sharpest behavioral axis across versions: 5.1/5.2 are
14/// float-only (one `number` type, every value an `f64`, no `math.type`), while
15/// 5.3/5.4/5.5 carry the dual integer/float subtype.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub enum NumberModel {
18    /// One `number` type; every numeric value is an `f64`. Lua 5.1/5.2.
19    FloatOnly,
20    /// Distinct integer (`i64`) and float (`f64`) subtypes. Lua 5.3/5.4/5.5.
21    Dual,
22}
23
24/// Which Lua language version a runtime instance speaks.
25///
26/// `Default` is [`LuaVersion::V54`], so `Lua::new()` and any other defaulted
27/// construction runs Lua 5.4.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29#[non_exhaustive]
30pub enum LuaVersion {
31    /// Lua 5.1 — float-only, `fenv`-based globals.
32    V51,
33    /// Lua 5.2 — float-only, modern `_ENV` globals.
34    V52,
35    /// Lua 5.3 — dual subtype, modern `_ENV`.
36    V53,
37    /// Lua 5.4 — the default and the most thoroughly tested version.
38    V54,
39    /// Lua 5.5 — dual subtype, declared-globals scope model.
40    V55,
41}
42
43impl Default for LuaVersion {
44    fn default() -> Self {
45        LuaVersion::V54
46    }
47}
48
49impl LuaVersion {
50    /// The family-level numeric model for this version.
51    pub fn number_model(self) -> NumberModel {
52        match self {
53            LuaVersion::V51 | LuaVersion::V52 => NumberModel::FloatOnly,
54            LuaVersion::V53 | LuaVersion::V54 | LuaVersion::V55 => NumberModel::Dual,
55        }
56    }
57
58    /// Whether the `__name` metafield overrides an object's type name (in
59    /// `tostring` and in type-error messages). `__name` is a 5.3 addition; 5.1
60    /// and 5.2 ignore it and always report the primitive type name.
61    pub fn honors_name_metafield(self) -> bool {
62        !matches!(self, LuaVersion::V51 | LuaVersion::V52)
63    }
64
65    /// Whether `io.lines(filename, ...)` returns the file as a fourth
66    /// to-be-closed result. The to-be-closed value (`<close>`) mechanism is a
67    /// 5.4 addition: 5.4/5.5 return four values (iterator, nil, nil, file) so a
68    /// generic `for` can close the file on loop exit; 5.1–5.3 return only the
69    /// iterator (one value).
70    pub fn lines_returns_to_be_closed(self) -> bool {
71        matches!(self, LuaVersion::V54 | LuaVersion::V55)
72    }
73
74    /// Whether this version has a real backend. The modern family (5.3/5.4/5.5)
75    /// and 5.2 (float-only + `_ENV`) are complete. 5.1 reuses the 5.2 float-only
76    /// core plus three faithful 5.1-specific axes:
77    /// - **fenv globals** — `getfenv`/`setfenv` (the per-function environment
78    ///   model, Option B over the reused `_ENV` upvalue; `specs/followup/5.1-fenv.md`).
79    /// - **metamethod diffs** — `#t` never consults a table `__len`, no
80    ///   `__pairs`/`__ipairs`, no `__gc` on tables (userdata only).
81    /// - **roster + syntax** — `unpack` is global (no `table.unpack`/`pack`/
82    ///   `move`); `loadstring` + reader-only `load`; `table.getn`/`setn`(stub)/
83    ///   `maxn`/`foreach`/`foreachi`; `module`/`package.seeall`/`package.loaders`
84    ///   (no `package.searchers`); `string.gfind`; `math.log` 1-arg +
85    ///   `log10`/`atan2`/`pow`/`mod` (no `math.type`); `gcinfo`; `newproxy`;
86    ///   `xpcall`-no-extra-args; `coroutine.running` nil in main; no `bit32`/
87    ///   `utf8`/`rawlen`; `goto`/labels/`//`/bitwise/`<const>`/`\x`-`\z` escapes
88    ///   rejected (`goto` stays a valid identifier). See
89    ///   `specs/followup/5.1-roster-syntax.md`. Documented divergences: the
90    ///   `math.random` C-`rand()` sequence and `os.execute` raw-status byte are
91    ///   host-dependent (contract matches; exact bytes do not).
92    pub fn is_supported(self) -> bool {
93        matches!(
94            self,
95            LuaVersion::V51 | LuaVersion::V52 | LuaVersion::V53 | LuaVersion::V54 | LuaVersion::V55
96        )
97    }
98
99    /// The `_VERSION` global string for this version (e.g. `"Lua 5.4"`).
100    pub fn version_str(self) -> &'static str {
101        match self {
102            LuaVersion::V51 => "Lua 5.1",
103            LuaVersion::V52 => "Lua 5.2",
104            LuaVersion::V53 => "Lua 5.3",
105            LuaVersion::V54 => "Lua 5.4",
106            LuaVersion::V55 => "Lua 5.5",
107        }
108    }
109
110    /// The `LUAC_VERSION` byte written into a `luac`/`string.dump` header for
111    /// this version. Upstream encodes the version as `(major << 4) | minor`,
112    /// e.g. 5.4 → `0x54`.
113    pub fn luac_version_byte(self) -> u8 {
114        match self {
115            LuaVersion::V51 => 0x51,
116            LuaVersion::V52 => 0x52,
117            LuaVersion::V53 => 0x53,
118            LuaVersion::V54 => 0x54,
119            LuaVersion::V55 => 0x55,
120        }
121    }
122
123    /// Whether this version has a given language [`Feature`] — the pure,
124    /// build-independent capability matrix (issue #234). This is the version
125    /// dimension only; an embedding instance additionally narrows
126    /// library-backed features by what was compiled in (see
127    /// `omnilua::Lua::supports`).
128    ///
129    /// The rows are the source of record `ANALYSES/version_feature_matrix.tsv`,
130    /// generated by probing the reference binaries
131    /// (`specs/oracle/gen_feature_matrix.sh`); a test asserts this function
132    /// against that fixture so the matrix can never drift from upstream.
133    pub fn supports(self, f: Feature) -> bool {
134        use Feature::*;
135        use LuaVersion::*;
136        match f {
137            IntegerSubtype | NativeBitwise | Utf8Lib | StringPack => {
138                matches!(self, V53 | V54 | V55)
139            }
140            EnvSandbox | GotoLabels | TableLenMetamethod | GcIsRunning => {
141                matches!(self, V52 | V53 | V54 | V55)
142            }
143            FenvSandbox => self == V51,
144            Bit32Lib => matches!(self, V52 | V53),
145            CloseAttribute | ConstAttribute | CoroutineClose | WarnFunction => {
146                matches!(self, V54 | V55)
147            }
148            GcParam | GlobalKeyword | NamedVararg | TableCreate => self == V55,
149        }
150    }
151
152    /// Iterate the [`Feature`]s this version supports (version dimension only).
153    pub fn features(self) -> impl Iterator<Item = Feature> {
154        Feature::ALL.iter().copied().filter(move |f| self.supports(*f))
155    }
156}
157
158/// A version-divergent language capability — one *present-or-absent* row of the
159/// support matrix (issue #234). Behavioral divergences (same call, different
160/// result — e.g. `<=`-from-`__lt`, integer `for`-loop wraparound, the RNG stream)
161/// are deliberately **not** features: they are resolved inside the core, not
162/// gated. Query with [`LuaVersion::supports`].
163#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
164#[non_exhaustive]
165pub enum Feature {
166    /// Integer/float subtypes and `math.type` — 5.3+.
167    IntegerSubtype,
168    /// `_ENV` and `load(.., env)` lexical-environment sandboxing — 5.2+.
169    EnvSandbox,
170    /// `setfenv`/`getfenv` function-environment access — 5.1 only.
171    FenvSandbox,
172    /// `goto` and `::labels::` — 5.2+.
173    GotoLabels,
174    /// Native bitwise operators `& | ~ << >>` and integer division `//` — 5.3+.
175    NativeBitwise,
176    /// The `bit32` library — 5.2 and 5.3 (removed in 5.4).
177    Bit32Lib,
178    /// The `utf8` library — 5.3+.
179    Utf8Lib,
180    /// `string.pack`/`string.unpack`/`string.packsize` — 5.3+.
181    StringPack,
182    /// `<close>` to-be-closed variables and the `__close` metamethod — 5.4+.
183    CloseAttribute,
184    /// `<const>` variables — 5.4+.
185    ConstAttribute,
186    /// `coroutine.close` — 5.4+.
187    CoroutineClose,
188    /// The `warn` function — 5.4+.
189    WarnFunction,
190    /// The `__len` metamethod honored on tables (not just userdata) — 5.2+.
191    TableLenMetamethod,
192    /// `collectgarbage("isrunning")` — 5.2+.
193    GcIsRunning,
194    /// `collectgarbage("param", name [, value])` — 5.5.
195    GcParam,
196    /// The `global` declaration keyword and declared-global scope model — 5.5.
197    GlobalKeyword,
198    /// Named vararg table parameters `function f(a, ...t)` — 5.5.
199    NamedVararg,
200    /// `table.create` — 5.5.
201    TableCreate,
202}
203
204impl Feature {
205    /// Every [`Feature`], the iteration source for [`LuaVersion::features`] and
206    /// the matrix-vs-reference test. A `match` in the test asserts this is
207    /// exhaustive, so adding a variant without adding it here fails to compile.
208    pub const ALL: [Feature; 18] = [
209        Feature::IntegerSubtype,
210        Feature::EnvSandbox,
211        Feature::FenvSandbox,
212        Feature::GotoLabels,
213        Feature::NativeBitwise,
214        Feature::Bit32Lib,
215        Feature::Utf8Lib,
216        Feature::StringPack,
217        Feature::CloseAttribute,
218        Feature::ConstAttribute,
219        Feature::CoroutineClose,
220        Feature::WarnFunction,
221        Feature::TableLenMetamethod,
222        Feature::GcIsRunning,
223        Feature::GcParam,
224        Feature::GlobalKeyword,
225        Feature::NamedVararg,
226        Feature::TableCreate,
227    ];
228
229    /// A short, stable token naming this feature, used in the fixture and in the
230    /// [`Unsupported`] error message.
231    pub fn name(self) -> &'static str {
232        match self {
233            Feature::IntegerSubtype => "integer subtype (math.type)",
234            Feature::EnvSandbox => "_ENV sandboxing",
235            Feature::FenvSandbox => "setfenv/getfenv",
236            Feature::GotoLabels => "goto/labels",
237            Feature::NativeBitwise => "native bitwise operators",
238            Feature::Bit32Lib => "bit32 library",
239            Feature::Utf8Lib => "utf8 library",
240            Feature::StringPack => "string.pack",
241            Feature::CloseAttribute => "<close> attribute",
242            Feature::ConstAttribute => "<const> attribute",
243            Feature::CoroutineClose => "coroutine.close",
244            Feature::WarnFunction => "warn",
245            Feature::TableLenMetamethod => "__len on tables",
246            Feature::GcIsRunning => "collectgarbage('isrunning')",
247            Feature::GcParam => "collectgarbage('param')",
248            Feature::GlobalKeyword => "global declarations",
249            Feature::NamedVararg => "named vararg tables",
250            Feature::TableCreate => "table.create",
251        }
252    }
253}
254
255impl core::fmt::Display for Feature {
256    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
257        f.write_str(self.name())
258    }
259}
260
261/// A typed record that a [`Feature`] absent on a given [`LuaVersion`] was
262/// requested at a host-API verb (issue #234). Carried by the public embedding
263/// error so a host can match the cause; see `omnilua::Error::as_unsupported`.
264#[derive(Debug, Clone, Copy, PartialEq, Eq)]
265pub struct Unsupported {
266    /// The feature that was requested.
267    pub feature: Feature,
268    /// The version that lacks it.
269    pub version: LuaVersion,
270}
271
272impl core::fmt::Display for Unsupported {
273    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
274        write!(
275            f,
276            "{} is not available in {}",
277            self.feature,
278            self.version.version_str()
279        )
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286
287    #[test]
288    fn feature_all_has_no_duplicates() {
289        // The fixed-size `[Feature; 18]` plus the exhaustive (wildcard-free)
290        // matches in `name()`/`supports()` are the compile-time completeness
291        // guard: a new variant forces both to be updated and the array resized.
292        // This test guards the remaining gap — a duplicate slipping into ALL.
293        for (i, a) in Feature::ALL.iter().enumerate() {
294            for b in &Feature::ALL[i + 1..] {
295                assert_ne!(a, b, "duplicate feature in Feature::ALL");
296            }
297        }
298    }
299
300    #[test]
301    fn default_is_v54() {
302        assert_eq!(LuaVersion::default(), LuaVersion::V54);
303    }
304
305    #[test]
306    fn number_model_split() {
307        assert_eq!(LuaVersion::V51.number_model(), NumberModel::FloatOnly);
308        assert_eq!(LuaVersion::V52.number_model(), NumberModel::FloatOnly);
309        assert_eq!(LuaVersion::V53.number_model(), NumberModel::Dual);
310        assert_eq!(LuaVersion::V54.number_model(), NumberModel::Dual);
311        assert_eq!(LuaVersion::V55.number_model(), NumberModel::Dual);
312    }
313
314    #[test]
315    fn version_str_and_byte() {
316        assert_eq!(LuaVersion::V54.version_str(), "Lua 5.4");
317        assert_eq!(LuaVersion::V54.luac_version_byte(), 0x54);
318        assert_eq!(LuaVersion::V53.version_str(), "Lua 5.3");
319        assert_eq!(LuaVersion::V53.luac_version_byte(), 0x53);
320    }
321}