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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
use std::fs;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use crate::GalvanFileExtension;
use thiserror::Error;

#[derive(Debug, Error)]
pub enum FileError {
    #[error("Error when trying to read source file {0}: {1}")]
    Io(PathBuf, #[source] std::io::Error),
    #[error("File name {0} is not valid UTF-8")]
    Utf8(String),
    #[error("File name {0} is not allowed. Only lowercase letters and _ are allowed in galvan file names")]
    Naming(String),
    #[error("File {0} has no extension")]
    MissingExtension(PathBuf),
}

impl FileError {
    pub fn io(path: impl AsRef<Path>, error: std::io::Error) -> Self {
        Self::Io(path.as_ref().to_owned(), error)
    }

    pub fn utf8(file_name: impl Into<String>) -> Self {
        Self::Utf8(file_name.into())
    }

    pub fn naming(file_name: impl Into<String>) -> Self {
        Self::Naming(file_name.into())
    }

    pub fn missing_extension(path: impl AsRef<Path>) -> Self {
        Self::MissingExtension(path.as_ref().to_owned())
    }
}

pub type SourceResult = Result<Source, FileError>;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Source {
    File {
        path: Arc<Path>,
        content: Arc<str>,
        canonical_name: Arc<str>,
    },
    Str(Arc<str>),
    Missing,
    Builtin,
}

impl Source {
    pub fn from_string(string: impl Into<Arc<str>>) -> Source {
        Self::Str(string.into())
    }

    pub fn read(path: impl AsRef<Path>) -> SourceResult {
        let path = path.as_ref();
        if !path.has_galvan_extension() {
            Err(FileError::missing_extension(path))?
        }
        let stem = path
            .file_stem()
            .ok_or_else(|| FileError::missing_extension(path))?;

        let stem = stem
            .to_str()
            .ok_or_else(|| FileError::utf8(stem.to_string_lossy()))?;
        if !stem.chars().all(|c| c.is_ascii_lowercase() || c == '_') {
            Err(FileError::naming(stem))?
        }
        let canonical_name = stem.replace(".", "_").into();
        let content = fs::read_to_string(path)
            .map_err(|e| FileError::io(path, e))?
            .into();
        let path = path.into();

        Ok(Self::File {
            path,
            content,
            canonical_name,
        })
    }

    pub fn content(&self) -> &str {
        match self {
            Self::File { content, .. } => content.as_ref(),
            Self::Str(content) => content.as_ref(),
            Self::Missing => "",
            Self::Builtin => "",
        }
    }

    pub fn origin(&self) -> Option<&Path> {
        match self {
            Self::File { path, .. } => Some(path),
            Self::Str(_) => None,
            Self::Missing => None,
            Self::Builtin => None,
        }
    }

    pub fn canonical_name(&self) -> Option<&str> {
        match self {
            Self::File {
                path: _,
                content: _,
                canonical_name,
            } => Some(canonical_name),
            Self::Str(_) => None,
            Self::Missing => None,
            Self::Builtin => Some("galvan_std"),
        }
    }
}

impl<T> From<T> for Source
where
    T: Into<Arc<str>>,
{
    fn from(value: T) -> Self {
        Self::from_string(value)
    }
}

impl Deref for Source {
    type Target = str;
    fn deref(&self) -> &Self::Target {
        self.content()
    }
}