ferroui-build 0.3.0

Build-script support of FerroUI: compiles the markup documents of a crate to Rust source and embeds its assets
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
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
//! ferroui-build
//!
//! Build-script support: compiles the markup documents of a crate to Rust
//! source and embeds its assets (docs/porting/xaml.md, section 9.6). The
//! counterpart of the build tasks of the upstream project
//! (`CompileXamlTask` with `XamlCompilerTaskExecutor`, and
//! `GenerateResourcesTask`), which run after the compiler and rewrite the
//! assembly; a Rust crate has no such step, so the build script of the crate
//! runs before the compiler and writes source the crate includes.
//!
//! ```ignore
//! // build.rs
//! fn main() {
//!     ferroui_controls::register_types();           // the types the documents name
//!     ferroui_build::Build::from_env()
//!         .assembly(&ASSEMBLY)                      // the assembly of the crate
//!         .embed_assets(&["Assets"])
//!         .compile_xaml()                           // every *.xaml of the crate
//!         .run();
//! }
//!
//! // lib.rs
//! ferroui_markup_xaml::include_compiled_xaml!();    // pub mod compiled_xaml, pub mod compiled_markup
//! pub fn register_types() { /* .. */ compiled_markup::register(); }
//! ```
//!
//! # What a run does, in order
//!
//! 1. Reads the `.xamlmeta` of every crate the crate depends on directly
//!    (`DEP_<CRATE>_XAML_XAMLMETA`, which Cargo sets from the `links` key and
//!    the `cargo::metadata=xamlmeta=<path>` line of that crate) and,
//!    transitively, the files they name: the compiled documents an include of
//!    a document of another crate is linked to.
//! 2. Compiles each group of documents as upstream compiles the documents of
//!    an assembly (parse, transform, group transformers, emit) and writes
//!    `$OUT_DIR/xaml/<module>.rs` with its position map.
//! 3. Lists the assets, leaving out the documents it compiled (upstream
//!    removes a compiled resource from the assembly).
//! 4. Writes `$OUT_DIR/<crate>.xamlmeta` (the compiled documents of the
//!    crate, and the paths of the files of step 1) and
//!    `$OUT_DIR/xaml/mod.rs` (the modules of the groups, the asset table, the
//!    loader table of the crate and `register()`).
//! 5. Prints the `cargo::` lines: `rerun-if-changed` for every input,
//!    `metadata=xamlmeta=<path>` for the crates that depend on this one, and
//!    `rustc-env=FERROUI_XAMLMETA=<path>` for the crate itself.
//!
//! Every document is compiled before the run fails: each error is printed as
//! a `cargo::error=` line, and the script exits with a failure once.
//!
//! # Diagnostics
//!
//! What the compiler reports has the code of upstream's build task
//! (`FerroXamlDiagnosticCodes`) and, where it is known, the document and the
//! position: `Views/Main.xaml(12,8): warning FRN2208: ..`. A diagnostic of the
//! transform goes through the filter of upstream's task
//! ([`xaml_compiler_diagnostics_filter`]): the EditorConfig files of the build
//! ([`Build::analyzer_config_files`]) state its severity by its code, and
//! [`Build::warnings_as_errors`] makes every warning that is left an error. A
//! warning is a `cargo::warning=` line; an error fails the build: a group that
//! does not transform (`FRN2000`, once for the group, or the diagnostics of the
//! transform that say why), a document the emitter refuses (`FRN3000`, with the
//! document and the node), a class no load by URI can create (`FRN3001`, a
//! warning).
//!
//! # Where the type metadata comes from
//!
//! A build compiles against the type models of the crates
//! ([`TypeSystem::Model`], the next section): this crate links the compiler
//! (the transform and the emitter of Rust source) and the base crate, and
//! neither the XAML runtime library nor the controls, so a build script that
//! uses it builds none of them for the host.
//!
//! The other host is the feature `runtime-host` ([`TypeSystem::Runtime`]): the
//! compiler transforms a document against the run-time type system, the
//! types, properties and constructors the crates registered in the process
//! (`register_types()` of each). A build script that enables it takes the crates
//! whose types its documents name as build dependencies and registers them
//! before it calls [`Build::run`], and it starts whatever application
//! services the transform of its documents needs. Two consequences:
//!
//! - those crates are built for the host as well as for the target (once
//!   more when the two differ or their features do);
//! - a build script cannot link the crate it builds, so it cannot compile a
//!   document that names a type of that crate: neither the document of a
//!   class of the crate (`x:Class`) nor a document that uses one of its
//!   types. Such a document is generated by a test of the crate and checked
//!   in (`rust_emitter::generate_class_file`); its loader table and its
//!   `.xamlmeta` join the ones of the build through [`Build::loader`] and
//!   [`Build::checked_in_metadata`].
//!
//! The feature links the XAML runtime library and, through it, the controls. No
//! crate of the repository enables it.
//!
//! # The build-time type model
//!
//! The way out of both consequences is xaml.md 9.5: the types read from the
//! sources instead of the process. With [`Build::type_system`] and
//! [`TypeSystem::Model`] a build scans the crate, reads the type models of
//! the crates it depends on from their `.xamlmeta` (the framework crates
//! export theirs from their own build scripts) and compiles every group
//! against the type system over those models: the build script registers
//! nothing, needs no crate for its types, and compiles the documents of the
//! classes of the crate it builds ([`XamlGroup::class_document`]). The
//! run-time type system stays the value of a build that does not state one, and
//! is an error of the build without the feature `runtime-host`.
//!
//! ```ignore
//! // build.rs
//! fn main() {
//!     ferroui_build::Build::from_env()
//!         .type_system(ferroui_build::TypeSystem::Model)   // the assembly is the one the sources state
//!         .compile_group(XamlGroup::new("compiled_xaml").documents(DOCUMENTS))
//!         .compile_group(XamlGroup::new("compiled_main_window").documents(VIEWS).class_document("MainWindow.xaml"))
//!         .run();
//! }
//! ```
//!
//! What is here:
//!
//! - [`model`], [`scanner`], [`model_set`], [`call_forms`], [`export`]: the
//!   type model of a crate and its file (the `.xamlmeta` of format 2), the
//!   source scanner that fills it, the models of several crates read together,
//!   the call form of every declared member, and the export of a model from a
//!   build script. They are the crate `ferroui-build-scan`, which links
//!   nothing of the framework so that the framework crates can scan
//!   themselves with it, exported here under the names they had in this crate;
//! - [`Build::export_metadata`]: the scan of the crate, with the models of
//!   its dependencies, written into its `.xamlmeta`;
//! - [`type_system`]: the type system of the compiler over the models
//!   (`ModelTypeSystem`, xaml.md 9.5.5), with the closed table of runtime
//!   library types it shares with the run-time type system, and what the
//!   models state for the emitter (`ModelEmitTypes`, xaml.md 9.5.12).
//!
//! What a build against the models does not have yet: the compile-time value
//! parser of the run-time host (text a type refuses is found when the document
//! is built, not when it is compiled), and a position map for the file of a
//! class.
//!
//! ```ignore
//! // build.rs of a crate that declares types and has no documents
//! fn main() {
//!     ferroui_build::Build::from_env().export_metadata().run();
//! }
//! ```
//!
//! # A crate with checked-in compiled markup
//!
//! A crate that keeps all of its compiled markup checked in (the two themes)
//! does not need this crate: its build script prints the line of step 5 for
//! its checked-in file, and its manifest has the `links` key.
//!
//! ```ignore
//! println!("cargo::metadata=xamlmeta={}/compiled_xaml.xamlmeta", env!("CARGO_MANIFEST_DIR"));
//! ```

#![forbid(unsafe_code)]

pub mod deterministic_id_generator;
mod diagnostics;
// The model, the scanner and the export are the crate the framework crates scan themselves
// with (`ferroui-build-scan`, which links nothing of the framework); they are exported
// here under the names they had in this crate.
pub use ferroui_build_scan::{call_forms, export, model, model_set, scanner};
pub mod type_system;
pub mod xaml_compiler_diagnostics_filter;

use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::time::Instant;

use ferroui_base::metadata::MarkupAssembly;
use xamlx::type_system::IXamlTypeSystem;

use crate::export::ScanReport;
use crate::model::AssemblyModel;
use crate::model_set::ModelSet;
use crate::scanner::{scan_crate, Scan, ScanOptions, Severity};
use crate::type_system::{ModelEmitTypes, ModelTypeSystem};
pub use ferroui_markup_xaml_loader::rust_emitter::ClassConstructor;
use crate::xaml_compiler_diagnostics_filter::XamlCompilerDiagnosticsFilter;
use ferroui_markup_xaml_loader::compiler_extensions::FerroXamlDiagnosticCodes;
use ferroui_markup_xaml_loader::rust_emitter::{
    class_document_group, class_of_document, generate_class_file_with, generate_file_with, rust_string_literal, ClassGroup, CompiledMarkupTypeSystem,
    EmitterHost, TransformOptions, XamlMetadata, CLASS_GROUP_NOT_TRANSFORMED, GROUP_NOT_TRANSFORMED,
};

/// The name of the module of the default group ([`Build::compile_xaml`]).
pub const DEFAULT_MODULE: &str = "compiled_xaml";

/// The environment variable the build sets for the crate: the path of its `.xamlmeta`
/// (`env!("FERROUI_XAMLMETA")`).
pub const XAMLMETA_VARIABLE: &str = "FERROUI_XAMLMETA";

/// A group of documents that are compiled together into one module: the group
/// transformers see every document of it, so includes between them are linked, as
/// upstream compiles the documents of an assembly.
pub struct XamlGroup {
    module: String,
    documents: Option<Vec<(String, String)>>,
    create_source_info: Option<bool>,
    exported: bool,
    class_document: Option<String>,
    constructor: Option<ClassConstructor>,
}

/// The type system the documents of a build are compiled against ([`Build::type_system`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TypeSystem {
    /// The run-time type system: the types the build script registered in its process. The
    /// script links the crates whose types its documents name, and cannot compile a
    /// document that names a type of the crate it builds. Only with the feature
    /// `runtime-host` of this crate, which links the XAML runtime library and the
    /// controls; without it a build that compiles documents against this type system
    /// fails with an error that says so.
    #[default]
    Runtime,
    /// The build-time type system over the type models (docs/porting/xaml.md, 9.5): the
    /// model of the crate, scanned from its sources, and the models of the crates it
    /// depends on, read from their `.xamlmeta`. The script links no crate for its types
    /// and compiles the documents of the classes of the crate ([`XamlGroup::class_document`]).
    Model,
}

impl XamlGroup {
    /// A group whose generated file is the body of the module `module` of the crate
    /// root. Without [`documents`](Self::documents) the group is every `.xaml` file
    /// below the XAML root of the build.
    pub fn new(module: &str) -> Self {
        Self { module: module.to_string(), documents: None, create_source_info: None, exported: true, class_document: None, constructor: None }
    }

    /// Makes the group the group of a class of the crate: `name` (its path below the root
    /// URI of the assembly) is the document of the class its root names with `x:Class`,
    /// and the group is that document with every document of the group it includes,
    /// directly or not. The generated file is the file of the class
    /// (`rust_emitter::generate_class_file`): `populate`, which the constructor of the
    /// class calls, the build functions of the included documents and the loader table.
    /// Its module is declared at the crate root like the module of any group
    /// (`crate::<module>::populate`).
    ///
    /// Only with [`TypeSystem::Model`]: the class is a type of the crate being built.
    pub fn class_document(mut self, name: &str) -> Self {
        self.class_document = Some(name.to_string());
        self
    }

    /// The constructor the loader table creates the class of a class group with. Without
    /// the call the compiler picks it as upstream's does: a public parameterless
    /// constructor, else a public constructor that takes the service provider.
    pub fn constructor(mut self, constructor: ClassConstructor) -> Self {
        self.constructor = Some(constructor);
        self
    }

    /// The documents of the group, by their path below the root URI of the assembly
    /// (`Views/Main.xaml`), in the order they are compiled. The build script states the
    /// files they come from with [`Build::input`].
    pub fn documents(mut self, documents: &[(&str, &str)]) -> Self {
        self.documents = Some(documents.iter().map(|(name, xaml)| (name.to_string(), xaml.to_string())).collect());
        self
    }

    /// Whether the documents are compiled with source information (`CreateSourceInfo`);
    /// without the call, as the assembly states it.
    pub fn create_source_info(mut self, value: bool) -> Self {
        self.create_source_info = Some(value);
        self
    }

    /// Keeps the group out of the loader table and of the `.xamlmeta` of the crate: its
    /// documents are reached by their build functions only (a second compilation of
    /// documents another group registers, as a test compiles them).
    pub fn internal(mut self) -> Self {
        self.exported = false;
        self
    }
}

pub use ferroui_build_scan::export::Outcome;

/// The build of the markup of a crate; see the crate documentation.
pub struct Build {
    manifest_dir: PathBuf,
    out_dir: PathBuf,
    crate_name: String,
    assembly: Option<&'static MarkupAssembly>,
    xaml_root: PathBuf,
    groups: Vec<XamlGroup>,
    asset_directories: Vec<String>,
    loaders: Vec<String>,
    checked_in_metadata: Vec<PathBuf>,
    inputs: Vec<PathBuf>,
    dependencies: Vec<PathBuf>,
    export_metadata: bool,
    source_root: Option<PathBuf>,
    type_system: TypeSystem,
    default_compile_bindings: bool,
    analyzer_config_files: Vec<PathBuf>,
    warnings_as_errors: bool,
}

impl Build {
    /// The build of the crate whose build script is running: `CARGO_MANIFEST_DIR`,
    /// `OUT_DIR`, `CARGO_PKG_NAME`, and the `.xamlmeta` of every direct dependency
    /// (`DEP_<CRATE>_XAML_XAMLMETA`), in the order of the names of the variables.
    ///
    /// # Panics
    /// Panics outside a build script (a variable Cargo sets is missing).
    pub fn from_env() -> Self {
        let variable = |name: &str| env::var_os(name).unwrap_or_else(|| panic!("{name} is not set: not a build script"));
        Self::new(
            PathBuf::from(variable("CARGO_MANIFEST_DIR")),
            PathBuf::from(variable("OUT_DIR")),
            &variable("CARGO_PKG_NAME").to_string_lossy(),
            ferroui_build_scan::export::dependencies_from_env(),
        )
    }

    /// The build of the package `package_name` in `manifest_dir`, writing below `out_dir`,
    /// with the `.xamlmeta` files of its direct dependencies.
    pub fn new(manifest_dir: PathBuf, out_dir: PathBuf, package_name: &str, dependencies: Vec<PathBuf>) -> Self {
        Self {
            manifest_dir,
            out_dir,
            crate_name: package_name.replace('-', "_"),
            assembly: None,
            xaml_root: PathBuf::new(),
            groups: Vec::new(),
            asset_directories: Vec::new(),
            loaders: Vec::new(),
            checked_in_metadata: Vec::new(),
            inputs: Vec::new(),
            dependencies,
            export_metadata: false,
            source_root: None,
            type_system: TypeSystem::Runtime,
            default_compile_bindings: false,
            analyzer_config_files: Vec::new(),
            warnings_as_errors: false,
        }
    }

    /// The type system the documents are compiled against; [`TypeSystem::Runtime`] without
    /// the call.
    ///
    /// With [`TypeSystem::Model`] the build scans the sources of the crate (as
    /// [`export_metadata`](Self::export_metadata) does, and writes the model the same
    /// way), reads the models of the crates it depends on from their `.xamlmeta`, and
    /// compiles every group against the type system over those models. The build script
    /// registers nothing and needs no [`assembly`](Self::assembly): the assembly is the
    /// `MarkupAssembly` the sources state. A document the models cannot answer a question
    /// of the emitter for is an error of the build that names the document and the
    /// question; it is never compiled from a guess.
    pub fn type_system(mut self, type_system: TypeSystem) -> Self {
        self.type_system = type_system;
        self
    }

    /// Whether `{Binding}` is a compiled binding in a document that does not say otherwise
    /// (`x:CompileBindings`): the `DefaultCompileBindings` of upstream's build task. Not
    /// without the call.
    pub fn default_compile_bindings(mut self, value: bool) -> Self {
        self.default_compile_bindings = value;
        self
    }

    /// The EditorConfig files of the build, relative to the crate directory (the
    /// `AnalyzerConfigFiles` of upstream's build task): an entry
    /// `ferro_xaml_diagnostic.<code>.severity = <severity>` states the severity a diagnostic
    /// of the markup compiler with that code is reported with (`error`, `warning`,
    /// `default`; anything else silences it). A file that does not exist is skipped; the
    /// build runs again when one changes.
    pub fn analyzer_config_files(mut self, files: &[&str]) -> Self {
        self.analyzer_config_files.extend(files.iter().map(|file| self.manifest_dir.join(file)));
        self
    }

    /// Reports every warning of the markup compiler as an error of the build (the
    /// `TreatWarningsAsErrors` upstream leaves to the build system), after the severities
    /// of the EditorConfig files: a warning a file silences stays silent. Every document is
    /// still compiled before the build fails.
    pub fn warnings_as_errors(mut self, value: bool) -> Self {
        self.warnings_as_errors = value;
        self
    }

    /// Scans the sources of the crate and writes its type model into its `.xamlmeta`
    /// (format 2: the model next to the compiled documents), which the crates that depend
    /// on this one read as they read its documents (xaml.md 9.6.3). The scan reads the
    /// models of the dependencies of the crate first, so that what the crate names of
    /// theirs is resolved ([`ScanOptions::dependencies`]).
    ///
    /// The sources are read as files: nothing of the crate is linked, and a crate that
    /// only exports its model needs no [`assembly`](Self::assembly) (the scan reads the
    /// `MarkupAssembly` the sources state; a crate without one is the assembly named after
    /// the crate). What the scanner cannot read of a declaration is a `cargo::warning=`
    /// line and does not fail the build.
    pub fn export_metadata(mut self) -> Self {
        self.export_metadata = true;
        self
    }

    /// The root file of the sources of the crate, relative to the crate directory, for
    /// [`export_metadata`](Self::export_metadata). Without the call: `src/lib.rs`, else
    /// `lib.rs`, else `src/main.rs`.
    pub fn source_root(mut self, file: &str) -> Self {
        self.source_root = Some(PathBuf::from(file));
        self
    }

    /// The scan of the sources of the crate, with the models of its dependencies.
    fn scan(&self, dependencies: Vec<AssemblyModel>) -> Result<Scan, String> {
        let root = ferroui_build_scan::export::source_root(&self.manifest_dir, self.source_root.as_deref())?;
        let mut options = ScanOptions::new(&self.crate_name, root).with_dependencies(dependencies);
        options.assembly_name = self.assembly.map(|assembly| assembly.name.to_string());
        Ok(scan_crate(&options))
    }

    /// The assembly of the crate: its name is the host of the URIs of its documents and
    /// assets, and its metadata the default of `CreateSourceInfo`. The same value the
    /// crate registers in its `register_types()`.
    pub fn assembly(mut self, assembly: &'static MarkupAssembly) -> Self {
        self.assembly = Some(assembly);
        self
    }

    /// The directory, relative to the crate directory, below which the documents of a
    /// group without stated documents are found. The crate directory by default.
    pub fn xaml_root(mut self, directory: &str) -> Self {
        self.xaml_root = PathBuf::from(directory);
        self
    }

    /// A file, relative to the crate directory, the build reads through the build
    /// script (a file the script includes): the build runs again when it changes.
    pub fn input(mut self, path: &str) -> Self {
        self.inputs.push(self.manifest_dir.join(path));
        self
    }

    /// Embeds every file below the directories (relative to the crate directory) as an
    /// asset of the crate, by its path below the crate directory, except the documents
    /// the build compiles.
    pub fn embed_assets(mut self, directories: &[&str]) -> Self {
        self.asset_directories.extend(directories.iter().map(|directory| directory.to_string()));
        self
    }

    /// Compiles every `.xaml` file below the XAML root as the group
    /// [`DEFAULT_MODULE`].
    pub fn compile_xaml(self) -> Self {
        self.compile_group(XamlGroup::new(DEFAULT_MODULE))
    }

    /// Compiles a group of documents.
    pub fn compile_group(mut self, group: XamlGroup) -> Self {
        self.groups.push(group);
        self
    }

    /// The loader table of a checked-in generated file of the crate, by the path of its
    /// `try_load` (`crate::compiled_main_window::try_load`): the table of the crate asks
    /// it first, in the order of the calls.
    pub fn loader(mut self, path: &str) -> Self {
        self.loaders.push(path.to_string());
        self
    }

    /// The `.xamlmeta` of a checked-in generated file of the crate, relative to the crate
    /// directory: its documents are added to the `.xamlmeta` of the crate.
    pub fn checked_in_metadata(mut self, path: &str) -> Self {
        self.checked_in_metadata.push(self.manifest_dir.join(path));
        self
    }

    /// Runs the build and prints its lines for Cargo. On an error every error is printed
    /// and the process exits with a failure.
    pub fn run(self) {
        let outcome = self.execute();
        for line in &outcome.lines {
            println!("{line}");
        }
        if !outcome.errors.is_empty() {
            for error in &outcome.errors {
                eprintln!("error: {error}");
                println!("cargo::error={error}");
            }
            std::process::exit(1);
        }
    }

    /// Runs the build and returns what [`run`](Self::run) prints.
    pub fn execute(self) -> Outcome {
        let mut lines = Vec::new();
        let mut errors = Vec::new();
        let rerun = |lines: &mut Vec<String>, path: &Path| lines.push(format!("cargo::rerun-if-changed={}", path.display()));
        rerun(&mut lines, &self.manifest_dir.join("build.rs"));
        rerun(&mut lines, &self.manifest_dir.join("Cargo.toml"));
        for input in &self.inputs {
            rerun(&mut lines, input);
        }
        let on_models = self.type_system == TypeSystem::Model;
        // The documents are compiled against the assembly the crate registers; a build
        // that reads the type model of the crate reads the assembly from the sources.
        if self.assembly.is_none() && !on_models && (!self.export_metadata || !self.groups.is_empty()) {
            errors.push("the assembly of the crate is not stated (Build::assembly)".to_string());
            return Outcome { lines, errors };
        }
        // The run-time type system is in the build only with the feature that links it.
        if !on_models && !self.groups.is_empty() && !cfg!(feature = "runtime-host") {
            errors.push(
                "the documents are compiled against the type models (Build::type_system(TypeSystem::Model)): the run-time type system is the feature `runtime-host` of ferroui-build, which links the XAML runtime library and the controls"
                    .to_string(),
            );
            return Outcome { lines, errors };
        }

        // 1. The compiled markup and the type models of the dependencies.
        let mut report = ScanReport { crate_name: self.crate_name.clone(), ..ScanReport::default() };
        let started = Instant::now();
        let (models, dependency_files) = match ModelSet::read(&self.dependencies) {
            Ok(read) => read,
            Err(error) => {
                errors.push(format!("the .xamlmeta of a dependency cannot be read: {error}"));
                return Outcome { lines, errors };
            }
        };
        report.read_dependencies = started.elapsed();
        report.dependency_files = dependency_files.len();
        report.dependency_models = models.len();
        for file in &dependency_files {
            rerun(&mut lines, file);
        }
        let dependencies: Vec<XamlMetadata> = models.iter().map(AssemblyModel::metadata).collect();

        // The type model of the crate, from its sources.
        let scanned = self.export_metadata || on_models;
        let mut model: Option<AssemblyModel> = None;
        // The models the documents are compiled against: the ones of the dependencies, then
        // the one of the crate.
        let mut compiled_against: Vec<AssemblyModel> = Vec::new();
        if scanned {
            if on_models {
                compiled_against = models.clone();
            }
            let started = Instant::now();
            match self.scan(models) {
                Ok(scan) => {
                    report.scanned(&scan, started.elapsed());
                    for file in &scan.files {
                        rerun(&mut lines, &file.path);
                    }
                    for diagnostic in scan.diagnostics_of(Severity::Error) {
                        lines.push(format!("cargo::warning={diagnostic}"));
                    }
                    model = Some(scan.model);
                }
                Err(error) => {
                    errors.push(error);
                    return Outcome { lines, errors };
                }
            }
        }
        let assembly_name: String = match (self.assembly, &model) {
            (Some(assembly), _) => assembly.name.to_string(),
            (None, Some(model)) if !model.name.is_empty() => model.name.clone(),
            // A crate that states no assembly is the assembly named after the crate, as
            // the type systems name it.
            (None, _) => self.crate_name.clone(),
        };
        // Whether source information is on for the assembly, as the configuration of the
        // run-time loader reads it from the metadata of the assembly.
        let assembly_source_info = model.as_ref().is_some_and(|model| {
            model.metadata.iter().find(|(key, _)| key == ferroui_build_scan::CREATE_SOURCE_INFO).is_some_and(|(_, value)| value.trim().eq_ignore_ascii_case("true"))
        });

        // The type system of the build.
        let mut model_host: Option<(Rc<dyn IXamlTypeSystem>, Rc<dyn IXamlTypeSystem>, ModelEmitTypes)> = None;
        if on_models {
            if let Some(model) = &model {
                let mut own = model.clone();
                own.name = assembly_name.clone();
                compiled_against.push(own);
            }
            let system = ModelTypeSystem::new(compiled_against);
            // No class is one "with markup of its own" for a build: that states which
            // classes the run-time loader populates, and a class whose document is compiled
            // populates itself from its compiled markup.
            let types = ModelEmitTypes::new(system.clone(), Vec::new());
            // The compiled documents of the dependencies are part of the type system, as
            // they are for the run-time host (`EmitterHost::runtime`).
            let type_system = match dependencies.is_empty() {
                true => Ok(system.as_type_system()),
                false => CompiledMarkupTypeSystem::new(system.as_type_system(), &dependencies).map(|wrapped| wrapped as Rc<dyn IXamlTypeSystem>),
            };
            match type_system {
                Ok(type_system) => model_host = Some((type_system, system.as_type_system(), types)),
                Err(error) => {
                    errors.push(format!("the compiled markup of a dependency cannot be read against the type models: {}", error.message()));
                    return Outcome { lines, errors };
                }
            }
        } else if let Some(assembly) = self.assembly {
            #[cfg(feature = "runtime-host")]
            runtime_host::register(assembly);
            #[cfg(not(feature = "runtime-host"))]
            let _ = assembly;
        }

        // 2. The groups.
        for file in &self.analyzer_config_files {
            rerun(&mut lines, file);
        }
        let diagnostics = diagnostics::Diagnostics::new(
            XamlCompilerDiagnosticsFilter::new(Some(self.analyzer_config_files.clone())),
            self.warnings_as_errors,
        );
        let xaml_directory = self.out_dir.join("xaml");
        let root_uri = format!("ferres://{assembly_name}/");
        let mut metadata = XamlMetadata {
            name: assembly_name.clone(),
            crate_name: self.crate_name.clone(),
            documents: Vec::new(),
            dependencies: self.dependencies.iter().map(|path| path.display().to_string()).collect(),
        };
        let mut modules: Vec<Module> = Vec::new();
        let mut compiled_documents: Vec<String> = Vec::new();
        for group in &self.groups {
            if self.assembly.is_none() && !on_models {
                break;
            }
            if modules.iter().any(|module| module.name == group.module) {
                errors.push(format!("two groups have the module `{}`", group.module));
                continue;
            }
            let documents = match &group.documents {
                Some(documents) => documents.clone(),
                None => {
                    let root = self.manifest_dir.join(&self.xaml_root);
                    rerun(&mut lines, &root);
                    let mut files = Vec::new();
                    if let Err(error) = collect(&self.manifest_dir, &root, &mut files) {
                        errors.push(error);
                    }
                    let mut documents = Vec::with_capacity(files.len());
                    for (rooted, path) in files {
                        if !path.extension().is_some_and(|extension| extension == "xaml") {
                            continue;
                        }
                        match fs::read_to_string(&path) {
                            Ok(text) => documents.push((rooted.trim_start_matches('/').to_string(), text)),
                            Err(error) => errors.push(format!("{}: {error}", path.display())),
                        }
                    }
                    documents
                }
            };
            let borrowed: Vec<(&str, &str)> = documents.iter().map(|(name, xaml)| (name.as_str(), xaml.as_str())).collect();
            let path = xaml_directory.join(format!("{}.rs", group.module));
            let module_path = format!("::{}::{}", self.crate_name, group.module);

            // The group of a class of the crate.
            if let Some(class_document) = &group.class_document {
                let Some((type_system, models, types)) = &model_host else {
                    errors.push(diagnostics::error(
                        FerroXamlDiagnosticCodes::TRANSFORM_ERROR,
                        class_document,
                        "the document of a class of the crate is compiled against the type models only (Build::type_system(TypeSystem::Model)): a build script cannot link the crate it builds",
                    ));
                    continue;
                };
                let host = EmitterHost { type_system: type_system.clone(), types, parsers: Vec::new() };
                let options = TransformOptions {
                    local_assembly: Some(assembly_name.clone()),
                    create_source_info: group.create_source_info.unwrap_or(assembly_source_info),
                    use_compiled_bindings_by_default: self.default_compile_bindings,
                    diagnostic_handler: Some(diagnostics.handler()),
                    design_mode: false,
                };
                let compiled = class_group(&host, &**models, &root_uri, &borrowed, class_document, group.constructor, &module_path, &options);
                let reported_errors = diagnostics.report(&mut lines, &mut errors);
                match compiled {
                    Ok(file) => {
                        // Upstream's `XamlLoaderUnreachable`, a warning the filter decides on.
                        for warning in &file.warnings {
                            diagnostics.warning(FerroXamlDiagnosticCodes::XAML_LOADER_UNREACHABLE, class_document, warning, &mut lines, &mut errors);
                        }
                        write_if_changed(&path, &file.source, &mut errors);
                        let class_metadata = file.metadata(&[]);
                        if group.exported {
                            compiled_documents.extend(class_metadata.documents.iter().filter_map(|document| document_path(&document.uri)));
                            metadata.documents.extend(class_metadata.documents);
                        }
                    }
                    // The class is not found, or its group does not transform: an error of the
                    // transform, which the diagnostics of the transform reported if they
                    // have it. Anything else is a document the emitter refuses.
                    Err(ClassGroupError::Transform(reason)) => {
                        if !reported_errors {
                            errors.push(diagnostics::error(FerroXamlDiagnosticCodes::TRANSFORM_ERROR, class_document, &reason));
                        }
                    }
                    Err(ClassGroupError::Emit(reasons)) => errors.extend(reasons.lines().map(|reason| {
                        // A reason names its document when it is not the document of the class.
                        let (document, reason) = borrowed
                            .iter()
                            .find_map(|(name, _)| reason.strip_prefix(*name).and_then(|rest| rest.strip_prefix(": ")).map(|rest| (*name, rest)))
                            .unwrap_or((class_document.as_str(), reason));
                        diagnostics::error(FerroXamlDiagnosticCodes::EMIT_ERROR, document, reason)
                    })),
                }
                modules.push(Module { name: group.module.clone(), path, exported: group.exported, file: true });
                continue;
            }

            let file = match &model_host {
                Some((type_system, _, types)) => {
                    let host = EmitterHost { type_system: type_system.clone(), types, parsers: Vec::new() };
                    let options = TransformOptions {
                        local_assembly: Some(assembly_name.clone()),
                        create_source_info: group.create_source_info.unwrap_or(assembly_source_info),
                        use_compiled_bindings_by_default: self.default_compile_bindings,
                        diagnostic_handler: Some(diagnostics.handler()),
                        design_mode: false,
                    };
                    generate_file_with(&host, &assembly_name, &root_uri, &borrowed, &options)
                }
                #[cfg(feature = "runtime-host")]
                None => {
                    let Some(assembly) = self.assembly else { break };
                    runtime_host::generate_file(assembly, &root_uri, &borrowed, group.create_source_info, self.default_compile_bindings, &dependencies)
                }
                // Reported before the groups: without the feature no group is compiled
                // against the run-time type system.
                #[cfg(not(feature = "runtime-host"))]
                None => break,
            };
            let reported_errors = diagnostics.report(&mut lines, &mut errors);
            // A group that does not transform is one error of the transform, which the
            // diagnostics of the transform reported if they have it; a document the emitter
            // refuses is an error of the emit, each with its document.
            let mut group_reported = reported_errors;
            for (name, reason) in &file.documents {
                let Some(reason) = reason else { continue };
                let reason = reason.replace(['\r', '\n'], " ");
                match reason.starts_with(GROUP_NOT_TRANSFORMED) {
                    true if group_reported => {}
                    true => {
                        group_reported = true;
                        errors.push(diagnostics::error(FerroXamlDiagnosticCodes::TRANSFORM_ERROR, &format!("the group `{}`", group.module), &reason));
                    }
                    false => errors.push(diagnostics::error(FerroXamlDiagnosticCodes::EMIT_ERROR, name, &reason)),
                }
            }
            write_if_changed(&path, &file.source, &mut errors);
            write_if_changed(&xaml_directory.join(format!("{}.map.json", group.module)), &file.position_map, &mut errors);
            if group.exported {
                metadata.documents.extend(file.metadata(&self.crate_name, &module_path, &[]).documents);
                compiled_documents.extend(documents.iter().map(|(name, _)| format!("/{name}")));
            }
            modules.push(Module { name: group.module.clone(), path, exported: group.exported, file: false });
        }
        for path in &self.checked_in_metadata {
            rerun(&mut lines, path);
            let read = fs::read_to_string(path).map_err(|error| error.to_string()).and_then(|text| XamlMetadata::parse(&text));
            match read {
                Ok(read) if read.name == assembly_name => metadata.documents.extend(read.documents),
                Ok(read) => errors.push(format!(
                    "{}: the file describes the assembly `{}`, the crate is `{}`",
                    path.display(),
                    read.name,
                    assembly_name
                )),
                Err(error) => errors.push(format!("{}: {error}", path.display())),
            }
        }

        // 3. The assets.
        let mut assets: Vec<(String, PathBuf)> = Vec::new();
        for directory in &self.asset_directories {
            let directory = self.manifest_dir.join(directory);
            rerun(&mut lines, &directory);
            if let Err(error) = collect(&self.manifest_dir, &directory, &mut assets) {
                errors.push(error);
            }
        }
        assets.retain(|(rooted, _)| !compiled_documents.contains(rooted));
        assets.sort();
        assets.dedup();

        if !errors.is_empty() {
            return Outcome { lines, errors };
        }

        // 4. The `.xamlmeta` (with the type model of the crate, when it was scanned) and
        // the file the crate includes.
        let metadata_path = self.out_dir.join(format!("{}.xamlmeta", self.crate_name));
        let metadata_text = match model {
            Some(mut model) => {
                model.name = metadata.name;
                model.crate_name = metadata.crate_name;
                model.documents = metadata.documents;
                model.dependencies = metadata.dependencies;
                model.to_json()
            }
            None => metadata.to_json(),
        };
        let started = Instant::now();
        report.model_bytes = metadata_text.len();
        match ferroui_build_scan::export::write_if_changed(&metadata_path, &metadata_text) {
            Ok(written) => report.model_written = written,
            Err(error) => errors.push(error),
        }
        report.write = started.elapsed();
        // What the scan cost, for whoever judges it (`export::ScanReport`).
        if scanned {
            if let Err(error) = report.write(&self.out_dir) {
                errors.push(error);
            }
        }
        // A crate that only exports its model includes nothing.
        if self.assembly.is_some() || !self.groups.is_empty() || !self.asset_directories.is_empty() {
            let text = crate_file(&assembly_name, &modules, &self.loaders, &assets);
            write_if_changed(&xaml_directory.join("mod.rs"), &text, &mut errors);
        }
        if !errors.is_empty() {
            return Outcome { lines, errors };
        }

        // 5. For the dependents, and for the crate itself.
        lines.push(format!("cargo::metadata=xamlmeta={}", metadata_path.display()));
        lines.push(format!("cargo::rustc-env={XAMLMETA_VARIABLE}={}", metadata_path.display()));
        Outcome { lines, errors }
    }
}

/// The run-time host of the compiler: the documents are compiled against the types the
/// build script registered in its process. With the feature `runtime-host`, which links
/// the XAML runtime library and, through it, the controls.
#[cfg(feature = "runtime-host")]
mod runtime_host {
    use ferroui_base::metadata::MarkupAssembly;
    use ferroui_markup_xaml::RuntimeXamlLoaderConfiguration;
    use ferroui_markup_xaml_loader::rust_emitter::{GeneratedFile, XamlMetadata};
    use ferroui_markup_xaml_loader::FerroRuntimeXamlLoader;

    /// Makes the assembly of the crate and the runtime library known to the compiler.
    pub(super) fn register(assembly: &'static MarkupAssembly) {
        // The compiler resolves the assembly of the crate and the types of the runtime
        // library; every other type is the build script's to register.
        ferroui_markup_xaml::register_types();
        MarkupAssembly::register(assembly);
        // Makes the assembly known to the asset loader, as the `register_types()` of the
        // crate does: the host of the emitter in the tests of a crate runs with it.
        ferroui_base::platform::register_assets(assembly.name, &[]);
        FerroRuntimeXamlLoader::register();
    }

    /// The generated file of a group, with the configuration of the run-time loader.
    pub(super) fn generate_file(
        assembly: &'static MarkupAssembly,
        root_uri: &str,
        documents: &[(&str, &str)],
        create_source_info: Option<bool>,
        default_compile_bindings: bool,
        dependencies: &[XamlMetadata],
    ) -> GeneratedFile {
        let mut configuration = RuntimeXamlLoaderConfiguration::new();
        configuration.local_assembly = Some(assembly);
        configuration.use_compiled_bindings_by_default = default_compile_bindings;
        if let Some(create_source_info) = create_source_info {
            configuration.set_create_source_info(create_source_info);
        }
        ferroui_markup_xaml_loader::rust_emitter::generate_file(assembly.name, root_uri, documents, &configuration, dependencies)
    }
}

/// The module of a group in the file the crate includes.
struct Module {
    name: String,
    /// The generated file.
    path: PathBuf,
    /// Whether the loader table of the crate asks the table of the module.
    exported: bool,
    /// Whether the generated file is a module file of its own (the file of a class, which
    /// starts with attributes of the module) and not the body of a module.
    file: bool,
}

/// The rooted path (`/Folder/Style.xaml`) of the document with the URI `uri`.
fn document_path(uri: &str) -> Option<String> {
    let rest = uri.split_once("://")?.1;
    rest.find('/').map(|separator| rest[separator..].to_string())
}

/// The file of the class whose document is `class_document`, among the documents of its
/// crate: the class is the type the models have for the `x:Class` of the document, and
/// the group is the document with the documents it includes.
#[allow(clippy::too_many_arguments)]
fn class_group(
    host: &EmitterHost<'_>,
    models: &dyn IXamlTypeSystem,
    root_uri: &str,
    documents: &[(&str, &str)],
    class_document: &str,
    constructor: Option<ClassConstructor>,
    module_path: &str,
    options: &TransformOptions,
) -> Result<ferroui_markup_xaml_loader::rust_emitter::ClassFile, ClassGroupError> {
    let group = class_document_group(root_uri, documents, class_document).map_err(ClassGroupError::Transform)?;
    let class_name = class_of_document(&group[0].1)
        .map_err(ClassGroupError::Transform)?
        .ok_or_else(|| ClassGroupError::Transform("the document names no class (`x:Class`)".to_string()))?;
    let class = models.find_type(&class_name).ok_or_else(|| {
        ClassGroupError::Transform(format!(
            "the type models have no type `{class_name}`, which the document names with `x:Class`: the class is not declared in the sources of the crate, or its declaration is not read"
        ))
    })?;
    generate_class_file_with(host, &ClassGroup { class, documents: &group, constructor, module_path }, options).map_err(|reasons| {
        match reasons.strip_prefix(CLASS_GROUP_NOT_TRANSFORMED) {
            Some(_) => ClassGroupError::Transform(reasons),
            None => ClassGroupError::Emit(reasons),
        }
    })
}

/// Why the file of a class is not generated.
enum ClassGroupError {
    /// The group of the class is not found or does not transform (upstream's
    /// `TransformError`).
    Transform(String),
    /// Documents the emitter refuses, one reason per line (upstream's `EmitError`).
    Emit(String),
}

/// Compiles every `.xaml` file of the crate whose build script is running
/// (`Build::from_env().assembly(assembly).compile_xaml().run()`).
pub fn compile_xaml(assembly: &'static MarkupAssembly) {
    Build::from_env().assembly(assembly).compile_xaml().run();
}

/// Embeds the files below `directories` as the assets of the crate whose build script
/// is running (`Build::from_env().assembly(assembly).embed_assets(directories).run()`).
pub fn embed_assets(assembly: &'static MarkupAssembly, directories: &[&str]) {
    Build::from_env().assembly(assembly).embed_assets(directories).run();
}

/// Scans the sources of the crate whose build script is running and exports its type
/// model (`Build::from_env().export_metadata().run()`).
pub fn export_metadata() {
    Build::from_env().export_metadata().run();
}

/// Every file below `directory`, with its rooted path below `root` (`/Assets/a.png`),
/// in the order of the names. Directories whose name starts with a dot and the
/// directory `target` of `root` are skipped.
fn collect(root: &Path, directory: &Path, found: &mut Vec<(String, PathBuf)>) -> Result<(), String> {
    let entries = fs::read_dir(directory).map_err(|error| format!("{}: {error}", directory.display()))?;
    let mut paths = Vec::new();
    for entry in entries {
        paths.push(entry.map_err(|error| format!("{}: {error}", directory.display()))?.path());
    }
    paths.sort();
    for path in paths {
        let name = path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default();
        if path.is_dir() {
            if !name.starts_with('.') && !(directory == root && name == "target") {
                collect(root, &path, found)?;
            }
            continue;
        }
        let relative = path.strip_prefix(root).map_err(|_| format!("{} is not below {}", path.display(), root.display()))?;
        let parts: Vec<String> = relative.components().map(|part| part.as_os_str().to_string_lossy().into_owned()).collect();
        found.push((format!("/{}", parts.join("/")), path));
    }
    Ok(())
}

/// Writes `text` to `path` unless the file holds it already, so that a build that
/// changed nothing does not make the compiler run again.
fn write_if_changed(path: &Path, text: &str, errors: &mut Vec<String>) {
    if let Err(error) = ferroui_build_scan::export::write_if_changed(path, text) {
        errors.push(error);
    }
}

/// The text of `$OUT_DIR/xaml/mod.rs`, which `include_compiled_xaml!()` includes at the
/// root of the crate: the module of every group, and the module `compiled_markup`
/// with the asset table, the loader table of the crate (the checked-in tables, then
/// the groups, in order) and `register()`.
fn crate_file(assembly_name: &str, modules: &[Module], loaders: &[String], assets: &[(String, PathBuf)]) -> String {
    let mut text = String::new();
    text.push_str("// @generated by ferroui-build (Build::run). Do not edit.\n");
    for Module { name: module, path, file, .. } in modules {
        text.push('\n');
        text.push_str(&format!("/// The compiled documents of the group `{module}`.\n"));
        text.push_str("#[doc(hidden)]\n");
        text.push_str("#[rustfmt::skip]\n");
        if *file {
            // The file of a class is a module file: it starts with attributes of the module.
            text.push_str(&format!("#[path = {}]\n", rust_string_literal(&path.display().to_string())));
            text.push_str(&format!("pub mod {module};\n"));
            continue;
        }
        // A document that is not public (`x:ClassModifier`) and that the documents of its
        // group only merge has a build function nothing calls: its content is in theirs.
        text.push_str("#[allow(dead_code)]\n");
        text.push_str(&format!("pub mod {module} {{\n"));
        text.push_str(&format!("    include!({});\n", rust_string_literal(&path.display().to_string())));
        text.push_str("}\n");
    }
    text.push('\n');
    text.push_str("/// The compiled markup and the embedded assets of the crate.\n");
    text.push_str("#[doc(hidden)]\n");
    text.push_str("#[rustfmt::skip]\n");
    text.push_str("pub mod compiled_markup {\n");
    text.push_str("    /// The assembly of the crate.\n");
    text.push_str(&format!("    pub const ASSEMBLY_NAME: &str = {};\n", rust_string_literal(assembly_name)));
    text.push('\n');
    text.push_str("    /// The embedded assets of the crate, by rooted path.\n");
    text.push_str("    pub static ASSETS: &[(&str, &[u8])] = &[\n");
    for (rooted, path) in assets {
        text.push_str(&format!(
            "        ({}, include_bytes!({})),\n",
            rust_string_literal(rooted),
            rust_string_literal(&path.display().to_string())
        ));
    }
    text.push_str("    ];\n");
    text.push('\n');
    text.push_str("    /// The loader of the compiled markup of the crate: the object of the document with the URI\n");
    text.push_str("    /// `uri`, from the first table that has it; `Ok(None)` if none has.\n");
    text.push_str("    #[allow(unused_variables)]\n");
    text.push_str("    pub fn try_load(\n");
    text.push_str("        service_provider: ::core::option::Option<&::std::rc::Rc<dyn ::ferroui_base::metadata::IServiceProvider>>,\n");
    text.push_str("        uri: &str,\n");
    text.push_str("    ) -> ::core::result::Result<::core::option::Option<::ferroui_base::BoxedValue>, ::ferroui_markup_xaml::XamlLoadException> {\n");
    let tables = loaders
        .iter()
        .cloned()
        .chain(modules.iter().filter(|module| module.exported).map(|module| format!("super::{}::try_load", module.name)));
    for table in tables {
        text.push_str(&format!("        if let ::core::option::Option::Some(loaded) = {table}(service_provider, uri)? {{\n"));
        text.push_str("            return ::core::result::Result::Ok(::core::option::Option::Some(loaded));\n");
        text.push_str("        }\n");
    }
    text.push_str("        ::core::result::Result::Ok(::core::option::Option::None)\n");
    text.push_str("    }\n");
    text.push('\n');
    text.push_str("    /// Registers the assets and the compiled markup of the crate. The assembly is made known\n");
    text.push_str("    /// to the asset loader even without assets: a load by URI asks it for the assembly of the\n");
    text.push_str("    /// document.\n");
    text.push_str("    pub fn register() {\n");
    text.push_str("        ::ferroui_base::platform::register_assets(ASSEMBLY_NAME, ASSETS);\n");
    text.push_str("        ::ferroui_markup_xaml::FerroXamlLoader::register_compiled_xaml(ASSEMBLY_NAME, try_load);\n");
    text.push_str("    }\n");
    text.push_str("}\n");
    text
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Not from upstream: the file a crate includes names the generated files, chains the
    /// loader tables (the checked-in ones first, a group that is not exported not at all)
    /// and registers the assets with the table.
    #[test]
    fn crate_file_declares_the_modules_and_the_loader_table() {
        let module = |name: &str, exported: bool, file: bool| Module { name: name.to_string(), path: PathBuf::from(format!("/out/xaml/{name}.rs")), exported, file };
        let modules = vec![module("compiled_xaml", true, false), module("compiled_xaml_source_info", false, false), module("compiled_main_window", true, true)];
        let assets = vec![("/Assets/a.png".to_string(), PathBuf::from("/crate/Assets/a.png"))];
        let text = crate_file("Tests", &modules, &["crate::compiled_main::try_load".to_string()], &assets);
        assert!(text.contains("pub mod compiled_xaml {\n    include!(\"/out/xaml/compiled_xaml.rs\");\n}\n"), "{text}");
        assert!(text.contains("pub mod compiled_xaml_source_info {\n"), "{text}");
        assert!(text.contains("    pub const ASSEMBLY_NAME: &str = \"Tests\";\n"), "{text}");
        assert!(text.contains("        (\"/Assets/a.png\", include_bytes!(\"/crate/Assets/a.png\")),\n"), "{text}");
        let checked_in = text.find("= crate::compiled_main::try_load(service_provider, uri)?").expect("the checked-in table");
        let group = text.find("= super::compiled_xaml::try_load(service_provider, uri)?").expect("the table of the group");
        assert!(checked_in < group, "{text}");
        assert!(!text.contains("super::compiled_xaml_source_info::try_load"), "{text}");
        // The file of a class is a module file of its own.
        assert!(text.contains("#[path = \"/out/xaml/compiled_main_window.rs\"]\npub mod compiled_main_window;\n"), "{text}");
        assert!(text.contains("= super::compiled_main_window::try_load(service_provider, uri)?"), "{text}");
    }

    /// Not from upstream: `export_metadata()` scans the sources of the crate, writes its
    /// type model into its `.xamlmeta` and names every file it read; the build of a crate
    /// that depends on it reads that file and resolves against the model in it.
    #[test]
    fn export_metadata_writes_the_model_and_reads_the_models_of_the_dependencies() {
        let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).with_file_name("FerroUI.Build.Scan").join("tests").join("fixtures");
        let out = env::temp_dir().join(format!("ferroui-build-export-{}", std::process::id()));
        let first = Build::new(fixtures.join("scanner"), out.join("fixture"), "fixture", Vec::new()).source_root("lib.rs").export_metadata().execute();
        assert_eq!(first.errors, Vec::<String>::new());
        let fixture_file = out.join("fixture").join("fixture.xamlmeta");
        assert!(first.lines.contains(&format!("cargo::metadata=xamlmeta={}", fixture_file.display())), "{:?}", first.lines);
        let border = fixtures.join("scanner").join("controls").join("border.rs");
        assert!(first.lines.contains(&format!("cargo::rerun-if-changed={}", border.display())), "{:?}", first.lines);
        // What the scanner does not read is a warning of the build.
        assert!(first.lines.iter().any(|line| line.starts_with("cargo::warning=") && line.contains("error FRN9010")), "{:?}", first.lines);
        let text = fs::read_to_string(&fixture_file).expect("the .xamlmeta of the fixture");
        let model = AssemblyModel::parse(&text).expect("a file of format 2");
        assert_eq!((model.name.as_str(), model.crate_name.as_str()), ("Fixture", "fixture"));
        assert!(model.find_type("Fixture.Controls.Border").is_some() && !model.exports.is_empty());
        assert!(model.documents.is_empty() && model.dependencies.is_empty());
        assert_eq!(XamlMetadata::parse(&text).map(|metadata| metadata.name), Ok("Fixture".to_string()));
        assert!(!out.join("fixture").join("xaml").join("mod.rs").exists(), "a crate that only exports its model includes nothing");

        let second = Build::new(fixtures.join("dependent"), out.join("dependent"), "dependent", vec![fixture_file.clone()]).export_metadata().execute();
        assert_eq!(second.errors, Vec::<String>::new());
        assert!(second.lines.contains(&format!("cargo::rerun-if-changed={}", fixture_file.display())), "{:?}", second.lines);
        let text = fs::read_to_string(out.join("dependent").join("dependent.xamlmeta")).expect("the .xamlmeta of the dependent crate");
        let model = AssemblyModel::parse(&text).expect("a file of format 2");
        assert_eq!((model.name.as_str(), model.crate_name.as_str()), ("dependent", "dependent"));
        assert_eq!(model.dependencies, [fixture_file.display().to_string()]);
        let card = model.find_type("Card").expect("the class of the dependent crate");
        assert_eq!(card.registered[0].name.as_deref(), Some("Background"));
        assert_eq!(card.base.as_ref().map(|base| base.text.as_str()), Some("::fixture::controls::border::Border"));
        // The models are read back as a set, the dependency through the file that names it.
        let (models, files) = ModelSet::read(&[out.join("dependent").join("dependent.xamlmeta")]).expect("the two files");
        assert_eq!(models.iter().map(|model| model.name.as_str()).collect::<Vec<_>>(), ["dependent", "Fixture"]);
        assert_eq!(files.len(), 2);

        let missing = Build::new(fixtures.join("dependent"), out.join("missing"), "dependent", Vec::new()).source_root("main.rs").export_metadata().execute();
        assert_eq!(missing.errors.len(), 1, "{:?}", missing.errors);
        assert!(missing.errors[0].ends_with("main.rs, is not a file"), "{:?}", missing.errors);
        let _ = fs::remove_dir_all(&out);
    }

    /// Not from upstream: the two texts of the base crate the scanner states itself, because
    /// the crate it is in cannot link the base crate, are the ones of the base crate.
    #[test]
    fn texts_the_scanner_states_are_the_ones_of_the_base_crate() {
        assert_eq!(ferroui_build_scan::FERRO_XML_NAMESPACE, ferroui_base::metadata::FERRO_XML_NAMESPACE);
        assert_eq!(ferroui_build_scan::CREATE_SOURCE_INFO, MarkupAssembly::CREATE_SOURCE_INFO);
        assert_eq!(ferroui_build_scan::USE_COMPILED_BINDINGS_BY_DEFAULT, MarkupAssembly::USE_COMPILED_BINDINGS_BY_DEFAULT);
    }

    /// Not from upstream: against the type models a build reads the assembly from the
    /// sources and compiles the document of a class of the crate; what the models do not
    /// have is an error that names the document. The fixture declares no framework type,
    /// so the group does not get as far as a transform here: the include fixture
    /// (`tests/XamlIncludeFixture`) is the build that compiles.
    #[test]
    fn class_document_is_compiled_against_the_models_only() {
        let fixtures = Path::new(env!("CARGO_MANIFEST_DIR")).with_file_name("FerroUI.Build.Scan").join("tests").join("fixtures");
        let out = env::temp_dir().join(format!("ferroui-build-class-{}", std::process::id()));
        let document = "<Border xmlns='https://github.com/ferroui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' x:Class='Fixture.Missing'/>";
        let group = || XamlGroup::new("compiled_border").documents(&[("Border.xaml", document)]).class_document("Border.xaml");
        let build = |name: &str| Build::new(fixtures.join("scanner"), out.join(name), "fixture", Vec::new()).source_root("lib.rs");

        let on_models = build("models").type_system(TypeSystem::Model).compile_group(group()).execute();
        assert_eq!(on_models.errors.len(), 1, "{:?}", on_models.errors);
        assert!(
            on_models.errors[0].starts_with("Border.xaml: error FRN2000: the type models have no type `Fixture.Missing`, which the document names with `x:Class`"),
            "{:?}",
            on_models.errors
        );
        // The sources were scanned: the files are inputs of the build.
        let border = fixtures.join("scanner").join("controls").join("border.rs");
        assert!(on_models.lines.contains(&format!("cargo::rerun-if-changed={}", border.display())), "{:?}", on_models.lines);

        // Against the run-time type system the document of a class is not compiled; without
        // the feature that links that type system no document is.
        static ASSEMBLY: MarkupAssembly =
            MarkupAssembly { name: "Fixture", crate_name: "fixture", xmlns_definitions: &[], xmlns_prefixes: &[], metadata: &[] };
        let at_run_time = build("runtime").assembly(&ASSEMBLY).compile_group(group()).execute();
        assert_eq!(at_run_time.errors.len(), 1, "{:?}", at_run_time.errors);
        let expected = match cfg!(feature = "runtime-host") {
            true => "Border.xaml: error FRN2000: the document of a class of the crate is compiled against the type models only",
            false => "the documents are compiled against the type models (Build::type_system(TypeSystem::Model)): the run-time type system is the feature `runtime-host`",
        };
        assert!(at_run_time.errors[0].starts_with(expected), "{:?}", at_run_time.errors);
        let _ = fs::remove_dir_all(&out);
    }

    /// Not from upstream: a build without an assembly reports it, with the lines that make
    /// Cargo run the script again.
    #[test]
    fn build_without_an_assembly_is_an_error() {
        let outcome = Build::new(PathBuf::from("/crate"), PathBuf::from("/out"), "my-crate", Vec::new()).compile_xaml().execute();
        assert_eq!(outcome.errors, ["the assembly of the crate is not stated (Build::assembly)"]);
        assert_eq!(outcome.lines, ["cargo::rerun-if-changed=/crate/build.rs", "cargo::rerun-if-changed=/crate/Cargo.toml"]);
    }
}