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