1use toml::{Table, Value};
20
21pub const MANIFEST: &str = "hexicon.toml";
23
24pub(crate) fn is_manifest(path: &str) -> bool {
26 path.len() >= 5 && path[path.len() - 5..].eq_ignore_ascii_case(".toml")
27}
28
29pub(crate) fn source_name(name: &str) -> String {
32 let file = name.rsplit(['/', '\\']).next().unwrap_or(name);
33 if file.contains('.') {
34 name.to_owned()
35 } else {
36 format!("{name}.hxn")
37 }
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
43pub(crate) enum ModuleRef {
44 Source(String),
46 Library {
49 name: String,
51 exclude: Vec<String>,
53 include: Vec<String>,
56 },
57}
58
59#[derive(Debug, Default)]
61pub(crate) struct Library {
62 pub modules: Vec<ModuleRef>,
65 pub resources: Vec<String>,
67 pub needs: Vec<(String, String)>,
69 pub header: Option<String>,
72 pub text_tags: Vec<String>,
75 pub object_tags: Vec<String>,
79 pub object_keys: Vec<String>,
84 pub ifid: Option<String>,
87}
88
89struct Section<'t> {
91 table: &'t Table,
92 name: &'static str,
93}
94
95impl Section<'_> {
96 fn check_keys(&self, known: &[&str]) -> Result<(), String> {
97 for key in self.table.keys() {
98 if !known.contains(&key.as_str()) {
99 return Err(format!("unknown key \"{key}\" in [{}]", self.name));
100 }
101 }
102 Ok(())
103 }
104
105 fn string(&self, key: &str) -> Result<Option<String>, String> {
106 match self.table.get(key) {
107 None => Ok(None),
108 Some(Value::String(s)) => Ok(Some(s.clone())),
109 Some(_) => Err(format!("\"{key}\" in [{}] must be a string", self.name)),
110 }
111 }
112
113 fn boolean(&self, key: &str) -> Result<Option<bool>, String> {
114 match self.table.get(key) {
115 None => Ok(None),
116 Some(Value::Boolean(b)) => Ok(Some(*b)),
117 Some(_) => Err(format!(
118 "\"{key}\" in [{}] must be true or false",
119 self.name
120 )),
121 }
122 }
123
124 fn strings(&self, key: &str) -> Result<Vec<String>, String> {
125 match self.table.get(key) {
126 None => Ok(Vec::new()),
127 Some(Value::Array(items)) => items
128 .iter()
129 .map(|item| match item {
130 Value::String(s) => Ok(s.clone()),
131 _ => Err(self.not_strings(key)),
132 })
133 .collect(),
134 Some(_) => Err(self.not_strings(key)),
135 }
136 }
137
138 fn not_strings(&self, key: &str) -> String {
139 format!("\"{key}\" in [{}] must be a list of strings", self.name)
140 }
141}
142
143fn parse(text: &[u8]) -> Result<Table, String> {
144 let text = std::str::from_utf8(text).map_err(|_| "the manifest is not UTF-8".to_owned())?;
145 text.parse::<Table>()
146 .map_err(|error| error.to_string().trim_end().to_owned())
147}
148
149fn section<'t>(top: &'t Table, name: &'static str) -> Result<Option<Section<'t>>, String> {
150 match top.get(name) {
151 None => Ok(None),
152 Some(Value::Table(table)) => Ok(Some(Section { table, name })),
153 Some(_) => Err(format!("\"{name}\" must be a table ([{name}])")),
154 }
155}
156
157fn module_refs(sec: &Section<'_>, libraries_first: bool) -> Result<Vec<ModuleRef>, String> {
161 let name = sec.name;
162 let library = |table: &Table, key: &str| -> Result<ModuleRef, String> {
163 let lib = Section {
164 table,
165 name: "a library",
166 };
167 lib.check_keys(&[key, "exclude", "include"])?;
168 let lib_name = lib
169 .string(key)?
170 .ok_or_else(|| format!("a library given as a table needs a \"{key}\""))?;
171 Ok(ModuleRef::Library {
172 name: lib_name,
173 exclude: lib.strings("exclude")?,
174 include: lib.strings("include")?,
175 })
176 };
177 if let Some(value) = sec.table.get("modules") {
178 if sec.table.contains_key("sources") || sec.table.contains_key("libraries") {
179 return Err(format!(
180 "[{name}] has \"modules\", so it cannot also have \"sources\" or \"libraries\""
181 ));
182 }
183 let bad = || {
184 format!(
185 "\"modules\" in [{name}] must be a list of sources, and of tables with a \"library\""
186 )
187 };
188 let Value::Array(items) = value else {
189 return Err(bad());
190 };
191 return items
192 .iter()
193 .map(|item| match item {
194 Value::String(source) => Ok(ModuleRef::Source(source.clone())),
195 Value::Table(table) => library(table, "library"),
196 _ => Err(bad()),
197 })
198 .collect();
199 }
200 let mut libraries = Vec::new();
201 match sec.table.get("libraries") {
202 None => {}
203 Some(Value::Array(items)) => {
204 for item in items {
205 libraries.push(match item {
206 Value::String(lib_name) => ModuleRef::Library {
207 name: lib_name.clone(),
208 exclude: Vec::new(),
209 include: Vec::new(),
210 },
211 Value::Table(table) => library(table, "name")?,
212 _ => return Err(bad_libraries(name)),
213 });
214 }
215 }
216 Some(_) => return Err(bad_libraries(name)),
217 }
218 let sources = sec.strings("sources")?.into_iter().map(ModuleRef::Source);
219 Ok(if libraries_first {
220 libraries.into_iter().chain(sources).collect()
221 } else {
222 sources.chain(libraries).collect()
223 })
224}
225
226fn check_sections(top: &Table, known: &[&str]) -> Result<(), String> {
227 for key in top.keys() {
228 if !known.contains(&key.as_str()) {
229 return Err(format!("unknown section [{key}]"));
230 }
231 }
232 Ok(())
233}
234
235pub(crate) struct GameArgs {
240 pub args: Vec<String>,
241 pub modules_at: usize,
242}
243
244fn push(args: &mut Vec<String>, items: &[&str]) {
245 args.extend(items.iter().map(|&s| s.to_owned()));
246}
247
248pub(crate) fn game_args(text: &[u8]) -> Result<GameArgs, String> {
249 let top = parse(text)?;
250 if top.contains_key("library") {
251 return Err("this is the manifest of a library, not of a game".to_owned());
252 }
253 check_sections(&top, &["game", "defines", "build"])?;
254 let game = section(&top, "game")?.ok_or("there is no [game] section")?;
255 game.check_keys(&[
256 "name",
257 "sources",
258 "libraries",
259 "modules",
260 "tests",
261 "image",
262 "resources",
263 "stylesheets",
264 ])?;
265 let mut args: Vec<String> = Vec::new();
266
267 if let Some(build) = section(&top, "build")? {
268 build.check_keys(&[
269 "preinit",
270 "debug",
271 "warnings",
272 "warnings-as-errors",
273 "verbose",
274 "charset",
275 "include-paths",
276 "library-paths",
277 "source-text-group",
278 "system",
279 ])?;
280 if build.boolean("system")? == Some(false) {
281 push(&mut args, &["--no-system"]);
282 }
283 if build.boolean("debug")? == Some(true) {
284 push(&mut args, &["-d"]);
285 }
286 match build.boolean("preinit")? {
287 Some(true) => push(&mut args, &["--preinit"]),
288 Some(false) => push(&mut args, &["--no-preinit"]),
289 None => {}
290 }
291 if build.boolean("warnings")? == Some(false) {
292 push(&mut args, &["--no-warnings"]);
293 }
294 if build.boolean("warnings-as-errors")? == Some(true) {
295 push(&mut args, &["--warnings-as-errors"]);
296 }
297 if build.boolean("verbose")? == Some(true) {
298 push(&mut args, &["-v"]);
299 }
300 if build.boolean("source-text-group")? == Some(true) {
301 push(&mut args, &["--source-text-groups"]);
302 }
303 if let Some(charset) = build.string("charset")? {
304 push(&mut args, &["--charset", &charset]);
305 }
306 for path in build.strings("include-paths")? {
307 push(&mut args, &["-I", &path]);
308 }
309 for path in build.strings("library-paths")? {
310 push(&mut args, &["--library-path", &path]);
311 }
312 }
313
314 if let Some(defines) = section(&top, "defines")? {
315 for (name, value) in defines.table {
316 match value {
317 Value::String(s) => push(&mut args, &["-D", &format!("{name}={s}")]),
318 Value::Integer(n) => push(&mut args, &["-D", &format!("{name}={n}")]),
319 Value::Boolean(true) => push(&mut args, &["-D", name]),
320 Value::Boolean(false) => push(&mut args, &["-U", name]),
321 _ => {
322 return Err(format!(
323 "\"{name}\" in [defines] must be a string, a number, or true or false"
324 ));
325 }
326 }
327 }
328 }
329
330 if let Some(image) = game.string("image")? {
331 push(&mut args, &["-o", &image]);
332 }
333 let _ = game.string("name")?;
334 let modules_at = args.len();
335
336 let modules = module_refs(&game, true)?;
339 if !modules
340 .iter()
341 .any(|module| matches!(module, ModuleRef::Source(_)))
342 {
343 return Err("[game] names no sources".to_owned());
344 }
345 for module in modules {
346 match module {
347 ModuleRef::Source(source) => push(&mut args, &["--source", &source]),
348 ModuleRef::Library {
349 name,
350 exclude,
351 include,
352 } => {
353 push(&mut args, &["--library", &name]);
354 for module in exclude {
355 push(&mut args, &["--exclude", &module]);
356 }
357 for module in include {
358 push(&mut args, &["--include", &module]);
359 }
360 }
361 }
362 }
363
364 for test in game.strings("tests")? {
367 push(&mut args, &["--test", &test]);
368 }
369
370 let mut resources = game.strings("resources")?;
373 resources.extend(game.strings("stylesheets")?);
374 if !resources.is_empty() {
375 push(&mut args, &["--resources"]);
376 for resource in resources {
377 push(&mut args, &[&resource]);
378 }
379 }
380 Ok(GameArgs { args, modules_at })
381}
382
383fn bad_libraries(section: &str) -> String {
384 format!("\"libraries\" in [{section}] must be a list of names, or of tables with a \"name\"")
385}
386
387pub(crate) fn library(text: &[u8]) -> Result<Library, String> {
389 let top = parse(text)?;
390 if top.contains_key("game") {
391 return Err("this is the manifest of a game, not of a library".to_owned());
392 }
393 check_sections(&top, &["library", "needs"])?;
394 let lib = section(&top, "library")?.ok_or("there is no [library] section")?;
395 lib.check_keys(&[
396 "name",
397 "sources",
398 "libraries",
399 "modules",
400 "resources",
401 "header",
402 "text-tags",
403 "object-tags",
404 "object-keys",
405 "ifid",
406 ])?;
407 let _ = lib.string("name")?;
408 let mut needs = Vec::new();
409 if let Some(section) = section(&top, "needs")? {
410 for key in section.table.keys() {
411 let why = section.string(key)?.unwrap_or_default();
412 needs.push((key.clone(), why));
413 }
414 }
415 let modules = module_refs(&lib, false)?;
418 if modules
419 .iter()
420 .any(|module| matches!(module, ModuleRef::Library { exclude, include, .. } if !exclude.is_empty() || !include.is_empty()))
421 {
422 return Err(
423 "a library cannot leave out or add to the sources of the libraries it names".to_owned(),
424 );
425 }
426 Ok(Library {
427 modules,
428 resources: lib.strings("resources")?,
429 needs,
430 header: lib.string("header")?,
431 text_tags: lib.strings("text-tags")?,
432 object_tags: lib.strings("object-tags")?,
433 object_keys: lib.strings("object-keys")?,
434 ifid: lib.string("ifid")?,
435 })
436}