1pub mod backend;
2pub(crate) mod internal;
3
4use crate::package;
5use path_slash::PathBufExt;
6
7use itertools::Itertools;
8
9use miette::Diagnostic;
10use serde::{de, de::IntoDeserializer, Deserialize, Deserializer};
11use std::{
12 collections::HashMap, convert::Infallible, env::consts::DLL_EXTENSION, env::consts::DLL_PREFIX,
13 fmt::Display, path::PathBuf, str::FromStr,
14};
15use thiserror::Error;
16
17use crate::rockspec::platform::per_platform_from_intermediate;
18
19use super::display::{AsLuaKV, AsLuaValue};
20use super::{display, lua_dependency, serde_util, PerPlatform};
21
22#[derive(Clone, Debug, PartialEq)]
24pub struct Spec {
25 pub backend: Option<backend::Spec>,
27 pub install: Install,
31 pub copy_directories: Vec<PathBuf>,
33 pub patches: HashMap<PathBuf, String>,
37}
38
39impl Default for Spec {
40 fn default() -> Self {
41 Self {
42 backend: Some(backend::Spec::default()),
43 install: Install::default(),
44 copy_directories: Vec::default(),
45 patches: HashMap::default(),
46 }
47 }
48}
49
50impl Spec {
51 pub(crate) fn from_internal_spec(internal: internal::Spec) -> Result<Self, internal::Error> {
52 let backend = match internal.build_type.unwrap_or_default() {
53 internal::Type::Builtin => {
54 Some(backend::Spec::Builtin(
55 backend::Builtin {
56 modules: internal
57 .builtin_spec
58 .unwrap_or_default()
59 .into_iter()
60 .map(|(key, module_spec_internal)| {
61 let key_str = match key {
62 serde_util::LuaTableKey::IntKey(_) => {
63 Err(internal::Error::ModulesHaveListElements)
64 }
65 serde_util::LuaTableKey::StringKey(str) => {
66 Ok(backend::Module::from_str(str.as_str())?)
67 }
68 }?;
69 match backend::ModuleSpec::from_internal(module_spec_internal) {
70 Ok(module_spec) => Ok((key_str, module_spec)),
71 Err(err) => Err(err.into()),
72 }
73 })
74 .collect::<Result<
75 HashMap<backend::Module, backend::ModuleSpec>,
76 internal::Error,
77 >>()?,
78 },
79 ))
80 }
81 internal::Type::Make => {
82 let default = backend::Make::default();
83 Some(backend::Spec::Make(backend::Make {
84 makefile: internal.makefile.unwrap_or(default.makefile),
85 build_target: internal.make_build_target,
86 build_pass: internal.build_pass.unwrap_or(default.build_pass),
87 install_target: internal
88 .make_install_target
89 .unwrap_or(default.install_target),
90 install_pass: internal.install_pass.unwrap_or(default.install_pass),
91 build_variables: internal.make_build_variables.unwrap_or_default(),
92 install_variables: internal.make_install_variables.unwrap_or_default(),
93 variables: internal.variables.unwrap_or_default(),
94 }))
95 }
96 internal::Type::CMake => {
97 let default = backend::CMake::default();
98 Some(backend::Spec::CMake(backend::CMake {
99 cmake_lists_content: internal.cmake_lists_content,
100 build_pass: internal.build_pass.unwrap_or(default.build_pass),
101 install_pass: internal.install_pass.unwrap_or(default.install_pass),
102 variables: internal.variables.unwrap_or_default(),
103 }))
104 }
105 internal::Type::Command => Some(backend::Spec::Command(backend::Command {
106 build_command: internal.build_command,
107 install_command: internal.install_command,
108 })),
109 internal::Type::None => None,
110 internal::Type::LuaRock(s) => Some(backend::Spec::LuaRock(s)),
111 internal::Type::RustMlua => Some(backend::Spec::RustMlua(backend::RustMlua {
112 modules: internal
113 .builtin_spec
114 .ok_or(internal::Error::NoModulesSpecified)?
115 .into_iter()
116 .map(|(key, value)| match (key, value) {
117 (
118 serde_util::LuaTableKey::IntKey(_),
119 backend::builtin::internal::ModuleSpec::SourcePath(module),
120 ) => {
121 let mut rust_lib: PathBuf =
122 format!("{DLL_PREFIX}{}", module.display()).into();
123 rust_lib.set_extension(DLL_EXTENSION);
124 Ok((module.to_string_lossy().to_string(), rust_lib))
125 }
126 (
127 serde_util::LuaTableKey::StringKey(module_name),
128 backend::builtin::internal::ModuleSpec::SourcePath(module),
129 ) => {
130 let mut rust_lib: PathBuf =
131 format!("{DLL_PREFIX}{}", module.display()).into();
132 rust_lib.set_extension(DLL_EXTENSION);
133 Ok((module_name, rust_lib))
134 }
135 _ => Err(internal::Error::InvalidRustMLuaFormat),
136 })
137 .try_collect()?,
138 target_path: internal.target_path.unwrap_or("target".into()),
139 default_features: internal.default_features.unwrap_or(true),
140 features: internal.features.unwrap_or_default(),
141 cargo_extra_args: internal.cargo_extra_args.unwrap_or_default(),
142 include: internal
143 .include
144 .unwrap_or_default()
145 .into_iter()
146 .map(|(key, dest)| match key {
147 serde_util::LuaTableKey::IntKey(_) => (dest.clone(), dest),
148 serde_util::LuaTableKey::StringKey(src) => (src.into(), dest),
149 })
150 .collect(),
151 })),
152 internal::Type::RustBinary => Some(backend::Spec::RustBinary(backend::RustBinary {
153 package: internal.package,
154 features: internal.features.unwrap_or_default(),
155 })),
156 internal::Type::TreesitterParser => {
157 Some(backend::Spec::TreesitterParser(backend::Treesitter {
158 lang: internal
159 .lang
160 .ok_or(internal::Error::NoTreesitterParserLanguageSpecified)?,
161 parser: internal.parser.unwrap_or(true),
162 generate: internal.generate.unwrap_or(false),
163 location: internal.location,
164 queries: internal.queries.unwrap_or_default(),
165 }))
166 }
167 internal::Type::Source => Some(backend::Spec::Source),
168 };
169 Ok(Self {
170 backend,
171 install: internal.install.unwrap_or_default(),
172 copy_directories: internal.copy_directories.unwrap_or_default(),
173 patches: internal.patches.unwrap_or_default(),
174 })
175 }
176}
177
178impl TryFrom<internal::Spec> for Spec {
179 type Error = internal::Error;
180
181 fn try_from(internal: internal::Spec) -> Result<Self, Self::Error> {
182 Spec::from_internal_spec(internal)
183 }
184}
185
186impl<'de> Deserialize<'de> for Spec {
187 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
188 where
189 D: Deserializer<'de>,
190 {
191 let internal = internal::Spec::deserialize(deserializer)?;
192 Spec::from_internal_spec(internal).map_err(de::Error::custom)
193 }
194}
195
196impl<'de> Deserialize<'de> for PerPlatform<Spec> {
201 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
202 where
203 D: Deserializer<'de>,
204 {
205 per_platform_from_intermediate::<_, internal::Spec, _>(deserializer)
206 }
207}
208
209#[derive(Clone, Debug)]
210struct LuaPathBufTable(HashMap<serde_util::LuaTableKey, PathBuf>);
211
212impl<'de> Deserialize<'de> for LuaPathBufTable {
213 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
214 Ok(LuaPathBufTable(
215 deserialize_map_or_seq(deserializer)?.unwrap_or_default(),
216 ))
217 }
218}
219
220impl LuaPathBufTable {
221 fn coerce<S>(self) -> Result<HashMap<S, PathBuf>, S::Err>
222 where
223 S: FromStr + Eq + std::hash::Hash,
224 {
225 self.0
226 .into_iter()
227 .map(|(key, value)| {
228 let key = match key {
229 serde_util::LuaTableKey::IntKey(_) => value
230 .with_extension("")
231 .file_name()
232 .unwrap_or_default()
233 .to_string_lossy()
234 .to_string(),
235 serde_util::LuaTableKey::StringKey(key) => key,
236 };
237 Ok((S::from_str(&key)?, value))
238 })
239 .try_collect()
240 }
241}
242
243#[derive(Clone, Debug)]
244struct LibPathBufTable(HashMap<serde_util::LuaTableKey, PathBuf>);
245
246impl<'de> Deserialize<'de> for LibPathBufTable {
247 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
248 Ok(LibPathBufTable(
249 deserialize_map_or_seq(deserializer)?.unwrap_or_default(),
250 ))
251 }
252}
253
254impl LibPathBufTable {
255 fn coerce<S>(self) -> Result<HashMap<S, PathBuf>, S::Err>
256 where
257 S: FromStr + Eq + std::hash::Hash,
258 {
259 self.0
260 .into_iter()
261 .map(|(key, value)| {
262 let key = match key {
263 serde_util::LuaTableKey::IntKey(_) => value
264 .file_name()
265 .unwrap_or_default()
266 .to_string_lossy()
267 .to_string(),
268 serde_util::LuaTableKey::StringKey(key) => key,
269 };
270 Ok((S::from_str(&key)?, value))
271 })
272 .try_collect()
273 }
274}
275
276#[derive(Debug, PartialEq, Default, Deserialize, Clone, lux_macros::AsLuaKV)]
285#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
286#[display_lua(key = "install")]
287pub struct Install {
288 #[serde(default, deserialize_with = "deserialize_module_path_map")]
290 #[cfg_attr(
291 feature = "schema",
292 schemars(with = "std::collections::BTreeMap<String, String>")
293 )]
294 pub lua: HashMap<backend::Module, PathBuf>,
295 #[serde(default, deserialize_with = "deserialize_file_name_path_map")]
297 #[cfg_attr(
298 feature = "schema",
299 schemars(with = "std::collections::BTreeMap<String, String>")
300 )]
301 pub lib: HashMap<String, PathBuf>,
302 #[serde(default)]
304 pub conf: HashMap<String, PathBuf>,
305 #[serde(default, deserialize_with = "deserialize_file_name_path_map")]
309 #[cfg_attr(
310 feature = "schema",
311 schemars(with = "std::collections::BTreeMap<String, String>")
312 )]
313 pub bin: HashMap<String, PathBuf>,
314}
315
316fn deserialize_module_path_map<'de, D>(
317 deserializer: D,
318) -> Result<HashMap<backend::Module, PathBuf>, D::Error>
319where
320 D: Deserializer<'de>,
321{
322 let modules = LuaPathBufTable::deserialize(deserializer)?;
323 modules.coerce().map_err(de::Error::custom)
324}
325
326fn deserialize_file_name_path_map<'de, D>(
327 deserializer: D,
328) -> Result<HashMap<String, PathBuf>, D::Error>
329where
330 D: Deserializer<'de>,
331{
332 let binaries = LibPathBufTable::deserialize(deserializer)?;
333 binaries.coerce().map_err(de::Error::custom)
334}
335
336fn deserialize_copy_directories<'de, D>(deserializer: D) -> Result<Option<Vec<PathBuf>>, D::Error>
337where
338 D: Deserializer<'de>,
339{
340 let value: Option<serde_value::Value> = Option::deserialize(deserializer)?;
341 let copy_directories: Option<Vec<String>> = match value {
342 Some(value) => Some(value.deserialize_into().map_err(de::Error::custom)?),
343 None => None,
344 };
345 let special_directories: Vec<String> = vec!["lua".into(), "lib".into(), "rock_manifest".into()];
346 match special_directories
347 .into_iter()
348 .find(|dir| copy_directories.clone().unwrap_or_default().contains(dir))
349 {
350 Some(d) => Err(format!(
353 "directory '{d}' in copy_directories clashes with the .rock format", )),
355 _ => Ok(copy_directories.map(|vec| vec.into_iter().map(PathBuf::from).collect())),
356 }
357 .map_err(de::Error::custom)
358}
359
360fn deserialize_map_or_seq<'de, D, V>(
362 deserializer: D,
363) -> Result<Option<HashMap<serde_util::LuaTableKey, V>>, D::Error>
364where
365 D: Deserializer<'de>,
366 V: de::DeserializeOwned,
367{
368 match de::DeserializeSeed::deserialize(serde_util::LuaValueSeed, deserializer)
369 .map_err(de::Error::custom)?
370 {
371 serde_value::Value::Map(map) => map
372 .into_iter()
373 .map(|(k, v)| {
374 let key = match k {
375 serde_value::Value::I64(i) => serde_util::LuaTableKey::IntKey(i as u64),
376 serde_value::Value::U64(u) => serde_util::LuaTableKey::IntKey(u),
377 serde_value::Value::String(s) => serde_util::LuaTableKey::StringKey(s),
378 other => {
379 return Err(de::Error::custom(format!("unexpected map key: {other:?}")))
380 }
381 };
382 let val = v.deserialize_into::<V>().map_err(de::Error::custom)?;
383 Ok((key, val))
384 })
385 .try_collect()
386 .map(Some),
387 serde_value::Value::Seq(seq) => seq
388 .into_iter()
389 .enumerate()
390 .map(|(i, v)| {
391 let val = v.deserialize_into::<V>().map_err(de::Error::custom)?;
392 Ok((serde_util::LuaTableKey::IntKey(i as u64 + 1), val))
393 })
394 .try_collect()
395 .map(Some),
396 serde_value::Value::Unit => Ok(None),
397 other => Err(de::Error::custom(format!(
398 "expected a table or nil, got {other:?}"
399 ))),
400 }
401}
402
403fn display_builtin_spec(
404 spec: &HashMap<serde_util::LuaTableKey, backend::builtin::internal::ModuleSpec>,
405) -> display::LuaValue {
406 display::LuaValue::Table(
407 spec.iter()
408 .map(|(key, value)| display::LuaKV {
409 key: match key {
410 serde_util::LuaTableKey::StringKey(s) => s.clone(),
411 serde_util::LuaTableKey::IntKey(_) => unreachable!("integer key in modules"),
412 },
413 value: value.display_lua_value(),
414 })
415 .collect(),
416 )
417}
418
419fn display_path_string_map(map: &HashMap<PathBuf, String>) -> display::LuaValue {
420 display::LuaValue::Table(
421 map.iter()
422 .map(|(k, v)| display::LuaKV {
423 key: k.to_slash_lossy().into_owned(),
424 value: display::LuaValue::String(v.clone()),
425 })
426 .collect(),
427 )
428}
429
430fn display_include(include: &HashMap<serde_util::LuaTableKey, PathBuf>) -> display::LuaValue {
431 display::LuaValue::Table(
432 include
433 .iter()
434 .map(|(key, value)| display::LuaKV {
435 key: match key {
436 serde_util::LuaTableKey::StringKey(s) => s.clone(),
437 serde_util::LuaTableKey::IntKey(_) => unreachable!("integer key in include"),
438 },
439 value: display::LuaValue::String(value.to_slash_lossy().into_owned()),
440 })
441 .collect(),
442 )
443}
444
445impl display::AsLuaValue for Install {
446 fn display_lua_value(&self) -> display::LuaValue {
447 self.display_lua().value
448 }
449}
450
451#[cfg(test)]
452mod tests {
453
454 use super::*;
455
456 fn eval_lua_global<T: serde::de::DeserializeOwned>(code: &str, key: &'static str) -> T {
457 use ottavino::{Closure, Executor, Fuel, Lua};
458 use ottavino_util::serde::from_value;
459 Lua::core()
460 .try_enter(|ctx| {
461 let closure = Closure::load(ctx, None, code.as_bytes())?;
462 let executor = Executor::start(ctx, closure.into(), ());
463 executor.step(ctx, &mut Fuel::with(i32::MAX))?;
464 from_value(ctx.globals().get_value(ctx, key)).map_err(ottavino::Error::from)
465 })
466 .unwrap()
467 }
468
469 #[tokio::test]
470 pub async fn deserialize_build_type() {
471 let build_type: internal::Type = serde_json::from_str("\"builtin\"").unwrap();
472 assert_eq!(build_type, internal::Type::Builtin);
473 let build_type: internal::Type = serde_json::from_str("\"module\"").unwrap();
474 assert_eq!(build_type, internal::Type::Builtin);
475 let build_type: internal::Type = serde_json::from_str("\"make\"").unwrap();
476 assert_eq!(build_type, internal::Type::Make);
477 let build_type: internal::Type = serde_json::from_str("\"custom_build_backend\"").unwrap();
478 assert_eq!(
479 build_type,
480 internal::Type::LuaRock("custom_build_backend".into())
481 );
482 let build_type: internal::Type = serde_json::from_str("\"rust-mlua\"").unwrap();
483 assert_eq!(build_type, internal::Type::RustMlua);
484 }
485
486 #[test]
487 pub fn install_spec_roundtrip() {
488 let spec = Install {
489 lua: HashMap::from([(
490 "mymod".parse::<backend::Module>().unwrap(),
491 "src/mymod.lua".into(),
492 )]),
493 lib: HashMap::from([("mylib".into(), "lib/mylib.so".into())]),
494 conf: HashMap::from([("myconf".into(), "conf/myconf.cfg".into())]),
495 bin: HashMap::from([("mybinary".into(), "bin/mybinary".into())]),
496 };
497 let lua = spec.display_lua().to_string();
498 let restored: Install = eval_lua_global(&lua, "install");
499 assert_eq!(spec, restored);
500 }
501
502 #[test]
503 pub fn install_spec_empty_roundtrip() {
504 let spec = Install::default();
505 let lua = spec.display_lua().to_string();
506 let lua = if lua.trim().is_empty() {
507 "install = {}".to_string()
508 } else {
509 lua
510 };
511 let restored: Install = eval_lua_global(&lua, "install");
512 assert_eq!(spec, restored);
513 }
514
515 #[test]
516 pub fn build_spec_internal_builtin_roundtrip() {
517 let spec = internal::Spec {
518 build_type: Some(internal::Type::Builtin),
519 builtin_spec: Some(HashMap::from([(
520 serde_util::LuaTableKey::StringKey("mymod".into()),
521 backend::builtin::internal::ModuleSpec::SourcePath("src/mymod.lua".into()),
522 )])),
523 install: Some(Install {
524 lua: HashMap::from([(
525 "extra".parse::<backend::Module>().unwrap(),
526 "src/extra.lua".into(),
527 )]),
528 bin: HashMap::from([("mytool".into(), "bin/mytool".into())]),
529 ..Default::default()
530 }),
531 copy_directories: Some(vec!["docs".into()]),
532 ..Default::default()
533 };
534 let lua = spec.display_lua().to_string();
535 let restored: internal::Spec = eval_lua_global(&lua, "build");
536 assert_eq!(spec, restored);
537 }
538
539 #[test]
540 pub fn build_spec_internal_make_roundtrip() {
541 let spec = internal::Spec {
542 build_type: Some(internal::Type::Make),
543 makefile: Some("GNUmakefile".into()),
544 make_build_target: Some("all".into()),
545 make_install_target: Some("install".into()),
546 make_build_variables: Some(HashMap::from([("CFLAGS".into(), "-O2".into())])),
547 make_install_variables: Some(HashMap::from([("PREFIX".into(), "/usr/local".into())])),
548 variables: Some(HashMap::from([("LUA_LIBDIR".into(), "/usr/lib".into())])),
549 ..Default::default()
550 };
551 let lua = spec.display_lua().to_string();
552 let restored: internal::Spec = eval_lua_global(&lua, "build");
553 assert_eq!(spec, restored);
554 }
555}