1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use std::path::Path;

use crate::ast::Span;
use crate::Source;
use crate::workspace::WorkspaceError;
use crate::compile::WithSpan;

use super::WorkspaceErrorKind;

/// A source loader.
pub trait SourceLoader {
    /// Load the given path.
    fn load(&mut self, span: Span, path: &Path) -> Result<Source, WorkspaceError>;
}

/// A filesystem-based source loader.
#[derive(Default)]
pub struct FileSourceLoader {}

impl FileSourceLoader {
    /// Construct a new filesystem-based source loader.
    pub fn new() -> Self {
        Self::default()
    }
}

impl SourceLoader for FileSourceLoader {
    fn load(&mut self, span: Span, path: &Path) -> Result<Source, WorkspaceError> {
        match Source::from_path(path) {
            Ok(source) => Ok(source),
            Err(error) => Err(WorkspaceError::new(
                span,
                WorkspaceErrorKind::Source {
                    path: path.try_into().with_span(span)?,
                    error,
                },
            )),
        }
    }
}