general_spice_core/include/
resolve.rs1use std::collections::HashMap;
6use std::path::{Path, PathBuf};
7
8use crate::dialect::Dialect;
9
10#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct PathDiagnostic {
14 pub message: String,
16 pub filename: String,
18 pub tried: Vec<String>,
21}
22
23pub trait FileSystem {
28 fn exists(&self, path: &Path) -> bool;
30 fn read_to_string(&self, path: &Path) -> std::io::Result<String>;
32}
33
34pub struct FakeFileSystem {
37 files: HashMap<PathBuf, String>,
38}
39
40impl FakeFileSystem {
41 pub fn new() -> Self {
43 FakeFileSystem {
44 files: HashMap::new(),
45 }
46 }
47
48 pub fn insert(&mut self, path: impl Into<PathBuf>, content: impl Into<String>) {
50 self.files.insert(path.into(), content.into());
51 }
52}
53
54impl Default for FakeFileSystem {
55 fn default() -> Self {
56 Self::new()
57 }
58}
59
60impl FileSystem for FakeFileSystem {
61 fn exists(&self, path: &Path) -> bool {
62 self.files.contains_key(path)
63 }
64
65 fn read_to_string(&self, path: &Path) -> std::io::Result<String> {
66 self.files
67 .get(path)
68 .cloned()
69 .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "file not found"))
70 }
71}
72
73pub fn resolve_include_path(
87 fs: &dyn FileSystem,
88 including_file_dir: &Path,
89 top_level_dir: &Path,
90 exec_dir: &Path,
91 raw_filename: &str,
92 _sourcepath_entries: &[PathBuf],
93 dialect: Dialect,
94) -> Result<PathBuf, PathDiagnostic> {
95 let filename = strip_quotes(raw_filename);
96 let mut tried = Vec::new();
97
98 match dialect {
99 Dialect::Ngspice => {
100 let relative = including_file_dir.join(&filename);
101 tried.push(relative.display().to_string());
102 if fs.exists(&relative) {
103 return Ok(relative);
104 }
105
106 for entry in _sourcepath_entries {
107 let candidate = entry.join(&filename);
108 tried.push(candidate.display().to_string());
109 if fs.exists(&candidate) {
110 return Ok(candidate);
111 }
112 }
113 }
114 Dialect::Xyce => {
115 let relative = including_file_dir.join(&filename);
116 tried.push(relative.display().to_string());
117 if fs.exists(&relative) {
118 return Ok(relative);
119 }
120
121 let top = top_level_dir.join(&filename);
122 tried.push(top.display().to_string());
123 if fs.exists(&top) {
124 return Ok(top);
125 }
126
127 let exec = exec_dir.join(&filename);
128 tried.push(exec.display().to_string());
129 if fs.exists(&exec) {
130 return Ok(exec);
131 }
132 }
133 }
134
135 Err(PathDiagnostic {
136 message: format!("unresolvable include file: '{filename}'"),
137 filename,
138 tried,
139 })
140}
141
142fn strip_quotes(s: &str) -> String {
143 let s = s.trim();
144 if (s.starts_with('"') && s.ends_with('"')) || (s.starts_with('\'') && s.ends_with('\'')) {
145 s[1..s.len() - 1].to_string()
146 } else {
147 s.to_string()
148 }
149}
150
151#[cfg(test)]
152mod tests {
153 use super::*;
154
155 fn setup_fs() -> FakeFileSystem {
156 let mut fs = FakeFileSystem::new();
157 fs.insert("/proj/sub/models.lib", "content");
158 fs.insert("/proj/models.lib", "content");
159 fs.insert("/cwd/models.lib", "content");
160 fs
161 }
162
163 #[test]
164 fn test_ngspice_resolves_relative_to_including_file() {
165 let fs = setup_fs();
166 let result = resolve_include_path(
167 &fs,
168 Path::new("/proj/sub"),
169 Path::new("/proj"),
170 Path::new("/cwd"),
171 "models.lib",
172 &[],
173 Dialect::Ngspice,
174 );
175 assert!(result.is_ok());
176 assert!(result.unwrap().ends_with("sub/models.lib"));
177 }
178
179 #[test]
180 fn test_xyce_resolves_relative_to_including_file_first() {
181 let fs = setup_fs();
182 let result = resolve_include_path(
183 &fs,
184 Path::new("/proj/sub"),
185 Path::new("/proj"),
186 Path::new("/cwd"),
187 "models.lib",
188 &[],
189 Dialect::Xyce,
190 );
191 assert!(result.is_ok());
192 assert!(result.unwrap().ends_with("sub/models.lib"));
193 }
194
195 #[test]
196 fn test_xyce_falls_back_to_top_level_netlist_dir() {
197 let mut fs = FakeFileSystem::new();
198 fs.insert("/proj/models.lib", "content");
199 let result = resolve_include_path(
200 &fs,
201 Path::new("/proj/sub"),
202 Path::new("/proj"),
203 Path::new("/cwd"),
204 "models.lib",
205 &[],
206 Dialect::Xyce,
207 );
208 assert!(result.is_ok());
209 assert!(result.unwrap().ends_with("proj/models.lib"));
210 }
211
212 #[test]
213 fn test_xyce_falls_back_to_exec_dir_last() {
214 let mut fs = FakeFileSystem::new();
215 fs.insert("/cwd/models.lib", "content");
216 let result = resolve_include_path(
217 &fs,
218 Path::new("/proj/sub"),
219 Path::new("/proj"),
220 Path::new("/cwd"),
221 "models.lib",
222 &[],
223 Dialect::Xyce,
224 );
225 assert!(result.is_ok());
226 assert!(result.unwrap().ends_with("cwd/models.lib"));
227 }
228
229 #[test]
230 fn test_unresolvable_filename_lists_all_tried_locations() {
231 let fs = FakeFileSystem::new();
232 let result = resolve_include_path(
233 &fs,
234 Path::new("/proj/sub"),
235 Path::new("/proj"),
236 Path::new("/cwd"),
237 "missing.lib",
238 &[],
239 Dialect::Xyce,
240 );
241 assert!(result.is_err());
242 let err = result.unwrap_err();
243 assert!(!err.tried.is_empty());
244 }
245
246 #[test]
247 fn test_quoted_filename_strips_quotes_before_resolution() {
248 let fs = setup_fs();
249 let result = resolve_include_path(
250 &fs,
251 Path::new("/proj/sub"),
252 Path::new("/proj"),
253 Path::new("/cwd"),
254 "\"models.lib\"",
255 &[],
256 Dialect::Ngspice,
257 );
258 assert!(result.is_ok());
259 }
260}