hexicon-compiler 0.3.0

The Hexicon compiler: source text to a program image
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
//! What to build: the options and the source files of a program, from
//! the command line and from a manifest (`hexicon.toml`, read by
//! [`crate::manifest`] as more of the command line). A library is a
//! folder with a manifest, or a `.toml` manifest of its name. Every
//! program is built on the system library, first, whether it names it or
//! not, unless told otherwise (`--no-system`, or `system = false` in a
//! manifest's `[build]`).
//!
//! Files are found and read through [`SourceFiles`], like everything
//! else the compiler reads.

use crate::compile::CompileOptions;
use crate::manifest::{self, MANIFEST, is_manifest};
use crate::pp::SourceFiles;

/// The separator of the folders in a path, as paths are made here.
const SEP: char = std::path::MAIN_SEPARATOR;

/// Where libraries are looked for, besides the folders `--library-path` names and
/// the libraries built into the compiler.
#[derive(Debug, Clone, Default)]
pub struct ProjectPaths {
    /// More folders to look for libraries and sources in, after any
    /// `--library-path` names and before the system library.
    pub user_libraries: Vec<String>,
}

/// A program to build.
#[derive(Debug, Clone, Default)]
pub struct Project {
    /// The source files, in the order they are put together.
    pub sources: Vec<String>,
    /// How to compile them. The time stamp is the caller's to set.
    pub options: CompileOptions,
    /// Where to write the image, if anything said.
    pub image: Option<String>,
    /// The program is to be run once before the image is written
    /// (preinitialization): `--preinit`, or by default unless `-d`.
    pub preinit: bool,
    /// Warnings are reported (`-w0` says not).
    pub warnings: bool,
    /// A warning stops the build (`-we`).
    pub warnings_as_errors: bool,
    /// Say what is being done (`-v`).
    pub verbose: bool,
    /// The program is built for debugging (`-d`): its resources are
    /// linked to their files rather than copied into the image.
    pub debug: bool,
    /// The files to bundle into the image as resources, in order: those
    /// the libraries name, then those after `-res`.
    pub resources: Vec<ResourceSpec>,
    /// What was said about the project that does not stop the build,
    /// in the words the reference uses: problems with libraries.
    pub messages: Vec<String>,
    /// It was read from a manifest (`hexicon.toml`), and not from the
    /// command line alone.
    pub manifest: bool,
    /// The manifests of the libraries it is built with, in the order they
    /// were read: those the project names first, each before the libraries
    /// it is built on, and the system library last.
    pub libraries: Vec<String>,
}

/// A file or a folder to bundle as resources.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResourceSpec {
    /// The file or folder.
    pub file: String,
    /// The name to give it in the image (`file=alias`), if not the
    /// file's own path written as a URL.
    pub alias: Option<String>,
    /// For a folder, whether the folders in it are bundled too.
    pub recurse: bool,
}

/// A file bundled as a resource, and its name in the image.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Resource {
    /// The file.
    pub file: String,
    /// The name the program asks for it by.
    pub name: String,
}

/// What is in a folder, as [`expand_resources`] is told it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirEntry {
    /// The file's name, without the folder's.
    pub name: String,
    /// It is a folder.
    pub is_dir: bool,
    /// Hidden, or belonging to the system: such files are left out.
    pub hidden: bool,
}

/// The files the resources name, each folder replaced by the files in
/// it, in the order the system lists them, as the reference does. A
/// file in a folder is named by the folder's name, a `/`, and its own.
/// `list_dir` gives what is in a folder, or nothing for a path that is
/// not one.
pub fn expand_resources(
    specs: &[ResourceSpec],
    list_dir: &mut dyn FnMut(&str) -> Option<Vec<DirEntry>>,
) -> Vec<Resource> {
    fn add(
        file: &str,
        name: &str,
        recurse: bool,
        list_dir: &mut dyn FnMut(&str) -> Option<Vec<DirEntry>>,
        out: &mut Vec<Resource>,
    ) {
        let Some(entries) = list_dir(file) else {
            out.push(Resource {
                file: file.to_owned(),
                name: name.to_owned(),
            });
            return;
        };
        for entry in entries {
            if entry.hidden || entry.name == "." || entry.name == ".." {
                continue;
            }
            let full = build_full_path(file, &entry.name);
            let mut full_name = name.to_owned();
            if !full_name.is_empty() && !full_name.ends_with('/') {
                full_name.push('/');
            }
            full_name.push_str(&entry.name);
            if !entry.is_dir {
                out.push(Resource {
                    file: full,
                    name: full_name,
                });
            } else if recurse {
                add(&full, &full_name, true, list_dir, out);
            }
        }
    }
    let mut out = Vec::new();
    for spec in specs {
        let name = spec
            .alias
            .clone()
            .unwrap_or_else(|| cvt_dir_url(&spec.file));
        add(&spec.file, &name, spec.recurse, list_dir, &mut out);
    }
    out
}

/// A path written as a relative URL, as the reference writes it on
/// Windows: with `/` between folders, a drive as `/C:`, and no `/` at
/// the end.
fn cvt_dir_url(path: &str) -> String {
    let mut out = String::new();
    let bytes = path.as_bytes();
    let mut rest = path;
    if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' {
        out.push('/');
        out.push_str(&path[..2]);
        rest = &path[2..];
        if !rest.starts_with(is_sep) {
            out.push_str("./");
        }
    } else if bytes.len() >= 2 && is_sep(bytes[0] as char) && is_sep(bytes[1] as char) {
        // A UNC path: the machine's name stays as it is, after a `/`.
        let end = path[2..].find(is_sep).map_or(path.len(), |at| at + 2);
        out.push('/');
        out.push_str(&path[..end]);
        rest = &path[end..];
    }
    out.extend(rest.chars().map(|c| if is_sep(c) { '/' } else { c }));
    while out.len() > 1 && out.ends_with('/') {
        out.pop();
    }
    out
}

/// Why there is nothing to build.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProjectError {
    /// The command line is wrong: the caller should say how it goes.
    /// The text says what was wrong, if anything in particular.
    Usage(String),
    /// What was found wrong, a line at a time, in the words the
    /// reference uses.
    Failed(Vec<String>),
}

// ---- paths, as the reference makes them on Windows ----

fn is_sep(c: char) -> bool {
    c == '/' || c == '\\'
}

/// The folder part of a path, without its last separator.
/// The last part of a path: the file's or folder's own name.
fn file_name_of(path: &str) -> &str {
    let path = path.trim_end_matches(['/', '\\']);
    path.rsplit(['/', '\\']).next().unwrap_or(path)
}

fn path_name(path: &str) -> &str {
    match path.rfind(|c| is_sep(c) || c == ':') {
        None => "",
        Some(at) if path[at..].starts_with(':') => &path[..=at],
        // The root itself keeps its separator.
        Some(at) if at == 0 || path[..at].ends_with(':') => &path[..=at],
        Some(at) => &path[..at],
    }
}

/// The name of the file a path is to, without its folders.
fn root_name(path: &str) -> &str {
    match path.rfind(|c| is_sep(c) || c == ':') {
        None => path,
        Some(at) => &path[at + 1..],
    }
}

fn is_absolute(path: &str) -> bool {
    let mut chars = path.chars();
    match (chars.next(), chars.next()) {
        (Some(c), _) if is_sep(c) => true,
        (Some(c), Some(':')) => c.is_ascii_alphabetic(),
        _ => false,
    }
}

fn build_full_path(dir: &str, file: &str) -> String {
    if dir.is_empty() {
        file.to_owned()
    } else if dir.ends_with(|c| is_sep(c) || c == ':') {
        format!("{dir}{file}")
    } else if crate::builtin::is_built_in(dir) {
        // The built-in files are named the same on every system.
        format!("{dir}/{file}")
    } else {
        format!("{dir}{SEP}{file}")
    }
}

/// A path without its file's extension.
fn rem_ext(path: &str) -> &str {
    let root = root_name(path);
    match root.rfind('.') {
        Some(at) => &path[..path.len() - root.len() + at],
        None => path,
    }
}

/// A path written with `/`, as a library writes them, written with the
/// system's separator.
fn cvt_url_dir(url: &str) -> String {
    url.replace('/', std::path::MAIN_SEPARATOR_STR)
}

/// Where a module comes from, for the message about two modules with
/// one name.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Origin {
    /// The command line or the project file.
    Normal,
    /// A library: its file.
    Lib(String),
}

#[derive(Debug, Clone)]
struct Module {
    /// The name the module was given: on the command line or in the
    /// project file, or in its library.
    orig_name: String,
    /// The source file, with `.t` if the name had no extension.
    source: String,
    /// The name to look for along the source path if the file is not
    /// where `source` says.
    search: String,
    origin: Origin,
    /// Its name in its library: the library's own name for it, after
    /// the names of the libraries it is in (`en_us/en_us/en_us`).
    url: String,
    excluded: bool,
    /// A test (`-test`, a manifest's `tests`): built only for
    /// debugging.
    test: bool,
}

struct Reader<'f, 'a> {
    files: &'f mut (dyn SourceFiles + 'a),
    /// The folders to look for sources and libraries in: those `--library-path`
    /// names, and then the system's.
    user_source_paths: Vec<String>,
    sys_source_paths: Vec<String>,
    /// The system library and its headers.
    /// The folders for `#include`, in order, but for the system's.
    include_paths: Vec<String>,
    /// The macros, as `-D` and `-U` gave them, in order.
    defs: Vec<(String, Option<String>)>,
    charset: Option<String>,
    modules: Vec<Module>,
    image: Option<String>,
    /// Built without the system library (`--no-system`).
    no_system: bool,
    /// The system library has been named among the libraries.
    system_included: bool,
    /// The tags the libraries' manifests list.
    text_tags: Vec<String>,
    /// The tags that name objects, and the keys that are objects, that
    /// the libraries' manifests list.
    object_tags: Vec<String>,
    object_keys: Vec<String>,
    /// The property a game gives its IFID in, as a library's manifest
    /// names it.
    ifid: Option<String>,
    preinit: Option<bool>,
    debug: bool,
    warnings: bool,
    warnings_as_errors: bool,
    verbose: bool,
    source_text_group: bool,
    resources: Vec<ResourceSpec>,
    /// Whether a folder named after `-res` has its folders bundled too
    /// (`--recurse`, which is the default, and `--no-recurse`).
    res_recurse: bool,
    messages: Vec<String>,
    lib_err: bool,
    /// The libraries a Hexicon source can import: each by the name of
    /// its folder or file, with the header its manifest names, if any.
    imports: Vec<(String, Option<String>)>,
    opt_file: Option<String>,
    /// The folder of the project file, once it has been read: what it
    /// names is relative to that.
    opt_file_path: Option<String>,
    /// What is being read is a manifest's: a source named with no
    /// extension is a Hexicon source.
    manifest: bool,
    /// The libraries' manifests, as they are read.
    libraries: Vec<String>,
    /// The manifests being read, each inside the one before: a library
    /// among them again would be read without end.
    reading: Vec<String>,
}

/// Read what to build from the command line of `hexicon build`, and
/// from the manifest it names.
pub fn read_project(
    files: &mut dyn SourceFiles,
    args: &[String],
    paths: &ProjectPaths,
) -> Result<Project, ProjectError> {
    // The built-in libraries' files are part of the compiler.
    let mut files = crate::builtin::WithBuiltIns::new(files);
    let mut reader = Reader {
        files: &mut files,
        user_source_paths: Vec::new(),
        sys_source_paths: paths.user_libraries.clone(),
        include_paths: Vec::new(),
        defs: Vec::new(),
        charset: None,
        modules: Vec::new(),
        image: None,
        no_system: false,
        system_included: false,
        text_tags: Vec::new(),
        object_tags: Vec::new(),
        object_keys: Vec::new(),
        ifid: None,
        preinit: None,
        debug: false,
        warnings: true,
        warnings_as_errors: false,
        verbose: false,
        source_text_group: false,
        resources: Vec::new(),
        res_recurse: true,
        messages: Vec::new(),
        lib_err: false,
        imports: Vec::new(),
        opt_file: None,
        opt_file_path: None,
        manifest: false,
        libraries: Vec::new(),
        reading: Vec::new(),
    };
    reader.parse(args)?;
    // With nothing on the command line, the manifest in the folder.
    if reader.modules.is_empty() && reader.opt_file.is_none() {
        if reader.files.exists(MANIFEST) {
            reader.opt_file = Some(MANIFEST.to_owned());
        } else {
            return Err(ProjectError::Usage(String::new()));
        }
    }
    if let Some(opt_file) = reader.opt_file.clone() {
        // A folder stands for the manifest in it.
        let in_folder = build_full_path(&opt_file, MANIFEST);
        let opt_file = if reader.files.exists(&in_folder) {
            in_folder
        } else {
            opt_file
        };
        if !is_manifest(&opt_file) {
            return Err(ProjectError::Failed(vec![format!(
                "error: \"{opt_file}\" is not a manifest: a game is built from a \
                 hexicon.toml, or a folder with one"
            )]));
        }
        let Some(text) = reader.files.read(&opt_file) else {
            return Err(ProjectError::Failed(vec![format!(
                "error: unable to read manifest \"{opt_file}\""
            )]));
        };
        let manifest = manifest::game_args(&text).map_err(|problem| {
            ProjectError::Failed(vec![format!("error: {opt_file}: {problem}")])
        })?;
        reader.opt_file_path = Some(path_name(&opt_file).to_owned());
        reader.manifest = true;
        // The manifest's options, then the command line's again, so that
        // what the command line says (-o, -D, --no-warnings, ...) wins:
        // before the manifest's modules, whose libraries may look a
        // macro up, as Hexad does $(LANGUAGE).
        let (options, modules) = manifest.args.split_at(manifest.modules_at);
        reader.parse(options)?;
        let in_manifest = reader.opt_file_path.take();
        reader.parse(&command_line_options(args))?;
        reader.opt_file_path = in_manifest;
        reader.parse(modules)?;
    }
    if reader.lib_err {
        return Err(ProjectError::Failed(reader.messages));
    }
    reader.finish()
}

/// The options at the start of a command line, as `Reader::parse` reads
/// them, but for `-f`, which names the manifest.
fn command_line_options(args: &[String]) -> Vec<String> {
    let mut out = Vec::new();
    let mut at = 0;
    while at < args.len() && args[at].starts_with('-') {
        let arg = &args[at];
        let long = arg.split_once('=').map_or(arg.as_str(), |(name, _)| name);
        if matches!(long, "--source" | "--test" | "--library" | "--resources") {
            break;
        }
        // How many words the option is: two where its value is the next.
        let words = match long {
            "--library-path" | "--charset" if !arg.contains('=') => 2,
            _ if long.starts_with("--") => 1,
            _ if matches!(arg.as_str(), "-f" | "-o" | "-I" | "-D" | "-U") => 2,
            _ => 1,
        };
        let end = (at + words).min(args.len());
        if !arg.starts_with("-f") {
            out.extend(args[at..end].iter().cloned());
        }
        at = end;
    }
    out
}

impl Reader<'_, '_> {
    /// What follows `-res`: files and folders, each as `file` or
    /// `file=name`, and `--recurse` and `--no-recurse` for the folders
    /// after them.
    fn parse_resources(&mut self, args: &[String]) -> Result<(), ProjectError> {
        for arg in args {
            match arg.as_str() {
                "--recurse" => self.res_recurse = true,
                "--no-recurse" => self.res_recurse = false,
                _ if arg.starts_with('-') => {
                    return Err(ProjectError::Usage(format!("unknown option \"{arg}\"")));
                }
                _ => {
                    let (file, alias) = match arg.split_once('=') {
                        Some((file, alias)) => (file, Some(alias.to_owned())),
                        None => (arg.as_str(), None),
                    };
                    self.resources.push(ResourceSpec {
                        file: self.relative(file),
                        alias,
                        recurse: self.res_recurse,
                    });
                }
            }
        }
        Ok(())
    }

    /// A path the project file gives, made relative to the folder the
    /// project file is in.
    fn relative(&self, name: &str) -> String {
        match &self.opt_file_path {
            None => name.to_owned(),
            Some(dir) => {
                let local = cvt_url_dir(name);
                if is_absolute(&local) {
                    local
                } else {
                    build_full_path(dir, &local)
                }
            }
        }
    }

    /// The value of a macro, as a library's `$(NAME)` sees it: the last
    /// `-D` or `-U` of the name says.
    fn look_up_pp_sym(&self, name: &str) -> Option<String> {
        let mut found = None;
        for (sym, value) in &self.defs {
            if sym == name {
                found = value.clone();
            }
        }
        found
    }

    /// Where a source or a library is: where its name says, if it is
    /// there, and otherwise along the source path.
    /// The folders sources and libraries are looked for in, in order:
    /// those `--library-path` names, the other library folders, the system
    /// library's, and last those of the libraries built into the
    /// compiler (the system library's folder, and the folder with each
    /// library in it).
    fn search_dirs(&self) -> Vec<String> {
        self.user_source_paths
            .iter()
            .chain(&self.sys_source_paths)
            .cloned()
            .chain([
                crate::builtin::SYSTEM.to_owned(),
                crate::builtin::ROOT.to_owned(),
            ])
            .collect()
    }

    fn find_source(&mut self, source: &str, search: &str) -> String {
        if is_absolute(search) || self.files.exists(source) {
            return source.to_owned();
        }
        for dir in self.search_dirs() {
            let path = build_full_path(&dir, search);
            if self.files.exists(&path) {
                return path;
            }
        }
        source.to_owned()
    }

    fn add_module(
        &mut self,
        name: &str,
        orig_name: &str,
        search: String,
        origin: Origin,
        url: String,
    ) {
        self.modules.push(Module {
            orig_name: orig_name.to_owned(),
            source: manifest::source_name(name),
            search,
            origin,
            url,
            excluded: false,
            test: false,
        });
    }

    fn maybe_add_include_path(&mut self, path: &str) {
        if !self.include_paths.iter().any(|have| have == path) {
            self.include_paths.push(path.to_owned());
        }
    }

    fn parse(&mut self, args: &[String]) -> Result<(), ProjectError> {
        let mut at = 0;
        // The value of an option: the rest of the word, or the next one.
        let opt_arg = |at: &mut usize, len: usize| -> Option<String> {
            let arg = &args[*at];
            if arg.len() > len {
                Some(arg[len..].to_owned())
            } else if *at + 1 < args.len() {
                *at += 1;
                Some(args[*at].clone())
            } else {
                None
            }
        };
        let missing = |arg: &str| ProjectError::Usage(format!("option \"{arg}\" needs a value"));
        let bad = |arg: &str| ProjectError::Usage(format!("unknown option \"{arg}\""));
        // The value of a long option: after `=`, or the next word.
        let long_arg = |at: &mut usize, arg: &str| -> Option<String> {
            match arg.split_once('=') {
                Some((_, value)) => Some(value.to_owned()),
                None if *at + 1 < args.len() => {
                    *at += 1;
                    Some(args[*at].clone())
                }
                None => None,
            }
        };
        while at < args.len() && args[at].starts_with('-') {
            let arg = args[at].clone();
            // A long option, with its value after `=` or in the next word.
            let long = arg.split_once('=').map_or(arg.as_str(), |(name, _)| name);
            if matches!(long, "--source" | "--test" | "--library" | "--resources") {
                break;
            }
            if long.starts_with("--") {
                match long {
                    "--library-path" => {
                        let path = long_arg(&mut at, &arg).ok_or_else(|| missing(long))?;
                        let path = self.relative(&path);
                        self.user_source_paths.push(path);
                    }
                    "--charset" => {
                        self.charset = Some(long_arg(&mut at, &arg).ok_or_else(|| missing(long))?);
                    }
                    "--preinit" => self.preinit = Some(true),
                    "--no-preinit" => self.preinit = Some(false),
                    "--no-system" => self.no_system = true,
                    "--warnings" => self.warnings = true,
                    "--no-warnings" => self.warnings = false,
                    "--warnings-as-errors" => self.warnings_as_errors = true,
                    "--source-text-groups" => self.source_text_group = true,
                    "--help" => return Err(ProjectError::Usage(String::new())),
                    _ => return Err(bad(&arg)),
                }
                at += 1;
                continue;
            }
            // The options every compiler has, a letter each, with the
            // value in the same word or the next: -f, -o, -I, -D, -U, -d,
            // and -v.
            let bytes = arg.as_bytes();
            match bytes.get(1).copied().unwrap_or(0) {
                b'f' => {
                    if self.opt_file.is_some() {
                        return Err(ProjectError::Failed(vec![
                            "error: only one option file (-f) is allowed".to_owned(),
                        ]));
                    }
                    self.opt_file = Some(opt_arg(&mut at, 2).ok_or_else(|| missing(&arg))?);
                }
                b'D' => {
                    let def = opt_arg(&mut at, 2).ok_or_else(|| missing(&arg))?;
                    let (name, value) = def.split_once('=').unwrap_or((&def, ""));
                    self.defs.push((name.to_owned(), Some(value.to_owned())));
                }
                b'U' => {
                    let name = opt_arg(&mut at, 2).ok_or_else(|| missing(&arg))?;
                    self.defs.push((name, None));
                }
                b'v' if arg == "-v" => self.verbose = true,
                b'd' if arg == "-d" => self.debug = true,
                b'I' => {
                    let path = opt_arg(&mut at, 2).ok_or_else(|| missing(&arg))?;
                    let path = self.relative(&path);
                    self.include_paths.push(path);
                }
                b'o' => {
                    let path = opt_arg(&mut at, 2).ok_or_else(|| missing(&arg))?;
                    self.image = Some(self.relative(&path));
                }
                b'?' | b'h' if bytes.len() == 2 => return Err(ProjectError::Usage(String::new())),
                _ => return Err(bad(&arg)),
            }
            at += 1;
        }

        // The modules: sources and libraries.
        while at < args.len() {
            let arg = args[at].clone();
            let (mut is_source, mut is_lib, mut is_test) = (false, false, false);
            let name = if arg.starts_with('-') {
                match arg.as_str() {
                    "--source" => is_source = true,
                    "--test" => {
                        is_source = true;
                        is_test = true;
                    }
                    "--library" => is_lib = true,
                    "--resources" => {
                        // The rest are resources.
                        return self.parse_resources(&args[at + 1..]);
                    }
                    _ => return Err(ProjectError::Usage(format!("unknown option \"{arg}\""))),
                }
                at += 1;
                match args.get(at) {
                    Some(name) => name.clone(),
                    None => {
                        return Err(ProjectError::Usage(format!(
                            "option \"{arg}\" needs a value"
                        )));
                    }
                }
            } else {
                arg.clone()
            };
            if !is_source && !is_lib && is_manifest(&name) {
                if self.opt_file.is_some() {
                    return Err(ProjectError::Failed(vec![
                        "error: only one option file (-f) is allowed".to_owned(),
                    ]));
                }
                self.opt_file = Some(name);
                at += 1;
                continue;
            }
            let path = self.relative(&name);
            if !is_lib {
                // The first source names the image, if nothing else
                // has: not a test, which a build may leave out.
                if self.image.is_none() && !is_test {
                    self.image = Some(format!("{}.hxg", rem_ext(&path)));
                }
                // Named, as a library's sources are, without the
                // extension.
                let file = manifest::source_name(&path);
                let search = manifest::source_name(&name);
                self.add_module(&file, rem_ext(&name), search, Origin::Normal, String::new());
                if let Some(module) = self.modules.last_mut() {
                    module.test = is_test;
                }
            } else {
                let found = self.find_library(&path, &name);
                let first_lib_module = self.modules.len();
                self.enter_lib(&found, "");
                // `--exclude name` after a library leaves one of its
                // modules out, by its name in the library; `--include
                // name` adds a source from the library's folder after it,
                // such as one of its extensions.
                while let Some(flag @ ("--exclude" | "--include")) =
                    args.get(at + 1).map(String::as_str)
                {
                    at += 2;
                    let Some(url) = args.get(at) else {
                        return Err(ProjectError::Usage(format!(
                            "option \"{flag}\" needs a value"
                        )));
                    };
                    if flag == "--include" {
                        let lib_path = path_name(&found).to_owned();
                        let full =
                            manifest::source_name(&build_full_path(&lib_path, &cvt_url_dir(url)));
                        let name = rem_ext(url).to_owned();
                        self.add_module(
                            &full,
                            &name,
                            full.clone(),
                            Origin::Lib(found.clone()),
                            name.clone(),
                        );
                    } else if let Some(module) = self.modules[first_lib_module..]
                        .iter_mut()
                        .find(|module| module.url.eq_ignore_ascii_case(url))
                    {
                        module.excluded = true;
                    }
                }
            }
            at += 1;
        }
        Ok(())
    }

    /// Where the library a project names is: a manifest, if `path` is
    /// one, or a folder with one, or a manifest of its name with `.toml`
    /// after it. Each is looked for where its name says, and then along
    /// the source path.
    fn find_library(&mut self, path: &str, name: &str) -> String {
        if is_manifest(path) {
            return self.find_source(path, name);
        }
        // Either kind, where the name says and then in each folder in
        // turn: the first folder with the library has it.
        let kinds = |path: &str| [build_full_path(path, MANIFEST), format!("{path}.toml")];
        for candidate in kinds(path) {
            if self.files.exists(&candidate) {
                return candidate;
            }
        }
        let fallback = build_full_path(path, MANIFEST);
        if is_absolute(name) {
            return fallback;
        }
        for dir in self.search_dirs() {
            for candidate in kinds(&build_full_path(&dir, name)) {
                if self.files.exists(&candidate) {
                    return candidate;
                }
            }
        }
        fallback
    }

    /// A library a library is built on, `full`: a manifest, a folder
    /// with one, or a manifest of its name.
    fn sub_library(&mut self, full: String) -> String {
        if is_manifest(&full) {
            return full;
        }
        let beside = format!("{full}.toml");
        if !self.files.exists(&build_full_path(&full, MANIFEST)) && self.files.exists(&beside) {
            return beside;
        }
        build_full_path(&full, MANIFEST)
    }

    /// `text` with each `$(NAME)` replaced by the value of the macro and
    /// each `$$` by a dollar, and what was wrong with it.
    fn expand_names(&self, text: &str) -> (String, Vec<String>) {
        const BAD_DOLLAR: &str =
            "invalid '$' sequence - use '$$' for a literal dollar sign character";
        let mut problems = Vec::new();
        let mut expanded = String::new();
        let mut rest = text;
        while let Some(at) = rest.find('$') {
            expanded.push_str(&rest[..at]);
            let after = &rest[at + 1..];
            if let Some(inner) = after.strip_prefix('(') {
                if let Some(close) = inner.find(')') {
                    let name = &inner[..close];
                    match self.look_up_pp_sym(name) {
                        Some(value) => expanded.push_str(&value),
                        None => problems.push(format!("undefined name \"{name}\"")),
                    }
                    rest = &inner[close + 1..];
                    continue;
                }
                problems.push(BAD_DOLLAR.to_owned());
                expanded.push('$');
                rest = after;
            } else if let Some(after) = after.strip_prefix('$') {
                expanded.push('$');
                rest = after;
            } else {
                problems.push(BAD_DOLLAR.to_owned());
                expanded.push('$');
                rest = after;
            }
        }
        expanded.push_str(rest);
        (expanded, problems)
    }

    /// A macro a library needs a game to define: if it is not defined,
    /// say so, and why.
    fn need_macro(&mut self, place: &str, macro_name: &str, why: &str) {
        if self.look_up_pp_sym(macro_name).is_none() {
            let shown = &macro_name[..macro_name.len().min(128)];
            self.messages.push(format!(
                "{place}: library requires the macro \"{shown}\" to be \
                 defined; use -D {shown}=value to define it, or {shown} = \
                 \"value\" in the manifest's [defines] ({why})"
            ));
        }
    }

    /// Read a library's manifest, unless it is being read already: one
    /// that leads back to itself is an error, not a build without end.
    fn enter_lib(&mut self, full_name: &str, lib_url: &str) {
        let same = |have: &String| {
            have.replace('\\', "/")
                .eq_ignore_ascii_case(&full_name.replace('\\', "/"))
        };
        if self.reading.iter().any(same) {
            self.messages.push(format!(
                "error: library \"{full_name}\" leads back to itself"
            ));
            self.lib_err = true;
            return;
        }
        self.reading.push(full_name.to_owned());
        self.process_lib(full_name, lib_url);
        self.reading.pop();
    }

    /// Read a library's manifest, adding its sources to the modules, and
    /// its libraries' in their places.
    fn process_lib(&mut self, full_name: &str, lib_url: &str) {
        let lib_path = path_name(full_name).to_owned();
        self.maybe_add_include_path(&lib_path);
        let Some(text) = self.files.read(full_name) else {
            self.messages
                .push(format!("unable to open library file \"{full_name}\""));
            self.lib_err = true;
            return;
        };
        self.libraries.push(full_name.to_owned());
        let lib = match manifest::library(&text) {
            Ok(lib) => lib,
            Err(problem) => {
                self.messages.push(format!("{full_name}: {problem}"));
                self.lib_err = true;
                return;
            }
        };
        // What the library needs a game to define, said first: a name
        // below made of an undefined macro is what it is about.
        for (name, why) in &lib.needs {
            self.need_macro(full_name, name, why);
        }
        // What a name in the manifest comes to, and where it is.
        let place = |reader: &mut Self, value: &str| {
            let (value, problems) = reader.expand_names(value);
            for problem in problems {
                reader.messages.push(format!("{full_name}: {problem}"));
            }
            let full = build_full_path(&lib_path, &cvt_url_dir(&value));
            (value, full)
        };
        // Imported by the name of its folder (`hexad/hexicon.toml`) or of
        // its file (`hexad.toml`).
        let import_name = if file_name_of(full_name).eq_ignore_ascii_case(MANIFEST) {
            file_name_of(&lib_path).to_owned()
        } else {
            rem_ext(file_name_of(full_name)).to_owned()
        };
        let header = lib.header.as_ref().map(|header| place(self, header).1);
        if import_name.eq_ignore_ascii_case("system") {
            self.system_included = true;
        }
        self.text_tags
            .extend(lib.text_tags.iter().map(|tag| tag.to_ascii_lowercase()));
        self.object_tags
            .extend(lib.object_tags.iter().map(|tag| tag.to_ascii_lowercase()));
        self.object_keys.extend(lib.object_keys.iter().cloned());
        if lib.ifid.is_some() {
            self.ifid.clone_from(&lib.ifid);
        }
        self.imports.push((import_name, header));
        for module in &lib.modules {
            match module {
                // A source is named without its extension.
                manifest::ModuleRef::Source(source) => {
                    let (value, full) = place(self, source);
                    let name = rem_ext(&value).to_owned();
                    let full = manifest::source_name(&full);
                    let url = format!("{lib_url}{name}");
                    self.add_module(
                        &full,
                        &name,
                        full.clone(),
                        Origin::Lib(full_name.to_owned()),
                        url,
                    );
                }
                manifest::ModuleRef::Library { name, .. } => {
                    // A name that could not be made (an undefined macro)
                    // names no library: what is left of it may be this
                    // library's own folder.
                    let before = self.messages.len();
                    let (value, full) = place(self, name);
                    if self.messages.len() > before || value.trim().is_empty() {
                        self.lib_err = true;
                        continue;
                    }
                    let url = format!("{lib_url}{value}/");
                    let target = self.sub_library(full);
                    self.enter_lib(&target, &url);
                }
            }
        }
        for resource in &lib.resources {
            let (value, full) = place(self, resource);
            self.resources.push(ResourceSpec {
                file: full,
                alias: Some(value),
                recurse: true,
            });
        }
    }

    fn finish(mut self) -> Result<Project, ProjectError> {
        // The system library comes first, unless the program named it
        // itself, or said it is built without it. It is found as a
        // library the program names is, so a folder of --library-path can give one
        // of its own.
        if !self.no_system && !self.system_included {
            let found = self.find_library("system", "system");
            let first = self.modules.len();
            self.enter_lib(&found, "");
            let system: Vec<Module> = self.modules.drain(first..).collect();
            self.modules.splice(0..0, system);
        }
        // No file can be among the sources twice: what it defines would be
        // defined twice. Two files of one name, in different folders, are
        // two modules, as a game's `status.hxn` and Hexad's are.
        let mut problems = Vec::new();
        let same_file = |a: &str, b: &str| {
            a.replace('\\', "/")
                .eq_ignore_ascii_case(&b.replace('\\', "/"))
        };
        for (index, module) in self.modules.iter().enumerate() {
            if module.excluded {
                continue;
            }
            let twice = self.modules[..index]
                .iter()
                .any(|earlier| !earlier.excluded && same_file(&earlier.source, &module.source));
            if twice {
                let from = match &module.origin {
                    Origin::Lib(lib) => format!(" (from library \"{lib}\")"),
                    Origin::Normal => String::new(),
                };
                problems.push(format!(
                    "error: \"{}\"{from} is among the sources twice",
                    module.source
                ));
            }
        }
        if !problems.is_empty() {
            let mut messages = self.messages;
            messages.extend(problems);
            return Err(ProjectError::Failed(messages));
        }
        // Each module's place in the build counts those left out too.
        let modules = std::mem::take(&mut self.modules);
        let mut sources = Vec::new();
        let mut module_names = Vec::new();
        let mut from_library = Vec::new();
        for (index, module) in modules.iter().enumerate() {
            // A test is built only for debugging.
            if module.excluded || (module.test && !self.debug) {
                continue;
            }
            let path = self.find_source(&module.source, &module.search);
            sources.push(path);
            module_names.push((module.orig_name.clone(), index + 1));
            from_library.push(!matches!(module.origin, Origin::Normal));
        }
        // What the macros come to: the last `-D` or `-U` of a name.
        let mut defines: Vec<(String, String)> = Vec::new();
        let mut undefines: Vec<String> = Vec::new();
        for (name, value) in &self.defs {
            defines.retain(|(have, _)| have != name);
            undefines.retain(|have| have != name);
            match value {
                Some(value) => defines.push((name.clone(), value.clone())),
                None => undefines.push(name.clone()),
            }
        }
        let include_paths = self.include_paths;
        // The headers built into the compiler need no place here: the
        // preprocessor looks there for any it does not find.
        Ok(Project {
            sources,
            options: CompileOptions {
                include_paths,
                defines,
                undefines,
                default_charset: self.charset,
                source_text_group: self.source_text_group,
                module_names,
                from_library,
                imports: std::mem::take(&mut self.imports),
                text_tags: std::mem::take(&mut self.text_tags),
                object_tags: std::mem::take(&mut self.object_tags),
                object_keys: std::mem::take(&mut self.object_keys),
                ifid: self.ifid.take(),
                debug: self.debug,
                ..CompileOptions::default()
            },
            image: self.image,
            preinit: self.preinit.unwrap_or(!self.debug),
            warnings: self.warnings,
            warnings_as_errors: self.warnings_as_errors,
            verbose: self.verbose,
            debug: self.debug,
            resources: self.resources,
            messages: self.messages,
            manifest: self.manifest,
            libraries: self.libraries,
        })
    }
}