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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//! The tags in a game's text: `<.p>`, `<.parser>`, `<.reveal key>`, and
//! the rest, which a library's output filters read as the text is shown
//! and which nothing shows. A misspelled one is dropped with nothing said,
//! so the build looks at the strings of a game's own sources and warns of
//! a tag no library and no source defines.
//!
//! What is defined: the tags a library's manifest lists (`text-tags`, for
//! those its filters handle), every `StyleTag` or `HtmlStyleTag` a source
//! makes (`roomnameStyleTag: HtmlStyleTag 'roomname'`, or `tagName =
//! 'roomname'`), and those a source adds to a filter (`customTags =
//! 'foo|bar'`). Tags are compared without regard to case, as the filters
//! compare them.
//!
//! The tags that name objects (`<.reveal pilotAwaited>`, `<.convnode
//! troublesNode>`: a library's manifest lists them, as `object-tags`)
//! are checked for the name: one that is no object's is an error. So is
//! a string where a library wants an object as a key (its manifest's
//! `object-keys`): `now.revealed('pilot-awaited')`, `openWhenRevealed =
//! 'x'`, a `ConvNode 'troubles'`.

use std::collections::HashSet;

use crate::pp::{Diagnostic, Severity};

/// A tag found in a string: its name, in lower case, its line, and its
/// argument as written (`<.reveal pilotAwaited>`), if it has one that is
/// all in the string, with no `<<...>>`.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct TagUse {
    pub(crate) name: String,
    pub(crate) line: u32,
    pub(crate) arg: Option<String>,
}

/// The tags written in a source's strings, outside its comments. The
/// strings inside a string's `<<...>>` are strings too.
pub(crate) fn tags_in_strings(text: &str) -> Vec<TagUse> {
    let bytes = text.as_bytes();
    let mut found = Vec::new();
    let mut line = 1u32;
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'\n' => {
                line += 1;
                i += 1;
            }
            b'/' if bytes.get(i + 1) == Some(&b'/') => {
                while i < bytes.len() && bytes[i] != b'\n' {
                    i += 1;
                }
            }
            b'/' if bytes.get(i + 1) == Some(&b'*') => {
                i += 2;
                while i < bytes.len() && !(bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/')) {
                    if bytes[i] == b'\n' {
                        line += 1;
                    }
                    i += 1;
                }
                i += 2;
            }
            quote @ (b'"' | b'\'') => {
                i = string(bytes, i, quote, &mut line, &mut found);
            }
            _ => i += 1,
        }
    }
    found
}

/// Read the string that starts at `start` with `quote`, noting its tags;
/// where it ends.
fn string(bytes: &[u8], start: usize, quote: u8, line: &mut u32, found: &mut Vec<TagUse>) -> usize {
    let triple = bytes.get(start + 1) == Some(&quote) && bytes.get(start + 2) == Some(&quote);
    let mut i = start + if triple { 3 } else { 1 };
    while i < bytes.len() {
        let c = bytes[i];
        if c == b'\\' {
            if bytes.get(i + 1) == Some(&b'\n') {
                *line += 1;
            }
            i += 2;
            continue;
        }
        if c == b'\n' {
            *line += 1;
        }
        if c == quote {
            if !triple {
                return i + 1;
            }
            if bytes.get(i + 1) == Some(&quote) && bytes.get(i + 2) == Some(&quote) {
                return i + 3;
            }
        }
        // An expression in the string, which can have strings of its own.
        if c == b'<' && bytes.get(i + 1) == Some(&b'<') {
            i += 2;
            while i < bytes.len() && !(bytes[i] == b'>' && bytes.get(i + 1) == Some(&b'>')) {
                match bytes[i] {
                    b'\n' => {
                        *line += 1;
                        i += 1;
                    }
                    q @ (b'"' | b'\'') => i = string(bytes, i, q, line, found),
                    _ => i += 1,
                }
            }
            i += 2;
            continue;
        }
        if c == b'<' && bytes.get(i + 1) == Some(&b'.') {
            let mut j = i + 2;
            if bytes.get(j) == Some(&b'/') {
                j += 1;
            }
            let name_start = j;
            while j < bytes.len() && bytes[j].is_ascii_alphanumeric() {
                j += 1;
            }
            if j > name_start && bytes[name_start].is_ascii_alphabetic() {
                found.push(TagUse {
                    name: String::from_utf8_lossy(&bytes[name_start..j]).to_ascii_lowercase(),
                    line: *line,
                    arg: argument(bytes, j, quote),
                });
            }
            i = j;
            continue;
        }
        i += 1;
    }
    i
}

/// A tag's argument, from where its name ends to its `>`: none if it has
/// none, or if it is not all in the string (it has a `<<...>>`, or the
/// string ends first).
fn argument(bytes: &[u8], from: usize, quote: u8) -> Option<String> {
    if !bytes.get(from).is_some_and(|c| *c == b' ' || *c == b'\t') {
        return None;
    }
    let mut k = from;
    while k < bytes.len() {
        match bytes[k] {
            b'>' => {
                let arg = String::from_utf8_lossy(&bytes[from..k]).trim().to_owned();
                return (!arg.is_empty()).then_some(arg);
            }
            b'<' if bytes.get(k + 1) == Some(&b'<') => return None,
            b'\n' | b'\\' => return None,
            c if c == quote => return None,
            _ => k += 1,
        }
    }
    None
}

/// The tags a source defines: its style tags, by their templates or their
/// `tagName`, and what it adds with `customTags`.
pub(crate) fn tags_defined(text: &str) -> Vec<String> {
    let mut out = Vec::new();
    let quoted_after = |rest: &str| -> Option<String> {
        let rest = rest.trim_start();
        let rest = rest.strip_prefix('\'')?;
        let end = rest.find('\'')?;
        Some(rest[..end].to_owned())
    };
    for line in text.lines() {
        let mut rest = line;
        while let Some(at) = rest.find("StyleTag") {
            let after = &rest[at + "StyleTag".len()..];
            if let Some(name) = quoted_after(after) {
                out.push(name.to_ascii_lowercase());
            }
            rest = after;
        }
        for key in ["tagName", "customTags"] {
            if let Some(at) = line.find(key) {
                let after = line[at + key.len()..].trim_start();
                if let Some(after) = after.strip_prefix('=')
                    && let Some(value) = quoted_after(after)
                {
                    out.extend(value.split('|').map(|n| n.trim().to_ascii_lowercase()));
                }
            }
        }
    }
    out
}

/// Whether two tag names are one slip apart: a letter added, dropped,
/// changed, or two swapped.
fn slip(a: &str, b: &str) -> bool {
    crate::names::is_slip(a.as_bytes(), b.as_bytes())
}

/// The warnings for a game's source: each tag in its strings that is not
/// one of `known`.
pub(crate) fn check(file: &str, text: &str, known: &HashSet<String>) -> Vec<Diagnostic> {
    let mut sorted: Vec<&String> = known.iter().collect();
    sorted.sort();
    let mut out: Vec<Diagnostic> = Vec::new();
    for tag in tags_in_strings(text) {
        if known.contains(&tag.name) {
            continue;
        }
        let note = match sorted.iter().find(|k| slip(&tag.name, k)) {
            Some(meant) => format!("did you mean \"<.{meant}>\"?"),
            None => "a tag is one the library defines, or a StyleTag a source makes".to_owned(),
        };
        let message = format!(
            "\"<.{}>\" is not a tag: nothing defines it, so it is dropped from the text",
            tag.name
        );
        if !out
            .iter()
            .any(|d| d.line == tag.line && d.message == message)
        {
            out.push(Diagnostic {
                file: file.to_owned(),
                line: tag.line,
                severity: Severity::Warning,
                message,
                note: Some(note),
                hexicon: true,
                ..Default::default()
            });
        }
    }
    out
}

/// A string written as a key, in a source's code: what it is the key of
/// (`revealed`, `openWhenRevealed`, `ConvNode`), the string, and its line.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct StringKey {
    pub(crate) of: String,
    pub(crate) key: String,
    pub(crate) line: u32,
}

/// The strings a source's code gives as keys: a string just after one of
/// `keys`, or after it and `(` or `=` (`now.revealed('x')`,
/// `openWhenRevealed = 'x'`, `ConvNode 'x'`). Comments are left, and
/// strings are not code.
pub(crate) fn string_keys(text: &str, keys: &[String]) -> Vec<StringKey> {
    let bytes = text.as_bytes();
    let mut found = Vec::new();
    let mut line = 1u32;
    let mut ignored = Vec::new();
    let ident = |c: u8| c.is_ascii_alphanumeric() || c == b'_';
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'\n' => {
                line += 1;
                i += 1;
            }
            b'/' if bytes.get(i + 1) == Some(&b'/') => {
                while i < bytes.len() && bytes[i] != b'\n' {
                    i += 1;
                }
            }
            b'/' if bytes.get(i + 1) == Some(&b'*') => {
                i += 2;
                while i < bytes.len() && !(bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/')) {
                    if bytes[i] == b'\n' {
                        line += 1;
                    }
                    i += 1;
                }
                i += 2;
            }
            quote @ (b'"' | b'\'') => {
                i = string(bytes, i, quote, &mut line, &mut ignored);
            }
            c if ident(c) && (i == 0 || !ident(bytes[i - 1])) => {
                let start = i;
                while i < bytes.len() && ident(bytes[i]) {
                    i += 1;
                }
                let word = &text[start..i];
                if !keys.iter().any(|k| k == word) {
                    continue;
                }
                let mut k = i;
                while k < bytes.len() && (bytes[k] == b' ' || bytes[k] == b'\t') {
                    k += 1;
                }
                if matches!(bytes.get(k), Some(b'(') | Some(b'=')) {
                    k += 1;
                    while k < bytes.len() && matches!(bytes[k], b' ' | b'\t' | b'=') {
                        k += 1;
                    }
                }
                if let Some(&q @ (b'\'' | b'"')) = bytes.get(k)
                    && let Some(len) = text[k + 1..].find(q as char)
                {
                    found.push(StringKey {
                        of: word.to_owned(),
                        key: text[k + 1..k + 1 + len].to_owned(),
                        line,
                    });
                }
            }
            _ => i += 1,
        }
    }
    found
}

/// The name a key written as a string would have as an object:
/// `new-enlightenment` and `blue door open` are `newEnlightenment` and
/// `blueDoorOpen`.
pub(crate) fn object_name(key: &str) -> String {
    let mut out = String::new();
    for word in key
        .split(|c: char| !c.is_ascii_alphanumeric())
        .filter(|w| !w.is_empty())
    {
        let mut chars = word.chars();
        let first = chars.next().expect("a word");
        if out.is_empty() {
            out.push(first.to_ascii_lowercase());
        } else {
            out.push(first.to_ascii_uppercase());
        }
        out.extend(chars);
    }
    if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) {
        out.insert_str(0, "key");
    }
    out
}

/// Whether a name could be an object's.
fn is_identifier(name: &str) -> bool {
    name.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_')
        && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}

/// What a node or key is declared as, to say in a message.
fn declaration(name: &str, node: bool) -> String {
    if node {
        format!("{name}: ConvNode")
    } else {
        format!("{name}: Fact")
    }
}

/// The errors for a game's source: each tag of `tag_names` whose argument
/// is no name of `objects`, and each string given as one of `keys`.
pub(crate) fn check_objects(
    file: &str,
    text: &str,
    tag_names: &HashSet<String>,
    keys: &[String],
    objects: &HashSet<&[u8]>,
) -> Vec<Diagnostic> {
    let error = |line: u32, message: String, note: String| Diagnostic {
        file: file.to_owned(),
        line,
        severity: Severity::Error,
        message,
        note: Some(note),
        hexicon: true,
        ..Default::default()
    };
    let mut sorted: Vec<&[u8]> = objects.iter().copied().collect();
    sorted.sort_unstable();
    let mut out: Vec<Diagnostic> = Vec::new();
    for tag in tags_in_strings(text) {
        let Some(arg) = &tag.arg else { continue };
        if !tag_names.contains(&tag.name) {
            continue;
        }
        let name = arg.split('=').next().unwrap_or("").trim();
        if name.is_empty() || objects.contains(name.as_bytes()) {
            continue;
        }
        let node = tag.name.starts_with("convnode");
        let note = if let Some(meant) = sorted
            .iter()
            .find(|o| crate::names::is_slip(name.as_bytes(), o))
        {
            format!("did you mean \"{}\"?", String::from_utf8_lossy(meant))
        } else if is_identifier(name) {
            format!(
                "a <.{}> tag names an object: declare it once ({}), or name a thing or a topic",
                tag.name,
                declaration(name, node)
            )
        } else {
            let named = object_name(name) + if node { "Node" } else { "" };
            format!(
                "a <.{}> tag names an object, not a string: declare it once ({}) and write <.{} {}>",
                tag.name,
                declaration(&named, node),
                tag.name,
                named
            )
        };
        let message = format!("\"{name}\" in <.{} {arg}> is no object's name", tag.name);
        if !out
            .iter()
            .any(|d| d.line == tag.line && d.message == message)
        {
            out.push(error(tag.line, message, note));
        }
    }
    for key in string_keys(text, keys) {
        let node = key.of == "ConvNode";
        let named = object_name(&key.key) + if node { "Node" } else { "" };
        let (message, note) = if node {
            (
                format!(
                    "a conversation node is named as an object, not by the string '{}'",
                    key.key
                ),
                format!(
                    "write {} (and <.convnode {named}>)",
                    declaration(&named, true)
                ),
            )
        } else {
            (
                format!("the key '{}' is a string, and a key is an object", key.key),
                format!(
                    "declare it once ({}), or name a thing or a topic, and write {} here",
                    declaration(&named, false),
                    named
                ),
            )
        };
        out.push(error(key.line, message, note));
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_tags_in_strings_and_not_in_comments() {
        let text = "// <.notme>\n\
                    a = \"one<.p>two\";\n\
                    /* <.notme> */ b = 'x<./parser>';\n\
                    c = '<<x ? 'on<.inner>' : 'off'>> <.after>';\n";
        let names: Vec<(String, u32)> = tags_in_strings(text)
            .into_iter()
            .map(|t| (t.name, t.line))
            .collect();
        assert_eq!(
            names,
            [
                ("p".to_owned(), 2),
                ("parser".to_owned(), 3),
                ("inner".to_owned(), 4),
                ("after".to_owned(), 4),
            ]
        );
    }

    #[test]
    fn the_tags_a_source_defines() {
        let text = "roomnameStyleTag: HtmlStyleTag 'roomname';\n\
                    tipStyleTag: StyleTag 'Tip' '' '';\n\
                    myTag: StyleTag\n    tagName = 'mine'\n;\n\
                    modify conversationManager customTags = 'foo|bar';\n";
        assert_eq!(
            tags_defined(text),
            ["roomname", "tip", "mine", "foo", "bar"]
        );
    }

    #[test]
    fn hexad_writes_only_the_tags_it_defines() {
        // Hexad's own text, held to what a game's is: every tag in it is
        // one its manifest lists or one of its style tags.
        let manifest = crate::builtin::FILES
            .iter()
            .find(|(path, _)| *path == "hexad/hexicon.toml")
            .expect("Hexad's manifest");
        let library = crate::manifest::library(manifest.1).expect("a library");
        let sources: Vec<(&str, String)> = crate::builtin::FILES
            .iter()
            .filter(|(path, _)| {
                path.starts_with("hexad/") && (path.ends_with(".hxn") || path.ends_with(".hxh"))
            })
            .map(|(path, bytes)| (*path, String::from_utf8_lossy(bytes).into_owned()))
            .collect();
        let mut known: HashSet<String> = library.text_tags.iter().cloned().collect();
        for (_, text) in &sources {
            known.extend(tags_defined(text));
        }
        let mut problems = Vec::new();
        for (path, text) in &sources {
            for warning in check(path, text, &known) {
                problems.push(format!("{}:{}: {}", path, warning.line, warning.message));
            }
        }
        assert!(problems.is_empty(), "{problems:#?}");
    }

    #[test]
    fn a_misspelled_tag_is_said_with_what_was_meant() {
        let known: HashSet<String> = ["p", "reveal"].iter().map(|s| s.to_string()).collect();
        let warnings = check("start.hxn", "x = 'a<.reveel key> b<.P> c<.zzz>';\n", &known);
        let said: Vec<(&str, Option<&str>)> = warnings
            .iter()
            .map(|d| (d.message.as_str(), d.note.as_deref()))
            .collect();
        assert_eq!(
            said,
            [
                (
                    "\"<.reveel>\" is not a tag: nothing defines it, so it is dropped from the text",
                    Some("did you mean \"<.reveal>\"?")
                ),
                (
                    "\"<.zzz>\" is not a tag: nothing defines it, so it is dropped from the text",
                    Some("a tag is one the library defines, or a StyleTag a source makes")
                ),
            ]
        );
    }

    #[test]
    fn a_tag_names_an_object_or_is_an_error() {
        let tags: HashSet<String> = ["reveal", "convnode"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let objects: HashSet<&[u8]> = [b"pilotAwaited".as_slice(), b"troublesNode".as_slice()]
            .into_iter()
            .collect();
        let text = "a = '<.reveal pilotAwaited><.reveal pilotAwaitd><.convnode troubles>';\n\
                    b = '<.reveal new-enlightenment> <.reveal <<k>>> <.reveal mood=angry>';\n";
        let said: Vec<(u32, String, String)> =
            check_objects("start.hxn", text, &tags, &[], &objects)
                .into_iter()
                .map(|d| (d.line, d.message, d.note.unwrap_or_default()))
                .collect();
        assert_eq!(
            said,
            [
                (
                    1,
                    "\"pilotAwaitd\" in <.reveal pilotAwaitd> is no object's name".to_owned(),
                    "did you mean \"pilotAwaited\"?".to_owned()
                ),
                (
                    1,
                    "\"troubles\" in <.convnode troubles> is no object's name".to_owned(),
                    "a <.convnode> tag names an object: declare it once (troubles: ConvNode), \
                     or name a thing or a topic"
                        .to_owned()
                ),
                (
                    2,
                    "\"new-enlightenment\" in <.reveal new-enlightenment> is no object's name"
                        .to_owned(),
                    "a <.reveal> tag names an object, not a string: declare it once \
                     (newEnlightenment: Fact) and write <.reveal newEnlightenment>"
                        .to_owned()
                ),
                (
                    2,
                    "\"mood\" in <.reveal mood=angry> is no object's name".to_owned(),
                    "a <.reveal> tag names an object: declare it once (mood: Fact), \
                     or name a thing or a topic"
                        .to_owned()
                ),
            ]
        );
    }

    #[test]
    fn a_string_where_a_key_is_an_object_is_an_error() {
        let keys: Vec<String> = ["revealed", "openWhenRevealed", "ConvNode"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let text = "// now.revealed('in-a-comment')\n\
                    isActive = now.revealed('pilot-awaited') && now.revealed(island)\n\
                    openWhenRevealed = 'blue door open'\n\
                    + ConvNode 'troubles';\n\
                    x = 'now.revealed(\\'in-a-string\\')';\n";
        let found: Vec<(String, String, u32)> = string_keys(text, &keys)
            .into_iter()
            .map(|k| (k.of, k.key, k.line))
            .collect();
        assert_eq!(
            found,
            [
                ("revealed".to_owned(), "pilot-awaited".to_owned(), 2),
                (
                    "openWhenRevealed".to_owned(),
                    "blue door open".to_owned(),
                    3
                ),
                ("ConvNode".to_owned(), "troubles".to_owned(), 4),
            ]
        );
        assert_eq!(object_name("blue door open"), "blueDoorOpen");
        assert_eq!(object_name("DeskTried"), "deskTried");
        assert_eq!(object_name("2nd-try"), "key2ndTry");
    }

    #[test]
    fn hexad_writes_no_key_as_a_string() {
        let manifest = crate::builtin::FILES
            .iter()
            .find(|(path, _)| *path == "hexad/hexicon.toml")
            .expect("Hexad's manifest");
        let library = crate::manifest::library(manifest.1).expect("a library");
        assert!(!library.object_keys.is_empty());
        let mut problems = Vec::new();
        for (path, bytes) in crate::builtin::FILES {
            if path.starts_with("hexad/") && (path.ends_with(".hxn") || path.ends_with(".hxh")) {
                let text = String::from_utf8_lossy(bytes);
                for key in string_keys(&text, &library.object_keys) {
                    problems.push(format!("{path}:{}: {} '{}'", key.line, key.of, key.key));
                }
            }
        }
        assert!(problems.is_empty(), "{problems:#?}");
    }
}