hexicon-compiler 0.2.0

The Hexicon compiler: source text to a program image
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Hexicon's manifest, `hexicon.toml`: what a game is built from, or
//! what a library is made of.
//!
//! A game's manifest is read by turning it into the options the command
//! line takes ([`crate::project`]); a library's says what the library
//! library says. A name the manifest does not know is an error, so that
//! a misspelling is not silently ignored.
//!
//! ```toml
//! [game]
//! sources = ["start.hxn", "plane.hxn"]
//! libraries = ["system", { name = "hexad", include = ["extensions/fueled"] }]
//! tests = ["scenarios"]
//!
//! [defines]
//! LANGUAGE = "english"
//! ```

use toml::{Table, Value};

/// The name a manifest has.
pub const MANIFEST: &str = "hexicon.toml";

/// Whether `path` names a manifest.
pub(crate) fn is_manifest(path: &str) -> bool {
    path.len() >= 5 && path[path.len() - 5..].eq_ignore_ascii_case(".toml")
}

/// The file a manifest's source names: one named with no extension is
/// a Hexicon source.
pub(crate) fn source_name(name: &str) -> String {
    let file = name.rsplit(['/', '\\']).next().unwrap_or(name);
    if file.contains('.') {
        name.to_owned()
    } else {
        format!("{name}.hxn")
    }
}

/// A part of a build: a source file, or a library, with the sources of
/// it to leave out and the ones from its folder to add.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ModuleRef {
    /// A source file.
    Source(String),
    /// A library: a folder with a manifest, a `.toml` manifest, or a
    /// manifest of its name with `.toml` after it.
    Library {
        /// Its name.
        name: String,
        /// Its sources to leave out, by their names in it.
        exclude: Vec<String>,
        /// Sources in its folder to build after it, such as its optional
        /// extensions (`extensions/fueled`), by their paths in it.
        include: Vec<String>,
    },
}

/// What a library's manifest says.
#[derive(Debug, Default)]
pub(crate) struct Library {
    /// Its sources and the libraries it is built on, relative to its
    /// folder, in order.
    pub modules: Vec<ModuleRef>,
    /// Files and folders to bundle as resources.
    pub resources: Vec<String>,
    /// Macros a game has to define, and why.
    pub needs: Vec<(String, String)>,
    /// The header a Hexicon source gets by importing the library
    /// (`import hexad;`), relative to the library's folder.
    pub header: Option<String>,
    /// The tags its output filters read in a game's text (`<.p>`,
    /// `<.reveal>`), besides the style tags its sources make.
    pub text_tags: Vec<String>,
    /// The tags whose argument is the name of an object of the program
    /// (`<.reveal pilotAwaited>`, `<.convnode troublesNode>`): the build
    /// checks the name.
    pub object_tags: Vec<String>,
    /// The functions, methods and properties whose key is an object,
    /// where a string is wrong (`now.revealed('pilot-awaited')`,
    /// `openWhenRevealed = 'x'`), and the classes an object of which is
    /// not named by a string (`ConvNode 'troubles'`).
    pub object_keys: Vec<String>,
    /// The property a game gives its IFID in (`IFID`): the build warns of
    /// a game that gives none, or one that is not an IFID.
    pub ifid: Option<String>,
}

/// A table of the manifest, and its name for messages.
struct Section<'t> {
    table: &'t Table,
    name: &'static str,
}

impl Section<'_> {
    fn check_keys(&self, known: &[&str]) -> Result<(), String> {
        for key in self.table.keys() {
            if !known.contains(&key.as_str()) {
                return Err(format!("unknown key \"{key}\" in [{}]", self.name));
            }
        }
        Ok(())
    }

    fn string(&self, key: &str) -> Result<Option<String>, String> {
        match self.table.get(key) {
            None => Ok(None),
            Some(Value::String(s)) => Ok(Some(s.clone())),
            Some(_) => Err(format!("\"{key}\" in [{}] must be a string", self.name)),
        }
    }

    fn boolean(&self, key: &str) -> Result<Option<bool>, String> {
        match self.table.get(key) {
            None => Ok(None),
            Some(Value::Boolean(b)) => Ok(Some(*b)),
            Some(_) => Err(format!(
                "\"{key}\" in [{}] must be true or false",
                self.name
            )),
        }
    }

    fn strings(&self, key: &str) -> Result<Vec<String>, String> {
        match self.table.get(key) {
            None => Ok(Vec::new()),
            Some(Value::Array(items)) => items
                .iter()
                .map(|item| match item {
                    Value::String(s) => Ok(s.clone()),
                    _ => Err(self.not_strings(key)),
                })
                .collect(),
            Some(_) => Err(self.not_strings(key)),
        }
    }

    fn not_strings(&self, key: &str) -> String {
        format!("\"{key}\" in [{}] must be a list of strings", self.name)
    }
}

fn parse(text: &[u8]) -> Result<Table, String> {
    let text = std::str::from_utf8(text).map_err(|_| "the manifest is not UTF-8".to_owned())?;
    text.parse::<Table>()
        .map_err(|error| error.to_string().trim_end().to_owned())
}

fn section<'t>(top: &'t Table, name: &'static str) -> Result<Option<Section<'t>>, String> {
    match top.get(name) {
        None => Ok(None),
        Some(Value::Table(table)) => Ok(Some(Section { table, name })),
        Some(_) => Err(format!("\"{name}\" must be a table ([{name}])")),
    }
}

/// The sources and libraries `sec` names, in order: as a `modules` list,
/// in which a source is a string and a library a table, or as lists of
/// `sources` and `libraries`, the libraries first if `libraries_first`.
fn module_refs(sec: &Section<'_>, libraries_first: bool) -> Result<Vec<ModuleRef>, String> {
    let name = sec.name;
    let library = |table: &Table, key: &str| -> Result<ModuleRef, String> {
        let lib = Section {
            table,
            name: "a library",
        };
        lib.check_keys(&[key, "exclude", "include"])?;
        let lib_name = lib
            .string(key)?
            .ok_or_else(|| format!("a library given as a table needs a \"{key}\""))?;
        Ok(ModuleRef::Library {
            name: lib_name,
            exclude: lib.strings("exclude")?,
            include: lib.strings("include")?,
        })
    };
    if let Some(value) = sec.table.get("modules") {
        if sec.table.contains_key("sources") || sec.table.contains_key("libraries") {
            return Err(format!(
                "[{name}] has \"modules\", so it cannot also have \"sources\" or \"libraries\""
            ));
        }
        let bad = || {
            format!(
                "\"modules\" in [{name}] must be a list of sources, and of tables with a \"library\""
            )
        };
        let Value::Array(items) = value else {
            return Err(bad());
        };
        return items
            .iter()
            .map(|item| match item {
                Value::String(source) => Ok(ModuleRef::Source(source.clone())),
                Value::Table(table) => library(table, "library"),
                _ => Err(bad()),
            })
            .collect();
    }
    let mut libraries = Vec::new();
    match sec.table.get("libraries") {
        None => {}
        Some(Value::Array(items)) => {
            for item in items {
                libraries.push(match item {
                    Value::String(lib_name) => ModuleRef::Library {
                        name: lib_name.clone(),
                        exclude: Vec::new(),
                        include: Vec::new(),
                    },
                    Value::Table(table) => library(table, "name")?,
                    _ => return Err(bad_libraries(name)),
                });
            }
        }
        Some(_) => return Err(bad_libraries(name)),
    }
    let sources = sec.strings("sources")?.into_iter().map(ModuleRef::Source);
    Ok(if libraries_first {
        libraries.into_iter().chain(sources).collect()
    } else {
        sources.chain(libraries).collect()
    })
}

fn check_sections(top: &Table, known: &[&str]) -> Result<(), String> {
    for key in top.keys() {
        if !known.contains(&key.as_str()) {
            return Err(format!("unknown section [{key}]"));
        }
    }
    Ok(())
}

/// The options a game's manifest stands for, as the command line takes
/// them.
pub(crate) fn game_args(text: &[u8]) -> Result<Vec<String>, String> {
    let top = parse(text)?;
    if top.contains_key("library") {
        return Err("this is the manifest of a library, not of a game".to_owned());
    }
    check_sections(&top, &["game", "defines", "build"])?;
    let game = section(&top, "game")?.ok_or("there is no [game] section")?;
    game.check_keys(&[
        "name",
        "sources",
        "libraries",
        "modules",
        "tests",
        "image",
        "resources",
        "stylesheets",
    ])?;
    let mut args: Vec<String> = Vec::new();
    let mut push = |items: &[&str]| args.extend(items.iter().map(|&s| s.to_owned()));

    if let Some(build) = section(&top, "build")? {
        build.check_keys(&[
            "preinit",
            "debug",
            "warnings",
            "warnings-as-errors",
            "verbose",
            "charset",
            "include-paths",
            "library-paths",
            "source-text-group",
            "system",
        ])?;
        if build.boolean("system")? == Some(false) {
            push(&["--no-system"]);
        }
        if build.boolean("debug")? == Some(true) {
            push(&["-d"]);
        }
        match build.boolean("preinit")? {
            Some(true) => push(&["--preinit"]),
            Some(false) => push(&["--no-preinit"]),
            None => {}
        }
        if build.boolean("warnings")? == Some(false) {
            push(&["--no-warnings"]);
        }
        if build.boolean("warnings-as-errors")? == Some(true) {
            push(&["--warnings-as-errors"]);
        }
        if build.boolean("verbose")? == Some(true) {
            push(&["-v"]);
        }
        if build.boolean("source-text-group")? == Some(true) {
            push(&["--source-text-groups"]);
        }
        if let Some(charset) = build.string("charset")? {
            push(&["--charset", &charset]);
        }
        for path in build.strings("include-paths")? {
            push(&["-I", &path]);
        }
        for path in build.strings("library-paths")? {
            push(&["--library-path", &path]);
        }
    }

    if let Some(defines) = section(&top, "defines")? {
        for (name, value) in defines.table {
            match value {
                Value::String(s) => push(&["-D", &format!("{name}={s}")]),
                Value::Integer(n) => push(&["-D", &format!("{name}={n}")]),
                Value::Boolean(true) => push(&["-D", name]),
                Value::Boolean(false) => push(&["-U", name]),
                _ => {
                    return Err(format!(
                        "\"{name}\" in [defines] must be a string, a number, or true or false"
                    ));
                }
            }
        }
    }

    if let Some(image) = game.string("image")? {
        push(&["-o", &image]);
    }
    let _ = game.string("name")?;

    // The libraries, then the sources, as a project file has them,
    // unless a list of modules gives the order.
    let modules = module_refs(&game, true)?;
    if !modules
        .iter()
        .any(|module| matches!(module, ModuleRef::Source(_)))
    {
        return Err("[game] names no sources".to_owned());
    }
    for module in modules {
        match module {
            ModuleRef::Source(source) => push(&["--source", &source]),
            ModuleRef::Library {
                name,
                exclude,
                include,
            } => {
                push(&["--library", &name]);
                for module in exclude {
                    push(&["--exclude", &module]);
                }
                for module in include {
                    push(&["--include", &module]);
                }
            }
        }
    }

    // Its tests, such as its scenarios, after everything else: sources
    // that a build for debugging takes in and one for release leaves out.
    for test in game.strings("tests")? {
        push(&["--test", &test]);
    }

    // A game's style sheets are resources too: a rich display applies
    // every resource whose name ends in ".css", in order.
    let mut resources = game.strings("resources")?;
    resources.extend(game.strings("stylesheets")?);
    if !resources.is_empty() {
        push(&["--resources"]);
        for resource in resources {
            push(&[&resource]);
        }
    }
    Ok(args)
}

fn bad_libraries(section: &str) -> String {
    format!("\"libraries\" in [{section}] must be a list of names, or of tables with a \"name\"")
}

/// What a library's manifest says.
pub(crate) fn library(text: &[u8]) -> Result<Library, String> {
    let top = parse(text)?;
    if top.contains_key("game") {
        return Err("this is the manifest of a game, not of a library".to_owned());
    }
    check_sections(&top, &["library", "needs"])?;
    let lib = section(&top, "library")?.ok_or("there is no [library] section")?;
    lib.check_keys(&[
        "name",
        "sources",
        "libraries",
        "modules",
        "resources",
        "header",
        "text-tags",
        "object-tags",
        "object-keys",
        "ifid",
    ])?;
    let _ = lib.string("name")?;
    let mut needs = Vec::new();
    if let Some(section) = section(&top, "needs")? {
        for key in section.table.keys() {
            let why = section.string(key)?.unwrap_or_default();
            needs.push((key.clone(), why));
        }
    }
    // A library's own sources come before the libraries it names, unless
    // a list of modules gives the order.
    let modules = module_refs(&lib, false)?;
    if modules
        .iter()
        .any(|module| matches!(module, ModuleRef::Library { exclude, include, .. } if !exclude.is_empty() || !include.is_empty()))
    {
        return Err(
            "a library cannot leave out or add to the sources of the libraries it names".to_owned(),
        );
    }
    Ok(Library {
        modules,
        resources: lib.strings("resources")?,
        needs,
        header: lib.string("header")?,
        text_tags: lib.strings("text-tags")?,
        object_tags: lib.strings("object-tags")?,
        object_keys: lib.strings("object-keys")?,
        ifid: lib.string("ifid")?,
    })
}