use crate::compiler::diagnostic::Message;
use crate::msg;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Included {
pub name: String,
pub text: String,
}
pub trait Include {
fn load(&self, path: &str, from: Option<&str>) -> Result<Included, Message>;
fn load_library(&self, _name: &str) -> Option<Result<Included, Message>> {
None
}
fn load_bytes(&self, path: &str) -> Result<std::sync::Arc<[u8]>, Message> {
Err(msg!("E0601-sample-unavailable", path = path))
}
fn list(&self, _dir: &str) -> Vec<String> {
Vec::new()
}
fn libraries(&self) -> Vec<(String, Vec<String>)> {
Vec::new()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Source<'a> {
pub name: &'a str,
pub text: &'a str,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Files {
base: PathBuf,
}
impl Files {
pub fn new(base: impl Into<PathBuf>) -> Self {
Files { base: base.into() }
}
pub fn beside(file: impl AsRef<Path>) -> Self {
let dir = file
.as_ref()
.parent()
.map(Path::to_path_buf)
.unwrap_or_default();
Files::new(dir)
}
pub fn base(&self) -> &Path {
&self.base
}
}
impl Include for Files {
fn list(&self, dir: &str) -> Vec<String> {
let Ok(rd) = std::fs::read_dir(self.base.join(dir)) else {
return Vec::new();
};
let mut names: Vec<String> = rd
.flatten()
.filter_map(|e| {
let name = e.file_name().into_string().ok()?;
let is_dir = e.file_type().ok()?.is_dir();
if is_dir {
Some(format!("{name}/"))
} else if name.ends_with(".mml") {
Some(name)
} else {
None
}
})
.collect();
names.sort();
names
}
fn load_bytes(&self, path: &str) -> Result<std::sync::Arc<[u8]>, Message> {
let full = self.base.join(path);
std::fs::read(&full).map(Into::into).map_err(|e| {
msg!(
"E0601-read-failed",
path = full.display().to_string(),
error = e.to_string()
)
})
}
fn load(&self, path: &str, from: Option<&str>) -> Result<Included, Message> {
let dir = match from {
Some(f) => Path::new(f)
.parent()
.map(Path::to_path_buf)
.unwrap_or_default(),
None => self.base.clone(),
};
let full = dir.join(path);
let text = std::fs::read_to_string(&full).map_err(|e| {
msg!(
"E0601-read-failed",
path = full.display().to_string(),
error = e.to_string()
)
})?;
let name = std::fs::canonicalize(&full)
.unwrap_or(full)
.to_string_lossy()
.into_owned();
Ok(Included { name, text })
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Sources {
entries: Vec<(String, String)>,
}
impl Sources {
pub fn new<N: Into<String>, T: Into<String>>(
entries: impl IntoIterator<Item = (N, T)>,
) -> Self {
Sources {
entries: entries
.into_iter()
.map(|(n, t)| (n.into(), t.into()))
.collect(),
}
}
pub fn insert(&mut self, name: impl Into<String>, text: impl Into<String>) {
let name = name.into();
let text = text.into();
match self.entries.iter_mut().find(|(n, _)| *n == name) {
Some(e) => e.1 = text,
None => self.entries.push((name, text)),
}
}
pub fn names(&self) -> impl Iterator<Item = &str> {
self.entries.iter().map(|(n, _)| n.as_str())
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
impl Include for Sources {
fn load(&self, path: &str, _from: Option<&str>) -> Result<Included, Message> {
self.entries
.iter()
.find(|(n, _)| n == path)
.map(|(n, t)| Included {
name: n.clone(),
text: t.clone(),
})
.ok_or_else(|| {
let names: Vec<&str> = self.names().collect();
if names.is_empty() {
msg!("E0601-not-given-none", path = path)
} else {
msg!("E0601-not-given", path = path, names = names.join(", "))
}
})
}
}
pub const MAX_DEPTH: usize = 8;