1use crate::compile::CompileOptions;
13use crate::manifest::{self, MANIFEST, is_manifest};
14use crate::pp::SourceFiles;
15
16const SEP: char = std::path::MAIN_SEPARATOR;
18
19#[derive(Debug, Clone, Default)]
22pub struct ProjectPaths {
23 pub user_libraries: Vec<String>,
26}
27
28#[derive(Debug, Clone, Default)]
30pub struct Project {
31 pub sources: Vec<String>,
33 pub options: CompileOptions,
35 pub image: Option<String>,
37 pub preinit: bool,
40 pub warnings: bool,
42 pub warnings_as_errors: bool,
44 pub verbose: bool,
46 pub debug: bool,
49 pub resources: Vec<ResourceSpec>,
52 pub messages: Vec<String>,
55 pub manifest: bool,
58 pub libraries: Vec<String>,
62}
63
64#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct ResourceSpec {
67 pub file: String,
69 pub alias: Option<String>,
72 pub recurse: bool,
74}
75
76#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct Resource {
79 pub file: String,
81 pub name: String,
83}
84
85#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct DirEntry {
88 pub name: String,
90 pub is_dir: bool,
92 pub hidden: bool,
94}
95
96pub fn expand_resources(
102 specs: &[ResourceSpec],
103 list_dir: &mut dyn FnMut(&str) -> Option<Vec<DirEntry>>,
104) -> Vec<Resource> {
105 fn add(
106 file: &str,
107 name: &str,
108 recurse: bool,
109 list_dir: &mut dyn FnMut(&str) -> Option<Vec<DirEntry>>,
110 out: &mut Vec<Resource>,
111 ) {
112 let Some(entries) = list_dir(file) else {
113 out.push(Resource {
114 file: file.to_owned(),
115 name: name.to_owned(),
116 });
117 return;
118 };
119 for entry in entries {
120 if entry.hidden || entry.name == "." || entry.name == ".." {
121 continue;
122 }
123 let full = build_full_path(file, &entry.name);
124 let mut full_name = name.to_owned();
125 if !full_name.is_empty() && !full_name.ends_with('/') {
126 full_name.push('/');
127 }
128 full_name.push_str(&entry.name);
129 if !entry.is_dir {
130 out.push(Resource {
131 file: full,
132 name: full_name,
133 });
134 } else if recurse {
135 add(&full, &full_name, true, list_dir, out);
136 }
137 }
138 }
139 let mut out = Vec::new();
140 for spec in specs {
141 let name = spec
142 .alias
143 .clone()
144 .unwrap_or_else(|| cvt_dir_url(&spec.file));
145 add(&spec.file, &name, spec.recurse, list_dir, &mut out);
146 }
147 out
148}
149
150fn cvt_dir_url(path: &str) -> String {
154 let mut out = String::new();
155 let bytes = path.as_bytes();
156 let mut rest = path;
157 if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' {
158 out.push('/');
159 out.push_str(&path[..2]);
160 rest = &path[2..];
161 if !rest.starts_with(is_sep) {
162 out.push_str("./");
163 }
164 } else if bytes.len() >= 2 && is_sep(bytes[0] as char) && is_sep(bytes[1] as char) {
165 let end = path[2..].find(is_sep).map_or(path.len(), |at| at + 2);
167 out.push('/');
168 out.push_str(&path[..end]);
169 rest = &path[end..];
170 }
171 out.extend(rest.chars().map(|c| if is_sep(c) { '/' } else { c }));
172 while out.len() > 1 && out.ends_with('/') {
173 out.pop();
174 }
175 out
176}
177
178#[derive(Debug, Clone, PartialEq, Eq)]
180pub enum ProjectError {
181 Usage(String),
184 Failed(Vec<String>),
187}
188
189fn is_sep(c: char) -> bool {
192 c == '/' || c == '\\'
193}
194
195fn file_name_of(path: &str) -> &str {
198 let path = path.trim_end_matches(['/', '\\']);
199 path.rsplit(['/', '\\']).next().unwrap_or(path)
200}
201
202fn path_name(path: &str) -> &str {
203 match path.rfind(|c| is_sep(c) || c == ':') {
204 None => "",
205 Some(at) if path[at..].starts_with(':') => &path[..=at],
206 Some(at) if at == 0 || path[..at].ends_with(':') => &path[..=at],
208 Some(at) => &path[..at],
209 }
210}
211
212fn root_name(path: &str) -> &str {
214 match path.rfind(|c| is_sep(c) || c == ':') {
215 None => path,
216 Some(at) => &path[at + 1..],
217 }
218}
219
220fn is_absolute(path: &str) -> bool {
221 let mut chars = path.chars();
222 match (chars.next(), chars.next()) {
223 (Some(c), _) if is_sep(c) => true,
224 (Some(c), Some(':')) => c.is_ascii_alphabetic(),
225 _ => false,
226 }
227}
228
229fn build_full_path(dir: &str, file: &str) -> String {
230 if dir.is_empty() {
231 file.to_owned()
232 } else if dir.ends_with(|c| is_sep(c) || c == ':') {
233 format!("{dir}{file}")
234 } else if crate::builtin::is_built_in(dir) {
235 format!("{dir}/{file}")
237 } else {
238 format!("{dir}{SEP}{file}")
239 }
240}
241
242fn rem_ext(path: &str) -> &str {
244 let root = root_name(path);
245 match root.rfind('.') {
246 Some(at) => &path[..path.len() - root.len() + at],
247 None => path,
248 }
249}
250
251fn cvt_url_dir(url: &str) -> String {
254 url.replace('/', std::path::MAIN_SEPARATOR_STR)
255}
256
257#[derive(Debug, Clone, PartialEq, Eq)]
260enum Origin {
261 Normal,
263 Lib(String),
265}
266
267#[derive(Debug, Clone)]
268struct Module {
269 orig_name: String,
272 source: String,
274 search: String,
277 origin: Origin,
278 url: String,
281 excluded: bool,
282 test: bool,
285}
286
287struct Reader<'f, 'a> {
288 files: &'f mut (dyn SourceFiles + 'a),
289 user_source_paths: Vec<String>,
292 sys_source_paths: Vec<String>,
293 include_paths: Vec<String>,
296 defs: Vec<(String, Option<String>)>,
298 charset: Option<String>,
299 modules: Vec<Module>,
300 image: Option<String>,
301 no_system: bool,
303 system_included: bool,
305 text_tags: Vec<String>,
307 object_tags: Vec<String>,
310 object_keys: Vec<String>,
311 ifid: Option<String>,
314 preinit: Option<bool>,
315 debug: bool,
316 warnings: bool,
317 warnings_as_errors: bool,
318 verbose: bool,
319 source_text_group: bool,
320 resources: Vec<ResourceSpec>,
321 res_recurse: bool,
324 messages: Vec<String>,
325 lib_err: bool,
326 imports: Vec<(String, Option<String>)>,
329 opt_file: Option<String>,
330 opt_file_path: Option<String>,
333 manifest: bool,
336 libraries: Vec<String>,
338 reading: Vec<String>,
341}
342
343pub fn read_project(
346 files: &mut dyn SourceFiles,
347 args: &[String],
348 paths: &ProjectPaths,
349) -> Result<Project, ProjectError> {
350 let mut files = crate::builtin::WithBuiltIns::new(files);
352 let mut reader = Reader {
353 files: &mut files,
354 user_source_paths: Vec::new(),
355 sys_source_paths: paths.user_libraries.clone(),
356 include_paths: Vec::new(),
357 defs: Vec::new(),
358 charset: None,
359 modules: Vec::new(),
360 image: None,
361 no_system: false,
362 system_included: false,
363 text_tags: Vec::new(),
364 object_tags: Vec::new(),
365 object_keys: Vec::new(),
366 ifid: None,
367 preinit: None,
368 debug: false,
369 warnings: true,
370 warnings_as_errors: false,
371 verbose: false,
372 source_text_group: false,
373 resources: Vec::new(),
374 res_recurse: true,
375 messages: Vec::new(),
376 lib_err: false,
377 imports: Vec::new(),
378 opt_file: None,
379 opt_file_path: None,
380 manifest: false,
381 libraries: Vec::new(),
382 reading: Vec::new(),
383 };
384 reader.parse(args)?;
385 if reader.modules.is_empty() && reader.opt_file.is_none() {
387 if reader.files.exists(MANIFEST) {
388 reader.opt_file = Some(MANIFEST.to_owned());
389 } else {
390 return Err(ProjectError::Usage(String::new()));
391 }
392 }
393 if let Some(opt_file) = reader.opt_file.clone() {
394 let in_folder = build_full_path(&opt_file, MANIFEST);
396 let opt_file = if reader.files.exists(&in_folder) {
397 in_folder
398 } else {
399 opt_file
400 };
401 if !is_manifest(&opt_file) {
402 return Err(ProjectError::Failed(vec![format!(
403 "error: \"{opt_file}\" is not a manifest: a game is built from a \
404 hexicon.toml, or a folder with one"
405 )]));
406 }
407 let Some(text) = reader.files.read(&opt_file) else {
408 return Err(ProjectError::Failed(vec![format!(
409 "error: unable to read manifest \"{opt_file}\""
410 )]));
411 };
412 let args = manifest::game_args(&text).map_err(|problem| {
413 ProjectError::Failed(vec![format!("error: {opt_file}: {problem}")])
414 })?;
415 reader.opt_file_path = Some(path_name(&opt_file).to_owned());
416 reader.manifest = true;
417 reader.parse(&args)?;
418 }
419 if reader.lib_err {
420 return Err(ProjectError::Failed(reader.messages));
421 }
422 reader.finish()
423}
424
425impl Reader<'_, '_> {
426 fn parse_resources(&mut self, args: &[String]) -> Result<(), ProjectError> {
430 for arg in args {
431 match arg.as_str() {
432 "--recurse" => self.res_recurse = true,
433 "--no-recurse" => self.res_recurse = false,
434 _ if arg.starts_with('-') => {
435 return Err(ProjectError::Usage(format!("unknown option \"{arg}\"")));
436 }
437 _ => {
438 let (file, alias) = match arg.split_once('=') {
439 Some((file, alias)) => (file, Some(alias.to_owned())),
440 None => (arg.as_str(), None),
441 };
442 self.resources.push(ResourceSpec {
443 file: self.relative(file),
444 alias,
445 recurse: self.res_recurse,
446 });
447 }
448 }
449 }
450 Ok(())
451 }
452
453 fn relative(&self, name: &str) -> String {
456 match &self.opt_file_path {
457 None => name.to_owned(),
458 Some(dir) => {
459 let local = cvt_url_dir(name);
460 if is_absolute(&local) {
461 local
462 } else {
463 build_full_path(dir, &local)
464 }
465 }
466 }
467 }
468
469 fn look_up_pp_sym(&self, name: &str) -> Option<String> {
472 let mut found = None;
473 for (sym, value) in &self.defs {
474 if sym == name {
475 found = value.clone();
476 }
477 }
478 found
479 }
480
481 fn search_dirs(&self) -> Vec<String> {
489 self.user_source_paths
490 .iter()
491 .chain(&self.sys_source_paths)
492 .cloned()
493 .chain([
494 crate::builtin::SYSTEM.to_owned(),
495 crate::builtin::ROOT.to_owned(),
496 ])
497 .collect()
498 }
499
500 fn find_source(&mut self, source: &str, search: &str) -> String {
501 if is_absolute(search) || self.files.exists(source) {
502 return source.to_owned();
503 }
504 for dir in self.search_dirs() {
505 let path = build_full_path(&dir, search);
506 if self.files.exists(&path) {
507 return path;
508 }
509 }
510 source.to_owned()
511 }
512
513 fn add_module(
514 &mut self,
515 name: &str,
516 orig_name: &str,
517 search: String,
518 origin: Origin,
519 url: String,
520 ) {
521 self.modules.push(Module {
522 orig_name: orig_name.to_owned(),
523 source: manifest::source_name(name),
524 search,
525 origin,
526 url,
527 excluded: false,
528 test: false,
529 });
530 }
531
532 fn maybe_add_include_path(&mut self, path: &str) {
533 if !self.include_paths.iter().any(|have| have == path) {
534 self.include_paths.push(path.to_owned());
535 }
536 }
537
538 fn parse(&mut self, args: &[String]) -> Result<(), ProjectError> {
539 let mut at = 0;
540 let opt_arg = |at: &mut usize, len: usize| -> Option<String> {
542 let arg = &args[*at];
543 if arg.len() > len {
544 Some(arg[len..].to_owned())
545 } else if *at + 1 < args.len() {
546 *at += 1;
547 Some(args[*at].clone())
548 } else {
549 None
550 }
551 };
552 let missing = |arg: &str| ProjectError::Usage(format!("option \"{arg}\" needs a value"));
553 let bad = |arg: &str| ProjectError::Usage(format!("unknown option \"{arg}\""));
554 let long_arg = |at: &mut usize, arg: &str| -> Option<String> {
556 match arg.split_once('=') {
557 Some((_, value)) => Some(value.to_owned()),
558 None if *at + 1 < args.len() => {
559 *at += 1;
560 Some(args[*at].clone())
561 }
562 None => None,
563 }
564 };
565 while at < args.len() && args[at].starts_with('-') {
566 let arg = args[at].clone();
567 let long = arg.split_once('=').map_or(arg.as_str(), |(name, _)| name);
569 if matches!(long, "--source" | "--test" | "--library" | "--resources") {
570 break;
571 }
572 if long.starts_with("--") {
573 match long {
574 "--library-path" => {
575 let path = long_arg(&mut at, &arg).ok_or_else(|| missing(long))?;
576 let path = self.relative(&path);
577 self.user_source_paths.push(path);
578 }
579 "--charset" => {
580 self.charset = Some(long_arg(&mut at, &arg).ok_or_else(|| missing(long))?);
581 }
582 "--preinit" => self.preinit = Some(true),
583 "--no-preinit" => self.preinit = Some(false),
584 "--no-system" => self.no_system = true,
585 "--warnings" => self.warnings = true,
586 "--no-warnings" => self.warnings = false,
587 "--warnings-as-errors" => self.warnings_as_errors = true,
588 "--source-text-groups" => self.source_text_group = true,
589 "--help" => return Err(ProjectError::Usage(String::new())),
590 _ => return Err(bad(&arg)),
591 }
592 at += 1;
593 continue;
594 }
595 let bytes = arg.as_bytes();
599 match bytes.get(1).copied().unwrap_or(0) {
600 b'f' => {
601 if self.opt_file.is_some() {
602 return Err(ProjectError::Failed(vec![
603 "error: only one option file (-f) is allowed".to_owned(),
604 ]));
605 }
606 self.opt_file = Some(opt_arg(&mut at, 2).ok_or_else(|| missing(&arg))?);
607 }
608 b'D' => {
609 let def = opt_arg(&mut at, 2).ok_or_else(|| missing(&arg))?;
610 let (name, value) = def.split_once('=').unwrap_or((&def, ""));
611 self.defs.push((name.to_owned(), Some(value.to_owned())));
612 }
613 b'U' => {
614 let name = opt_arg(&mut at, 2).ok_or_else(|| missing(&arg))?;
615 self.defs.push((name, None));
616 }
617 b'v' if arg == "-v" => self.verbose = true,
618 b'd' if arg == "-d" => self.debug = true,
619 b'I' => {
620 let path = opt_arg(&mut at, 2).ok_or_else(|| missing(&arg))?;
621 let path = self.relative(&path);
622 self.include_paths.push(path);
623 }
624 b'o' => {
625 let path = opt_arg(&mut at, 2).ok_or_else(|| missing(&arg))?;
626 self.image = Some(self.relative(&path));
627 }
628 b'?' | b'h' if bytes.len() == 2 => return Err(ProjectError::Usage(String::new())),
629 _ => return Err(bad(&arg)),
630 }
631 at += 1;
632 }
633
634 while at < args.len() {
636 let arg = args[at].clone();
637 let (mut is_source, mut is_lib, mut is_test) = (false, false, false);
638 let name = if arg.starts_with('-') {
639 match arg.as_str() {
640 "--source" => is_source = true,
641 "--test" => {
642 is_source = true;
643 is_test = true;
644 }
645 "--library" => is_lib = true,
646 "--resources" => {
647 return self.parse_resources(&args[at + 1..]);
649 }
650 _ => return Err(ProjectError::Usage(format!("unknown option \"{arg}\""))),
651 }
652 at += 1;
653 match args.get(at) {
654 Some(name) => name.clone(),
655 None => {
656 return Err(ProjectError::Usage(format!(
657 "option \"{arg}\" needs a value"
658 )));
659 }
660 }
661 } else {
662 arg.clone()
663 };
664 if !is_source && !is_lib && is_manifest(&name) {
665 if self.opt_file.is_some() {
666 return Err(ProjectError::Failed(vec![
667 "error: only one option file (-f) is allowed".to_owned(),
668 ]));
669 }
670 self.opt_file = Some(name);
671 at += 1;
672 continue;
673 }
674 let path = self.relative(&name);
675 if !is_lib {
676 if self.image.is_none() && !is_test {
679 self.image = Some(format!("{}.hxg", rem_ext(&path)));
680 }
681 let file = manifest::source_name(&path);
684 let search = manifest::source_name(&name);
685 self.add_module(&file, rem_ext(&name), search, Origin::Normal, String::new());
686 if let Some(module) = self.modules.last_mut() {
687 module.test = is_test;
688 }
689 } else {
690 let found = self.find_library(&path, &name);
691 let first_lib_module = self.modules.len();
692 self.enter_lib(&found, "");
693 while let Some(flag @ ("--exclude" | "--include")) =
698 args.get(at + 1).map(String::as_str)
699 {
700 at += 2;
701 let Some(url) = args.get(at) else {
702 return Err(ProjectError::Usage(format!(
703 "option \"{flag}\" needs a value"
704 )));
705 };
706 if flag == "--include" {
707 let lib_path = path_name(&found).to_owned();
708 let full =
709 manifest::source_name(&build_full_path(&lib_path, &cvt_url_dir(url)));
710 let name = rem_ext(url).to_owned();
711 self.add_module(
712 &full,
713 &name,
714 full.clone(),
715 Origin::Lib(found.clone()),
716 name.clone(),
717 );
718 } else if let Some(module) = self.modules[first_lib_module..]
719 .iter_mut()
720 .find(|module| module.url.eq_ignore_ascii_case(url))
721 {
722 module.excluded = true;
723 }
724 }
725 }
726 at += 1;
727 }
728 Ok(())
729 }
730
731 fn find_library(&mut self, path: &str, name: &str) -> String {
736 if is_manifest(path) {
737 return self.find_source(path, name);
738 }
739 let kinds = |path: &str| [build_full_path(path, MANIFEST), format!("{path}.toml")];
742 for candidate in kinds(path) {
743 if self.files.exists(&candidate) {
744 return candidate;
745 }
746 }
747 let fallback = build_full_path(path, MANIFEST);
748 if is_absolute(name) {
749 return fallback;
750 }
751 for dir in self.search_dirs() {
752 for candidate in kinds(&build_full_path(&dir, name)) {
753 if self.files.exists(&candidate) {
754 return candidate;
755 }
756 }
757 }
758 fallback
759 }
760
761 fn sub_library(&mut self, full: String) -> String {
764 if is_manifest(&full) {
765 return full;
766 }
767 let beside = format!("{full}.toml");
768 if !self.files.exists(&build_full_path(&full, MANIFEST)) && self.files.exists(&beside) {
769 return beside;
770 }
771 build_full_path(&full, MANIFEST)
772 }
773
774 fn expand_names(&self, text: &str) -> (String, Vec<String>) {
777 const BAD_DOLLAR: &str =
778 "invalid '$' sequence - use '$$' for a literal dollar sign character";
779 let mut problems = Vec::new();
780 let mut expanded = String::new();
781 let mut rest = text;
782 while let Some(at) = rest.find('$') {
783 expanded.push_str(&rest[..at]);
784 let after = &rest[at + 1..];
785 if let Some(inner) = after.strip_prefix('(') {
786 if let Some(close) = inner.find(')') {
787 let name = &inner[..close];
788 match self.look_up_pp_sym(name) {
789 Some(value) => expanded.push_str(&value),
790 None => problems.push(format!("undefined name \"{name}\"")),
791 }
792 rest = &inner[close + 1..];
793 continue;
794 }
795 problems.push(BAD_DOLLAR.to_owned());
796 expanded.push('$');
797 rest = after;
798 } else if let Some(after) = after.strip_prefix('$') {
799 expanded.push('$');
800 rest = after;
801 } else {
802 problems.push(BAD_DOLLAR.to_owned());
803 expanded.push('$');
804 rest = after;
805 }
806 }
807 expanded.push_str(rest);
808 (expanded, problems)
809 }
810
811 fn need_macro(&mut self, place: &str, macro_name: &str, why: &str) {
814 if self.look_up_pp_sym(macro_name).is_none() {
815 let shown = ¯o_name[..macro_name.len().min(128)];
816 self.messages.push(format!(
817 "{place}: library requires the macro \"{shown}\" to be \
818 defined; use -D {shown}=value to define it, or {shown} = \
819 \"value\" in the manifest's [defines] ({why})"
820 ));
821 }
822 }
823
824 fn enter_lib(&mut self, full_name: &str, lib_url: &str) {
827 let same = |have: &String| {
828 have.replace('\\', "/")
829 .eq_ignore_ascii_case(&full_name.replace('\\', "/"))
830 };
831 if self.reading.iter().any(same) {
832 self.messages.push(format!(
833 "error: library \"{full_name}\" leads back to itself"
834 ));
835 self.lib_err = true;
836 return;
837 }
838 self.reading.push(full_name.to_owned());
839 self.process_lib(full_name, lib_url);
840 self.reading.pop();
841 }
842
843 fn process_lib(&mut self, full_name: &str, lib_url: &str) {
846 let lib_path = path_name(full_name).to_owned();
847 self.maybe_add_include_path(&lib_path);
848 let Some(text) = self.files.read(full_name) else {
849 self.messages
850 .push(format!("unable to open library file \"{full_name}\""));
851 self.lib_err = true;
852 return;
853 };
854 self.libraries.push(full_name.to_owned());
855 let lib = match manifest::library(&text) {
856 Ok(lib) => lib,
857 Err(problem) => {
858 self.messages.push(format!("{full_name}: {problem}"));
859 self.lib_err = true;
860 return;
861 }
862 };
863 for (name, why) in &lib.needs {
866 self.need_macro(full_name, name, why);
867 }
868 let place = |reader: &mut Self, value: &str| {
870 let (value, problems) = reader.expand_names(value);
871 for problem in problems {
872 reader.messages.push(format!("{full_name}: {problem}"));
873 }
874 let full = build_full_path(&lib_path, &cvt_url_dir(&value));
875 (value, full)
876 };
877 let import_name = if file_name_of(full_name).eq_ignore_ascii_case(MANIFEST) {
880 file_name_of(&lib_path).to_owned()
881 } else {
882 rem_ext(file_name_of(full_name)).to_owned()
883 };
884 let header = lib.header.as_ref().map(|header| place(self, header).1);
885 if import_name.eq_ignore_ascii_case("system") {
886 self.system_included = true;
887 }
888 self.text_tags
889 .extend(lib.text_tags.iter().map(|tag| tag.to_ascii_lowercase()));
890 self.object_tags
891 .extend(lib.object_tags.iter().map(|tag| tag.to_ascii_lowercase()));
892 self.object_keys.extend(lib.object_keys.iter().cloned());
893 if lib.ifid.is_some() {
894 self.ifid.clone_from(&lib.ifid);
895 }
896 self.imports.push((import_name, header));
897 for module in &lib.modules {
898 match module {
899 manifest::ModuleRef::Source(source) => {
901 let (value, full) = place(self, source);
902 let name = rem_ext(&value).to_owned();
903 let full = manifest::source_name(&full);
904 let url = format!("{lib_url}{name}");
905 self.add_module(
906 &full,
907 &name,
908 full.clone(),
909 Origin::Lib(full_name.to_owned()),
910 url,
911 );
912 }
913 manifest::ModuleRef::Library { name, .. } => {
914 let before = self.messages.len();
918 let (value, full) = place(self, name);
919 if self.messages.len() > before || value.trim().is_empty() {
920 self.lib_err = true;
921 continue;
922 }
923 let url = format!("{lib_url}{value}/");
924 let target = self.sub_library(full);
925 self.enter_lib(&target, &url);
926 }
927 }
928 }
929 for resource in &lib.resources {
930 let (value, full) = place(self, resource);
931 self.resources.push(ResourceSpec {
932 file: full,
933 alias: Some(value),
934 recurse: true,
935 });
936 }
937 }
938
939 fn finish(mut self) -> Result<Project, ProjectError> {
940 if !self.no_system && !self.system_included {
945 let found = self.find_library("system", "system");
946 let first = self.modules.len();
947 self.enter_lib(&found, "");
948 let system: Vec<Module> = self.modules.drain(first..).collect();
949 self.modules.splice(0..0, system);
950 }
951 let mut problems = Vec::new();
955 let same_file = |a: &str, b: &str| {
956 a.replace('\\', "/")
957 .eq_ignore_ascii_case(&b.replace('\\', "/"))
958 };
959 for (index, module) in self.modules.iter().enumerate() {
960 if module.excluded {
961 continue;
962 }
963 let twice = self.modules[..index]
964 .iter()
965 .any(|earlier| !earlier.excluded && same_file(&earlier.source, &module.source));
966 if twice {
967 let from = match &module.origin {
968 Origin::Lib(lib) => format!(" (from library \"{lib}\")"),
969 Origin::Normal => String::new(),
970 };
971 problems.push(format!(
972 "error: \"{}\"{from} is among the sources twice",
973 module.source
974 ));
975 }
976 }
977 if !problems.is_empty() {
978 let mut messages = self.messages;
979 messages.extend(problems);
980 return Err(ProjectError::Failed(messages));
981 }
982 let modules = std::mem::take(&mut self.modules);
984 let mut sources = Vec::new();
985 let mut module_names = Vec::new();
986 let mut from_library = Vec::new();
987 for (index, module) in modules.iter().enumerate() {
988 if module.excluded || (module.test && !self.debug) {
990 continue;
991 }
992 let path = self.find_source(&module.source, &module.search);
993 sources.push(path);
994 module_names.push((module.orig_name.clone(), index + 1));
995 from_library.push(!matches!(module.origin, Origin::Normal));
996 }
997 let mut defines: Vec<(String, String)> = Vec::new();
999 let mut undefines: Vec<String> = Vec::new();
1000 for (name, value) in &self.defs {
1001 defines.retain(|(have, _)| have != name);
1002 undefines.retain(|have| have != name);
1003 match value {
1004 Some(value) => defines.push((name.clone(), value.clone())),
1005 None => undefines.push(name.clone()),
1006 }
1007 }
1008 let include_paths = self.include_paths;
1009 Ok(Project {
1012 sources,
1013 options: CompileOptions {
1014 include_paths,
1015 defines,
1016 undefines,
1017 default_charset: self.charset,
1018 source_text_group: self.source_text_group,
1019 module_names,
1020 from_library,
1021 imports: std::mem::take(&mut self.imports),
1022 text_tags: std::mem::take(&mut self.text_tags),
1023 object_tags: std::mem::take(&mut self.object_tags),
1024 object_keys: std::mem::take(&mut self.object_keys),
1025 ifid: self.ifid.take(),
1026 debug: self.debug,
1027 ..CompileOptions::default()
1028 },
1029 image: self.image,
1030 preinit: self.preinit.unwrap_or(!self.debug),
1031 warnings: self.warnings,
1032 warnings_as_errors: self.warnings_as_errors,
1033 verbose: self.verbose,
1034 debug: self.debug,
1035 resources: self.resources,
1036 messages: self.messages,
1037 manifest: self.manifest,
1038 libraries: self.libraries,
1039 })
1040 }
1041}