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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
//! Compiling a program: source files in, an image out.

use crate::emit;
use crate::image;
use crate::link::{self, Linked, Module};
use crate::parse::{Exports, Global, Parser, Program, merge_exports};
use crate::pp::{Diagnostic, LinkMacro, Preprocessor, Severity, SourceFiles};

/// What to compile, and how.
#[derive(Debug, Clone)]
pub struct CompileOptions {
    /// Directories to look in for included files.
    pub include_paths: Vec<String>,
    /// Macros to define before the source is read: name and expansion.
    pub defines: Vec<(String, String)>,
    /// Macros to remove before the source is read.
    pub undefines: Vec<String>,
    /// The character set of source files that do not say what they are
    /// in. Without one, they are taken to be UTF-8.
    pub default_charset: Option<String>,
    /// When the program is compiled, as the 24 characters the image
    /// records (`Thu Nov 19 09:24:12 2026`). The compiler has no clock
    /// of its own.
    pub timestamp: [u8; 24],
    /// Objects say which source file they are in from the start of each
    /// file (`--source-text-groups`), as `#pragma sourceTextGroup(on)` makes them.
    pub source_text_group: bool,
    /// For each source, the name its source text group gives it and
    /// its place among the modules of the build, from 1. Without them,
    /// a source is named as it is given, and numbered by its place in
    /// the list.
    pub module_names: Vec<(String, usize)>,
    /// For each source, whether a library brought it in. A game's own
    /// Hexicon sources are checked for properties given values that
    /// nothing reads (see [`crate::names`]); a library's are not.
    /// Without them, no source is a library's.
    pub from_library: Vec<bool>,
    /// The libraries a Hexicon source can import (`import hexad;`): each
    /// by name, with its header, or none if it names none.
    pub imports: Vec<(String, Option<String>)>,
    /// The tags the libraries' output filters read in a game's text, as
    /// their manifests list them: with any, a tag in a game's own source
    /// that nothing defines is warned of (see [`crate::tags`]).
    pub text_tags: Vec<String>,
    /// The tags whose argument names an object, as the libraries'
    /// manifests list them: a name in such a tag that is no object's is
    /// an error in a game's own source (see [`crate::tags`]).
    pub object_tags: Vec<String>,
    /// Where a key is an object, as the libraries' manifests list them:
    /// a string there is an error in a game's own source.
    pub object_keys: Vec<String>,
    /// The property a game gives its IFID in, as a library's manifest
    /// names it: with one, a game whose own sources give no IFID there,
    /// or one that is not an IFID, is warned of (see [`crate::ifid`]).
    pub ifid: Option<String>,
    /// Compile for debugging (`-d`): `__DEBUG` is defined, and the image
    /// has what a debugger needs: the global symbols, the macros, and
    /// the address of each line's code.
    pub debug: bool,
    /// The image says where in the source each statement's code came
    /// from, so that a run-time error can say where it happened. On by
    /// default, and always when compiling for debugging; off only where
    /// the code alone matters, as in tests that two sources compile to
    /// the same image.
    pub line_records: bool,
}

impl Default for CompileOptions {
    fn default() -> Self {
        Self {
            include_paths: Vec::new(),
            defines: Vec::new(),
            undefines: Vec::new(),
            default_charset: None,
            timestamp: *b"Thu Jan  1 00:00:00 1970",
            source_text_group: false,
            module_names: Vec::new(),
            from_library: Vec::new(),
            imports: Vec::new(),
            text_tags: Vec::new(),
            object_tags: Vec::new(),
            object_keys: Vec::new(),
            ifid: None,
            debug: false,
            line_records: true,
        }
    }
}

/// What came of compiling.
#[derive(Debug, Clone, Default)]
pub struct Compiled {
    /// The image, unless there were errors.
    pub image: Option<Vec<u8>>,
    /// Stretches of the image, as offset and length, whose contents mean
    /// nothing to a program: the time it was compiled, bytes that are
    /// the compiler's own, and fields that are written but never read.
    /// Two images of the same program can differ there.
    pub unspecified: Vec<(usize, usize)>,
    /// The problems found.
    pub diagnostics: Vec<Diagnostic>,
    /// The program's global symbols, each with its value in the image,
    /// in the order of the reference's table of them when the program
    /// is put together: what `globalSymbols()` gives a program run before
    /// its image is written.
    pub symbols: Vec<RuntimeSymbol>,
    /// The program's macros, likewise: what
    /// `globalSymbols(MacroTable)` gives it.
    pub macros: Vec<LinkMacro>,
}

/// A global symbol, and its value in the image.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuntimeSymbol {
    /// The name.
    pub name: Vec<u8>,
    /// What the name means.
    pub value: RuntimeValue,
}

/// What a global symbol means.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuntimeValue {
    /// A function: its address in the code.
    Function(u32),
    /// An object.
    Object(u32),
    /// A property.
    Property(u16),
    /// A value of an enumeration.
    Enum(u32),
    /// A built-in function: its set, and its place in the set.
    BuiltIn {
        /// The set's number.
        set: u16,
        /// The function's place in it.
        index: u16,
    },
    /// A built-in class: the object that stands for it.
    Class(u32),
}

/// The macros the compiler defines before any source is read: what is
/// compiling, and when. The date is `Nov 19 2026` and the time
/// `09:24:12`, as strings. A source is told it is Hexicon's
/// (`__HEXICON`, and Hexicon's version). Then those the options define.
fn predefined_macros(options: &CompileOptions) -> Vec<(String, String)> {
    let stamp = String::from_utf8_lossy(&options.timestamp);
    let part = |range: std::ops::Range<usize>| stamp.get(range).unwrap_or("").to_owned();
    let mut macros = vec![
        (
            "__DATE__".to_owned(),
            format!("'{} {} {}'", part(4..7), part(8..10), part(20..24)),
        ),
        ("__TIME__".to_owned(), format!("'{}'", part(11..19))),
    ];
    if options.debug {
        macros.push(("__DEBUG".to_owned(), "1".to_owned()));
    }
    macros.extend([
        ("__HEXICON".to_owned(), "1".to_owned()),
        (
            "__HEXICON_VERSION_MAJOR".to_owned(),
            env!("CARGO_PKG_VERSION_MAJOR").to_owned(),
        ),
        (
            "__HEXICON_VERSION_MINOR".to_owned(),
            env!("CARGO_PKG_VERSION_MINOR").to_owned(),
        ),
    ]);
    macros.extend(options.defines.iter().cloned());
    macros
}

/// The table of macros the reference has when it puts the program
/// together, and the names it undefined on the way.
struct MacroTable {
    /// The macros, each with whether it is one the preprocessor works
    /// out as it goes, which are `__LINE__` and `__FILE__`.
    macros: Vec<(LinkMacro, bool)>,
    undefined: std::collections::HashSet<Vec<u8>>,
}

/// The macros as the `MACR` block has them, for the debugger: those
/// that mean the same throughout, which are those never undefined, but
/// for `__LINE__` and `__FILE__`. Each is its name, its flags, its
/// parameters, and its expansion. Also where in it the date and time of
/// the compilation are, which mean nothing to a comparison of images.
fn debug_macros(table: &MacroTable) -> (Vec<u8>, Vec<(usize, usize)>) {
    let mut count = 0u32;
    let mut out = Vec::new();
    let mut clock = Vec::new();
    for (mac, pseudo) in &table.macros {
        if *pseudo || table.undefined.contains(&mac.name) {
            continue;
        }
        count += 1;
        out.extend_from_slice(&(mac.name.len() as u16).to_le_bytes());
        out.extend_from_slice(&mac.name);
        let flags = u16::from(mac.has_args) | u16::from(mac.has_varargs) << 1;
        out.extend_from_slice(&flags.to_le_bytes());
        out.extend_from_slice(&(mac.params.len() as u16).to_le_bytes());
        for param in &mac.params {
            out.extend_from_slice(&(param.len() as u16).to_le_bytes());
            out.extend_from_slice(param);
        }
        out.extend_from_slice(&(mac.expansion.len() as u32).to_le_bytes());
        if matches!(mac.name.as_slice(), b"__DATE__" | b"__TIME__") {
            clock.push((4 + out.len(), mac.expansion.len()));
        }
        out.extend_from_slice(&mac.expansion);
    }
    let mut block = count.to_le_bytes().to_vec();
    block.extend_from_slice(&out);
    (block, clock)
}

/// The table of macros as the reference has it when it puts the program
/// together: the ones it defines itself, then each module's in turn. A
/// macro two modules define differently is in neither, unless a later
/// module defines it again. `__LINE__` and `__FILE__` are in the table,
/// as `0` and nothing, as they are when no source is being read.
fn link_macro_table(options: &CompileOptions, modules: Vec<Vec<LinkMacro>>) -> MacroTable {
    struct Entry {
        mac: LinkMacro,
        pseudo: bool,
        seq: usize,
    }
    let mut table: Vec<Entry> = Vec::new();
    let mut seq = 0;
    let mut add = |table: &mut Vec<Entry>, mac: LinkMacro, pseudo: bool| {
        table.push(Entry { mac, pseudo, seq });
        seq += 1;
    };
    let plain = |name: &str, expansion: &str| LinkMacro {
        name: name.as_bytes().to_vec(),
        has_args: false,
        has_varargs: false,
        params: Vec::new(),
        expansion: expansion.as_bytes().to_vec(),
    };
    add(&mut table, plain("__LINE__", "0"), true);
    add(&mut table, plain("__FILE__", ""), true);
    for (name, expansion) in predefined_macros(options) {
        add(&mut table, plain(&name, &expansion), false);
    }
    let mut undefined = std::collections::HashSet::new();
    for name in &options.undefines {
        table.retain(|entry| entry.pseudo || entry.mac.name != name.as_bytes());
        undefined.insert(name.as_bytes().to_vec());
    }
    for module in modules {
        for mac in module {
            match table.iter().position(|entry| entry.mac.name == mac.name) {
                Some(at) => {
                    let entry = &table[at];
                    if !entry.pseudo && entry.mac != mac {
                        undefined.insert(mac.name.clone());
                        table.remove(at);
                    }
                }
                None => add(&mut table, mac, false),
            }
        }
    }
    table.sort_by_key(|entry| {
        (
            crate::pp::macro_chain(&entry.mac.name),
            std::cmp::Reverse(entry.seq),
        )
    });
    MacroTable {
        macros: table
            .into_iter()
            .map(|entry| (entry.mac, entry.pseudo))
            .collect(),
        undefined,
    }
}

/// Four bytes in the image's header that are the compiler's to use.
const TOOL_DATA: [u8; 4] = *b"hxcn";

/// The problems of a build that are shown, as `hexicon build` and the
/// language server show them, and those that are only counted.
#[derive(Debug, Default)]
pub struct Shown<'a> {
    /// The problems to show, in order.
    pub problems: Vec<&'a Diagnostic>,
    /// For each file with a string with no end, how many problems after
    /// it were not shown, as following from it.
    pub unshown: Vec<(String, usize)>,
}

/// Which of a build's problems are shown. In a Hexicon source, a message
/// is shown once, and what follows a string with no end in the same file
/// is only counted: it follows from that. Whether warnings are shown is
/// the caller's to decide.
pub fn shown(diagnostics: &[Diagnostic]) -> Shown<'_> {
    let mut shown = Shown::default();
    let mut seen: Vec<(&str, u32, &str)> = Vec::new();
    for problem in diagnostics {
        if problem.hexicon {
            if let Some((_, count)) = shown
                .unshown
                .iter_mut()
                .find(|(file, _)| *file == problem.file)
            {
                *count += 1;
                continue;
            }
            let key = (
                problem.file.as_str(),
                problem.line,
                problem.message.as_str(),
            );
            if seen.contains(&key) {
                continue;
            }
            seen.push(key);
            if problem.message.starts_with("this string has no end") {
                shown.unshown.push((problem.file.clone(), 0));
            }
        }
        shown.problems.push(problem);
    }
    shown
}

fn has_errors(diagnostics: &[Diagnostic]) -> bool {
    diagnostics.iter().any(|diagnostic| {
        matches!(
            diagnostic.severity,
            Severity::Error | Severity::Fatal | Severity::Internal
        )
    })
}

pub(crate) fn start<'a>(
    files: &'a mut dyn SourceFiles,
    source: &str,
    options: &CompileOptions,
) -> Result<Preprocessor<'a>, Diagnostic> {
    let mut pp = set_up(files, source, options)?;
    pp.set_compile_mode();
    Ok(pp)
}

/// Do something with a source's preprocessor, set up as a build of the
/// program `sources` sets it up: its macros, include paths, character
/// set, and imports, with the libraries built into the compiler, and an
/// English source read as the Hexicon it means. It gives preprocessed
/// text; `set_compile_mode` makes it give tokens.
pub fn with_preprocessor<R>(
    files: &mut dyn SourceFiles,
    sources: &[&str],
    source: &str,
    options: &CompileOptions,
    then: impl FnOnce(&mut Preprocessor<'_>) -> R,
) -> Result<R, Diagnostic> {
    let mut with_sources: Vec<&str> = sources.to_vec();
    if !with_sources.contains(&source) {
        with_sources.push(source);
    }
    let mut files = crate::builtin::WithBuiltIns::for_sources(files, &with_sources);
    let mut pp = set_up(&mut files, source, options)?;
    Ok(then(&mut pp))
}

/// A source's preprocessor, set up as a build sets it up.
fn set_up<'a>(
    files: &'a mut dyn SourceFiles,
    source: &str,
    options: &CompileOptions,
) -> Result<Preprocessor<'a>, Diagnostic> {
    let mut pp = Preprocessor::new(files);
    if let Some(charset) = &options.default_charset {
        pp.set_default_charset(charset);
    }

    for (name, expansion) in predefined_macros(options) {
        pp.define(&name, &expansion);
    }
    for path in &options.include_paths {
        pp.add_include_path(path);
    }
    for name in &options.undefines {
        pp.undefine(name);
    }
    if !pp.set_source(source) {
        return Err(Diagnostic {
            // A message about no place in particular.
            file: String::new(),
            line: 0,
            severity: Severity::Error,
            message: format!("unable to open source file \"{source}\""),
            ..Default::default()
        });
    }
    pp.set_imports(options.imports.clone());
    Ok(pp)
}

/// Compile a program that is a single source file.
pub fn compile(files: &mut dyn SourceFiles, source: &str, options: &CompileOptions) -> Compiled {
    compile_program(files, &[source], options)
}

/// Compile a program from its source files, which are put together in
/// the order given.
///
/// Each source is read twice, as the reference compiler reads it: once
/// to learn what it defines, and once more, knowing what all of them
/// define, to generate its code. Then what was generated for each is
/// made into one program.
pub fn compile_program(
    files: &mut dyn SourceFiles,
    sources: &[&str],
    options: &CompileOptions,
) -> Compiled {
    compile_reading(files, sources, options, None)
}

/// Compile a program, as [`compile_program`] does, and say what its
/// sources define, as [`crate::document`] does, from the same reading:
/// the second reading of each source, which both need, is done once. If
/// the compile stops before every source is read, what was found is said
/// with the problems that stopped it (its `diagnostics`), as
/// [`crate::document`] says what stopped it.
pub fn compile_and_document(
    files: &mut dyn SourceFiles,
    sources: &[&str],
    options: &CompileOptions,
) -> (Compiled, crate::Documented) {
    let mut reading = Some(crate::docs::Reading::default());
    let mut documented = None;
    let compiled = compile_reading(
        files,
        sources,
        options,
        Some((&mut reading, &mut documented)),
    );
    let documented = documented.unwrap_or_else(|| {
        let mut problems: Vec<Diagnostic> = compiled
            .diagnostics
            .iter()
            .filter(|d| d.severity != Severity::Warning)
            .cloned()
            .collect();
        if problems.is_empty() {
            problems.push(Diagnostic {
                severity: Severity::Error,
                message: "the sources were not all read".to_owned(),
                ..Diagnostic::default()
            });
        }
        reading.take().unwrap_or_default().stopped(problems)
    });
    (compiled, documented)
}

/// Where a build that documents the program keeps what it finds: the
/// reading as it goes, and what it found when every source is read.
type Documenting<'r> = (
    &'r mut Option<crate::docs::Reading>,
    &'r mut Option<crate::Documented>,
);

fn compile_reading(
    files: &mut dyn SourceFiles,
    sources: &[&str],
    options: &CompileOptions,
    mut documenting: Option<Documenting<'_>>,
) -> Compiled {
    // The built-in libraries' files are part of the compiler.
    let mut files = crate::builtin::WithBuiltIns::for_sources(files, sources);
    let files: &mut dyn SourceFiles = &mut files;
    let mut compiled = Compiled::default();

    let mut exports = Vec::new();
    // The warnings of a Hexicon source's first reading, which its second
    // reading gives again: the reference reports both, Hexicon each once.
    let mut first_warnings: Vec<Vec<Diagnostic>> = Vec::new();
    for source in sources {
        let mut pp = match start(files, source, options) {
            Ok(pp) => pp,
            Err(diagnostic) => {
                compiled.diagnostics.push(diagnostic);
                return compiled;
            }
        };
        let prog = Parser::new(&mut pp, true, Exports::default()).parse_top();
        let mut found = pp.take_diagnostics();
        found.iter_mut().for_each(crate::wording::for_hexicon);
        // A warning is given once, by the second reading, unless only
        // the first gave it.
        let (warnings, mut found): (Vec<_>, Vec<_>) = found
            .into_iter()
            .partition(|d| d.severity == Severity::Warning);
        first_warnings.push(warnings);
        compiled.diagnostics.append(&mut found);
        if has_errors(&compiled.diagnostics) {
            return compiled;
        }
        exports.push(prog.exports());
    }
    // What each source defines: for a game's source, a name a source
    // before it defines is reported where it is defined again, and an
    // action or verb rule of the built-in libraries' may be replaced.
    let defined: Vec<Vec<Vec<u8>>> = exports
        .iter()
        .map(|exported| {
            exported
                .objs
                .iter()
                .map(|obj| obj.name.clone())
                .chain(exported.funcs.iter().map(|func| func.name.clone()))
                .collect()
        })
        .collect();
    // What every source knows on its second reading, made once.
    let known = Program::knowing(merge_exports(exports));

    let mut modules = Vec::new();
    let mut module_macros = Vec::new();
    // The source files of all the modules, in order: each module's
    // files are numbered after those of the modules before it, a file
    // that two modules read once for each.
    let mut source_files: Vec<String> = Vec::new();
    // Names are checked when the game has a source of its own.
    let from_library = |index: usize| options.from_library.get(index) == Some(&true);
    let checks_names = (0..sources.len()).any(|index| !from_library(index));
    let mut names = crate::names::Checker::default();
    for (index, source) in sources.iter().enumerate() {
        let module = options
            .module_names
            .get(index)
            .cloned()
            .unwrap_or_else(|| ((*source).to_owned(), index + 1));
        let mut pp = match start(files, source, options) {
            Ok(pp) => pp,
            Err(diagnostic) => {
                compiled.diagnostics.push(diagnostic);
                return compiled;
            }
        };
        let mut parser = Parser::with_program(&mut pp, false, known.clone());
        parser.set_module(module, options.source_text_group);
        // Where a game's own names are used, for the editor.
        parser.set_record_uses(documenting.is_some() && !from_library(index));
        if !from_library(index) {
            let mut before = std::collections::HashMap::new();
            for (earlier, names) in defined.iter().enumerate().take(index) {
                let by = (!from_library(earlier)).then(|| sources[earlier].to_owned());
                for name in names {
                    before.entry(name.clone()).or_insert_with(|| by.clone());
                }
            }
            parser.set_defined_before(before);
        }
        let mut prog = parser.parse_top();
        let mut found = pp.take_diagnostics();
        for diagnostic in &mut found {
            crate::wording::for_hexicon(diagnostic);
            crate::wording::suggest_name(diagnostic, &prog.globals);
        }
        // A warning only the first reading gave is still reported.
        for warning in std::mem::take(&mut first_warnings[index]) {
            if !found.contains(&warning) {
                compiled.diagnostics.push(warning);
            }
        }
        compiled.diagnostics.extend(found);
        module_macros.push(pp.link_macros());
        if has_errors(&compiled.diagnostics) {
            return compiled;
        }
        // What it defines, from the program as it was read, before the
        // code is generated from it.
        if let Some((Some(reading), _)) = documenting.as_mut().map(|(r, d)| (&mut **r, d)) {
            let names = pp.file_names();
            reading.add(&prog, &names, from_library(index), pp.files());
        }

        if checks_names {
            names.add(
                crate::names::collect(&prog),
                !from_library(index),
                from_library(index),
                &|file| pp.file_name(file).to_owned(),
            );
        }
        prog.from_library = from_library(index);
        let mut generated = emit::generate(
            &mut prog,
            options.debug,
            options.line_records || options.debug,
            source_files.len(),
        );
        source_files.extend(pp.file_names());
        for diagnostic in std::mem::take(&mut generated.diagnostics) {
            let meant = diagnostic.meant.clone();
            // A problem that is nowhere in particular has no file. Nor
            // has one found before any statement was come to.
            let file = if diagnostic.file == usize::MAX || diagnostic.line == 0 {
                String::new()
            } else {
                pp.file_name(diagnostic.file).to_owned()
            };
            let mut diagnostic = Diagnostic {
                file,
                line: diagnostic.line,
                severity: diagnostic.severity,
                message: diagnostic.message,
                ..Default::default()
            };
            crate::wording::for_hexicon(&mut diagnostic);
            crate::wording::suggest_name(&mut diagnostic, &prog.globals);
            if let Some(meant) = &meant {
                diagnostic.note = Some(format!(
                    "did you mean \"{}\"?",
                    String::from_utf8_lossy(meant)
                ));
            }
            compiled.diagnostics.push(diagnostic);
        }
        if has_errors(&compiled.diagnostics) {
            return compiled;
        }
        // What is wrong in putting the sources together names the
        // source it was found in.
        let object_file = source
            .rsplit(['/', '\\'])
            .next()
            .unwrap_or(source)
            .to_owned();
        modules.push(Module {
            prog,
            out: generated,
            object_file,
        });
    }

    // Every source read, what they define is all found.
    if let Some((reading, documented)) = documenting.take()
        && let Some(reading) = reading.take()
    {
        *documented = Some(reading.finish(files));
    }
    compiled.diagnostics.extend(names.warnings());
    // The tags in the text of a game's own sources, where a library says
    // which it reads.
    let texts: Vec<String> = if options.text_tags.is_empty()
        && options.object_tags.is_empty()
        && options.object_keys.is_empty()
        && options.ifid.is_none()
    {
        Vec::new()
    } else {
        sources
            .iter()
            .map(|source| {
                files
                    .read(source)
                    .map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
                    .unwrap_or_default()
            })
            .collect()
    };
    if !options.text_tags.is_empty() {
        let mut known: std::collections::HashSet<String> =
            options.text_tags.iter().cloned().collect();
        for text in &texts {
            known.extend(crate::tags::tags_defined(text));
        }
        for (index, source) in sources.iter().enumerate() {
            if !from_library(index) {
                compiled
                    .diagnostics
                    .extend(crate::tags::check(source, &texts[index], &known));
            }
        }
    }
    // The game's IFID, where a library says where a game gives it.
    if let Some(property) = &options.ifid {
        let own: Vec<(&str, &str)> = sources
            .iter()
            .enumerate()
            .filter(|(index, _)| !from_library(*index))
            .map(|(index, source)| (*source, texts[index].as_str()))
            .collect();
        compiled
            .diagnostics
            .extend(crate::ifid::check(&own, property));
    }
    // Putting the program together: everything it refers to has to be
    // in it.
    let note = |compiled: &mut Compiled, severity: Severity, message: String| {
        compiled.diagnostics.push(Diagnostic {
            file: String::new(),
            line: 0,
            severity,
            message,
            ..Default::default()
        });
    };
    let Linked {
        mut prog,
        out,
        enum_ids,
        errors,
    } = link::link(modules);
    // The reference reads every object file even when one is wrong,
    // and goes no further if any was.
    if !errors.is_empty() {
        for message in errors {
            note(&mut compiled, Severity::Error, message);
        }
        return compiled;
    }
    // The names in the tags that name objects, and the keys written as
    // strings where a key is an object, in a game's own sources.
    if !options.object_tags.is_empty() || !options.object_keys.is_empty() {
        let objects: std::collections::HashSet<&[u8]> = prog
            .globals
            .names()
            .filter(|name| matches!(prog.globals.peek(name), Some(Global::Obj(_))))
            .collect();
        let tag_names: std::collections::HashSet<String> =
            options.object_tags.iter().cloned().collect();
        for (index, source) in sources.iter().enumerate() {
            if !from_library(index) {
                compiled.diagnostics.extend(crate::tags::check_objects(
                    source,
                    &texts[index],
                    &tag_names,
                    &options.object_keys,
                    &objects,
                ));
            }
        }
        if has_errors(&compiled.diagnostics) {
            return compiled;
        }
    }
    let mut generated = emit::link_generate(&mut prog, out, enum_ids.clone());
    for name in emit::unresolved_externs(&prog, &generated) {
        // The system library starts the program by calling its main.
        let message = if name.as_slice() == b"main" {
            "the program has no main(args) function, which the system library calls \
             when it starts"
                .to_owned()
        } else {
            format!(
                "unresolved external reference \"{}\"",
                crate::pp::show_name(&name)
            )
        };
        note(&mut compiled, Severity::Error, message);
    }
    // A program has to have somewhere to start.
    let has_main = matches!(
        prog.globals.peek(b"_main".as_slice()),
        Some(Global::Func(func)) if generated.func_anchor.contains_key(func)
    );
    if !has_main && prog.globals.peek(b"_main".as_slice()).is_none() {
        note(
            &mut compiled,
            Severity::Error,
            "function _main() is not defined: a program built without the system \
             library (--no-system) has to define its own"
                .to_owned(),
        );
        return compiled;
    }
    let exports = emit::resolve_exports(&prog, &mut generated);
    for (severity, message) in exports.problems {
        note(&mut compiled, severity, message);
    }
    for (name, id) in exports.assumed_props {
        prog.add_assumed_prop(name, id);
    }
    if has_errors(&compiled.diagnostics) {
        return compiled;
    }
    // What is found wrong as the image is put together, which the
    // reference does not get to if anything above was.
    for message in std::mem::take(&mut generated.link_errors) {
        note(&mut compiled, Severity::Error, message);
    }
    if has_errors(&compiled.diagnostics) {
        return compiled;
    }

    let table = link_macro_table(options, module_macros);
    let debug = options.debug.then(|| {
        let (macros, macros_unspecified) = debug_macros(&table);
        image::DebugRecords {
            enum_ids: enum_ids.clone(),
            macros,
            macros_unspecified,
        }
    });
    match image::write_image(
        &prog,
        generated,
        &options.timestamp,
        &TOOL_DATA,
        if options.line_records || options.debug {
            &source_files
        } else {
            &[]
        },
        debug.as_ref(),
    ) {
        Ok(image) => {
            compiled.symbols = runtime_symbols(&prog, &enum_ids, &image.func_addrs);
            compiled.macros = table.macros.into_iter().map(|(mac, _)| mac).collect();
            compiled.image = Some(image.bytes);
            compiled.unspecified = image.unspecified;
        }
        Err(message) => note(&mut compiled, Severity::Error, message),
    }
    compiled
}

/// The global symbols, each with its value in the image, in the order of
/// the reference's table of global names when the program is put
/// together.
fn runtime_symbols(
    prog: &crate::parse::Program,
    enum_ids: &[u32],
    func_addrs: &std::collections::HashMap<usize, u32>,
) -> Vec<RuntimeSymbol> {
    prog.globals
        .in_table_order()
        .into_iter()
        .filter_map(|(name, global)| {
            let value = match global {
                Global::Func(func) => RuntimeValue::Function(*func_addrs.get(&func)?),
                Global::Obj(obj) => RuntimeValue::Object(prog.objs[obj].id),
                Global::Prop(prop) => RuntimeValue::Property(prog.props[prop].id),
                Global::Enum(sym) => RuntimeValue::Enum(*enum_ids.get(sym)?),
                Global::Bif(bif) => RuntimeValue::BuiltIn {
                    set: prog.bifs[bif].set as u16,
                    index: prog.bifs[bif].index as u16,
                },
                Global::Meta(meta) => RuntimeValue::Class(prog.metas[meta].obj_id),
                // Only code compiled while the program runs has these.
                Global::DynLocal(_) => return None,
            };
            Some(RuntimeSymbol {
                name: name.to_vec(),
                value,
            })
        })
        .collect()
}