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 manifest = 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        // The manifest's options, then the command line's again, so that
418        // what the command line says (-o, -D, --no-warnings, ...) wins:
419        // before the manifest's modules, whose libraries may look a
420        // macro up, as Hexad does $(LANGUAGE).
421        let (options, modules) = manifest.args.split_at(manifest.modules_at);
422        reader.parse(options)?;
423        let in_manifest = reader.opt_file_path.take();
424        reader.parse(&command_line_options(args))?;
425        reader.opt_file_path = in_manifest;
426        reader.parse(modules)?;
427    }
428    if reader.lib_err {
429        return Err(ProjectError::Failed(reader.messages));
430    }
431    reader.finish()
432}
433
434/// The options at the start of a command line, as `Reader::parse` reads
435/// them, but for `-f`, which names the manifest.
436fn command_line_options(args: &[String]) -> Vec<String> {
437    let mut out = Vec::new();
438    let mut at = 0;
439    while at < args.len() && args[at].starts_with('-') {
440        let arg = &args[at];
441        let long = arg.split_once('=').map_or(arg.as_str(), |(name, _)| name);
442        if matches!(long, "--source" | "--test" | "--library" | "--resources") {
443            break;
444        }
445        // How many words the option is: two where its value is the next.
446        let words = match long {
447            "--library-path" | "--charset" if !arg.contains('=') => 2,
448            _ if long.starts_with("--") => 1,
449            _ if matches!(arg.as_str(), "-f" | "-o" | "-I" | "-D" | "-U") => 2,
450            _ => 1,
451        };
452        let end = (at + words).min(args.len());
453        if !arg.starts_with("-f") {
454            out.extend(args[at..end].iter().cloned());
455        }
456        at = end;
457    }
458    out
459}
460
461impl Reader<'_, '_> {
462    /// What follows `-res`: files and folders, each as `file` or
463    /// `file=name`, and `--recurse` and `--no-recurse` for the folders
464    /// after them.
465    fn parse_resources(&mut self, args: &[String]) -> Result<(), ProjectError> {
466        for arg in args {
467            match arg.as_str() {
468                "--recurse" => self.res_recurse = true,
469                "--no-recurse" => self.res_recurse = false,
470                _ if arg.starts_with('-') => {
471                    return Err(ProjectError::Usage(format!("unknown option \"{arg}\"")));
472                }
473                _ => {
474                    let (file, alias) = match arg.split_once('=') {
475                        Some((file, alias)) => (file, Some(alias.to_owned())),
476                        None => (arg.as_str(), None),
477                    };
478                    self.resources.push(ResourceSpec {
479                        file: self.relative(file),
480                        alias,
481                        recurse: self.res_recurse,
482                    });
483                }
484            }
485        }
486        Ok(())
487    }
488
489    /// A path the project file gives, made relative to the folder the
490    /// project file is in.
491    fn relative(&self, name: &str) -> String {
492        match &self.opt_file_path {
493            None => name.to_owned(),
494            Some(dir) => {
495                let local = cvt_url_dir(name);
496                if is_absolute(&local) {
497                    local
498                } else {
499                    build_full_path(dir, &local)
500                }
501            }
502        }
503    }
504
505    /// The value of a macro, as a library's `$(NAME)` sees it: the last
506    /// `-D` or `-U` of the name says.
507    fn look_up_pp_sym(&self, name: &str) -> Option<String> {
508        let mut found = None;
509        for (sym, value) in &self.defs {
510            if sym == name {
511                found = value.clone();
512            }
513        }
514        found
515    }
516
517    /// Where a source or a library is: where its name says, if it is
518    /// there, and otherwise along the source path.
519    /// The folders sources and libraries are looked for in, in order:
520    /// those `--library-path` names, the other library folders, the system
521    /// library's, and last those of the libraries built into the
522    /// compiler (the system library's folder, and the folder with each
523    /// library in it).
524    fn search_dirs(&self) -> Vec<String> {
525        self.user_source_paths
526            .iter()
527            .chain(&self.sys_source_paths)
528            .cloned()
529            .chain([
530                crate::builtin::SYSTEM.to_owned(),
531                crate::builtin::ROOT.to_owned(),
532            ])
533            .collect()
534    }
535
536    fn find_source(&mut self, source: &str, search: &str) -> String {
537        if is_absolute(search) || self.files.exists(source) {
538            return source.to_owned();
539        }
540        for dir in self.search_dirs() {
541            let path = build_full_path(&dir, search);
542            if self.files.exists(&path) {
543                return path;
544            }
545        }
546        source.to_owned()
547    }
548
549    fn add_module(
550        &mut self,
551        name: &str,
552        orig_name: &str,
553        search: String,
554        origin: Origin,
555        url: String,
556    ) {
557        self.modules.push(Module {
558            orig_name: orig_name.to_owned(),
559            source: manifest::source_name(name),
560            search,
561            origin,
562            url,
563            excluded: false,
564            test: false,
565        });
566    }
567
568    fn maybe_add_include_path(&mut self, path: &str) {
569        if !self.include_paths.iter().any(|have| have == path) {
570            self.include_paths.push(path.to_owned());
571        }
572    }
573
574    fn parse(&mut self, args: &[String]) -> Result<(), ProjectError> {
575        let mut at = 0;
576        // The value of an option: the rest of the word, or the next one.
577        let opt_arg = |at: &mut usize, len: usize| -> Option<String> {
578            let arg = &args[*at];
579            if arg.len() > len {
580                Some(arg[len..].to_owned())
581            } else if *at + 1 < args.len() {
582                *at += 1;
583                Some(args[*at].clone())
584            } else {
585                None
586            }
587        };
588        let missing = |arg: &str| ProjectError::Usage(format!("option \"{arg}\" needs a value"));
589        let bad = |arg: &str| ProjectError::Usage(format!("unknown option \"{arg}\""));
590        // The value of a long option: after `=`, or the next word.
591        let long_arg = |at: &mut usize, arg: &str| -> Option<String> {
592            match arg.split_once('=') {
593                Some((_, value)) => Some(value.to_owned()),
594                None if *at + 1 < args.len() => {
595                    *at += 1;
596                    Some(args[*at].clone())
597                }
598                None => None,
599            }
600        };
601        while at < args.len() && args[at].starts_with('-') {
602            let arg = args[at].clone();
603            // A long option, with its value after `=` or in the next word.
604            let long = arg.split_once('=').map_or(arg.as_str(), |(name, _)| name);
605            if matches!(long, "--source" | "--test" | "--library" | "--resources") {
606                break;
607            }
608            if long.starts_with("--") {
609                match long {
610                    "--library-path" => {
611                        let path = long_arg(&mut at, &arg).ok_or_else(|| missing(long))?;
612                        let path = self.relative(&path);
613                        self.user_source_paths.push(path);
614                    }
615                    "--charset" => {
616                        self.charset = Some(long_arg(&mut at, &arg).ok_or_else(|| missing(long))?);
617                    }
618                    "--preinit" => self.preinit = Some(true),
619                    "--no-preinit" => self.preinit = Some(false),
620                    "--no-system" => self.no_system = true,
621                    "--warnings" => self.warnings = true,
622                    "--no-warnings" => self.warnings = false,
623                    "--warnings-as-errors" => self.warnings_as_errors = true,
624                    "--source-text-groups" => self.source_text_group = true,
625                    "--help" => return Err(ProjectError::Usage(String::new())),
626                    _ => return Err(bad(&arg)),
627                }
628                at += 1;
629                continue;
630            }
631            // The options every compiler has, a letter each, with the
632            // value in the same word or the next: -f, -o, -I, -D, -U, -d,
633            // and -v.
634            let bytes = arg.as_bytes();
635            match bytes.get(1).copied().unwrap_or(0) {
636                b'f' => {
637                    if self.opt_file.is_some() {
638                        return Err(ProjectError::Failed(vec![
639                            "error: only one option file (-f) is allowed".to_owned(),
640                        ]));
641                    }
642                    self.opt_file = Some(opt_arg(&mut at, 2).ok_or_else(|| missing(&arg))?);
643                }
644                b'D' => {
645                    let def = opt_arg(&mut at, 2).ok_or_else(|| missing(&arg))?;
646                    let (name, value) = def.split_once('=').unwrap_or((&def, ""));
647                    self.defs.push((name.to_owned(), Some(value.to_owned())));
648                }
649                b'U' => {
650                    let name = opt_arg(&mut at, 2).ok_or_else(|| missing(&arg))?;
651                    self.defs.push((name, None));
652                }
653                b'v' if arg == "-v" => self.verbose = true,
654                b'd' if arg == "-d" => self.debug = true,
655                b'I' => {
656                    let path = opt_arg(&mut at, 2).ok_or_else(|| missing(&arg))?;
657                    let path = self.relative(&path);
658                    self.include_paths.push(path);
659                }
660                b'o' => {
661                    let path = opt_arg(&mut at, 2).ok_or_else(|| missing(&arg))?;
662                    self.image = Some(self.relative(&path));
663                }
664                b'?' | b'h' if bytes.len() == 2 => return Err(ProjectError::Usage(String::new())),
665                _ => return Err(bad(&arg)),
666            }
667            at += 1;
668        }
669
670        // The modules: sources and libraries.
671        while at < args.len() {
672            let arg = args[at].clone();
673            let (mut is_source, mut is_lib, mut is_test) = (false, false, false);
674            let name = if arg.starts_with('-') {
675                match arg.as_str() {
676                    "--source" => is_source = true,
677                    "--test" => {
678                        is_source = true;
679                        is_test = true;
680                    }
681                    "--library" => is_lib = true,
682                    "--resources" => {
683                        // The rest are resources.
684                        return self.parse_resources(&args[at + 1..]);
685                    }
686                    _ => return Err(ProjectError::Usage(format!("unknown option \"{arg}\""))),
687                }
688                at += 1;
689                match args.get(at) {
690                    Some(name) => name.clone(),
691                    None => {
692                        return Err(ProjectError::Usage(format!(
693                            "option \"{arg}\" needs a value"
694                        )));
695                    }
696                }
697            } else {
698                arg.clone()
699            };
700            if !is_source && !is_lib && is_manifest(&name) {
701                if self.opt_file.is_some() {
702                    return Err(ProjectError::Failed(vec![
703                        "error: only one option file (-f) is allowed".to_owned(),
704                    ]));
705                }
706                self.opt_file = Some(name);
707                at += 1;
708                continue;
709            }
710            let path = self.relative(&name);
711            if !is_lib {
712                // The first source names the image, if nothing else
713                // has: not a test, which a build may leave out.
714                if self.image.is_none() && !is_test {
715                    self.image = Some(format!("{}.hxg", rem_ext(&path)));
716                }
717                // Named, as a library's sources are, without the
718                // extension.
719                let file = manifest::source_name(&path);
720                let search = manifest::source_name(&name);
721                self.add_module(&file, rem_ext(&name), search, Origin::Normal, String::new());
722                if let Some(module) = self.modules.last_mut() {
723                    module.test = is_test;
724                }
725            } else {
726                let found = self.find_library(&path, &name);
727                let first_lib_module = self.modules.len();
728                self.enter_lib(&found, "");
729                // `--exclude name` after a library leaves one of its
730                // modules out, by its name in the library; `--include
731                // name` adds a source from the library's folder after it,
732                // such as one of its extensions.
733                while let Some(flag @ ("--exclude" | "--include")) =
734                    args.get(at + 1).map(String::as_str)
735                {
736                    at += 2;
737                    let Some(url) = args.get(at) else {
738                        return Err(ProjectError::Usage(format!(
739                            "option \"{flag}\" needs a value"
740                        )));
741                    };
742                    if flag == "--include" {
743                        let lib_path = path_name(&found).to_owned();
744                        let full =
745                            manifest::source_name(&build_full_path(&lib_path, &cvt_url_dir(url)));
746                        let name = rem_ext(url).to_owned();
747                        self.add_module(
748                            &full,
749                            &name,
750                            full.clone(),
751                            Origin::Lib(found.clone()),
752                            name.clone(),
753                        );
754                    } else if let Some(module) = self.modules[first_lib_module..]
755                        .iter_mut()
756                        .find(|module| module.url.eq_ignore_ascii_case(url))
757                    {
758                        module.excluded = true;
759                    }
760                }
761            }
762            at += 1;
763        }
764        Ok(())
765    }
766
767    /// Where the library a project names is: a manifest, if `path` is
768    /// one, or a folder with one, or a manifest of its name with `.toml`
769    /// after it. Each is looked for where its name says, and then along
770    /// the source path.
771    fn find_library(&mut self, path: &str, name: &str) -> String {
772        if is_manifest(path) {
773            return self.find_source(path, name);
774        }
775        // Either kind, where the name says and then in each folder in
776        // turn: the first folder with the library has it.
777        let kinds = |path: &str| [build_full_path(path, MANIFEST), format!("{path}.toml")];
778        for candidate in kinds(path) {
779            if self.files.exists(&candidate) {
780                return candidate;
781            }
782        }
783        let fallback = build_full_path(path, MANIFEST);
784        if is_absolute(name) {
785            return fallback;
786        }
787        for dir in self.search_dirs() {
788            for candidate in kinds(&build_full_path(&dir, name)) {
789                if self.files.exists(&candidate) {
790                    return candidate;
791                }
792            }
793        }
794        fallback
795    }
796
797    /// A library a library is built on, `full`: a manifest, a folder
798    /// with one, or a manifest of its name.
799    fn sub_library(&mut self, full: String) -> String {
800        if is_manifest(&full) {
801            return full;
802        }
803        let beside = format!("{full}.toml");
804        if !self.files.exists(&build_full_path(&full, MANIFEST)) && self.files.exists(&beside) {
805            return beside;
806        }
807        build_full_path(&full, MANIFEST)
808    }
809
810    /// `text` with each `$(NAME)` replaced by the value of the macro and
811    /// each `$$` by a dollar, and what was wrong with it.
812    fn expand_names(&self, text: &str) -> (String, Vec<String>) {
813        const BAD_DOLLAR: &str =
814            "invalid '$' sequence - use '$$' for a literal dollar sign character";
815        let mut problems = Vec::new();
816        let mut expanded = String::new();
817        let mut rest = text;
818        while let Some(at) = rest.find('$') {
819            expanded.push_str(&rest[..at]);
820            let after = &rest[at + 1..];
821            if let Some(inner) = after.strip_prefix('(') {
822                if let Some(close) = inner.find(')') {
823                    let name = &inner[..close];
824                    match self.look_up_pp_sym(name) {
825                        Some(value) => expanded.push_str(&value),
826                        None => problems.push(format!("undefined name \"{name}\"")),
827                    }
828                    rest = &inner[close + 1..];
829                    continue;
830                }
831                problems.push(BAD_DOLLAR.to_owned());
832                expanded.push('$');
833                rest = after;
834            } else if let Some(after) = after.strip_prefix('$') {
835                expanded.push('$');
836                rest = after;
837            } else {
838                problems.push(BAD_DOLLAR.to_owned());
839                expanded.push('$');
840                rest = after;
841            }
842        }
843        expanded.push_str(rest);
844        (expanded, problems)
845    }
846
847    /// A macro a library needs a game to define: if it is not defined,
848    /// say so, and why.
849    fn need_macro(&mut self, place: &str, macro_name: &str, why: &str) {
850        if self.look_up_pp_sym(macro_name).is_none() {
851            let shown = &macro_name[..macro_name.len().min(128)];
852            self.messages.push(format!(
853                "{place}: library requires the macro \"{shown}\" to be \
854                 defined; use -D {shown}=value to define it, or {shown} = \
855                 \"value\" in the manifest's [defines] ({why})"
856            ));
857        }
858    }
859
860    /// Read a library's manifest, unless it is being read already: one
861    /// that leads back to itself is an error, not a build without end.
862    fn enter_lib(&mut self, full_name: &str, lib_url: &str) {
863        let same = |have: &String| {
864            have.replace('\\', "/")
865                .eq_ignore_ascii_case(&full_name.replace('\\', "/"))
866        };
867        if self.reading.iter().any(same) {
868            self.messages.push(format!(
869                "error: library \"{full_name}\" leads back to itself"
870            ));
871            self.lib_err = true;
872            return;
873        }
874        self.reading.push(full_name.to_owned());
875        self.process_lib(full_name, lib_url);
876        self.reading.pop();
877    }
878
879    /// Read a library's manifest, adding its sources to the modules, and
880    /// its libraries' in their places.
881    fn process_lib(&mut self, full_name: &str, lib_url: &str) {
882        let lib_path = path_name(full_name).to_owned();
883        self.maybe_add_include_path(&lib_path);
884        let Some(text) = self.files.read(full_name) else {
885            self.messages
886                .push(format!("unable to open library file \"{full_name}\""));
887            self.lib_err = true;
888            return;
889        };
890        self.libraries.push(full_name.to_owned());
891        let lib = match manifest::library(&text) {
892            Ok(lib) => lib,
893            Err(problem) => {
894                self.messages.push(format!("{full_name}: {problem}"));
895                self.lib_err = true;
896                return;
897            }
898        };
899        // What the library needs a game to define, said first: a name
900        // below made of an undefined macro is what it is about.
901        for (name, why) in &lib.needs {
902            self.need_macro(full_name, name, why);
903        }
904        // What a name in the manifest comes to, and where it is.
905        let place = |reader: &mut Self, value: &str| {
906            let (value, problems) = reader.expand_names(value);
907            for problem in problems {
908                reader.messages.push(format!("{full_name}: {problem}"));
909            }
910            let full = build_full_path(&lib_path, &cvt_url_dir(&value));
911            (value, full)
912        };
913        // Imported by the name of its folder (`hexad/hexicon.toml`) or of
914        // its file (`hexad.toml`).
915        let import_name = if file_name_of(full_name).eq_ignore_ascii_case(MANIFEST) {
916            file_name_of(&lib_path).to_owned()
917        } else {
918            rem_ext(file_name_of(full_name)).to_owned()
919        };
920        let header = lib.header.as_ref().map(|header| place(self, header).1);
921        if import_name.eq_ignore_ascii_case("system") {
922            self.system_included = true;
923        }
924        self.text_tags
925            .extend(lib.text_tags.iter().map(|tag| tag.to_ascii_lowercase()));
926        self.object_tags
927            .extend(lib.object_tags.iter().map(|tag| tag.to_ascii_lowercase()));
928        self.object_keys.extend(lib.object_keys.iter().cloned());
929        if lib.ifid.is_some() {
930            self.ifid.clone_from(&lib.ifid);
931        }
932        self.imports.push((import_name, header));
933        for module in &lib.modules {
934            match module {
935                // A source is named without its extension.
936                manifest::ModuleRef::Source(source) => {
937                    let (value, full) = place(self, source);
938                    let name = rem_ext(&value).to_owned();
939                    let full = manifest::source_name(&full);
940                    let url = format!("{lib_url}{name}");
941                    self.add_module(
942                        &full,
943                        &name,
944                        full.clone(),
945                        Origin::Lib(full_name.to_owned()),
946                        url,
947                    );
948                }
949                manifest::ModuleRef::Library { name, .. } => {
950                    // A name that could not be made (an undefined macro)
951                    // names no library: what is left of it may be this
952                    // library's own folder.
953                    let before = self.messages.len();
954                    let (value, full) = place(self, name);
955                    if self.messages.len() > before || value.trim().is_empty() {
956                        self.lib_err = true;
957                        continue;
958                    }
959                    let url = format!("{lib_url}{value}/");
960                    let target = self.sub_library(full);
961                    self.enter_lib(&target, &url);
962                }
963            }
964        }
965        for resource in &lib.resources {
966            let (value, full) = place(self, resource);
967            self.resources.push(ResourceSpec {
968                file: full,
969                alias: Some(value),
970                recurse: true,
971            });
972        }
973    }
974
975    fn finish(mut self) -> Result<Project, ProjectError> {
976        // The system library comes first, unless the program named it
977        // itself, or said it is built without it. It is found as a
978        // library the program names is, so a folder of --library-path can give one
979        // of its own.
980        if !self.no_system && !self.system_included {
981            let found = self.find_library("system", "system");
982            let first = self.modules.len();
983            self.enter_lib(&found, "");
984            let system: Vec<Module> = self.modules.drain(first..).collect();
985            self.modules.splice(0..0, system);
986        }
987        // No file can be among the sources twice: what it defines would be
988        // defined twice. Two files of one name, in different folders, are
989        // two modules, as a game's `status.hxn` and Hexad's are.
990        let mut problems = Vec::new();
991        let same_file = |a: &str, b: &str| {
992            a.replace('\\', "/")
993                .eq_ignore_ascii_case(&b.replace('\\', "/"))
994        };
995        for (index, module) in self.modules.iter().enumerate() {
996            if module.excluded {
997                continue;
998            }
999            let twice = self.modules[..index]
1000                .iter()
1001                .any(|earlier| !earlier.excluded && same_file(&earlier.source, &module.source));
1002            if twice {
1003                let from = match &module.origin {
1004                    Origin::Lib(lib) => format!(" (from library \"{lib}\")"),
1005                    Origin::Normal => String::new(),
1006                };
1007                problems.push(format!(
1008                    "error: \"{}\"{from} is among the sources twice",
1009                    module.source
1010                ));
1011            }
1012        }
1013        if !problems.is_empty() {
1014            let mut messages = self.messages;
1015            messages.extend(problems);
1016            return Err(ProjectError::Failed(messages));
1017        }
1018        // Each module's place in the build counts those left out too.
1019        let modules = std::mem::take(&mut self.modules);
1020        let mut sources = Vec::new();
1021        let mut module_names = Vec::new();
1022        let mut from_library = Vec::new();
1023        for (index, module) in modules.iter().enumerate() {
1024            // A test is built only for debugging.
1025            if module.excluded || (module.test && !self.debug) {
1026                continue;
1027            }
1028            let path = self.find_source(&module.source, &module.search);
1029            sources.push(path);
1030            module_names.push((module.orig_name.clone(), index + 1));
1031            from_library.push(!matches!(module.origin, Origin::Normal));
1032        }
1033        // What the macros come to: the last `-D` or `-U` of a name.
1034        let mut defines: Vec<(String, String)> = Vec::new();
1035        let mut undefines: Vec<String> = Vec::new();
1036        for (name, value) in &self.defs {
1037            defines.retain(|(have, _)| have != name);
1038            undefines.retain(|have| have != name);
1039            match value {
1040                Some(value) => defines.push((name.clone(), value.clone())),
1041                None => undefines.push(name.clone()),
1042            }
1043        }
1044        let include_paths = self.include_paths;
1045        // The headers built into the compiler need no place here: the
1046        // preprocessor looks there for any it does not find.
1047        Ok(Project {
1048            sources,
1049            options: CompileOptions {
1050                include_paths,
1051                defines,
1052                undefines,
1053                default_charset: self.charset,
1054                source_text_group: self.source_text_group,
1055                module_names,
1056                from_library,
1057                imports: std::mem::take(&mut self.imports),
1058                text_tags: std::mem::take(&mut self.text_tags),
1059                object_tags: std::mem::take(&mut self.object_tags),
1060                object_keys: std::mem::take(&mut self.object_keys),
1061                ifid: self.ifid.take(),
1062                debug: self.debug,
1063                ..CompileOptions::default()
1064            },
1065            image: self.image,
1066            preinit: self.preinit.unwrap_or(!self.debug),
1067            warnings: self.warnings,
1068            warnings_as_errors: self.warnings_as_errors,
1069            verbose: self.verbose,
1070            debug: self.debug,
1071            resources: self.resources,
1072            messages: self.messages,
1073            manifest: self.manifest,
1074            libraries: self.libraries,
1075        })
1076    }
1077}