Skip to main content

hexicon_compiler/
manifest.rs

1//! Hexicon's manifest, `hexicon.toml`: what a game is built from, or
2//! what a library is made of.
3//!
4//! A game's manifest is read by turning it into the options the command
5//! line takes ([`crate::project`]); a library's says what the library
6//! library says. A name the manifest does not know is an error, so that
7//! a misspelling is not silently ignored.
8//!
9//! ```toml
10//! [game]
11//! sources = ["start.hxn", "plane.hxn"]
12//! libraries = ["system", { name = "hexad", include = ["extensions/fueled"] }]
13//! tests = ["scenarios"]
14//!
15//! [defines]
16//! LANGUAGE = "english"
17//! ```
18
19use toml::{Table, Value};
20
21/// The name a manifest has.
22pub const MANIFEST: &str = "hexicon.toml";
23
24/// Whether `path` names a manifest.
25pub(crate) fn is_manifest(path: &str) -> bool {
26    path.len() >= 5 && path[path.len() - 5..].eq_ignore_ascii_case(".toml")
27}
28
29/// The file a manifest's source names: one named with no extension is
30/// a Hexicon source.
31pub(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/// A part of a build: a source file, or a library, with the sources of
41/// it to leave out and the ones from its folder to add.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub(crate) enum ModuleRef {
44    /// A source file.
45    Source(String),
46    /// A library: a folder with a manifest, a `.toml` manifest, or a
47    /// manifest of its name with `.toml` after it.
48    Library {
49        /// Its name.
50        name: String,
51        /// Its sources to leave out, by their names in it.
52        exclude: Vec<String>,
53        /// Sources in its folder to build after it, such as its optional
54        /// extensions (`extensions/fueled`), by their paths in it.
55        include: Vec<String>,
56    },
57}
58
59/// What a library's manifest says.
60#[derive(Debug, Default)]
61pub(crate) struct Library {
62    /// Its sources and the libraries it is built on, relative to its
63    /// folder, in order.
64    pub modules: Vec<ModuleRef>,
65    /// Files and folders to bundle as resources.
66    pub resources: Vec<String>,
67    /// Macros a game has to define, and why.
68    pub needs: Vec<(String, String)>,
69    /// The header a Hexicon source gets by importing the library
70    /// (`import hexad;`), relative to the library's folder.
71    pub header: Option<String>,
72    /// The tags its output filters read in a game's text (`<.p>`,
73    /// `<.reveal>`), besides the style tags its sources make.
74    pub text_tags: Vec<String>,
75    /// The tags whose argument is the name of an object of the program
76    /// (`<.reveal pilotAwaited>`, `<.convnode troublesNode>`): the build
77    /// checks the name.
78    pub object_tags: Vec<String>,
79    /// The functions, methods and properties whose key is an object,
80    /// where a string is wrong (`now.revealed('pilot-awaited')`,
81    /// `openWhenRevealed = 'x'`), and the classes an object of which is
82    /// not named by a string (`ConvNode 'troubles'`).
83    pub object_keys: Vec<String>,
84    /// The property a game gives its IFID in (`IFID`): the build warns of
85    /// a game that gives none, or one that is not an IFID.
86    pub ifid: Option<String>,
87}
88
89/// A table of the manifest, and its name for messages.
90struct 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
157/// The sources and libraries `sec` names, in order: as a `modules` list,
158/// in which a source is a string and a library a table, or as lists of
159/// `sources` and `libraries`, the libraries first if `libraries_first`.
160fn 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
235/// The options a game's manifest stands for, as the command line takes
236/// them.
237/// The options a game's manifest stands for, as the command line takes
238/// them: first its options, then, from `modules_at` on, its modules.
239pub(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    // The libraries, then the sources, as a project file has them,
337    // unless a list of modules gives the order.
338    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    // Its tests, such as its scenarios, after everything else: sources
365    // that a build for debugging takes in and one for release leaves out.
366    for test in game.strings("tests")? {
367        push(&mut args, &["--test", &test]);
368    }
369
370    // A game's style sheets are resources too: a rich display applies
371    // every resource whose name ends in ".css", in order.
372    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
387/// What a library's manifest says.
388pub(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    // A library's own sources come before the libraries it names, unless
416    // a list of modules gives the order.
417    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}