1mod builtin;
2mod cmake;
3mod make;
4mod rust_binary;
5mod rust_mlua;
6mod tree_sitter;
7
8pub use builtin::{BuiltinBuildSpec, LuaModule, ModulePaths, ModuleSpec, ParseLuaModuleError};
9pub use cmake::*;
10pub use make::*;
11use path_slash::PathBufExt;
12pub use rust_binary::*;
13pub use rust_mlua::*;
14pub use tree_sitter::*;
15
16pub(crate) use builtin::ModuleSpecInternal;
17
18use builtin::{ModulePathsMissingSources, ModuleSpecAmbiguousPlatformOverride};
19
20use itertools::Itertools;
21
22use miette::Diagnostic;
23use serde::{de, de::IntoDeserializer, Deserialize, Deserializer};
24use std::{
25 collections::HashMap, convert::Infallible, env::consts::DLL_EXTENSION, env::consts::DLL_PREFIX,
26 fmt::Display, path::PathBuf, str::FromStr,
27};
28use thiserror::Error;
29
30use crate::{
31 lua_rockspec::per_platform_from_intermediate,
32 package::{PackageName, PackageReq},
33 rockspec::lua_dependency::LuaDependencySpec,
34};
35
36use super::{
37 DisplayAsLuaKV, DisplayAsLuaValue, DisplayLuaKV, DisplayLuaValue, LuaTableKey, LuaValueSeed,
38 PartialOverride, PerPlatform, PlatformOverridable,
39};
40
41#[derive(Clone, Debug, PartialEq)]
43pub struct BuildSpec {
44 pub build_backend: Option<BuildBackendSpec>,
46 pub install: InstallSpec,
50 pub copy_directories: Vec<PathBuf>,
52 pub patches: HashMap<PathBuf, String>,
56}
57
58impl Default for BuildSpec {
59 fn default() -> Self {
60 Self {
61 build_backend: Some(BuildBackendSpec::default()),
62 install: InstallSpec::default(),
63 copy_directories: Vec::default(),
64 patches: HashMap::default(),
65 }
66 }
67}
68
69#[derive(Error, Debug, Diagnostic)]
70#[non_exhaustive]
71pub enum BuildSpecInternalError {
72 #[error("'builtin' modules should not have list elements")]
73 ModulesHaveListElements,
74 #[error("no 'modules' specified for the 'rust-mlua' build backend")]
75 NoModulesSpecified,
76 #[error("no 'lang' specified for 'treesitter-parser' build backend")]
77 NoTreesitterParserLanguageSpecified,
78 #[error("invalid 'rust-mlua' modules format")]
79 InvalidRustMLuaFormat,
80 #[error(transparent)]
81 #[diagnostic(transparent)]
82 ModulePathsMissingSources(#[from] ModulePathsMissingSources),
83 #[error(transparent)]
84 #[diagnostic(transparent)]
85 ParseLuaModuleError(#[from] ParseLuaModuleError),
86}
87
88impl BuildSpec {
89 pub(crate) fn from_internal_spec(
90 internal: BuildSpecInternal,
91 ) -> Result<Self, BuildSpecInternalError> {
92 let build_backend = match internal.build_type.unwrap_or_default() {
93 BuildType::Builtin => Some(BuildBackendSpec::Builtin(BuiltinBuildSpec {
94 modules: internal
95 .builtin_spec
96 .unwrap_or_default()
97 .into_iter()
98 .map(|(key, module_spec_internal)| {
99 let key_str = match key {
100 LuaTableKey::IntKey(_) => {
101 Err(BuildSpecInternalError::ModulesHaveListElements)
102 }
103 LuaTableKey::StringKey(str) => Ok(LuaModule::from_str(str.as_str())?),
104 }?;
105 match ModuleSpec::from_internal(module_spec_internal) {
106 Ok(module_spec) => Ok((key_str, module_spec)),
107 Err(err) => Err(err.into()),
108 }
109 })
110 .collect::<Result<HashMap<LuaModule, ModuleSpec>, BuildSpecInternalError>>()?,
111 })),
112 BuildType::Make => {
113 let default = MakeBuildSpec::default();
114 Some(BuildBackendSpec::Make(MakeBuildSpec {
115 makefile: internal.makefile.unwrap_or(default.makefile),
116 build_target: internal.make_build_target,
117 build_pass: internal.build_pass.unwrap_or(default.build_pass),
118 install_target: internal
119 .make_install_target
120 .unwrap_or(default.install_target),
121 install_pass: internal.install_pass.unwrap_or(default.install_pass),
122 build_variables: internal.make_build_variables.unwrap_or_default(),
123 install_variables: internal.make_install_variables.unwrap_or_default(),
124 variables: internal.variables.unwrap_or_default(),
125 }))
126 }
127 BuildType::CMake => {
128 let default = CMakeBuildSpec::default();
129 Some(BuildBackendSpec::CMake(CMakeBuildSpec {
130 cmake_lists_content: internal.cmake_lists_content,
131 build_pass: internal.build_pass.unwrap_or(default.build_pass),
132 install_pass: internal.install_pass.unwrap_or(default.install_pass),
133 variables: internal.variables.unwrap_or_default(),
134 }))
135 }
136 BuildType::Command => Some(BuildBackendSpec::Command(CommandBuildSpec {
137 build_command: internal.build_command,
138 install_command: internal.install_command,
139 })),
140 BuildType::None => None,
141 BuildType::LuaRock(s) => Some(BuildBackendSpec::LuaRock(s)),
142 BuildType::RustMlua => Some(BuildBackendSpec::RustMlua(RustMluaBuildSpec {
143 modules: internal
144 .builtin_spec
145 .ok_or(BuildSpecInternalError::NoModulesSpecified)?
146 .into_iter()
147 .map(|(key, value)| match (key, value) {
148 (LuaTableKey::IntKey(_), ModuleSpecInternal::SourcePath(module)) => {
149 let mut rust_lib: PathBuf =
150 format!("{DLL_PREFIX}{}", module.display()).into();
151 rust_lib.set_extension(DLL_EXTENSION);
152 Ok((module.to_string_lossy().to_string(), rust_lib))
153 }
154 (
155 LuaTableKey::StringKey(module_name),
156 ModuleSpecInternal::SourcePath(module),
157 ) => {
158 let mut rust_lib: PathBuf =
159 format!("{DLL_PREFIX}{}", module.display()).into();
160 rust_lib.set_extension(DLL_EXTENSION);
161 Ok((module_name, rust_lib))
162 }
163 _ => Err(BuildSpecInternalError::InvalidRustMLuaFormat),
164 })
165 .try_collect()?,
166 target_path: internal.target_path.unwrap_or("target".into()),
167 default_features: internal.default_features.unwrap_or(true),
168 features: internal.features.unwrap_or_default(),
169 cargo_extra_args: internal.cargo_extra_args.unwrap_or_default(),
170 include: internal
171 .include
172 .unwrap_or_default()
173 .into_iter()
174 .map(|(key, dest)| match key {
175 LuaTableKey::IntKey(_) => (dest.clone(), dest),
176 LuaTableKey::StringKey(src) => (src.into(), dest),
177 })
178 .collect(),
179 })),
180 BuildType::RustBinary => Some(BuildBackendSpec::RustBinary(RustBinaryBuildSpec {
181 package: internal.package,
182 features: internal.features.unwrap_or_default(),
183 })),
184 BuildType::TreesitterParser => Some(BuildBackendSpec::TreesitterParser(
185 TreesitterParserBuildSpec {
186 lang: internal
187 .lang
188 .ok_or(BuildSpecInternalError::NoTreesitterParserLanguageSpecified)?,
189 parser: internal.parser.unwrap_or(false),
190 generate: internal.generate.unwrap_or(false),
191 location: internal.location,
192 queries: internal.queries.unwrap_or_default(),
193 },
194 )),
195 BuildType::Source => Some(BuildBackendSpec::Source),
196 };
197 Ok(Self {
198 build_backend,
199 install: internal.install.unwrap_or_default(),
200 copy_directories: internal.copy_directories.unwrap_or_default(),
201 patches: internal.patches.unwrap_or_default(),
202 })
203 }
204}
205
206impl TryFrom<BuildSpecInternal> for BuildSpec {
207 type Error = BuildSpecInternalError;
208
209 fn try_from(internal: BuildSpecInternal) -> Result<Self, Self::Error> {
210 BuildSpec::from_internal_spec(internal)
211 }
212}
213
214impl<'de> Deserialize<'de> for BuildSpec {
215 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
216 where
217 D: Deserializer<'de>,
218 {
219 let internal = BuildSpecInternal::deserialize(deserializer)?;
220 BuildSpec::from_internal_spec(internal).map_err(de::Error::custom)
221 }
222}
223
224impl<'de> Deserialize<'de> for PerPlatform<BuildSpec> {
229 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
230 where
231 D: Deserializer<'de>,
232 {
233 per_platform_from_intermediate::<_, BuildSpecInternal, _>(deserializer)
234 }
235}
236
237impl Default for BuildBackendSpec {
238 fn default() -> Self {
239 Self::Builtin(BuiltinBuildSpec::default())
240 }
241}
242
243#[derive(Debug, PartialEq, Clone)]
250pub enum BuildBackendSpec {
251 Builtin(BuiltinBuildSpec),
252 Make(MakeBuildSpec),
253 CMake(CMakeBuildSpec),
254 Command(CommandBuildSpec),
255 LuaRock(String),
256 RustMlua(RustMluaBuildSpec),
257 RustBinary(RustBinaryBuildSpec),
258 TreesitterParser(TreesitterParserBuildSpec),
259 Source,
265}
266
267impl BuildBackendSpec {
268 pub(crate) fn can_use_build_dependencies(&self) -> bool {
269 match self {
270 Self::Make(_) | Self::CMake(_) | Self::Command(_) | Self::LuaRock(_) => true,
271 Self::Builtin(_)
272 | Self::RustMlua(_)
273 | Self::RustBinary(_)
274 | Self::TreesitterParser(_)
275 | Self::Source => false,
276 }
277 }
278}
279
280#[derive(Debug, PartialEq, Clone)]
282pub struct CommandBuildSpec {
283 pub build_command: Option<String>,
284 pub install_command: Option<String>,
285}
286
287#[derive(Clone, Debug)]
288struct LuaPathBufTable(HashMap<LuaTableKey, PathBuf>);
289
290impl<'de> Deserialize<'de> for LuaPathBufTable {
291 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
292 Ok(LuaPathBufTable(
293 deserialize_map_or_seq(deserializer)?.unwrap_or_default(),
294 ))
295 }
296}
297
298impl LuaPathBufTable {
299 fn coerce<S>(self) -> Result<HashMap<S, PathBuf>, S::Err>
300 where
301 S: FromStr + Eq + std::hash::Hash,
302 {
303 self.0
304 .into_iter()
305 .map(|(key, value)| {
306 let key = match key {
307 LuaTableKey::IntKey(_) => value
308 .with_extension("")
309 .file_name()
310 .unwrap_or_default()
311 .to_string_lossy()
312 .to_string(),
313 LuaTableKey::StringKey(key) => key,
314 };
315 Ok((S::from_str(&key)?, value))
316 })
317 .try_collect()
318 }
319}
320
321#[derive(Clone, Debug)]
322struct LibPathBufTable(HashMap<LuaTableKey, PathBuf>);
323
324impl<'de> Deserialize<'de> for LibPathBufTable {
325 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
326 Ok(LibPathBufTable(
327 deserialize_map_or_seq(deserializer)?.unwrap_or_default(),
328 ))
329 }
330}
331
332impl LibPathBufTable {
333 fn coerce<S>(self) -> Result<HashMap<S, PathBuf>, S::Err>
334 where
335 S: FromStr + Eq + std::hash::Hash,
336 {
337 self.0
338 .into_iter()
339 .map(|(key, value)| {
340 let key = match key {
341 LuaTableKey::IntKey(_) => value
342 .file_name()
343 .unwrap_or_default()
344 .to_string_lossy()
345 .to_string(),
346 LuaTableKey::StringKey(key) => key,
347 };
348 Ok((S::from_str(&key)?, value))
349 })
350 .try_collect()
351 }
352}
353
354#[derive(Debug, PartialEq, Default, Deserialize, Clone, lux_macros::DisplayAsLuaKV)]
363#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
364#[display_lua(key = "install")]
365pub struct InstallSpec {
366 #[serde(default, deserialize_with = "deserialize_module_path_map")]
368 #[cfg_attr(
369 feature = "schema",
370 schemars(with = "std::collections::BTreeMap<String, String>")
371 )]
372 pub lua: HashMap<LuaModule, PathBuf>,
373 #[serde(default, deserialize_with = "deserialize_file_name_path_map")]
375 #[cfg_attr(
376 feature = "schema",
377 schemars(with = "std::collections::BTreeMap<String, String>")
378 )]
379 pub lib: HashMap<String, PathBuf>,
380 #[serde(default)]
382 pub conf: HashMap<String, PathBuf>,
383 #[serde(default, deserialize_with = "deserialize_file_name_path_map")]
387 #[cfg_attr(
388 feature = "schema",
389 schemars(with = "std::collections::BTreeMap<String, String>")
390 )]
391 pub bin: HashMap<String, PathBuf>,
392}
393
394fn deserialize_module_path_map<'de, D>(
395 deserializer: D,
396) -> Result<HashMap<LuaModule, PathBuf>, D::Error>
397where
398 D: Deserializer<'de>,
399{
400 let modules = LuaPathBufTable::deserialize(deserializer)?;
401 modules.coerce().map_err(de::Error::custom)
402}
403
404fn deserialize_file_name_path_map<'de, D>(
405 deserializer: D,
406) -> Result<HashMap<String, PathBuf>, D::Error>
407where
408 D: Deserializer<'de>,
409{
410 let binaries = LibPathBufTable::deserialize(deserializer)?;
411 binaries.coerce().map_err(de::Error::custom)
412}
413
414fn deserialize_copy_directories<'de, D>(deserializer: D) -> Result<Option<Vec<PathBuf>>, D::Error>
415where
416 D: Deserializer<'de>,
417{
418 let value: Option<serde_value::Value> = Option::deserialize(deserializer)?;
419 let copy_directories: Option<Vec<String>> = match value {
420 Some(value) => Some(value.deserialize_into().map_err(de::Error::custom)?),
421 None => None,
422 };
423 let special_directories: Vec<String> = vec!["lua".into(), "lib".into(), "rock_manifest".into()];
424 match special_directories
425 .into_iter()
426 .find(|dir| copy_directories.clone().unwrap_or_default().contains(dir))
427 {
428 Some(d) => Err(format!(
431 "directory '{d}' in copy_directories clashes with the .rock format", )),
433 _ => Ok(copy_directories.map(|vec| vec.into_iter().map(PathBuf::from).collect())),
434 }
435 .map_err(de::Error::custom)
436}
437
438fn deserialize_map_or_seq<'de, D, V>(
440 deserializer: D,
441) -> Result<Option<HashMap<LuaTableKey, V>>, D::Error>
442where
443 D: Deserializer<'de>,
444 V: de::DeserializeOwned,
445{
446 match de::DeserializeSeed::deserialize(LuaValueSeed, deserializer).map_err(de::Error::custom)? {
447 serde_value::Value::Map(map) => map
448 .into_iter()
449 .map(|(k, v)| {
450 let key = match k {
451 serde_value::Value::I64(i) => LuaTableKey::IntKey(i as u64),
452 serde_value::Value::U64(u) => LuaTableKey::IntKey(u),
453 serde_value::Value::String(s) => LuaTableKey::StringKey(s),
454 other => {
455 return Err(de::Error::custom(format!("unexpected map key: {other:?}")))
456 }
457 };
458 let val = v.deserialize_into::<V>().map_err(de::Error::custom)?;
459 Ok((key, val))
460 })
461 .try_collect()
462 .map(Some),
463 serde_value::Value::Seq(seq) => seq
464 .into_iter()
465 .enumerate()
466 .map(|(i, v)| {
467 let val = v.deserialize_into::<V>().map_err(de::Error::custom)?;
468 Ok((LuaTableKey::IntKey(i as u64 + 1), val))
469 })
470 .try_collect()
471 .map(Some),
472 serde_value::Value::Unit => Ok(None),
473 other => Err(de::Error::custom(format!(
474 "expected a table or nil, got {other:?}"
475 ))),
476 }
477}
478
479fn display_builtin_spec(spec: &HashMap<LuaTableKey, ModuleSpecInternal>) -> DisplayLuaValue {
480 DisplayLuaValue::Table(
481 spec.iter()
482 .map(|(key, value)| DisplayLuaKV {
483 key: match key {
484 LuaTableKey::StringKey(s) => s.clone(),
485 LuaTableKey::IntKey(_) => unreachable!("integer key in modules"),
486 },
487 value: value.display_lua_value(),
488 })
489 .collect(),
490 )
491}
492
493fn display_path_string_map(map: &HashMap<PathBuf, String>) -> DisplayLuaValue {
494 DisplayLuaValue::Table(
495 map.iter()
496 .map(|(k, v)| DisplayLuaKV {
497 key: k.to_slash_lossy().into_owned(),
498 value: DisplayLuaValue::String(v.clone()),
499 })
500 .collect(),
501 )
502}
503
504fn display_include(include: &HashMap<LuaTableKey, PathBuf>) -> DisplayLuaValue {
505 DisplayLuaValue::Table(
506 include
507 .iter()
508 .map(|(key, value)| DisplayLuaKV {
509 key: match key {
510 LuaTableKey::StringKey(s) => s.clone(),
511 LuaTableKey::IntKey(_) => unreachable!("integer key in include"),
512 },
513 value: DisplayLuaValue::String(value.to_slash_lossy().into_owned()),
514 })
515 .collect(),
516 )
517}
518
519#[derive(Debug, PartialEq, Deserialize, Default, Clone, lux_macros::DisplayAsLuaKV)]
520#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
521#[display_lua(key = "build")]
522pub(crate) struct BuildSpecInternal {
523 #[serde(rename = "type", default)]
528 #[display_lua(rename = "type")]
529 #[cfg_attr(feature = "schema", schemars(with = "Option<String>"))]
530 pub(crate) build_type: Option<BuildType>,
531 #[serde(
535 rename = "modules",
536 default,
537 deserialize_with = "deserialize_map_or_seq"
538 )]
539 #[display_lua(rename = "modules", convert_with = "display_builtin_spec")]
540 #[cfg_attr(
541 feature = "schema",
542 schemars(with = "Option<std::collections::BTreeMap<String, crate::schema::ModuleSpec>>")
543 )]
544 pub(crate) builtin_spec: Option<HashMap<LuaTableKey, ModuleSpecInternal>>,
545 #[serde(default)]
547 pub(crate) makefile: Option<PathBuf>,
548 #[serde(rename = "build_target", default)]
550 #[display_lua(rename = "build_target")]
551 pub(crate) make_build_target: Option<String>,
552 #[serde(default)]
554 pub(crate) build_pass: Option<bool>,
555 #[serde(rename = "install_target", default)]
557 #[display_lua(rename = "install_target")]
558 pub(crate) make_install_target: Option<String>,
559 #[serde(default)]
561 pub(crate) install_pass: Option<bool>,
562 #[serde(rename = "build_variables", default)]
564 #[display_lua(rename = "build_variables")]
565 pub(crate) make_build_variables: Option<HashMap<String, String>>,
566 #[serde(rename = "install_variables", default)]
568 #[display_lua(rename = "install_variables")]
569 pub(crate) make_install_variables: Option<HashMap<String, String>>,
570 #[serde(default)]
572 pub(crate) variables: Option<HashMap<String, String>>,
573 #[serde(rename = "cmake", default)]
576 #[display_lua(rename = "cmake")]
577 pub(crate) cmake_lists_content: Option<String>,
578 #[serde(default)]
580 pub(crate) build_command: Option<String>,
581 #[serde(default)]
583 pub(crate) install_command: Option<String>,
584 #[serde(default)]
586 pub(crate) install: Option<InstallSpec>,
587 #[serde(default, deserialize_with = "deserialize_copy_directories")]
590 #[cfg_attr(feature = "schema", schemars(with = "Option<Vec<String>>"))]
591 pub(crate) copy_directories: Option<Vec<PathBuf>>,
592 #[serde(default)]
595 #[display_lua(convert_with = "display_path_string_map")]
596 #[cfg_attr(
597 feature = "schema",
598 schemars(with = "Option<std::collections::BTreeMap<String, String>>")
599 )]
600 pub(crate) patches: Option<HashMap<PathBuf, String>>,
601 #[serde(default)]
603 pub(crate) target_path: Option<PathBuf>,
604 #[serde(default)]
606 pub(crate) default_features: Option<bool>,
607 #[serde(default)]
609 pub(crate) features: Option<Vec<String>>,
610 pub(crate) cargo_extra_args: Option<Vec<String>>,
612 #[serde(default)]
615 pub(crate) package: Option<String>,
616 #[serde(default, deserialize_with = "deserialize_map_or_seq")]
619 #[display_lua(convert_with = "display_include")]
620 #[cfg_attr(
621 feature = "schema",
622 schemars(with = "Option<std::collections::BTreeMap<String, String>>")
623 )]
624 pub(crate) include: Option<HashMap<LuaTableKey, PathBuf>>,
625 #[serde(default)]
627 pub(crate) lang: Option<String>,
628 #[serde(default)]
631 pub(crate) parser: Option<bool>,
632 #[serde(default)]
635 pub(crate) generate: Option<bool>,
636 #[serde(default)]
638 pub(crate) location: Option<PathBuf>,
639 #[serde(default)]
642 #[display_lua(convert_with = "display_path_string_map")]
643 #[cfg_attr(
644 feature = "schema",
645 schemars(with = "Option<std::collections::BTreeMap<String, String>>")
646 )]
647 pub(crate) queries: Option<HashMap<PathBuf, String>>,
648}
649
650impl PartialOverride for BuildSpecInternal {
651 type Err = ModuleSpecAmbiguousPlatformOverride;
652
653 fn apply_overrides(&self, override_spec: &Self) -> Result<Self, Self::Err> {
654 override_build_spec_internal(self, override_spec)
655 }
656}
657
658impl PlatformOverridable for BuildSpecInternal {
659 type Err = Infallible;
660
661 fn on_nil<T>() -> Result<PerPlatform<T>, <Self as PlatformOverridable>::Err>
662 where
663 T: PlatformOverridable,
664 T: Default,
665 {
666 Ok(PerPlatform::default())
667 }
668}
669
670fn override_build_spec_internal(
671 base: &BuildSpecInternal,
672 override_spec: &BuildSpecInternal,
673) -> Result<BuildSpecInternal, ModuleSpecAmbiguousPlatformOverride> {
674 Ok(BuildSpecInternal {
675 build_type: override_opt(&override_spec.build_type, &base.build_type),
676 builtin_spec: match (
677 override_spec.builtin_spec.clone(),
678 base.builtin_spec.clone(),
679 ) {
680 (Some(override_val), Some(base_spec_map)) => {
681 Some(base_spec_map.into_iter().chain(override_val).try_fold(
682 HashMap::default(),
683 |mut acc: HashMap<LuaTableKey, ModuleSpecInternal>,
684 (k, module_spec_override)|
685 -> Result<
686 HashMap<LuaTableKey, ModuleSpecInternal>,
687 ModuleSpecAmbiguousPlatformOverride,
688 > {
689 let overridden = match acc.get(&k) {
690 None => module_spec_override,
691 Some(base_module_spec) => {
692 base_module_spec.apply_overrides(&module_spec_override)?
693 }
694 };
695 acc.insert(k, overridden);
696 Ok(acc)
697 },
698 )?)
699 }
700 (override_val @ Some(_), _) => override_val,
701 (_, base_val @ Some(_)) => base_val,
702 _ => None,
703 },
704 makefile: override_opt(&override_spec.makefile, &base.makefile),
705 make_build_target: override_opt(&override_spec.make_build_target, &base.make_build_target),
706 build_pass: override_opt(&override_spec.build_pass, &base.build_pass),
707 make_install_target: override_opt(
708 &override_spec.make_install_target,
709 &base.make_install_target,
710 ),
711 install_pass: override_opt(&override_spec.install_pass, &base.install_pass),
712 make_build_variables: merge_map_opts(
713 &override_spec.make_build_variables,
714 &base.make_build_variables,
715 ),
716 make_install_variables: merge_map_opts(
717 &override_spec.make_install_variables,
718 &base.make_build_variables,
719 ),
720 variables: merge_map_opts(&override_spec.variables, &base.variables),
721 cmake_lists_content: override_opt(
722 &override_spec.cmake_lists_content,
723 &base.cmake_lists_content,
724 ),
725 build_command: override_opt(&override_spec.build_command, &base.build_command),
726 install_command: override_opt(&override_spec.install_command, &base.install_command),
727 install: override_opt(&override_spec.install, &base.install),
728 copy_directories: match (
729 override_spec.copy_directories.clone(),
730 base.copy_directories.clone(),
731 ) {
732 (Some(override_vec), Some(base_vec)) => {
733 let merged: Vec<PathBuf> =
734 base_vec.into_iter().chain(override_vec).unique().collect();
735 Some(merged)
736 }
737 (None, base_vec @ Some(_)) => base_vec,
738 (override_vec @ Some(_), None) => override_vec,
739 _ => None,
740 },
741 patches: override_opt(&override_spec.patches, &base.patches),
742 target_path: override_opt(&override_spec.target_path, &base.target_path),
743 default_features: override_opt(&override_spec.default_features, &base.default_features),
744 features: override_opt(&override_spec.features, &base.features),
745 cargo_extra_args: override_opt(&override_spec.cargo_extra_args, &base.cargo_extra_args),
746 package: override_opt(&override_spec.package, &base.package),
747 include: merge_map_opts(&override_spec.include, &base.include),
748 lang: override_opt(&override_spec.lang, &base.lang),
749 parser: override_opt(&override_spec.parser, &base.parser),
750 generate: override_opt(&override_spec.generate, &base.generate),
751 location: override_opt(&override_spec.location, &base.location),
752 queries: merge_map_opts(&override_spec.queries, &base.queries),
753 })
754}
755
756fn override_opt<T: Clone>(override_opt: &Option<T>, base: &Option<T>) -> Option<T> {
757 match override_opt.clone() {
758 override_val @ Some(_) => override_val,
759 None => base.clone(),
760 }
761}
762
763fn merge_map_opts<K, V>(
764 override_map: &Option<HashMap<K, V>>,
765 base_map: &Option<HashMap<K, V>>,
766) -> Option<HashMap<K, V>>
767where
768 K: Clone,
769 K: Eq,
770 K: std::hash::Hash,
771 V: Clone,
772{
773 match (override_map.clone(), base_map.clone()) {
774 (Some(override_map), Some(base_map)) => {
775 Some(base_map.into_iter().chain(override_map).collect())
776 }
777 (_, base_map @ Some(_)) => base_map,
778 (override_map @ Some(_), _) => override_map,
779 _ => None,
780 }
781}
782
783#[derive(Debug, PartialEq, Deserialize, Clone)]
785#[serde(rename_all = "lowercase", remote = "BuildType")]
786#[derive(Default)]
787pub(crate) enum BuildType {
788 #[default]
790 Builtin,
791 Make,
793 CMake,
795 Command,
797 None,
799 LuaRock(String),
801 #[serde(rename = "rust-mlua")]
802 RustMlua,
803 #[serde(rename = "rust-binary")]
804 RustBinary,
805 #[serde(rename = "treesitter-parser")]
806 TreesitterParser,
807 Source,
808}
809
810impl BuildType {
811 pub(crate) fn luarocks_build_backend(&self) -> Option<LuaDependencySpec> {
812 match self {
813 &BuildType::Builtin
814 | &BuildType::Make
815 | &BuildType::CMake
816 | &BuildType::Command
817 | &BuildType::None
818 | &BuildType::Source => None,
819 BuildType::LuaRock(s) => Some(PackageName::new(format!("luarocks-build-{s}")).into()),
820 &BuildType::RustMlua => unsafe {
821 Some(
822 PackageReq::parse("luarocks-build-rust-mlua >= 0.2.6")
823 .unwrap_unchecked()
824 .into(),
825 )
826 },
827 &BuildType::RustBinary => unsafe {
828 Some(
829 PackageReq::parse("luarocks-build-rust-binary >= 4.0.0")
830 .unwrap_unchecked()
831 .into(),
832 )
833 },
834 &BuildType::TreesitterParser => {
835 Some(PackageName::new("luarocks-build-treesitter-parser >= 6.1.0".into()).into())
836 } }
839 }
840}
841
842impl<'de> Deserialize<'de> for BuildType {
845 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
846 where
847 D: Deserializer<'de>,
848 {
849 let s = String::deserialize(deserializer)?;
850 if s == "builtin" || s == "module" {
851 Ok(Self::Builtin)
852 } else {
853 match Self::deserialize(s.clone().into_deserializer()) {
854 Err(_) => Ok(Self::LuaRock(s)),
855 ok => ok,
856 }
857 }
858 }
859}
860
861impl Display for BuildType {
862 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
863 match self {
864 BuildType::Builtin => write!(f, "builtin"),
865 BuildType::Make => write!(f, "make"),
866 BuildType::CMake => write!(f, "cmake"),
867 BuildType::Command => write!(f, "command"),
868 BuildType::None => write!(f, "none"),
869 BuildType::LuaRock(s) => write!(f, "{s}"),
870 BuildType::RustMlua => write!(f, "rust-mlua"),
871 BuildType::RustBinary => write!(f, "rust-binary"),
872 BuildType::TreesitterParser => write!(f, "treesitter-parser"),
873 BuildType::Source => write!(f, "source"),
874 }
875 }
876}
877
878impl DisplayAsLuaValue for BuildType {
879 fn display_lua_value(&self) -> DisplayLuaValue {
880 DisplayLuaValue::String(self.to_string())
881 }
882}
883
884impl DisplayAsLuaValue for InstallSpec {
885 fn display_lua_value(&self) -> DisplayLuaValue {
886 self.display_lua().value
887 }
888}
889
890#[cfg(test)]
891mod tests {
892
893 use super::*;
894
895 fn eval_lua_global<T: serde::de::DeserializeOwned>(code: &str, key: &'static str) -> T {
896 use ottavino::{Closure, Executor, Fuel, Lua};
897 use ottavino_util::serde::from_value;
898 Lua::core()
899 .try_enter(|ctx| {
900 let closure = Closure::load(ctx, None, code.as_bytes())?;
901 let executor = Executor::start(ctx, closure.into(), ());
902 executor.step(ctx, &mut Fuel::with(i32::MAX))?;
903 from_value(ctx.globals().get_value(ctx, key)).map_err(ottavino::Error::from)
904 })
905 .unwrap()
906 }
907
908 #[tokio::test]
909 pub async fn deserialize_build_type() {
910 let build_type: BuildType = serde_json::from_str("\"builtin\"").unwrap();
911 assert_eq!(build_type, BuildType::Builtin);
912 let build_type: BuildType = serde_json::from_str("\"module\"").unwrap();
913 assert_eq!(build_type, BuildType::Builtin);
914 let build_type: BuildType = serde_json::from_str("\"make\"").unwrap();
915 assert_eq!(build_type, BuildType::Make);
916 let build_type: BuildType = serde_json::from_str("\"custom_build_backend\"").unwrap();
917 assert_eq!(
918 build_type,
919 BuildType::LuaRock("custom_build_backend".into())
920 );
921 let build_type: BuildType = serde_json::from_str("\"rust-mlua\"").unwrap();
922 assert_eq!(build_type, BuildType::RustMlua);
923 }
924
925 #[test]
926 pub fn install_spec_roundtrip() {
927 let spec = InstallSpec {
928 lua: HashMap::from([(
929 "mymod".parse::<LuaModule>().unwrap(),
930 "src/mymod.lua".into(),
931 )]),
932 lib: HashMap::from([("mylib".into(), "lib/mylib.so".into())]),
933 conf: HashMap::from([("myconf".into(), "conf/myconf.cfg".into())]),
934 bin: HashMap::from([("mybinary".into(), "bin/mybinary".into())]),
935 };
936 let lua = spec.display_lua().to_string();
937 let restored: InstallSpec = eval_lua_global(&lua, "install");
938 assert_eq!(spec, restored);
939 }
940
941 #[test]
942 pub fn install_spec_empty_roundtrip() {
943 let spec = InstallSpec::default();
944 let lua = spec.display_lua().to_string();
945 let lua = if lua.trim().is_empty() {
946 "install = {}".to_string()
947 } else {
948 lua
949 };
950 let restored: InstallSpec = eval_lua_global(&lua, "install");
951 assert_eq!(spec, restored);
952 }
953
954 #[test]
955 pub fn build_spec_internal_builtin_roundtrip() {
956 let spec = BuildSpecInternal {
957 build_type: Some(BuildType::Builtin),
958 builtin_spec: Some(HashMap::from([(
959 LuaTableKey::StringKey("mymod".into()),
960 ModuleSpecInternal::SourcePath("src/mymod.lua".into()),
961 )])),
962 install: Some(InstallSpec {
963 lua: HashMap::from([(
964 "extra".parse::<LuaModule>().unwrap(),
965 "src/extra.lua".into(),
966 )]),
967 bin: HashMap::from([("mytool".into(), "bin/mytool".into())]),
968 ..Default::default()
969 }),
970 copy_directories: Some(vec!["docs".into()]),
971 ..Default::default()
972 };
973 let lua = spec.display_lua().to_string();
974 let restored: BuildSpecInternal = eval_lua_global(&lua, "build");
975 assert_eq!(spec, restored);
976 }
977
978 #[test]
979 pub fn build_spec_internal_make_roundtrip() {
980 let spec = BuildSpecInternal {
981 build_type: Some(BuildType::Make),
982 makefile: Some("GNUmakefile".into()),
983 make_build_target: Some("all".into()),
984 make_install_target: Some("install".into()),
985 make_build_variables: Some(HashMap::from([("CFLAGS".into(), "-O2".into())])),
986 make_install_variables: Some(HashMap::from([("PREFIX".into(), "/usr/local".into())])),
987 variables: Some(HashMap::from([("LUA_LIBDIR".into(), "/usr/lib".into())])),
988 ..Default::default()
989 };
990 let lua = spec.display_lua().to_string();
991 let restored: BuildSpecInternal = eval_lua_global(&lua, "build");
992 assert_eq!(spec, restored);
993 }
994}