Skip to main content

lux_lib/rockspec/build/backend/
builtin.rs

1use super::super::super::platform;
2use crate::{
3    rockspec::{display, serde_util, PerPlatform},
4    target::c_dylib_extension,
5};
6use itertools::Itertools;
7use miette::Diagnostic;
8use path_slash::PathBufExt;
9use serde::{de, Deserialize, Deserializer};
10use std::{collections::HashMap, convert::Infallible, fmt::Display, path::PathBuf, str::FromStr};
11use thiserror::Error;
12
13#[derive(Debug, PartialEq, Deserialize, Default, Clone)]
14pub struct Builtin {
15    /// Keys are module names in the format normally used by the `require()` function
16    pub modules: HashMap<Module, ModuleSpec>,
17}
18
19#[derive(Debug, PartialEq, Eq, Deserialize, Default, Clone, Hash)]
20pub struct Module(String);
21
22impl Module {
23    pub fn to_lua_path(&self) -> PathBuf {
24        self.to_file_path(".lua")
25    }
26
27    pub fn to_lua_init_path(&self) -> PathBuf {
28        self.to_path_buf().join("init.lua")
29    }
30
31    pub fn to_luau_path(&self) -> PathBuf {
32        self.to_file_path(".luau")
33    }
34
35    pub fn to_luau_init_path(&self) -> PathBuf {
36        self.to_path_buf().join("init.luau")
37    }
38
39    pub fn to_lib_path(&self) -> PathBuf {
40        self.to_file_path(&format!(".{}", c_dylib_extension()))
41    }
42
43    fn to_path_buf(&self) -> PathBuf {
44        PathBuf::from(self.0.replace('.', std::path::MAIN_SEPARATOR_STR))
45    }
46
47    pub(crate) fn to_file_path(&self, extension: &str) -> PathBuf {
48        PathBuf::from(self.0.replace('.', std::path::MAIN_SEPARATOR_STR) + extension)
49    }
50
51    pub fn from_pathbuf(path: PathBuf) -> Result<Self, ParseLuaModuleError> {
52        let extension = path
53            .extension()
54            .map(|ext| ext.to_string_lossy().to_string())
55            .unwrap_or("".into());
56        let module = path
57            .to_string_lossy()
58            .trim_end_matches(format!("init.{extension}").as_str())
59            .trim_end_matches(format!(".{extension}").as_str())
60            .trim_end_matches(std::path::MAIN_SEPARATOR_STR)
61            .replace(std::path::MAIN_SEPARATOR_STR, ".");
62        if module.is_empty() {
63            Err(ParseLuaModuleError::EmptyModule(
64                path.to_slash_lossy().to_string(),
65            ))
66        } else {
67            Ok(Module(module))
68        }
69    }
70
71    pub fn join(&self, other: &Module) -> Module {
72        Module(format!("{}.{}", self.0, other.0))
73    }
74
75    pub fn as_str(&self) -> &str {
76        self.0.as_str()
77    }
78}
79
80#[derive(Error, Debug, Diagnostic)]
81#[non_exhaustive]
82pub enum ParseLuaModuleError {
83    #[error("path '{0}' resulted in an empty Lua module.")]
84    EmptyModule(String),
85    #[error("cannot parse a Lua module from an empty string")]
86    EmptyString,
87}
88
89impl FromStr for Module {
90    type Err = ParseLuaModuleError;
91
92    // NOTE: We may want to add some additional validations
93    fn from_str(s: &str) -> Result<Self, Self::Err> {
94        if s.is_empty() {
95            Err(ParseLuaModuleError::EmptyString)
96        } else {
97            Ok(Module(s.into()))
98        }
99    }
100}
101
102impl Display for Module {
103    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104        self.0.fmt(f)
105    }
106}
107
108impl display::AsLuaValue for Module {
109    fn display_lua_value(&self) -> display::LuaValue {
110        display::LuaValue::String(self.to_string())
111    }
112}
113
114impl display::AsLuaValue for HashMap<Module, PathBuf> {
115    fn display_lua_value(&self) -> display::LuaValue {
116        use path_slash::PathBufExt as _;
117        display::LuaValue::Table(
118            self.iter()
119                .map(|(k, v)| display::LuaKV {
120                    key: k.to_string(),
121                    value: display::LuaValue::String(v.to_slash_lossy().into_owned()),
122                })
123                .collect_vec(),
124        )
125    }
126}
127
128#[derive(Debug, PartialEq, Clone)]
129pub enum ModuleSpec {
130    /// Pathnames of Lua files or C sources, for modules based on a single source file.
131    SourcePath(PathBuf),
132    /// Pathnames of C sources of a simple module written in C composed of multiple files.
133    SourcePaths(Vec<PathBuf>),
134    ModulePaths(ModulePaths),
135}
136
137impl ModuleSpec {
138    pub fn from_internal(
139        internal: internal::ModuleSpec,
140    ) -> Result<ModuleSpec, internal::ModulePathsMissingSources> {
141        match internal {
142            internal::ModuleSpec::SourcePath(path) => Ok(ModuleSpec::SourcePath(path)),
143            internal::ModuleSpec::SourcePaths(paths) => Ok(ModuleSpec::SourcePaths(paths)),
144            internal::ModuleSpec::ModulePaths(module_paths) => Ok(ModuleSpec::ModulePaths(
145                ModulePaths::from_internal(module_paths)?,
146            )),
147        }
148    }
149}
150
151impl<'de> Deserialize<'de> for ModuleSpec {
152    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
153    where
154        D: Deserializer<'de>,
155    {
156        Self::from_internal(internal::ModuleSpec::deserialize(deserializer)?)
157            .map_err(de::Error::custom)
158    }
159}
160
161impl TryFrom<internal::ModuleSpec> for ModuleSpec {
162    type Error = internal::ModulePathsMissingSources;
163
164    fn try_from(internal: internal::ModuleSpec) -> Result<Self, Self::Error> {
165        Self::from_internal(internal)
166    }
167}
168
169impl From<ModuleSpec> for internal::ModuleSpec {
170    fn from(spec: ModuleSpec) -> Self {
171        match spec {
172            ModuleSpec::SourcePath(path) => Self::SourcePath(path),
173            ModuleSpec::SourcePaths(paths) => Self::SourcePaths(paths),
174            ModuleSpec::ModulePaths(paths) => Self::ModulePaths(paths.into()),
175        }
176    }
177}
178
179impl display::AsLuaValue for ModuleSpec {
180    fn display_lua_value(&self) -> display::LuaValue {
181        internal::ModuleSpec::from(self.clone()).display_lua_value()
182    }
183}
184
185fn deserialize_definitions<'de, D>(
186    deserializer: D,
187) -> Result<Vec<(String, Option<String>)>, D::Error>
188where
189    D: Deserializer<'de>,
190{
191    let values: Vec<String> = serde_util::deserialize_vec_from_lua_array_or_string(deserializer)?;
192    values
193        .iter()
194        .map(|val| {
195            if let Some((key, value)) = val.split_once('=') {
196                Ok((key.into(), Some(value.into())))
197            } else {
198                Ok((val.into(), None))
199            }
200        })
201        .try_collect()
202}
203
204#[derive(Debug, PartialEq, Clone)]
205pub struct ModulePaths {
206    /// Path names of C sources, mandatory field
207    pub sources: Vec<PathBuf>,
208    /// External libraries to be linked
209    pub libraries: Vec<PathBuf>,
210    /// C defines, e.g. { "FOO=bar", "USE_BLA" }
211    pub defines: Vec<(String, Option<String>)>,
212    /// Directories to be added to the compiler's headers lookup directory list.
213    pub incdirs: Vec<PathBuf>,
214    /// Directories to be added to the linker's library lookup directory list.
215    pub libdirs: Vec<PathBuf>,
216}
217
218impl ModulePaths {
219    fn from_internal(
220        internal: internal::ModulePaths,
221    ) -> Result<ModulePaths, internal::ModulePathsMissingSources> {
222        if internal.sources.is_empty() {
223            Err(internal::ModulePathsMissingSources)
224        } else {
225            Ok(ModulePaths {
226                sources: internal.sources,
227                libraries: internal.libraries,
228                defines: internal.defines,
229                incdirs: internal.incdirs,
230                libdirs: internal.libdirs,
231            })
232        }
233    }
234}
235
236impl TryFrom<internal::ModulePaths> for ModulePaths {
237    type Error = internal::ModulePathsMissingSources;
238
239    fn try_from(internal: internal::ModulePaths) -> Result<Self, Self::Error> {
240        Self::from_internal(internal)
241    }
242}
243
244impl From<ModulePaths> for internal::ModulePaths {
245    fn from(paths: ModulePaths) -> Self {
246        Self {
247            sources: paths.sources,
248            libraries: paths.libraries,
249            defines: paths.defines,
250            incdirs: paths.incdirs,
251            libdirs: paths.libdirs,
252        }
253    }
254}
255
256impl<'de> Deserialize<'de> for ModulePaths {
257    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
258    where
259        D: Deserializer<'de>,
260    {
261        Self::from_internal(internal::ModulePaths::deserialize(deserializer)?)
262            .map_err(de::Error::custom)
263    }
264}
265
266pub(crate) mod internal {
267    use super::*;
268
269    #[derive(Debug, PartialEq, Clone)]
270    pub enum ModuleSpec {
271        SourcePath(PathBuf),
272        SourcePaths(Vec<PathBuf>),
273        ModulePaths(ModulePaths),
274    }
275
276    impl<'de> Deserialize<'de> for ModuleSpec {
277        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
278        where
279            D: Deserializer<'de>,
280        {
281            let value =
282                serde_util::normalize_lua_value(serde_value::Value::deserialize(deserializer)?);
283            match value {
284                serde_value::Value::String(s) => Ok(Self::SourcePath(PathBuf::from(s))),
285                serde_value::Value::Seq(_) => {
286                    let src_paths: Vec<PathBuf> =
287                        value.deserialize_into().map_err(de::Error::custom)?;
288                    Ok(Self::SourcePaths(src_paths))
289                }
290                serde_value::Value::Map(_) => {
291                    let module_paths: ModulePaths =
292                        value.deserialize_into().map_err(de::Error::custom)?;
293                    Ok(Self::ModulePaths(module_paths))
294                }
295                _ => Err(de::Error::custom(format!(
296                    "expected a string, list, or table for module spec, got: {value:?}"
297                ))),
298            }
299        }
300    }
301
302    impl display::AsLuaValue for ModuleSpec {
303        fn display_lua_value(&self) -> display::LuaValue {
304            match self {
305                ModuleSpec::SourcePath(path) => {
306                    display::LuaValue::String(path.to_string_lossy().into())
307                }
308                ModuleSpec::SourcePaths(paths) => display::LuaValue::List(
309                    paths
310                        .iter()
311                        .map(|p| display::LuaValue::String(p.to_string_lossy().into()))
312                        .collect(),
313                ),
314                ModuleSpec::ModulePaths(module_paths) => module_paths.display_lua_value(),
315            }
316        }
317    }
318
319    #[derive(Error, Debug, Diagnostic)]
320    #[non_exhaustive]
321    #[error("cannot resolve ambiguous platform override for `build.modules`.")]
322    pub struct ModuleSpecAmbiguousPlatformOverride;
323
324    impl platform::PartialOverride for ModuleSpec {
325        type Err = ModuleSpecAmbiguousPlatformOverride;
326
327        fn apply_overrides(&self, override_spec: &Self) -> Result<Self, Self::Err> {
328            match (override_spec, self) {
329                (ModuleSpec::SourcePath(_), b @ ModuleSpec::SourcePath(_)) => Ok(b.to_owned()),
330                (ModuleSpec::SourcePaths(_), b @ ModuleSpec::SourcePaths(_)) => Ok(b.to_owned()),
331                (ModuleSpec::ModulePaths(a), ModuleSpec::ModulePaths(b)) => {
332                    Ok(ModuleSpec::ModulePaths(a.apply_overrides(b).unwrap()))
333                }
334                _ => Err(ModuleSpecAmbiguousPlatformOverride),
335            }
336        }
337    }
338
339    #[derive(Error, Debug, Diagnostic)]
340    #[non_exhaustive]
341    #[error("could not resolve platform override for `build.modules`. THIS IS A BUG!")]
342    pub struct BuildModulesPlatformOverride;
343
344    impl platform::Overridable for ModuleSpec {
345        type Err = BuildModulesPlatformOverride;
346
347        fn on_nil<T>() -> Result<PerPlatform<T>, <Self as platform::Overridable>::Err>
348        where
349            T: platform::Overridable,
350        {
351            Err(BuildModulesPlatformOverride)
352        }
353    }
354
355    #[derive(Error, Debug, Diagnostic)]
356    #[non_exhaustive]
357    #[error("missing or empty field `sources`")]
358    pub struct ModulePathsMissingSources;
359
360    /// Specification for building a Lua module from various sources
361    #[derive(Debug, PartialEq, Deserialize, Clone, Default)]
362    pub struct ModulePaths {
363        #[serde(
364            default,
365            deserialize_with = "serde_util::deserialize_vec_from_lua_array_or_string"
366        )]
367        pub sources: Vec<PathBuf>,
368        #[serde(
369            default,
370            deserialize_with = "serde_util::deserialize_vec_from_lua_array_or_string"
371        )]
372        pub libraries: Vec<PathBuf>,
373        #[serde(default, deserialize_with = "deserialize_definitions")]
374        pub defines: Vec<(String, Option<String>)>,
375        #[serde(
376            default,
377            deserialize_with = "serde_util::deserialize_vec_from_lua_array_or_string"
378        )]
379        pub incdirs: Vec<PathBuf>,
380        #[serde(
381            default,
382            deserialize_with = "serde_util::deserialize_vec_from_lua_array_or_string"
383        )]
384        pub libdirs: Vec<PathBuf>,
385    }
386
387    impl display::AsLuaValue for ModulePaths {
388        fn display_lua_value(&self) -> display::LuaValue {
389            display::LuaValue::Table(vec![
390                display::LuaKV {
391                    key: "sources".into(),
392                    value: display::LuaValue::List(
393                        self.sources
394                            .iter()
395                            .map(|s| display::LuaValue::String(s.to_string_lossy().into()))
396                            .collect(),
397                    ),
398                },
399                display::LuaKV {
400                    key: "libraries".into(),
401                    value: display::LuaValue::List(
402                        self.libraries
403                            .iter()
404                            .map(|s| display::LuaValue::String(s.to_string_lossy().into()))
405                            .collect(),
406                    ),
407                },
408                display::LuaKV {
409                    key: "defines".into(),
410                    value: display::LuaValue::List(
411                        self.defines
412                            .iter()
413                            .map(|(k, v)| {
414                                if let Some(v) = v {
415                                    display::LuaValue::String(format!("{k}={v}"))
416                                } else {
417                                    display::LuaValue::String(k.clone())
418                                }
419                            })
420                            .collect(),
421                    ),
422                },
423                display::LuaKV {
424                    key: "incdirs".into(),
425                    value: display::LuaValue::List(
426                        self.incdirs
427                            .iter()
428                            .map(|s| display::LuaValue::String(s.to_string_lossy().into()))
429                            .collect(),
430                    ),
431                },
432                display::LuaKV {
433                    key: "libdirs".into(),
434                    value: display::LuaValue::List(
435                        self.libdirs
436                            .iter()
437                            .map(|s| display::LuaValue::String(s.to_string_lossy().into()))
438                            .collect(),
439                    ),
440                },
441            ])
442        }
443    }
444
445    impl platform::PartialOverride for ModulePaths {
446        type Err = Infallible;
447
448        fn apply_overrides(&self, override_spec: &Self) -> Result<Self, Self::Err> {
449            Ok(Self {
450                sources: override_vec(override_spec.sources.as_ref(), self.sources.as_ref()),
451                libraries: override_vec(override_spec.libraries.as_ref(), self.libraries.as_ref()),
452                defines: override_vec(override_spec.defines.as_ref(), self.defines.as_ref()),
453                incdirs: override_vec(override_spec.incdirs.as_ref(), self.incdirs.as_ref()),
454                libdirs: override_vec(override_spec.libdirs.as_ref(), self.libdirs.as_ref()),
455            })
456        }
457    }
458
459    impl platform::Overridable for ModulePaths {
460        type Err = Infallible;
461
462        fn on_nil<T>() -> Result<PerPlatform<T>, <Self as platform::Overridable>::Err>
463        where
464            T: platform::Overridable,
465            T: Default,
466        {
467            Ok(PerPlatform::default())
468        }
469    }
470
471    fn override_vec<T: Clone>(override_vec: &[T], base: &[T]) -> Vec<T> {
472        if override_vec.is_empty() {
473            return base.to_owned();
474        }
475        override_vec.to_owned()
476    }
477}
478
479#[cfg(test)]
480mod tests {
481    use ottavino::{Closure, Executor, Fuel, Lua};
482    use ottavino_util::serde::from_value;
483
484    use super::*;
485
486    fn exec_lua<T: serde::de::DeserializeOwned>(
487        code: &str,
488        key: &'static str,
489    ) -> Result<T, ottavino::ExternError> {
490        Lua::core().try_enter(|ctx| {
491            let closure = Closure::load(ctx, None, code.as_bytes())?;
492            let executor = Executor::start(ctx, closure.into(), ());
493            executor.step(ctx, &mut Fuel::with(i32::MAX))?;
494            from_value(ctx.globals().get_value(ctx, key)).map_err(ottavino::Error::from)
495        })
496    }
497
498    #[tokio::test]
499    pub async fn parse_lua_module_from_path() {
500        let lua_module = Module::from_pathbuf("foo/init.lua".into()).unwrap();
501        assert_eq!(&lua_module.0, "foo");
502        let lua_module = Module::from_pathbuf("foo/bar.lua".into()).unwrap();
503        assert_eq!(&lua_module.0, "foo.bar");
504        let lua_module = Module::from_pathbuf("foo/bar/init.lua".into()).unwrap();
505        assert_eq!(&lua_module.0, "foo.bar");
506        let lua_module = Module::from_pathbuf("foo/bar/baz.lua".into()).unwrap();
507        assert_eq!(&lua_module.0, "foo.bar.baz");
508    }
509
510    #[tokio::test]
511    pub async fn modules_spec_from_lua() {
512        let lua_content = "
513        build = {\n
514            modules = {\n
515                foo = 'lua/foo/init.lua',\n
516                bar = {\n
517                  'lua/bar.lua',\n
518                  'lua/bar/internal.lua',\n
519                },\n
520                baz = {\n
521                    sources = {\n
522                        'lua/baz.lua',\n
523                    },\n
524                    defines = { 'USE_BAZ' },\n
525                },\n
526                foo = 'lua/foo/init.lua',
527            },\n
528        }\n
529        ";
530        let build_spec: Builtin = exec_lua(lua_content, "build").unwrap();
531        let foo = build_spec
532            .modules
533            .get(&Module::from_str("foo").unwrap())
534            .unwrap();
535        assert_eq!(*foo, ModuleSpec::SourcePath("lua/foo/init.lua".into()));
536        let bar = build_spec
537            .modules
538            .get(&Module::from_str("bar").unwrap())
539            .unwrap();
540        assert_eq!(
541            *bar,
542            ModuleSpec::SourcePaths(vec!["lua/bar.lua".into(), "lua/bar/internal.lua".into()])
543        );
544        let baz = build_spec
545            .modules
546            .get(&Module::from_str("baz").unwrap())
547            .unwrap();
548        assert!(matches!(baz, ModuleSpec::ModulePaths { .. }));
549        let lua_content_no_sources = "
550        build = {\n
551            modules = {\n
552                baz = {\n
553                    defines = { 'USE_BAZ' },\n
554                },\n
555            },\n
556        }\n
557        ";
558        let result: Result<Builtin, _> = exec_lua(lua_content_no_sources, "build");
559        let _err = result.unwrap_err();
560        let lua_content_complex_defines = "
561        build = {\n
562            modules = {\n
563                baz = {\n
564                    sources = {\n
565                        'lua/baz.lua',\n
566                    },\n
567                    defines = { 'USE_BAZ=1', 'ENABLE_LOGGING=true', 'LINK_STATIC' },\n
568                },\n
569            },\n
570        }\n
571        ";
572        let build_spec: Builtin = exec_lua(lua_content_complex_defines, "build").unwrap();
573        let baz = build_spec
574            .modules
575            .get(&Module::from_str("baz").unwrap())
576            .unwrap();
577        match baz {
578            ModuleSpec::ModulePaths(paths) => assert_eq!(
579                paths.defines,
580                vec![
581                    ("USE_BAZ".into(), Some("1".into())),
582                    ("ENABLE_LOGGING".into(), Some("true".into())),
583                    ("LINK_STATIC".into(), None)
584                ]
585            ),
586            _ => panic!(),
587        }
588    }
589}