1use crate::oo::ClassCode;
5use crate::unit::{LoadError, LoadedProgram, Loader, RunUnit};
6use crate::Compiled;
7use rt::unit::FoundClass;
8use std::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>,
18 pub dirs: Vec<PathBuf>,
19 pub copy: copy::Libraries,
20 pub flags: Vec<String>,
21}
22
23fn member_name(name: &str) -> bool {
24 !name.is_empty() && name.len() <= 30 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '@' || c == '#' || c == '$')
25}
26
27impl Library {
28 fn search(&mut self, name: &str) -> Result<(Program, PathBuf), LoadError> {
29 let candidates = [name.to_owned(), name.to_ascii_lowercase()];
30 let path = self
31 .dirs
32 .iter()
33 .flat_map(|d| candidates.iter().flat_map(move |n| ["", ".cbl", ".CBL", ".cob", ".COB"].iter().map(move |e| d.join(format!("{n}{e}")))))
34 .find(|p| p.is_file())
35 .ok_or(LoadError::NotFound)?;
36 let text = std::fs::read(&path).map(|b| copy::decode(&b)).map_err(|e| LoadError::Compile(format!("{}: {e}", path.display())))?;
37 let mut programs = syntax::parse_all_with(&text, &self.copy.with_program(&path))
38 .map_err(|e| LoadError::Compile(format!("{name} does not compile: {}", e.place(&path.display().to_string()))))?;
39 let first = programs.remove(0);
40 self.programs.extend(programs);
41 Ok((first, path))
42 }
43}
44
45impl Loader<Rc<Compiled>> for Library {
46 type Class = Rc<ClassCode>;
47
48 fn program(&mut self, name: &str) -> Result<LoadedProgram<Rc<Compiled>>, LoadError> {
49 if !member_name(name) {
50 return Err(LoadError::NotFound);
51 }
52 let (program, source) = match self.programs.iter().position(|p| p.id.eq_ignore_ascii_case(name)) {
53 Some(i) => (self.programs.remove(i), None),
54 None => self.search(name).map(|(p, path)| (p, Some(path)))?,
55 };
56 let compiled = crate::compile(program, &self.flags).map_err(|errors| {
57 let first = syntax::most_severe(&errors).map(|e| e.place(name)).unwrap_or_default();
58 LoadError::Compile(format!("{name} does not compile: {first}"))
59 })?;
60 let compiled = Rc::new(compiled);
61 let (files, size) = Self::shape(&compiled);
62 Ok(LoadedProgram { name: compiled.program.id.to_ascii_uppercase(), files, size, source, compiled })
63 }
64
65 fn holder(&self, entry: &str) -> Option<String> {
66 self.programs.iter().find(|p| crate::entry_points(p).iter().any(|e| e.name == entry)).map(|p| p.id.to_ascii_uppercase())
67 }
68
69 fn entry(program: &Rc<Compiled>, name: &str) -> Option<usize> {
70 program.entries.iter().position(|e| e.name == name)
71 }
72
73 fn shape(program: &Rc<Compiled>) -> (usize, usize) {
74 (program.program.files.len(), program.layout.size as usize)
75 }
76
77 fn class(&mut self, external: &str) -> Result<Option<FoundClass<Rc<ClassCode>>>, String> {
78 let Some((program, path)) = crate::oo::find_class(self, external)? else { return Ok(None) };
79 let at = crate::compile_time().map_err(|m| format!("class {external} does not compile: {m}"))?;
80 let (code, _) = crate::oo::class_code(&program, &self.flags, at).map_err(|errors| {
81 let first = syntax::most_severe(&errors).map(|e| e.place(external)).unwrap_or_default();
82 format!("class {external} does not compile: {first}")
83 })?;
84 let mut sources = program.sources;
85 if let (Some(own), Some(path)) = (sources.first_mut(), path) {
86 *own = path;
87 }
88 Ok(Some(FoundClass { code: Rc::new(code), sources }))
89 }
90}
91
92pub trait AddProgram {
94 fn add(&mut self, compiled: Option<Rc<Compiled>>, program: &Program, size: usize) -> usize;
95}
96
97impl AddProgram for RunUnit<'_> {
98 fn add(&mut self, compiled: Option<Rc<Compiled>>, program: &Program, size: usize) -> usize {
99 self.add_named(compiled, program.id.to_ascii_uppercase(), program.files.len(), size)
100 }
101}