use std::fmt;
use std::path::{Path, PathBuf};
use crate::Spanned;
use crate::ast::{Definition, DeqFile};
pub type FileId = usize;
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ResolvedDeqFile {
pub definitions: Vec<Spanned<Definition>>,
pub sources: Vec<FileId>,
pub files: Vec<String>,
}
impl ResolvedDeqFile {
#[must_use]
pub fn source_of(&self, index: usize) -> &str {
&self.files[self.sources[index]]
}
#[must_use]
pub fn into_deq_file(self) -> DeqFile {
DeqFile {
imports: Vec::new(),
definitions: self.definitions,
}
}
}
pub trait ImportLoader {
fn resolve(&mut self, base: Option<&str>, path: &str) -> Result<String, LoadError>;
fn load(&mut self, id: &str) -> Result<String, LoadError>;
}
#[derive(Debug, Clone)]
pub struct LoadError {
pub path: String,
pub message: String,
}
impl fmt::Display for LoadError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "cannot load {:?}: {}", self.path, self.message)
}
}
impl std::error::Error for LoadError {}
#[derive(Debug)]
pub enum ResolveError {
Load(LoadError),
Parse {
file: String,
error: Box<crate::ParseError>,
},
}
impl fmt::Display for ResolveError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ResolveError::Load(e) => write!(f, "{e}"),
ResolveError::Parse { file, error } => write!(f, "{file}: {error}"),
}
}
}
impl std::error::Error for ResolveError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
ResolveError::Load(e) => Some(e),
ResolveError::Parse { error, .. } => Some(error),
}
}
}
impl From<LoadError> for ResolveError {
fn from(e: LoadError) -> Self {
ResolveError::Load(e)
}
}
pub fn resolve(root_id: &str, loader: &mut impl ImportLoader) -> Result<ResolvedDeqFile, ResolveError> {
let mut resolved = ResolvedDeqFile::default();
resolve_into(root_id, loader, &mut resolved)?;
Ok(resolved)
}
fn resolve_into(id: &str, loader: &mut impl ImportLoader, resolved: &mut ResolvedDeqFile) -> Result<(), ResolveError> {
if resolved.files.iter().any(|f| f == id) {
return Ok(());
}
let file_id: FileId = resolved.files.len();
resolved.files.push(id.to_string());
let text = loader.load(id)?;
let parsed: DeqFile = text.parse().map_err(|error| ResolveError::Parse {
file: id.to_string(),
error: Box::new(error),
})?;
for import in &parsed.imports {
let child = loader.resolve(Some(id), import)?;
resolve_into(&child, loader, resolved)?;
}
for definition in parsed.definitions {
resolved.definitions.push(definition);
resolved.sources.push(file_id);
}
Ok(())
}
#[derive(Debug, Default, Clone, Copy)]
pub struct FsLoader;
impl ImportLoader for FsLoader {
fn resolve(&mut self, base: Option<&str>, path: &str) -> Result<String, LoadError> {
let target: PathBuf = match base {
Some(base) => Path::new(base).parent().unwrap_or_else(|| Path::new(".")).join(path),
None => PathBuf::from(path),
};
target
.canonicalize()
.map(|p| p.to_string_lossy().into_owned())
.map_err(|e| LoadError {
path: target.to_string_lossy().into_owned(),
message: e.to_string(),
})
}
fn load(&mut self, id: &str) -> Result<String, LoadError> {
std::fs::read_to_string(id).map_err(|e| LoadError {
path: id.to_string(),
message: e.to_string(),
})
}
}
pub fn parse_file(path: &Path) -> Result<ResolvedDeqFile, ResolveError> {
let mut loader = FsLoader;
let root = loader.resolve(None, &path.to_string_lossy())?;
resolve(&root, &mut loader)
}
#[cfg(test)]
mod tests;