1use crate::oo::ClassCode;
5use crate::unit::{LoadError, LoadedProgram, Loader, RunUnit};
6use crate::Compiled;
7use rt::unit::FoundClass;
8use std::path::{Path, PathBuf};
9use std::rc::Rc;
10use syntax::ast::Program;
11use syntax::copy;
12
13#[derive(Clone, Debug, Default)]
16pub struct Library {
17 pub programs: Vec<Program>,
20 pub dirs: Vec<PathBuf>,
21 pub copy: copy::Libraries,
22 pub flags: Vec<String>,
23 pub trace_statements: Option<rt::unit::StatementFilter>,
25 pub trace_input: bool,
27 pub statement_limit: Option<u64>,
29}
30
31impl Library {
32 fn search(&mut self, name: &str) -> Result<(Program, PathBuf), LoadError> {
33 let candidates = [name.to_owned(), name.to_ascii_lowercase()];
34 let path = self
35 .dirs
36 .iter()
37 .flat_map(|d| candidates.iter().flat_map(move |n| ["", ".cbl", ".CBL", ".cob", ".COB"].iter().map(move |e| d.join(format!("{n}{e}")))))
38 .find(|p| p.is_file())
39 .ok_or(LoadError::NotFound)?;
40 let text = std::fs::read(&path).map(|b| copy::decode(&b)).map_err(|e| LoadError::Compile(format!("{}: {e}", path.display())))?;
41 let mut programs = syntax::parse_all_with(&text, &self.copy.with_program(&path))
42 .map_err(|e| LoadError::Compile(format!("{name} does not compile: {}", e.place(&path.display().to_string()))))?;
43 let wanted = programs.iter().position(|p| loads_as(p, name)).or_else(|| programs.iter().position(|p| !p.is_prototype())).unwrap_or(0);
44 let found = programs.remove(wanted);
45 self.add_read(&path, programs);
46 Ok((found, path))
47 }
48
49 pub fn add_read(&mut self, path: &Path, programs: Vec<Program>) {
51 let shown = path.display().to_string();
52 self.programs.extend(programs.into_iter().map(|mut p| {
53 if let Some(own) = p.sources.first_mut() {
54 own.clone_from(&shown);
55 }
56 p
57 }));
58 }
59}
60
61pub(crate) fn loads_as(program: &Program, name: &str) -> bool {
64 !program.is_prototype() && program.load_name().eq_ignore_ascii_case(name)
65}
66
67impl Loader<Rc<Compiled>> for Library {
68 fn program(&mut self, name: &str) -> Result<LoadedProgram<Rc<Compiled>>, LoadError> {
69 if !rt::module::member_name(name) {
70 return Err(LoadError::NotFound);
71 }
72 let (program, source) = match self.programs.iter().position(|p| loads_as(p, name)) {
73 Some(i) => {
74 let program = self.programs.remove(i);
75 let source = program.sources.first().filter(|s| !s.is_empty()).map(PathBuf::from);
76 (program, source)
77 }
78 None => self.search(name).map(|(p, path)| (p, Some(path)))?,
79 };
80 let compiled = crate::compile(program, &self.flags).map_err(|errors| {
81 let first = syntax::most_severe(&errors).map(|e| e.place(name)).unwrap_or_default();
82 LoadError::Compile(format!("{name} does not compile: {first}"))
83 })?;
84 let compiled = Rc::new(compiled);
85 let (files, size) = Self::shape(&compiled);
86 Ok(LoadedProgram { name: compiled.program.load_name().to_ascii_uppercase(), files, size, source, compiled, recorded: Vec::new() })
87 }
88
89 fn holder(&self, entry: &str) -> Option<String> {
90 self.programs.iter().find(|p| crate::entry_points(p).iter().any(|e| e.name == entry)).map(|p| p.id.to_ascii_uppercase())
91 }
92
93 fn entry(program: &Rc<Compiled>, name: &str) -> Option<usize> {
94 program.entries.iter().position(|e| e.name == name)
95 }
96
97 fn shape(program: &Rc<Compiled>) -> (usize, usize) {
98 (program.program.files.len(), program.layout.size as usize)
99 }
100
101 fn nested(program: &Rc<Compiled>) -> &[String] {
102 &program.program.nested
103 }
104
105 fn source(program: &Rc<Compiled>, file: usize) -> Option<String> {
106 program.program.sources.get(file).cloned()
107 }
108
109 fn class(&mut self, external: &str) -> Result<Option<FoundClass<Rc<ClassCode>>>, String> {
110 let Some((program, path)) = crate::oo::find_class(self, external)? else { return Ok(None) };
111 let at = crate::compile_time().map_err(|m| format!("class {external} does not compile: {m}"))?;
112 let (code, _) = crate::oo::class_code(&program, &self.flags, at).map_err(|errors| {
113 let first = syntax::most_severe(&errors).map(|e| e.place(external)).unwrap_or_default();
114 format!("class {external} does not compile: {first}")
115 })?;
116 let mut sources = program.sources;
117 if let (Some(own), Some(path)) = (sources.first_mut(), path) {
118 *own = path;
119 }
120 Ok(Some(FoundClass { code: Rc::new(code), sources }))
121 }
122
123 fn mapset(&mut self, name: &str) -> Option<Result<rt::bms::Mapset, String>> {
124 syntax::bms::find_mapset(&self.copy, name).map(|found| found.map_err(|e| e.message))
125 }
126}
127
128pub trait AddProgram {
130 fn add(&mut self, compiled: Option<Rc<Compiled>>, program: &Program, size: usize) -> usize;
131}
132
133impl AddProgram for RunUnit<'_> {
134 fn add(&mut self, compiled: Option<Rc<Compiled>>, program: &Program, size: usize) -> usize {
135 self.add_named(compiled, program.id.to_ascii_uppercase(), program.files.len(), size)
136 }
137}