Skip to main content

hexicon_compiler/
project.rs

1//! What to build: the options and the source files of a program, from
2//! the command line and from a manifest (`hexicon.toml`, read by
3//! [`crate::manifest`] as more of the command line). A library is a
4//! folder with a manifest, or a `.toml` manifest of its name. Every
5//! program is built on the system library, first, whether it names it or
6//! not, unless told otherwise (`--no-system`, or `system = false` in a
7//! manifest's `[build]`).
8//!
9//! Files are found and read through [`SourceFiles`], like everything
10//! else the compiler reads.
11
12use crate::compile::CompileOptions;
13use crate::manifest::{self, MANIFEST, is_manifest};
14use crate::pp::SourceFiles;
15
16/// The separator of the folders in a path, as paths are made here.
17const SEP: char = std::path::MAIN_SEPARATOR;
18
19/// Where libraries are looked for, besides the folders `--library-path` names and
20/// the libraries built into the compiler.
21#[derive(Debug, Clone, Default)]
22pub struct ProjectPaths {
23    /// More folders to look for libraries and sources in, after any
24    /// `--library-path` names and before the system library.
25    pub user_libraries: Vec<String>,
26}
27
28/// A program to build.
29#[derive(Debug, Clone, Default)]
30pub struct Project {
31    /// The source files, in the order they are put together.
32    pub sources: Vec<String>,
33    /// How to compile them. The time stamp is the caller's to set.
34    pub options: CompileOptions,
35    /// Where to write the image, if anything said.
36    pub image: Option<String>,
37    /// The program is to be run once before the image is written
38    /// (preinitialization): `--preinit`, or by default unless `-d`.
39    pub preinit: bool,
40    /// Warnings are reported (`-w0` says not).
41    pub warnings: bool,
42    /// A warning stops the build (`-we`).
43    pub warnings_as_errors: bool,
44    /// Say what is being done (`-v`).
45    pub verbose: bool,
46    /// The program is built for debugging (`-d`): its resources are
47    /// linked to their files rather than copied into the image.
48    pub debug: bool,
49    /// The files to bundle into the image as resources, in order: those
50    /// the libraries name, then those after `-res`.
51    pub resources: Vec<ResourceSpec>,
52    /// What was said about the project that does not stop the build,
53    /// in the words the reference uses: problems with libraries.
54    pub messages: Vec<String>,
55    /// It was read from a manifest (`hexicon.toml`), and not from the
56    /// command line alone.
57    pub manifest: bool,
58    /// The manifests of the libraries it is built with, in the order they
59    /// were read: those the project names first, each before the libraries
60    /// it is built on, and the system library last.
61    pub libraries: Vec<String>,
62}
63
64/// A file or a folder to bundle as resources.
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct ResourceSpec {
67    /// The file or folder.
68    pub file: String,
69    /// The name to give it in the image (`file=alias`), if not the
70    /// file's own path written as a URL.
71    pub alias: Option<String>,
72    /// For a folder, whether the folders in it are bundled too.
73    pub recurse: bool,
74}
75
76/// A file bundled as a resource, and its name in the image.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct Resource {
79    /// The file.
80    pub file: String,
81    /// The name the program asks for it by.
82    pub name: String,
83}
84
85/// What is in a folder, as [`expand_resources`] is told it.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct DirEntry {
88    /// The file's name, without the folder's.
89    pub name: String,
90    /// It is a folder.
91    pub is_dir: bool,
92    /// Hidden, or belonging to the system: such files are left out.
93    pub hidden: bool,
94}
95
96/// The files the resources name, each folder replaced by the files in
97/// it, in the order the system lists them, as the reference does. A
98/// file in a folder is named by the folder's name, a `/`, and its own.
99/// `list_dir` gives what is in a folder, or nothing for a path that is
100/// not one.
101pub fn expand_resources(
102    specs: &[ResourceSpec],
103    list_dir: &mut dyn FnMut(&str) -> Option<Vec<DirEntry>>,
104) -> Vec<Resource> {
105    fn add(
106        file: &str,
107        name: &str,
108        recurse: bool,
109        list_dir: &mut dyn FnMut(&str) -> Option<Vec<DirEntry>>,
110        out: &mut Vec<Resource>,
111    ) {
112        let Some(entries) = list_dir(file) else {
113            out.push(Resource {
114                file: file.to_owned(),
115                name: name.to_owned(),
116            });
117            return;
118        };
119        for entry in entries {
120            if entry.hidden || entry.name == "." || entry.name == ".." {
121                continue;
122            }
123            let full = build_full_path(file, &entry.name);
124            let mut full_name = name.to_owned();
125            if !full_name.is_empty() && !full_name.ends_with('/') {
126                full_name.push('/');
127            }
128            full_name.push_str(&entry.name);
129            if !entry.is_dir {
130                out.push(Resource {
131                    file: full,
132                    name: full_name,
133                });
134            } else if recurse {
135                add(&full, &full_name, true, list_dir, out);
136            }
137        }
138    }
139    let mut out = Vec::new();
140    for spec in specs {
141        let name = spec
142            .alias
143            .clone()
144            .unwrap_or_else(|| cvt_dir_url(&spec.file));
145        add(&spec.file, &name, spec.recurse, list_dir, &mut out);
146    }
147    out
148}
149
150/// A path written as a relative URL, as the reference writes it on
151/// Windows: with `/` between folders, a drive as `/C:`, and no `/` at
152/// the end.
153fn cvt_dir_url(path: &str) -> String {
154    let mut out = String::new();
155    let bytes = path.as_bytes();
156    let mut rest = path;
157    if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' {
158        out.push('/');
159        out.push_str(&path[..2]);
160        rest = &path[2..];
161        if !rest.starts_with(is_sep) {
162            out.push_str("./");
163        }
164    } else if bytes.len() >= 2 && is_sep(bytes[0] as char) && is_sep(bytes[1] as char) {
165        // A UNC path: the machine's name stays as it is, after a `/`.
166        let end = path[2..].find(is_sep).map_or(path.len(), |at| at + 2);
167        out.push('/');
168        out.push_str(&path[..end]);
169        rest = &path[end..];
170    }
171    out.extend(rest.chars().map(|c| if is_sep(c) { '/' } else { c }));
172    while out.len() > 1 && out.ends_with('/') {
173        out.pop();
174    }
175    out
176}
177
178/// Why there is nothing to build.
179#[derive(Debug, Clone, PartialEq, Eq)]
180pub enum ProjectError {
181    /// The command line is wrong: the caller should say how it goes.
182    /// The text says what was wrong, if anything in particular.
183    Usage(String),
184    /// What was found wrong, a line at a time, in the words the
185    /// reference uses.
186    Failed(Vec<String>),
187}
188
189// ---- paths, as the reference makes them on Windows ----
190
191fn is_sep(c: char) -> bool {
192    c == '/' || c == '\\'
193}
194
195/// The folder part of a path, without its last separator.
196/// The last part of a path: the file's or folder's own name.
197fn file_name_of(path: &str) -> &str {
198    let path = path.trim_end_matches(['/', '\\']);
199    path.rsplit(['/', '\\']).next().unwrap_or(path)
200}
201
202fn path_name(path: &str) -> &str {
203    match path.rfind(|c| is_sep(c) || c == ':') {
204        None => "",
205        Some(at) if path[at..].starts_with(':') => &path[..=at],
206        // The root itself keeps its separator.
207        Some(at) if at == 0 || path[..at].ends_with(':') => &path[..=at],
208        Some(at) => &path[..at],
209    }
210}
211
212/// The name of the file a path is to, without its folders.
213fn root_name(path: &str) -> &str {
214    match path.rfind(|c| is_sep(c) || c == ':') {
215        None => path,
216        Some(at) => &path[at + 1..],
217    }
218}
219
220fn is_absolute(path: &str) -> bool {
221    let mut chars = path.chars();
222    match (chars.next(), chars.next()) {
223        (Some(c), _) if is_sep(c) => true,
224        (Some(c), Some(':')) => c.is_ascii_alphabetic(),
225        _ => false,
226    }
227}
228
229fn build_full_path(dir: &str, file: &str) -> String {
230    if dir.is_empty() {
231        file.to_owned()
232    } else if dir.ends_with(|c| is_sep(c) || c == ':') {
233        format!("{dir}{file}")
234    } else if crate::builtin::is_built_in(dir) {
235        // The built-in files are named the same on every system.
236        format!("{dir}/{file}")
237    } else {
238        format!("{dir}{SEP}{file}")
239    }
240}
241
242/// A path without its file's extension.
243fn rem_ext(path: &str) -> &str {
244    let root = root_name(path);
245    match root.rfind('.') {
246        Some(at) => &path[..path.len() - root.len() + at],
247        None => path,
248    }
249}
250
251/// A path written with `/`, as a library writes them, written with the
252/// system's separator.
253fn cvt_url_dir(url: &str) -> String {
254    url.replace('/', std::path::MAIN_SEPARATOR_STR)
255}
256
257/// Where a module comes from, for the message about two modules with
258/// one name.
259#[derive(Debug, Clone, PartialEq, Eq)]
260enum Origin {
261    /// The command line or the project file.
262    Normal,
263    /// A library: its file.
264    Lib(String),
265}
266
267#[derive(Debug, Clone)]
268struct Module {
269    /// The name the module was given: on the command line or in the
270    /// project file, or in its library.
271    orig_name: String,
272    /// The source file, with `.t` if the name had no extension.
273    source: String,
274    /// The name to look for along the source path if the file is not
275    /// where `source` says.
276    search: String,
277    origin: Origin,
278    /// Its name in its library: the library's own name for it, after
279    /// the names of the libraries it is in (`en_us/en_us/en_us`).
280    url: String,
281    excluded: bool,
282    /// A test (`-test`, a manifest's `tests`): built only for
283    /// debugging.
284    test: bool,
285}
286
287struct Reader<'f, 'a> {
288    files: &'f mut (dyn SourceFiles + 'a),
289    /// The folders to look for sources and libraries in: those `--library-path`
290    /// names, and then the system's.
291    user_source_paths: Vec<String>,
292    sys_source_paths: Vec<String>,
293    /// The system library and its headers.
294    /// The folders for `#include`, in order, but for the system's.
295    include_paths: Vec<String>,
296    /// The macros, as `-D` and `-U` gave them, in order.
297    defs: Vec<(String, Option<String>)>,
298    charset: Option<String>,
299    modules: Vec<Module>,
300    image: Option<String>,
301    /// Built without the system library (`--no-system`).
302    no_system: bool,
303    /// The system library has been named among the libraries.
304    system_included: bool,
305    /// The tags the libraries' manifests list.
306    text_tags: Vec<String>,
307    /// The tags that name objects, and the keys that are objects, that
308    /// the libraries' manifests list.
309    object_tags: Vec<String>,
310    object_keys: Vec<String>,
311    /// The property a game gives its IFID in, as a library's manifest
312    /// names it.
313    ifid: Option<String>,
314    preinit: Option<bool>,
315    debug: bool,
316    warnings: bool,
317    warnings_as_errors: bool,
318    verbose: bool,
319    source_text_group: bool,
320    resources: Vec<ResourceSpec>,
321    /// Whether a folder named after `-res` has its folders bundled too
322    /// (`--recurse`, which is the default, and `--no-recurse`).
323    res_recurse: bool,
324    messages: Vec<String>,
325    lib_err: bool,
326    /// The libraries a Hexicon source can import: each by the name of
327    /// its folder or file, with the header its manifest names, if any.
328    imports: Vec<(String, Option<String>)>,
329    opt_file: Option<String>,
330    /// The folder of the project file, once it has been read: what it
331    /// names is relative to that.
332    opt_file_path: Option<String>,
333    /// What is being read is a manifest's: a source named with no
334    /// extension is a Hexicon source.
335    manifest: bool,
336    /// The libraries' manifests, as they are read.
337    libraries: Vec<String>,
338    /// The manifests being read, each inside the one before: a library
339    /// among them again would be read without end.
340    reading: Vec<String>,
341}
342
343/// Read what to build from the command line of `hexicon build`, and
344/// from the manifest it names.
345pub fn read_project(
346    files: &mut dyn SourceFiles,
347    args: &[String],
348    paths: &ProjectPaths,
349) -> Result<Project, ProjectError> {
350    // The built-in libraries' files are part of the compiler.
351    let mut files = crate::builtin::WithBuiltIns::new(files);
352    let mut reader = Reader {
353        files: &mut files,
354        user_source_paths: Vec::new(),
355        sys_source_paths: paths.user_libraries.clone(),
356        include_paths: Vec::new(),
357        defs: Vec::new(),
358        charset: None,
359        modules: Vec::new(),
360        image: None,
361        no_system: false,
362        system_included: false,
363        text_tags: Vec::new(),
364        object_tags: Vec::new(),
365        object_keys: Vec::new(),
366        ifid: None,
367        preinit: None,
368        debug: false,
369        warnings: true,
370        warnings_as_errors: false,
371        verbose: false,
372        source_text_group: false,
373        resources: Vec::new(),
374        res_recurse: true,
375        messages: Vec::new(),
376        lib_err: false,
377        imports: Vec::new(),
378        opt_file: None,
379        opt_file_path: None,
380        manifest: false,
381        libraries: Vec::new(),
382        reading: Vec::new(),
383    };
384    reader.parse(args)?;
385    // With nothing on the command line, the manifest in the folder.
386    if reader.modules.is_empty() && reader.opt_file.is_none() {
387        if reader.files.exists(MANIFEST) {
388            reader.opt_file = Some(MANIFEST.to_owned());
389        } else {
390            return Err(ProjectError::Usage(String::new()));
391        }
392    }
393    if let Some(opt_file) = reader.opt_file.clone() {
394        // A folder stands for the manifest in it.
395        let in_folder = build_full_path(&opt_file, MANIFEST);
396        let opt_file = if reader.files.exists(&in_folder) {
397            in_folder
398        } else {
399            opt_file
400        };
401        if !is_manifest(&opt_file) {
402            return Err(ProjectError::Failed(vec![format!(
403                "error: \"{opt_file}\" is not a manifest: a game is built from a \
404                 hexicon.toml, or a folder with one"
405            )]));
406        }
407        let Some(text) = reader.files.read(&opt_file) else {
408            return Err(ProjectError::Failed(vec![format!(
409                "error: unable to read manifest \"{opt_file}\""
410            )]));
411        };
412        let args = manifest::game_args(&text).map_err(|problem| {
413            ProjectError::Failed(vec![format!("error: {opt_file}: {problem}")])
414        })?;
415        reader.opt_file_path = Some(path_name(&opt_file).to_owned());
416        reader.manifest = true;
417        reader.parse(&args)?;
418    }
419    if reader.lib_err {
420        return Err(ProjectError::Failed(reader.messages));
421    }
422    reader.finish()
423}
424
425impl Reader<'_, '_> {
426    /// What follows `-res`: files and folders, each as `file` or
427    /// `file=name`, and `--recurse` and `--no-recurse` for the folders
428    /// after them.
429    fn parse_resources(&mut self, args: &[String]) -> Result<(), ProjectError> {
430        for arg in args {
431            match arg.as_str() {
432                "--recurse" => self.res_recurse = true,
433                "--no-recurse" => self.res_recurse = false,
434                _ if arg.starts_with('-') => {
435                    return Err(ProjectError::Usage(format!("unknown option \"{arg}\"")));
436                }
437                _ => {
438                    let (file, alias) = match arg.split_once('=') {
439                        Some((file, alias)) => (file, Some(alias.to_owned())),
440                        None => (arg.as_str(), None),
441                    };
442                    self.resources.push(ResourceSpec {
443                        file: self.relative(file),
444                        alias,
445                        recurse: self.res_recurse,
446                    });
447                }
448            }
449        }
450        Ok(())
451    }
452
453    /// A path the project file gives, made relative to the folder the
454    /// project file is in.
455    fn relative(&self, name: &str) -> String {
456        match &self.opt_file_path {
457            None => name.to_owned(),
458            Some(dir) => {
459                let local = cvt_url_dir(name);
460                if is_absolute(&local) {
461                    local
462                } else {
463                    build_full_path(dir, &local)
464                }
465            }
466        }
467    }
468
469    /// The value of a macro, as a library's `$(NAME)` sees it: the last
470    /// `-D` or `-U` of the name says.
471    fn look_up_pp_sym(&self, name: &str) -> Option<String> {
472        let mut found = None;
473        for (sym, value) in &self.defs {
474            if sym == name {
475                found = value.clone();
476            }
477        }
478        found
479    }
480
481    /// Where a source or a library is: where its name says, if it is
482    /// there, and otherwise along the source path.
483    /// The folders sources and libraries are looked for in, in order:
484    /// those `--library-path` names, the other library folders, the system
485    /// library's, and last those of the libraries built into the
486    /// compiler (the system library's folder, and the folder with each
487    /// library in it).
488    fn search_dirs(&self) -> Vec<String> {
489        self.user_source_paths
490            .iter()
491            .chain(&self.sys_source_paths)
492            .cloned()
493            .chain([
494                crate::builtin::SYSTEM.to_owned(),
495                crate::builtin::ROOT.to_owned(),
496            ])
497            .collect()
498    }
499
500    fn find_source(&mut self, source: &str, search: &str) -> String {
501        if is_absolute(search) || self.files.exists(source) {
502            return source.to_owned();
503        }
504        for dir in self.search_dirs() {
505            let path = build_full_path(&dir, search);
506            if self.files.exists(&path) {
507                return path;
508            }
509        }
510        source.to_owned()
511    }
512
513    fn add_module(
514        &mut self,
515        name: &str,
516        orig_name: &str,
517        search: String,
518        origin: Origin,
519        url: String,
520    ) {
521        self.modules.push(Module {
522            orig_name: orig_name.to_owned(),
523            source: manifest::source_name(name),
524            search,
525            origin,
526            url,
527            excluded: false,
528            test: false,
529        });
530    }
531
532    fn maybe_add_include_path(&mut self, path: &str) {
533        if !self.include_paths.iter().any(|have| have == path) {
534            self.include_paths.push(path.to_owned());
535        }
536    }
537
538    fn parse(&mut self, args: &[String]) -> Result<(), ProjectError> {
539        let mut at = 0;
540        // The value of an option: the rest of the word, or the next one.
541        let opt_arg = |at: &mut usize, len: usize| -> Option<String> {
542            let arg = &args[*at];
543            if arg.len() > len {
544                Some(arg[len..].to_owned())
545            } else if *at + 1 < args.len() {
546                *at += 1;
547                Some(args[*at].clone())
548            } else {
549                None
550            }
551        };
552        let missing = |arg: &str| ProjectError::Usage(format!("option \"{arg}\" needs a value"));
553        let bad = |arg: &str| ProjectError::Usage(format!("unknown option \"{arg}\""));
554        // The value of a long option: after `=`, or the next word.
555        let long_arg = |at: &mut usize, arg: &str| -> Option<String> {
556            match arg.split_once('=') {
557                Some((_, value)) => Some(value.to_owned()),
558                None if *at + 1 < args.len() => {
559                    *at += 1;
560                    Some(args[*at].clone())
561                }
562                None => None,
563            }
564        };
565        while at < args.len() && args[at].starts_with('-') {
566            let arg = args[at].clone();
567            // A long option, with its value after `=` or in the next word.
568            let long = arg.split_once('=').map_or(arg.as_str(), |(name, _)| name);
569            if matches!(long, "--source" | "--test" | "--library" | "--resources") {
570                break;
571            }
572            if long.starts_with("--") {
573                match long {
574                    "--library-path" => {
575                        let path = long_arg(&mut at, &arg).ok_or_else(|| missing(long))?;
576                        let path = self.relative(&path);
577                        self.user_source_paths.push(path);
578                    }
579                    "--charset" => {
580                        self.charset = Some(long_arg(&mut at, &arg).ok_or_else(|| missing(long))?);
581                    }
582                    "--preinit" => self.preinit = Some(true),
583                    "--no-preinit" => self.preinit = Some(false),
584                    "--no-system" => self.no_system = true,
585                    "--warnings" => self.warnings = true,
586                    "--no-warnings" => self.warnings = false,
587                    "--warnings-as-errors" => self.warnings_as_errors = true,
588                    "--source-text-groups" => self.source_text_group = true,
589                    "--help" => return Err(ProjectError::Usage(String::new())),
590                    _ => return Err(bad(&arg)),
591                }
592                at += 1;
593                continue;
594            }
595            // The options every compiler has, a letter each, with the
596            // value in the same word or the next: -f, -o, -I, -D, -U, -d,
597            // and -v.
598            let bytes = arg.as_bytes();
599            match bytes.get(1).copied().unwrap_or(0) {
600                b'f' => {
601                    if self.opt_file.is_some() {
602                        return Err(ProjectError::Failed(vec![
603                            "error: only one option file (-f) is allowed".to_owned(),
604                        ]));
605                    }
606                    self.opt_file = Some(opt_arg(&mut at, 2).ok_or_else(|| missing(&arg))?);
607                }
608                b'D' => {
609                    let def = opt_arg(&mut at, 2).ok_or_else(|| missing(&arg))?;
610                    let (name, value) = def.split_once('=').unwrap_or((&def, ""));
611                    self.defs.push((name.to_owned(), Some(value.to_owned())));
612                }
613                b'U' => {
614                    let name = opt_arg(&mut at, 2).ok_or_else(|| missing(&arg))?;
615                    self.defs.push((name, None));
616                }
617                b'v' if arg == "-v" => self.verbose = true,
618                b'd' if arg == "-d" => self.debug = true,
619                b'I' => {
620                    let path = opt_arg(&mut at, 2).ok_or_else(|| missing(&arg))?;
621                    let path = self.relative(&path);
622                    self.include_paths.push(path);
623                }
624                b'o' => {
625                    let path = opt_arg(&mut at, 2).ok_or_else(|| missing(&arg))?;
626                    self.image = Some(self.relative(&path));
627                }
628                b'?' | b'h' if bytes.len() == 2 => return Err(ProjectError::Usage(String::new())),
629                _ => return Err(bad(&arg)),
630            }
631            at += 1;
632        }
633
634        // The modules: sources and libraries.
635        while at < args.len() {
636            let arg = args[at].clone();
637            let (mut is_source, mut is_lib, mut is_test) = (false, false, false);
638            let name = if arg.starts_with('-') {
639                match arg.as_str() {
640                    "--source" => is_source = true,
641                    "--test" => {
642                        is_source = true;
643                        is_test = true;
644                    }
645                    "--library" => is_lib = true,
646                    "--resources" => {
647                        // The rest are resources.
648                        return self.parse_resources(&args[at + 1..]);
649                    }
650                    _ => return Err(ProjectError::Usage(format!("unknown option \"{arg}\""))),
651                }
652                at += 1;
653                match args.get(at) {
654                    Some(name) => name.clone(),
655                    None => {
656                        return Err(ProjectError::Usage(format!(
657                            "option \"{arg}\" needs a value"
658                        )));
659                    }
660                }
661            } else {
662                arg.clone()
663            };
664            if !is_source && !is_lib && is_manifest(&name) {
665                if self.opt_file.is_some() {
666                    return Err(ProjectError::Failed(vec![
667                        "error: only one option file (-f) is allowed".to_owned(),
668                    ]));
669                }
670                self.opt_file = Some(name);
671                at += 1;
672                continue;
673            }
674            let path = self.relative(&name);
675            if !is_lib {
676                // The first source names the image, if nothing else
677                // has: not a test, which a build may leave out.
678                if self.image.is_none() && !is_test {
679                    self.image = Some(format!("{}.hxg", rem_ext(&path)));
680                }
681                // Named, as a library's sources are, without the
682                // extension.
683                let file = manifest::source_name(&path);
684                let search = manifest::source_name(&name);
685                self.add_module(&file, rem_ext(&name), search, Origin::Normal, String::new());
686                if let Some(module) = self.modules.last_mut() {
687                    module.test = is_test;
688                }
689            } else {
690                let found = self.find_library(&path, &name);
691                let first_lib_module = self.modules.len();
692                self.enter_lib(&found, "");
693                // `--exclude name` after a library leaves one of its
694                // modules out, by its name in the library; `--include
695                // name` adds a source from the library's folder after it,
696                // such as one of its extensions.
697                while let Some(flag @ ("--exclude" | "--include")) =
698                    args.get(at + 1).map(String::as_str)
699                {
700                    at += 2;
701                    let Some(url) = args.get(at) else {
702                        return Err(ProjectError::Usage(format!(
703                            "option \"{flag}\" needs a value"
704                        )));
705                    };
706                    if flag == "--include" {
707                        let lib_path = path_name(&found).to_owned();
708                        let full =
709                            manifest::source_name(&build_full_path(&lib_path, &cvt_url_dir(url)));
710                        let name = rem_ext(url).to_owned();
711                        self.add_module(
712                            &full,
713                            &name,
714                            full.clone(),
715                            Origin::Lib(found.clone()),
716                            name.clone(),
717                        );
718                    } else if let Some(module) = self.modules[first_lib_module..]
719                        .iter_mut()
720                        .find(|module| module.url.eq_ignore_ascii_case(url))
721                    {
722                        module.excluded = true;
723                    }
724                }
725            }
726            at += 1;
727        }
728        Ok(())
729    }
730
731    /// Where the library a project names is: a manifest, if `path` is
732    /// one, or a folder with one, or a manifest of its name with `.toml`
733    /// after it. Each is looked for where its name says, and then along
734    /// the source path.
735    fn find_library(&mut self, path: &str, name: &str) -> String {
736        if is_manifest(path) {
737            return self.find_source(path, name);
738        }
739        // Either kind, where the name says and then in each folder in
740        // turn: the first folder with the library has it.
741        let kinds = |path: &str| [build_full_path(path, MANIFEST), format!("{path}.toml")];
742        for candidate in kinds(path) {
743            if self.files.exists(&candidate) {
744                return candidate;
745            }
746        }
747        let fallback = build_full_path(path, MANIFEST);
748        if is_absolute(name) {
749            return fallback;
750        }
751        for dir in self.search_dirs() {
752            for candidate in kinds(&build_full_path(&dir, name)) {
753                if self.files.exists(&candidate) {
754                    return candidate;
755                }
756            }
757        }
758        fallback
759    }
760
761    /// A library a library is built on, `full`: a manifest, a folder
762    /// with one, or a manifest of its name.
763    fn sub_library(&mut self, full: String) -> String {
764        if is_manifest(&full) {
765            return full;
766        }
767        let beside = format!("{full}.toml");
768        if !self.files.exists(&build_full_path(&full, MANIFEST)) && self.files.exists(&beside) {
769            return beside;
770        }
771        build_full_path(&full, MANIFEST)
772    }
773
774    /// `text` with each `$(NAME)` replaced by the value of the macro and
775    /// each `$$` by a dollar, and what was wrong with it.
776    fn expand_names(&self, text: &str) -> (String, Vec<String>) {
777        const BAD_DOLLAR: &str =
778            "invalid '$' sequence - use '$$' for a literal dollar sign character";
779        let mut problems = Vec::new();
780        let mut expanded = String::new();
781        let mut rest = text;
782        while let Some(at) = rest.find('$') {
783            expanded.push_str(&rest[..at]);
784            let after = &rest[at + 1..];
785            if let Some(inner) = after.strip_prefix('(') {
786                if let Some(close) = inner.find(')') {
787                    let name = &inner[..close];
788                    match self.look_up_pp_sym(name) {
789                        Some(value) => expanded.push_str(&value),
790                        None => problems.push(format!("undefined name \"{name}\"")),
791                    }
792                    rest = &inner[close + 1..];
793                    continue;
794                }
795                problems.push(BAD_DOLLAR.to_owned());
796                expanded.push('$');
797                rest = after;
798            } else if let Some(after) = after.strip_prefix('$') {
799                expanded.push('$');
800                rest = after;
801            } else {
802                problems.push(BAD_DOLLAR.to_owned());
803                expanded.push('$');
804                rest = after;
805            }
806        }
807        expanded.push_str(rest);
808        (expanded, problems)
809    }
810
811    /// A macro a library needs a game to define: if it is not defined,
812    /// say so, and why.
813    fn need_macro(&mut self, place: &str, macro_name: &str, why: &str) {
814        if self.look_up_pp_sym(macro_name).is_none() {
815            let shown = &macro_name[..macro_name.len().min(128)];
816            self.messages.push(format!(
817                "{place}: library requires the macro \"{shown}\" to be \
818                 defined; use -D {shown}=value to define it, or {shown} = \
819                 \"value\" in the manifest's [defines] ({why})"
820            ));
821        }
822    }
823
824    /// Read a library's manifest, unless it is being read already: one
825    /// that leads back to itself is an error, not a build without end.
826    fn enter_lib(&mut self, full_name: &str, lib_url: &str) {
827        let same = |have: &String| {
828            have.replace('\\', "/")
829                .eq_ignore_ascii_case(&full_name.replace('\\', "/"))
830        };
831        if self.reading.iter().any(same) {
832            self.messages.push(format!(
833                "error: library \"{full_name}\" leads back to itself"
834            ));
835            self.lib_err = true;
836            return;
837        }
838        self.reading.push(full_name.to_owned());
839        self.process_lib(full_name, lib_url);
840        self.reading.pop();
841    }
842
843    /// Read a library's manifest, adding its sources to the modules, and
844    /// its libraries' in their places.
845    fn process_lib(&mut self, full_name: &str, lib_url: &str) {
846        let lib_path = path_name(full_name).to_owned();
847        self.maybe_add_include_path(&lib_path);
848        let Some(text) = self.files.read(full_name) else {
849            self.messages
850                .push(format!("unable to open library file \"{full_name}\""));
851            self.lib_err = true;
852            return;
853        };
854        self.libraries.push(full_name.to_owned());
855        let lib = match manifest::library(&text) {
856            Ok(lib) => lib,
857            Err(problem) => {
858                self.messages.push(format!("{full_name}: {problem}"));
859                self.lib_err = true;
860                return;
861            }
862        };
863        // What the library needs a game to define, said first: a name
864        // below made of an undefined macro is what it is about.
865        for (name, why) in &lib.needs {
866            self.need_macro(full_name, name, why);
867        }
868        // What a name in the manifest comes to, and where it is.
869        let place = |reader: &mut Self, value: &str| {
870            let (value, problems) = reader.expand_names(value);
871            for problem in problems {
872                reader.messages.push(format!("{full_name}: {problem}"));
873            }
874            let full = build_full_path(&lib_path, &cvt_url_dir(&value));
875            (value, full)
876        };
877        // Imported by the name of its folder (`hexad/hexicon.toml`) or of
878        // its file (`hexad.toml`).
879        let import_name = if file_name_of(full_name).eq_ignore_ascii_case(MANIFEST) {
880            file_name_of(&lib_path).to_owned()
881        } else {
882            rem_ext(file_name_of(full_name)).to_owned()
883        };
884        let header = lib.header.as_ref().map(|header| place(self, header).1);
885        if import_name.eq_ignore_ascii_case("system") {
886            self.system_included = true;
887        }
888        self.text_tags
889            .extend(lib.text_tags.iter().map(|tag| tag.to_ascii_lowercase()));
890        self.object_tags
891            .extend(lib.object_tags.iter().map(|tag| tag.to_ascii_lowercase()));
892        self.object_keys.extend(lib.object_keys.iter().cloned());
893        if lib.ifid.is_some() {
894            self.ifid.clone_from(&lib.ifid);
895        }
896        self.imports.push((import_name, header));
897        for module in &lib.modules {
898            match module {
899                // A source is named without its extension.
900                manifest::ModuleRef::Source(source) => {
901                    let (value, full) = place(self, source);
902                    let name = rem_ext(&value).to_owned();
903                    let full = manifest::source_name(&full);
904                    let url = format!("{lib_url}{name}");
905                    self.add_module(
906                        &full,
907                        &name,
908                        full.clone(),
909                        Origin::Lib(full_name.to_owned()),
910                        url,
911                    );
912                }
913                manifest::ModuleRef::Library { name, .. } => {
914                    // A name that could not be made (an undefined macro)
915                    // names no library: what is left of it may be this
916                    // library's own folder.
917                    let before = self.messages.len();
918                    let (value, full) = place(self, name);
919                    if self.messages.len() > before || value.trim().is_empty() {
920                        self.lib_err = true;
921                        continue;
922                    }
923                    let url = format!("{lib_url}{value}/");
924                    let target = self.sub_library(full);
925                    self.enter_lib(&target, &url);
926                }
927            }
928        }
929        for resource in &lib.resources {
930            let (value, full) = place(self, resource);
931            self.resources.push(ResourceSpec {
932                file: full,
933                alias: Some(value),
934                recurse: true,
935            });
936        }
937    }
938
939    fn finish(mut self) -> Result<Project, ProjectError> {
940        // The system library comes first, unless the program named it
941        // itself, or said it is built without it. It is found as a
942        // library the program names is, so a folder of --library-path can give one
943        // of its own.
944        if !self.no_system && !self.system_included {
945            let found = self.find_library("system", "system");
946            let first = self.modules.len();
947            self.enter_lib(&found, "");
948            let system: Vec<Module> = self.modules.drain(first..).collect();
949            self.modules.splice(0..0, system);
950        }
951        // No file can be among the sources twice: what it defines would be
952        // defined twice. Two files of one name, in different folders, are
953        // two modules, as a game's `status.hxn` and Hexad's are.
954        let mut problems = Vec::new();
955        let same_file = |a: &str, b: &str| {
956            a.replace('\\', "/")
957                .eq_ignore_ascii_case(&b.replace('\\', "/"))
958        };
959        for (index, module) in self.modules.iter().enumerate() {
960            if module.excluded {
961                continue;
962            }
963            let twice = self.modules[..index]
964                .iter()
965                .any(|earlier| !earlier.excluded && same_file(&earlier.source, &module.source));
966            if twice {
967                let from = match &module.origin {
968                    Origin::Lib(lib) => format!(" (from library \"{lib}\")"),
969                    Origin::Normal => String::new(),
970                };
971                problems.push(format!(
972                    "error: \"{}\"{from} is among the sources twice",
973                    module.source
974                ));
975            }
976        }
977        if !problems.is_empty() {
978            let mut messages = self.messages;
979            messages.extend(problems);
980            return Err(ProjectError::Failed(messages));
981        }
982        // Each module's place in the build counts those left out too.
983        let modules = std::mem::take(&mut self.modules);
984        let mut sources = Vec::new();
985        let mut module_names = Vec::new();
986        let mut from_library = Vec::new();
987        for (index, module) in modules.iter().enumerate() {
988            // A test is built only for debugging.
989            if module.excluded || (module.test && !self.debug) {
990                continue;
991            }
992            let path = self.find_source(&module.source, &module.search);
993            sources.push(path);
994            module_names.push((module.orig_name.clone(), index + 1));
995            from_library.push(!matches!(module.origin, Origin::Normal));
996        }
997        // What the macros come to: the last `-D` or `-U` of a name.
998        let mut defines: Vec<(String, String)> = Vec::new();
999        let mut undefines: Vec<String> = Vec::new();
1000        for (name, value) in &self.defs {
1001            defines.retain(|(have, _)| have != name);
1002            undefines.retain(|have| have != name);
1003            match value {
1004                Some(value) => defines.push((name.clone(), value.clone())),
1005                None => undefines.push(name.clone()),
1006            }
1007        }
1008        let include_paths = self.include_paths;
1009        // The headers built into the compiler need no place here: the
1010        // preprocessor looks there for any it does not find.
1011        Ok(Project {
1012            sources,
1013            options: CompileOptions {
1014                include_paths,
1015                defines,
1016                undefines,
1017                default_charset: self.charset,
1018                source_text_group: self.source_text_group,
1019                module_names,
1020                from_library,
1021                imports: std::mem::take(&mut self.imports),
1022                text_tags: std::mem::take(&mut self.text_tags),
1023                object_tags: std::mem::take(&mut self.object_tags),
1024                object_keys: std::mem::take(&mut self.object_keys),
1025                ifid: self.ifid.take(),
1026                debug: self.debug,
1027                ..CompileOptions::default()
1028            },
1029            image: self.image,
1030            preinit: self.preinit.unwrap_or(!self.debug),
1031            warnings: self.warnings,
1032            warnings_as_errors: self.warnings_as_errors,
1033            verbose: self.verbose,
1034            debug: self.debug,
1035            resources: self.resources,
1036            messages: self.messages,
1037            manifest: self.manifest,
1038            libraries: self.libraries,
1039        })
1040    }
1041}