Skip to main content

hexicon_compiler/
compile.rs

1//! Compiling a program: source files in, an image out.
2
3use crate::emit;
4use crate::image;
5use crate::link::{self, Linked, Module};
6use crate::parse::{Exports, Global, Parser, Program, merge_exports};
7use crate::pp::{Diagnostic, LinkMacro, Preprocessor, Severity, SourceFiles};
8
9/// What to compile, and how.
10#[derive(Debug, Clone)]
11pub struct CompileOptions {
12    /// Directories to look in for included files.
13    pub include_paths: Vec<String>,
14    /// Macros to define before the source is read: name and expansion.
15    pub defines: Vec<(String, String)>,
16    /// Macros to remove before the source is read.
17    pub undefines: Vec<String>,
18    /// The character set of source files that do not say what they are
19    /// in. Without one, they are taken to be UTF-8.
20    pub default_charset: Option<String>,
21    /// When the program is compiled, as the 24 characters the image
22    /// records (`Thu Nov 19 09:24:12 2026`). The compiler has no clock
23    /// of its own.
24    pub timestamp: [u8; 24],
25    /// Objects say which source file they are in from the start of each
26    /// file (`--source-text-groups`), as `#pragma sourceTextGroup(on)` makes them.
27    pub source_text_group: bool,
28    /// For each source, the name its source text group gives it and
29    /// its place among the modules of the build, from 1. Without them,
30    /// a source is named as it is given, and numbered by its place in
31    /// the list.
32    pub module_names: Vec<(String, usize)>,
33    /// For each source, whether a library brought it in. A game's own
34    /// Hexicon sources are checked for properties given values that
35    /// nothing reads (see [`crate::names`]); a library's are not.
36    /// Without them, no source is a library's.
37    pub from_library: Vec<bool>,
38    /// The libraries a Hexicon source can import (`import hexad;`): each
39    /// by name, with its header, or none if it names none.
40    pub imports: Vec<(String, Option<String>)>,
41    /// The tags the libraries' output filters read in a game's text, as
42    /// their manifests list them: with any, a tag in a game's own source
43    /// that nothing defines is warned of (see [`crate::tags`]).
44    pub text_tags: Vec<String>,
45    /// The tags whose argument names an object, as the libraries'
46    /// manifests list them: a name in such a tag that is no object's is
47    /// an error in a game's own source (see [`crate::tags`]).
48    pub object_tags: Vec<String>,
49    /// Where a key is an object, as the libraries' manifests list them:
50    /// a string there is an error in a game's own source.
51    pub object_keys: Vec<String>,
52    /// The property a game gives its IFID in, as a library's manifest
53    /// names it: with one, a game whose own sources give no IFID there,
54    /// or one that is not an IFID, is warned of (see [`crate::ifid`]).
55    pub ifid: Option<String>,
56    /// Compile for debugging (`-d`): `__DEBUG` is defined, and the image
57    /// has what a debugger needs: the global symbols, the macros, and
58    /// the address of each line's code.
59    pub debug: bool,
60    /// The image says where in the source each statement's code came
61    /// from, so that a run-time error can say where it happened. On by
62    /// default, and always when compiling for debugging; off only where
63    /// the code alone matters, as in tests that two sources compile to
64    /// the same image.
65    pub line_records: bool,
66}
67
68impl Default for CompileOptions {
69    fn default() -> Self {
70        Self {
71            include_paths: Vec::new(),
72            defines: Vec::new(),
73            undefines: Vec::new(),
74            default_charset: None,
75            timestamp: *b"Thu Jan  1 00:00:00 1970",
76            source_text_group: false,
77            module_names: Vec::new(),
78            from_library: Vec::new(),
79            imports: Vec::new(),
80            text_tags: Vec::new(),
81            object_tags: Vec::new(),
82            object_keys: Vec::new(),
83            ifid: None,
84            debug: false,
85            line_records: true,
86        }
87    }
88}
89
90/// What came of compiling.
91#[derive(Debug, Clone, Default)]
92pub struct Compiled {
93    /// The image, unless there were errors.
94    pub image: Option<Vec<u8>>,
95    /// Stretches of the image, as offset and length, whose contents mean
96    /// nothing to a program: the time it was compiled, bytes that are
97    /// the compiler's own, and fields that are written but never read.
98    /// Two images of the same program can differ there.
99    pub unspecified: Vec<(usize, usize)>,
100    /// The problems found.
101    pub diagnostics: Vec<Diagnostic>,
102    /// The program's global symbols, each with its value in the image,
103    /// in the order of the reference's table of them when the program
104    /// is put together: what `globalSymbols()` gives a program run before
105    /// its image is written.
106    pub symbols: Vec<RuntimeSymbol>,
107    /// The program's macros, likewise: what
108    /// `globalSymbols(MacroTable)` gives it.
109    pub macros: Vec<LinkMacro>,
110}
111
112/// A global symbol, and its value in the image.
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct RuntimeSymbol {
115    /// The name.
116    pub name: Vec<u8>,
117    /// What the name means.
118    pub value: RuntimeValue,
119}
120
121/// What a global symbol means.
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub enum RuntimeValue {
124    /// A function: its address in the code.
125    Function(u32),
126    /// An object.
127    Object(u32),
128    /// A property.
129    Property(u16),
130    /// A value of an enumeration.
131    Enum(u32),
132    /// A built-in function: its set, and its place in the set.
133    BuiltIn {
134        /// The set's number.
135        set: u16,
136        /// The function's place in it.
137        index: u16,
138    },
139    /// A built-in class: the object that stands for it.
140    Class(u32),
141}
142
143/// The macros the compiler defines before any source is read: what is
144/// compiling, and when. The date is `Nov 19 2026` and the time
145/// `09:24:12`, as strings. A source is told it is Hexicon's
146/// (`__HEXICON`, and Hexicon's version). Then those the options define.
147fn predefined_macros(options: &CompileOptions) -> Vec<(String, String)> {
148    let stamp = String::from_utf8_lossy(&options.timestamp);
149    let part = |range: std::ops::Range<usize>| stamp.get(range).unwrap_or("").to_owned();
150    let mut macros = vec![
151        (
152            "__DATE__".to_owned(),
153            format!("'{} {} {}'", part(4..7), part(8..10), part(20..24)),
154        ),
155        ("__TIME__".to_owned(), format!("'{}'", part(11..19))),
156    ];
157    if options.debug {
158        macros.push(("__DEBUG".to_owned(), "1".to_owned()));
159    }
160    macros.extend([
161        ("__HEXICON".to_owned(), "1".to_owned()),
162        (
163            "__HEXICON_VERSION_MAJOR".to_owned(),
164            env!("CARGO_PKG_VERSION_MAJOR").to_owned(),
165        ),
166        (
167            "__HEXICON_VERSION_MINOR".to_owned(),
168            env!("CARGO_PKG_VERSION_MINOR").to_owned(),
169        ),
170    ]);
171    macros.extend(options.defines.iter().cloned());
172    macros
173}
174
175/// The table of macros the reference has when it puts the program
176/// together, and the names it undefined on the way.
177struct MacroTable {
178    /// The macros, each with whether it is one the preprocessor works
179    /// out as it goes, which are `__LINE__` and `__FILE__`.
180    macros: Vec<(LinkMacro, bool)>,
181    undefined: std::collections::HashSet<Vec<u8>>,
182}
183
184/// The macros as the `MACR` block has them, for the debugger: those
185/// that mean the same throughout, which are those never undefined, but
186/// for `__LINE__` and `__FILE__`. Each is its name, its flags, its
187/// parameters, and its expansion. Also where in it the date and time of
188/// the compilation are, which mean nothing to a comparison of images.
189fn debug_macros(table: &MacroTable) -> (Vec<u8>, Vec<(usize, usize)>) {
190    let mut count = 0u32;
191    let mut out = Vec::new();
192    let mut clock = Vec::new();
193    for (mac, pseudo) in &table.macros {
194        if *pseudo || table.undefined.contains(&mac.name) {
195            continue;
196        }
197        count += 1;
198        out.extend_from_slice(&(mac.name.len() as u16).to_le_bytes());
199        out.extend_from_slice(&mac.name);
200        let flags = u16::from(mac.has_args) | u16::from(mac.has_varargs) << 1;
201        out.extend_from_slice(&flags.to_le_bytes());
202        out.extend_from_slice(&(mac.params.len() as u16).to_le_bytes());
203        for param in &mac.params {
204            out.extend_from_slice(&(param.len() as u16).to_le_bytes());
205            out.extend_from_slice(param);
206        }
207        out.extend_from_slice(&(mac.expansion.len() as u32).to_le_bytes());
208        if matches!(mac.name.as_slice(), b"__DATE__" | b"__TIME__") {
209            clock.push((4 + out.len(), mac.expansion.len()));
210        }
211        out.extend_from_slice(&mac.expansion);
212    }
213    let mut block = count.to_le_bytes().to_vec();
214    block.extend_from_slice(&out);
215    (block, clock)
216}
217
218/// The table of macros as the reference has it when it puts the program
219/// together: the ones it defines itself, then each module's in turn. A
220/// macro two modules define differently is in neither, unless a later
221/// module defines it again. `__LINE__` and `__FILE__` are in the table,
222/// as `0` and nothing, as they are when no source is being read.
223fn link_macro_table(options: &CompileOptions, modules: Vec<Vec<LinkMacro>>) -> MacroTable {
224    struct Entry {
225        mac: LinkMacro,
226        pseudo: bool,
227        seq: usize,
228    }
229    let mut table: Vec<Entry> = Vec::new();
230    let mut seq = 0;
231    let mut add = |table: &mut Vec<Entry>, mac: LinkMacro, pseudo: bool| {
232        table.push(Entry { mac, pseudo, seq });
233        seq += 1;
234    };
235    let plain = |name: &str, expansion: &str| LinkMacro {
236        name: name.as_bytes().to_vec(),
237        has_args: false,
238        has_varargs: false,
239        params: Vec::new(),
240        expansion: expansion.as_bytes().to_vec(),
241    };
242    add(&mut table, plain("__LINE__", "0"), true);
243    add(&mut table, plain("__FILE__", ""), true);
244    for (name, expansion) in predefined_macros(options) {
245        add(&mut table, plain(&name, &expansion), false);
246    }
247    let mut undefined = std::collections::HashSet::new();
248    for name in &options.undefines {
249        table.retain(|entry| entry.pseudo || entry.mac.name != name.as_bytes());
250        undefined.insert(name.as_bytes().to_vec());
251    }
252    for module in modules {
253        for mac in module {
254            match table.iter().position(|entry| entry.mac.name == mac.name) {
255                Some(at) => {
256                    let entry = &table[at];
257                    if !entry.pseudo && entry.mac != mac {
258                        undefined.insert(mac.name.clone());
259                        table.remove(at);
260                    }
261                }
262                None => add(&mut table, mac, false),
263            }
264        }
265    }
266    table.sort_by_key(|entry| {
267        (
268            crate::pp::macro_chain(&entry.mac.name),
269            std::cmp::Reverse(entry.seq),
270        )
271    });
272    MacroTable {
273        macros: table
274            .into_iter()
275            .map(|entry| (entry.mac, entry.pseudo))
276            .collect(),
277        undefined,
278    }
279}
280
281/// Four bytes in the image's header that are the compiler's to use.
282const TOOL_DATA: [u8; 4] = *b"hxcn";
283
284/// The problems of a build that are shown, as `hexicon build` and the
285/// language server show them, and those that are only counted.
286#[derive(Debug, Default)]
287pub struct Shown<'a> {
288    /// The problems to show, in order.
289    pub problems: Vec<&'a Diagnostic>,
290    /// For each file with a string with no end, how many problems after
291    /// it were not shown, as following from it.
292    pub unshown: Vec<(String, usize)>,
293}
294
295/// Which of a build's problems are shown. In a Hexicon source, a message
296/// is shown once, and what follows a string with no end in the same file
297/// is only counted: it follows from that. Whether warnings are shown is
298/// the caller's to decide.
299pub fn shown(diagnostics: &[Diagnostic]) -> Shown<'_> {
300    let mut shown = Shown::default();
301    let mut seen: Vec<(&str, u32, &str)> = Vec::new();
302    for problem in diagnostics {
303        if problem.hexicon {
304            if let Some((_, count)) = shown
305                .unshown
306                .iter_mut()
307                .find(|(file, _)| *file == problem.file)
308            {
309                *count += 1;
310                continue;
311            }
312            let key = (
313                problem.file.as_str(),
314                problem.line,
315                problem.message.as_str(),
316            );
317            if seen.contains(&key) {
318                continue;
319            }
320            seen.push(key);
321            if problem.message.starts_with("this string has no end") {
322                shown.unshown.push((problem.file.clone(), 0));
323            }
324        }
325        shown.problems.push(problem);
326    }
327    shown
328}
329
330fn has_errors(diagnostics: &[Diagnostic]) -> bool {
331    diagnostics.iter().any(|diagnostic| {
332        matches!(
333            diagnostic.severity,
334            Severity::Error | Severity::Fatal | Severity::Internal
335        )
336    })
337}
338
339pub(crate) fn start<'a>(
340    files: &'a mut dyn SourceFiles,
341    source: &str,
342    options: &CompileOptions,
343) -> Result<Preprocessor<'a>, Diagnostic> {
344    let mut pp = set_up(files, source, options)?;
345    pp.set_compile_mode();
346    Ok(pp)
347}
348
349/// Do something with a source's preprocessor, set up as a build of the
350/// program `sources` sets it up: its macros, include paths, character
351/// set, and imports, with the libraries built into the compiler, and an
352/// English source read as the Hexicon it means. It gives preprocessed
353/// text; `set_compile_mode` makes it give tokens.
354pub fn with_preprocessor<R>(
355    files: &mut dyn SourceFiles,
356    sources: &[&str],
357    source: &str,
358    options: &CompileOptions,
359    then: impl FnOnce(&mut Preprocessor<'_>) -> R,
360) -> Result<R, Diagnostic> {
361    let mut with_sources: Vec<&str> = sources.to_vec();
362    if !with_sources.contains(&source) {
363        with_sources.push(source);
364    }
365    let mut files = crate::builtin::WithBuiltIns::for_sources(files, &with_sources);
366    let mut pp = set_up(&mut files, source, options)?;
367    Ok(then(&mut pp))
368}
369
370/// A source's preprocessor, set up as a build sets it up.
371fn set_up<'a>(
372    files: &'a mut dyn SourceFiles,
373    source: &str,
374    options: &CompileOptions,
375) -> Result<Preprocessor<'a>, Diagnostic> {
376    let mut pp = Preprocessor::new(files);
377    if let Some(charset) = &options.default_charset {
378        pp.set_default_charset(charset);
379    }
380
381    for (name, expansion) in predefined_macros(options) {
382        pp.define(&name, &expansion);
383    }
384    for path in &options.include_paths {
385        pp.add_include_path(path);
386    }
387    for name in &options.undefines {
388        pp.undefine(name);
389    }
390    if !pp.set_source(source) {
391        return Err(Diagnostic {
392            // A message about no place in particular.
393            file: String::new(),
394            line: 0,
395            severity: Severity::Error,
396            message: format!("unable to open source file \"{source}\""),
397            ..Default::default()
398        });
399    }
400    pp.set_imports(options.imports.clone());
401    Ok(pp)
402}
403
404/// Compile a program that is a single source file.
405pub fn compile(files: &mut dyn SourceFiles, source: &str, options: &CompileOptions) -> Compiled {
406    compile_program(files, &[source], options)
407}
408
409/// Compile a program from its source files, which are put together in
410/// the order given.
411///
412/// Each source is read twice, as the reference compiler reads it: once
413/// to learn what it defines, and once more, knowing what all of them
414/// define, to generate its code. Then what was generated for each is
415/// made into one program.
416pub fn compile_program(
417    files: &mut dyn SourceFiles,
418    sources: &[&str],
419    options: &CompileOptions,
420) -> Compiled {
421    compile_reading(files, sources, options, None)
422}
423
424/// Compile a program, as [`compile_program`] does, and say what its
425/// sources define, as [`crate::document`] does, from the same reading:
426/// the second reading of each source, which both need, is done once. If
427/// the compile stops before every source is read, what was found is said
428/// with the problems that stopped it (its `diagnostics`), as
429/// [`crate::document`] says what stopped it.
430pub fn compile_and_document(
431    files: &mut dyn SourceFiles,
432    sources: &[&str],
433    options: &CompileOptions,
434) -> (Compiled, crate::Documented) {
435    let mut reading = Some(crate::docs::Reading::default());
436    let mut documented = None;
437    let compiled = compile_reading(
438        files,
439        sources,
440        options,
441        Some((&mut reading, &mut documented)),
442    );
443    let documented = documented.unwrap_or_else(|| {
444        let mut problems: Vec<Diagnostic> = compiled
445            .diagnostics
446            .iter()
447            .filter(|d| d.severity != Severity::Warning)
448            .cloned()
449            .collect();
450        if problems.is_empty() {
451            problems.push(Diagnostic {
452                severity: Severity::Error,
453                message: "the sources were not all read".to_owned(),
454                ..Diagnostic::default()
455            });
456        }
457        reading.take().unwrap_or_default().stopped(problems)
458    });
459    (compiled, documented)
460}
461
462/// Where a build that documents the program keeps what it finds: the
463/// reading as it goes, and what it found when every source is read.
464type Documenting<'r> = (
465    &'r mut Option<crate::docs::Reading>,
466    &'r mut Option<crate::Documented>,
467);
468
469fn compile_reading(
470    files: &mut dyn SourceFiles,
471    sources: &[&str],
472    options: &CompileOptions,
473    mut documenting: Option<Documenting<'_>>,
474) -> Compiled {
475    // The built-in libraries' files are part of the compiler.
476    let mut files = crate::builtin::WithBuiltIns::for_sources(files, sources);
477    let files: &mut dyn SourceFiles = &mut files;
478    let mut compiled = Compiled::default();
479
480    let mut exports = Vec::new();
481    // The warnings of a Hexicon source's first reading, which its second
482    // reading gives again: the reference reports both, Hexicon each once.
483    let mut first_warnings: Vec<Vec<Diagnostic>> = Vec::new();
484    for source in sources {
485        let mut pp = match start(files, source, options) {
486            Ok(pp) => pp,
487            Err(diagnostic) => {
488                compiled.diagnostics.push(diagnostic);
489                return compiled;
490            }
491        };
492        let prog = Parser::new(&mut pp, true, Exports::default()).parse_top();
493        let mut found = pp.take_diagnostics();
494        found.iter_mut().for_each(crate::wording::for_hexicon);
495        // A warning is given once, by the second reading, unless only
496        // the first gave it.
497        let (warnings, mut found): (Vec<_>, Vec<_>) = found
498            .into_iter()
499            .partition(|d| d.severity == Severity::Warning);
500        first_warnings.push(warnings);
501        compiled.diagnostics.append(&mut found);
502        if has_errors(&compiled.diagnostics) {
503            return compiled;
504        }
505        exports.push(prog.exports());
506    }
507    // What each source defines: for a game's source, a name a source
508    // before it defines is reported where it is defined again, and an
509    // action or verb rule of the built-in libraries' may be replaced.
510    let defined: Vec<Vec<Vec<u8>>> = exports
511        .iter()
512        .map(|exported| {
513            exported
514                .objs
515                .iter()
516                .map(|obj| obj.name.clone())
517                .chain(exported.funcs.iter().map(|func| func.name.clone()))
518                .collect()
519        })
520        .collect();
521    // What every source knows on its second reading, made once.
522    let known = Program::knowing(merge_exports(exports));
523
524    let mut modules = Vec::new();
525    let mut module_macros = Vec::new();
526    // The source files of all the modules, in order: each module's
527    // files are numbered after those of the modules before it, a file
528    // that two modules read once for each.
529    let mut source_files: Vec<String> = Vec::new();
530    // Names are checked when the game has a source of its own.
531    let from_library = |index: usize| options.from_library.get(index) == Some(&true);
532    let checks_names = (0..sources.len()).any(|index| !from_library(index));
533    let mut names = crate::names::Checker::default();
534    for (index, source) in sources.iter().enumerate() {
535        let module = options
536            .module_names
537            .get(index)
538            .cloned()
539            .unwrap_or_else(|| ((*source).to_owned(), index + 1));
540        let mut pp = match start(files, source, options) {
541            Ok(pp) => pp,
542            Err(diagnostic) => {
543                compiled.diagnostics.push(diagnostic);
544                return compiled;
545            }
546        };
547        let mut parser = Parser::with_program(&mut pp, false, known.clone());
548        parser.set_module(module, options.source_text_group);
549        // Where a game's own names are used, for the editor.
550        parser.set_record_uses(documenting.is_some() && !from_library(index));
551        if !from_library(index) {
552            let mut before = std::collections::HashMap::new();
553            for (earlier, names) in defined.iter().enumerate().take(index) {
554                let by = (!from_library(earlier)).then(|| sources[earlier].to_owned());
555                for name in names {
556                    before.entry(name.clone()).or_insert_with(|| by.clone());
557                }
558            }
559            parser.set_defined_before(before);
560        }
561        let mut prog = parser.parse_top();
562        let mut found = pp.take_diagnostics();
563        for diagnostic in &mut found {
564            crate::wording::for_hexicon(diagnostic);
565            crate::wording::suggest_name(diagnostic, &prog.globals);
566        }
567        // A warning only the first reading gave is still reported.
568        for warning in std::mem::take(&mut first_warnings[index]) {
569            if !found.contains(&warning) {
570                compiled.diagnostics.push(warning);
571            }
572        }
573        compiled.diagnostics.extend(found);
574        module_macros.push(pp.link_macros());
575        if has_errors(&compiled.diagnostics) {
576            return compiled;
577        }
578        // What it defines, from the program as it was read, before the
579        // code is generated from it.
580        if let Some((Some(reading), _)) = documenting.as_mut().map(|(r, d)| (&mut **r, d)) {
581            let names = pp.file_names();
582            reading.add(&prog, &names, from_library(index), pp.files());
583        }
584
585        if checks_names {
586            names.add(
587                crate::names::collect(&prog),
588                !from_library(index),
589                from_library(index),
590                &|file| pp.file_name(file).to_owned(),
591            );
592        }
593        prog.from_library = from_library(index);
594        let mut generated = emit::generate(
595            &mut prog,
596            options.debug,
597            options.line_records || options.debug,
598            source_files.len(),
599        );
600        source_files.extend(pp.file_names());
601        for diagnostic in std::mem::take(&mut generated.diagnostics) {
602            let meant = diagnostic.meant.clone();
603            // A problem that is nowhere in particular has no file. Nor
604            // has one found before any statement was come to.
605            let file = if diagnostic.file == usize::MAX || diagnostic.line == 0 {
606                String::new()
607            } else {
608                pp.file_name(diagnostic.file).to_owned()
609            };
610            let mut diagnostic = Diagnostic {
611                file,
612                line: diagnostic.line,
613                severity: diagnostic.severity,
614                message: diagnostic.message,
615                ..Default::default()
616            };
617            crate::wording::for_hexicon(&mut diagnostic);
618            crate::wording::suggest_name(&mut diagnostic, &prog.globals);
619            if let Some(meant) = &meant {
620                diagnostic.note = Some(format!(
621                    "did you mean \"{}\"?",
622                    String::from_utf8_lossy(meant)
623                ));
624            }
625            compiled.diagnostics.push(diagnostic);
626        }
627        if has_errors(&compiled.diagnostics) {
628            return compiled;
629        }
630        // What is wrong in putting the sources together names the
631        // source it was found in.
632        let object_file = source
633            .rsplit(['/', '\\'])
634            .next()
635            .unwrap_or(source)
636            .to_owned();
637        modules.push(Module {
638            prog,
639            out: generated,
640            object_file,
641        });
642    }
643
644    // Every source read, what they define is all found.
645    if let Some((reading, documented)) = documenting.take()
646        && let Some(reading) = reading.take()
647    {
648        *documented = Some(reading.finish(files));
649    }
650    compiled.diagnostics.extend(names.warnings());
651    // The tags in the text of a game's own sources, where a library says
652    // which it reads.
653    let texts: Vec<String> = if options.text_tags.is_empty()
654        && options.object_tags.is_empty()
655        && options.object_keys.is_empty()
656        && options.ifid.is_none()
657    {
658        Vec::new()
659    } else {
660        sources
661            .iter()
662            .map(|source| {
663                files
664                    .read(source)
665                    .map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
666                    .unwrap_or_default()
667            })
668            .collect()
669    };
670    if !options.text_tags.is_empty() {
671        let mut known: std::collections::HashSet<String> =
672            options.text_tags.iter().cloned().collect();
673        for text in &texts {
674            known.extend(crate::tags::tags_defined(text));
675        }
676        for (index, source) in sources.iter().enumerate() {
677            if !from_library(index) {
678                compiled
679                    .diagnostics
680                    .extend(crate::tags::check(source, &texts[index], &known));
681            }
682        }
683    }
684    // The game's IFID, where a library says where a game gives it.
685    if let Some(property) = &options.ifid {
686        let own: Vec<(&str, &str)> = sources
687            .iter()
688            .enumerate()
689            .filter(|(index, _)| !from_library(*index))
690            .map(|(index, source)| (*source, texts[index].as_str()))
691            .collect();
692        compiled
693            .diagnostics
694            .extend(crate::ifid::check(&own, property));
695    }
696    // Putting the program together: everything it refers to has to be
697    // in it.
698    let note = |compiled: &mut Compiled, severity: Severity, message: String| {
699        compiled.diagnostics.push(Diagnostic {
700            file: String::new(),
701            line: 0,
702            severity,
703            message,
704            ..Default::default()
705        });
706    };
707    let Linked {
708        mut prog,
709        out,
710        enum_ids,
711        errors,
712    } = link::link(modules);
713    // The reference reads every object file even when one is wrong,
714    // and goes no further if any was.
715    if !errors.is_empty() {
716        for message in errors {
717            note(&mut compiled, Severity::Error, message);
718        }
719        return compiled;
720    }
721    // The names in the tags that name objects, and the keys written as
722    // strings where a key is an object, in a game's own sources.
723    if !options.object_tags.is_empty() || !options.object_keys.is_empty() {
724        let objects: std::collections::HashSet<&[u8]> = prog
725            .globals
726            .names()
727            .filter(|name| matches!(prog.globals.peek(name), Some(Global::Obj(_))))
728            .collect();
729        let tag_names: std::collections::HashSet<String> =
730            options.object_tags.iter().cloned().collect();
731        for (index, source) in sources.iter().enumerate() {
732            if !from_library(index) {
733                compiled.diagnostics.extend(crate::tags::check_objects(
734                    source,
735                    &texts[index],
736                    &tag_names,
737                    &options.object_keys,
738                    &objects,
739                ));
740            }
741        }
742        if has_errors(&compiled.diagnostics) {
743            return compiled;
744        }
745    }
746    let mut generated = emit::link_generate(&mut prog, out, enum_ids.clone());
747    for name in emit::unresolved_externs(&prog, &generated) {
748        // The system library starts the program by calling its main.
749        let message = if name.as_slice() == b"main" {
750            "the program has no main(args) function, which the system library calls \
751             when it starts"
752                .to_owned()
753        } else {
754            format!(
755                "unresolved external reference \"{}\"",
756                crate::pp::show_name(&name)
757            )
758        };
759        note(&mut compiled, Severity::Error, message);
760    }
761    // A program has to have somewhere to start.
762    let has_main = matches!(
763        prog.globals.peek(b"_main".as_slice()),
764        Some(Global::Func(func)) if generated.func_anchor.contains_key(func)
765    );
766    if !has_main && prog.globals.peek(b"_main".as_slice()).is_none() {
767        note(
768            &mut compiled,
769            Severity::Error,
770            "function _main() is not defined: a program built without the system \
771             library (--no-system) has to define its own"
772                .to_owned(),
773        );
774        return compiled;
775    }
776    let exports = emit::resolve_exports(&prog, &mut generated);
777    for (severity, message) in exports.problems {
778        note(&mut compiled, severity, message);
779    }
780    for (name, id) in exports.assumed_props {
781        prog.add_assumed_prop(name, id);
782    }
783    if has_errors(&compiled.diagnostics) {
784        return compiled;
785    }
786    // What is found wrong as the image is put together, which the
787    // reference does not get to if anything above was.
788    for message in std::mem::take(&mut generated.link_errors) {
789        note(&mut compiled, Severity::Error, message);
790    }
791    if has_errors(&compiled.diagnostics) {
792        return compiled;
793    }
794
795    let table = link_macro_table(options, module_macros);
796    let debug = options.debug.then(|| {
797        let (macros, macros_unspecified) = debug_macros(&table);
798        image::DebugRecords {
799            enum_ids: enum_ids.clone(),
800            macros,
801            macros_unspecified,
802        }
803    });
804    match image::write_image(
805        &prog,
806        generated,
807        &options.timestamp,
808        &TOOL_DATA,
809        if options.line_records || options.debug {
810            &source_files
811        } else {
812            &[]
813        },
814        debug.as_ref(),
815    ) {
816        Ok(image) => {
817            compiled.symbols = runtime_symbols(&prog, &enum_ids, &image.func_addrs);
818            compiled.macros = table.macros.into_iter().map(|(mac, _)| mac).collect();
819            compiled.image = Some(image.bytes);
820            compiled.unspecified = image.unspecified;
821        }
822        Err(message) => note(&mut compiled, Severity::Error, message),
823    }
824    compiled
825}
826
827/// The global symbols, each with its value in the image, in the order of
828/// the reference's table of global names when the program is put
829/// together.
830fn runtime_symbols(
831    prog: &crate::parse::Program,
832    enum_ids: &[u32],
833    func_addrs: &std::collections::HashMap<usize, u32>,
834) -> Vec<RuntimeSymbol> {
835    prog.globals
836        .in_table_order()
837        .into_iter()
838        .filter_map(|(name, global)| {
839            let value = match global {
840                Global::Func(func) => RuntimeValue::Function(*func_addrs.get(&func)?),
841                Global::Obj(obj) => RuntimeValue::Object(prog.objs[obj].id),
842                Global::Prop(prop) => RuntimeValue::Property(prog.props[prop].id),
843                Global::Enum(sym) => RuntimeValue::Enum(*enum_ids.get(sym)?),
844                Global::Bif(bif) => RuntimeValue::BuiltIn {
845                    set: prog.bifs[bif].set as u16,
846                    index: prog.bifs[bif].index as u16,
847                },
848                Global::Meta(meta) => RuntimeValue::Class(prog.metas[meta].obj_id),
849                // Only code compiled while the program runs has these.
850                Global::DynLocal(_) => return None,
851            };
852            Some(RuntimeSymbol {
853                name: name.to_vec(),
854                value,
855            })
856        })
857        .collect()
858}