1use std::io::{self, Write};
2use std::path::{Path, PathBuf};
3
4use nybl::{NyblError, NyblHost, Value};
5
6#[derive(Debug, Clone)]
7struct PrintFailure {
8 kind: io::ErrorKind,
9 message: String,
10}
11
12#[derive(Debug, Clone, Default)]
14pub struct StandardHost {
15 module_root: Option<PathBuf>,
18 print_failure: Option<PrintFailure>,
19}
20
21pub use StandardHost as StdHost;
23
24pub fn resolve_module_from_root(root: &Path, name: &str) -> Option<Result<String, NyblError>> {
35 if let Err(error) = validate_module_name(name) {
36 return Some(Err(error));
37 }
38
39 resolve_validated_module_from_root(root, name)
40}
41
42fn resolve_validated_module_from_root(
43 root: &Path,
44 name: &str,
45) -> Option<Result<String, NyblError>> {
46 let mut path = root.to_path_buf();
47 for segment in name.split('.') {
48 path.push(segment);
49 }
50 path.set_extension("nybl");
51 match std::fs::read_to_string(&path) {
52 Ok(source) => Some(Ok(source)),
53 Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
54 Err(err) => Some(Err(crate::error::io_error(
55 &format!("couldn't read module `{name}`: {err}"),
56 None,
57 ))),
58 }
59}
60
61impl StandardHost {
62 pub fn new() -> Self {
65 Self::default()
66 }
67
68 pub fn with_module_root(mut self, root: impl Into<PathBuf>) -> Self {
71 self.module_root = Some(root.into());
72 self
73 }
74
75 pub fn is_broken_pipe(&self) -> bool {
80 self.print_failure
81 .as_ref()
82 .is_some_and(|failure| failure.kind == io::ErrorKind::BrokenPipe)
83 }
84
85 fn write_stdout_line(message: &str) -> io::Result<()> {
86 let stdout = io::stdout();
87 let mut output = stdout.lock();
88 writeln!(output, "{message}")?;
89 output.flush()
90 }
91
92 fn record_print_failure(&mut self, error: io::Error) {
93 if self.print_failure.is_none() {
94 self.print_failure = Some(PrintFailure {
95 kind: error.kind(),
96 message: error.to_string(),
97 });
98 }
99 }
100}
101
102impl NyblHost for StandardHost {
103 fn call(&mut self, name: &str, args: &[Value], line: u32) -> Option<Result<Value, NyblError>> {
104 match name {
105 "readline" => Some(crate::stdio::readline(args, line)),
106 "read_file" => Some(crate::fs::read_file(args, line)),
107 "write_file" => Some(crate::fs::write_file(args, line)),
108 "append_file" => Some(crate::fs::append_file(args, line)),
109 "file_exists" => Some(crate::fs::file_exists(args, line)),
110 "env" => Some(crate::env::env(args, line)),
111 "unix_time" => Some(crate::time::unix_time(args, line)),
112 "unix_time_ms" => Some(crate::time::unix_time_ms(args, line)),
113 _ => None,
114 }
115 }
116
117 fn on_print(&mut self, message: &str) {
118 if self.print_failure.is_some() {
119 return;
120 }
121 if let Err(error) = Self::write_stdout_line(message) {
122 self.record_print_failure(error);
123 }
124 }
125
126 fn print_error(&self, line: u32) -> Option<NyblError> {
127 self.print_failure.as_ref().map(|failure| {
128 let message = if failure.kind == io::ErrorKind::BrokenPipe {
129 "stdout pipe closed".to_string()
130 } else {
131 format!("failed to write to stdout: {}", failure.message)
132 };
133 NyblError::fatal(message, line)
134 })
135 }
136
137 fn function_hint(&self) -> &str {
138 enabled_function_hint()
139 }
140
141 fn resolve_module(&mut self, name: &str) -> Option<Result<String, NyblError>> {
157 #[cfg(feature = "nybl-std")]
158 {
159 if let Some(src) = nybl::stdlib::resolve(name) {
160 return Some(Ok(src.to_string()));
161 }
162 }
163 if let Err(error) = validate_module_name(name) {
164 return Some(Err(error));
165 }
166 let root = match self.module_root.clone() {
167 Some(r) => r,
168 None => match std::env::current_dir() {
169 Ok(d) => d,
170 Err(e) => {
171 return Some(Err(crate::error::io_error(
172 &format!("couldn't read current directory: {e}"),
173 None,
174 )));
175 }
176 },
177 };
178 resolve_validated_module_from_root(&root, name)
179 }
180}
181
182fn is_valid_module_name(name: &str) -> bool {
187 if name.is_empty() {
188 return false;
189 }
190 name.split('.')
191 .all(|seg| !seg.is_empty() && seg.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))
192}
193
194fn validate_module_name(name: &str) -> Result<(), NyblError> {
195 if is_valid_module_name(name) {
196 Ok(())
197 } else {
198 Err(crate::error::io_error(
199 &format!("Invalid module name `{name}`"),
200 None,
201 ))
202 }
203}
204
205fn enabled_function_hint() -> &'static str {
206 "Available nybl-sys functions: readline(prompt?), read_file(path), write_file(path, contents), append_file(path, contents), file_exists(path), env(name), unix_time(), unix_time_ms()"
207}
208
209#[cfg(test)]
210mod tests {
211 use super::*;
212
213 #[test]
214 fn standard_host_does_not_handle_unknown_calls_by_default() {
215 let mut host = StandardHost::new();
216
217 assert!(host.call("unknown", &[], 1).is_none());
218 }
219
220 #[test]
221 fn standard_host_exposes_function_hint() {
222 let host = StandardHost::new();
223
224 assert!(host.function_hint().contains("nybl-sys"));
225 }
226
227 #[test]
228 fn standard_host_reads_and_writes_files() {
229 let mut host = StandardHost::new();
230 let path = temp_path("nybl_sys_file_test.txt");
231 let path_value = Value::new_str(path.to_string_lossy().into_owned());
232
233 host.call(
234 "write_file",
235 &[path_value.clone(), Value::new_str("hello".to_string())],
236 1,
237 )
238 .expect("write_file should be handled")
239 .expect("write_file should succeed");
240
241 host.call(
242 "append_file",
243 &[path_value.clone(), Value::new_str(" world".to_string())],
244 1,
245 )
246 .expect("append_file should be handled")
247 .expect("append_file should succeed");
248
249 let exists = host
250 .call("file_exists", std::slice::from_ref(&path_value), 1)
251 .expect("file_exists should be handled")
252 .expect("file_exists should succeed");
253 assert!(matches!(exists, Value::Bool(true)));
254
255 let contents = host
256 .call("read_file", std::slice::from_ref(&path_value), 1)
257 .expect("read_file should be handled")
258 .expect("read_file should succeed");
259 assert_eq!(contents.to_string(), "hello world");
260
261 let _ = std::fs::remove_file(path);
262 }
263
264 #[test]
265 fn standard_host_returns_none_for_missing_env_vars() {
266 let mut host = StandardHost::new();
267 let name = Value::new_str("NYBL_SYS_ENV_VAR_THAT_SHOULD_NOT_EXIST".to_string());
268
269 let value = host
270 .call("env", &[name], 1)
271 .expect("env should be handled")
272 .expect("env should succeed");
273
274 assert!(matches!(value, Value::None));
275 }
276
277 #[test]
278 fn standard_host_returns_unix_time() {
279 let mut host = StandardHost::new();
280
281 let value = host
282 .call("unix_time_ms", &[], 1)
283 .expect("unix_time_ms should be handled")
284 .expect("unix_time_ms should succeed");
285
286 match value {
287 Value::Number(n) => assert!(n > 0.0),
288 other => panic!("expected number, got {}", other.type_name()),
289 }
290 }
291
292 #[test]
293 fn standard_host_classifies_broken_pipe_as_a_fatal_print_error() {
294 let mut host = StandardHost::new();
295 host.record_print_failure(io::Error::new(io::ErrorKind::BrokenPipe, "reader closed"));
296
297 assert!(host.is_broken_pipe());
298 let error = host.print_error(7).expect("print failure");
299 assert_eq!(error.message, "stdout pipe closed");
300 assert_eq!(error.line, Some(7));
301 assert!(error.is_fatal);
302 }
303
304 #[test]
305 fn standard_host_surfaces_unrelated_stdout_failures() {
306 let mut host = StandardHost::new();
307 host.record_print_failure(io::Error::new(
308 io::ErrorKind::PermissionDenied,
309 "write denied",
310 ));
311
312 assert!(!host.is_broken_pipe());
313 let error = host.print_error(11).expect("print failure");
314 assert_eq!(error.message, "failed to write to stdout: write denied",);
315 assert_eq!(error.line, Some(11));
316 assert!(error.is_fatal);
317 }
318
319 fn temp_path(name: &str) -> std::path::PathBuf {
320 let mut path = std::env::temp_dir();
321 path.push(format!("{}_{}", std::process::id(), name));
322 path
323 }
324
325 #[test]
326 fn resolve_module_maps_dotted_path_to_file() {
327 let dir = std::env::temp_dir().join(format!("nybl_sys_resolve_{}", std::process::id()));
328 let sub = dir.join("math");
329 std::fs::create_dir_all(&sub).unwrap();
330 let file = sub.join("util.nybl");
331 std::fs::write(&file, "let answer = 42").unwrap();
332
333 let mut host = StandardHost::new().with_module_root(&dir);
334 let source = host
335 .resolve_module("math.util")
336 .expect("module should resolve")
337 .expect("should succeed");
338 assert_eq!(source, "let answer = 42");
339
340 let _ = std::fs::remove_dir_all(&dir);
341 }
342
343 #[test]
344 fn resolve_module_missing_returns_none() {
345 let dir =
346 std::env::temp_dir().join(format!("nybl_sys_resolve_none_{}", std::process::id()));
347 std::fs::create_dir_all(&dir).unwrap();
348
349 let mut host = StandardHost::new().with_module_root(&dir);
350 assert!(host.resolve_module("does_not_exist").is_none());
351
352 let _ = std::fs::remove_dir_all(&dir);
353 }
354
355 #[test]
356 fn resolve_module_surfaces_non_not_found_read_errors() {
357 let dir =
358 std::env::temp_dir().join(format!("nybl_sys_resolve_error_{}", std::process::id()));
359 std::fs::create_dir_all(dir.join("broken.nybl")).unwrap();
360
361 let mut host = StandardHost::new().with_module_root(&dir);
362 let error = host
363 .resolve_module("broken")
364 .expect("non-NotFound failures must be handled")
365 .expect_err("reading a directory as module text must fail");
366 assert!(
367 error.message.contains("couldn't read module `broken`"),
368 "unexpected error: {}",
369 error.message
370 );
371
372 let _ = std::fs::remove_dir_all(&dir);
373 }
374
375 #[test]
376 fn resolve_module_rejects_bad_names() {
377 let mut host = StandardHost::new();
378 let result = host.resolve_module("..").expect("should error");
380 assert!(result.is_err());
381 let result = host.resolve_module("foo/bar").expect("should error");
382 assert!(result.is_err());
383 }
384}