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
use std::borrow::Cow;
use std::path::{self, PathBuf};
use glsl_lang::ast::Path;
use thiserror::Error;
use super::PreprocessorFs;
#[derive(Default, Debug, Clone)]
pub struct StdPreprocessorFs {
include: Vec<PathBuf>,
}
impl StdPreprocessorFs {
pub fn new() -> Self {
Self { include: vec![] }
}
pub fn with_include_path(include: &[PathBuf]) -> Self {
Self {
include: include.to_vec(),
}
}
}
#[derive(Debug, Error)]
pub enum StdPreprocessorFsError {
#[error("i/o error: {0}")]
Io(#[from] std::io::Error),
#[error("unresolved include: {0:?}")]
UnresolvedInclude(Path),
#[error("parse error: {0}")]
ParseError(#[from] glsl_lang::parse::ParseError),
}
impl PartialEq for StdPreprocessorFsError {
fn eq(&self, other: &Self) -> bool {
match self {
Self::Io(a) => match other {
Self::Io(b) => a.kind() == b.kind(),
_ => false,
},
Self::UnresolvedInclude(a) => match other {
Self::UnresolvedInclude(b) => a == b,
_ => false,
},
Self::ParseError(a) => match other {
Self::ParseError(b) => a == b,
_ => false,
},
}
}
}
impl PreprocessorFs for StdPreprocessorFs {
type Error = StdPreprocessorFsError;
fn read(&self, path: &path::Path) -> Result<Cow<str>, Self::Error> {
Ok(Cow::Owned(std::fs::read_to_string(path)?))
}
fn canonicalize(&self, path: &path::Path) -> Result<PathBuf, Self::Error> {
Ok(std::fs::canonicalize(path)?)
}
fn resolve(&self, base_path: &path::Path, path: &Path) -> Result<PathBuf, Self::Error> {
match &path {
Path::Absolute(abs_path) => {
let path_buf = PathBuf::from(abs_path);
self.include
.iter()
.find_map(|dir| std::fs::canonicalize(dir.join(&path_buf)).ok())
}
Path::Relative(path) => {
let path = PathBuf::from(path);
std::iter::once(base_path)
.chain(self.include.iter().map(|p| p.as_path()))
.find_map(|dir| std::fs::canonicalize(dir.join(&path)).ok())
}
}
.ok_or_else(|| Self::Error::UnresolvedInclude(path.clone()))
}
}