appstruct_compiler/
loading.rs1use crate::surface::Located;
2use crate::yaml;
3use appstruct_ir::{Diagnostic, SourceSpan};
4use std::fs;
5use std::path::{Path, PathBuf};
6
7pub fn discover_project(start: &Path) -> Result<PathBuf, Diagnostic> {
13 let start = fs::canonicalize(start).map_err(|error| {
14 Diagnostic::error(
15 "AS1008",
16 format!("cannot access project path `{}`: {error}", start.display()),
17 synthetic_span(&start.to_string_lossy()),
18 )
19 })?;
20 let mut directory = if start.is_file() {
21 start.parent().map(Path::to_path_buf)
22 } else {
23 Some(start)
24 };
25 while let Some(candidate) = directory {
26 if candidate.join("appstruct.yaml").is_file() {
27 return Ok(candidate);
28 }
29 directory = candidate.parent().map(Path::to_path_buf);
30 }
31 Err(Diagnostic::error(
32 "AS1008",
33 "could not find `appstruct.yaml` in this directory or any parent",
34 synthetic_span("appstruct.yaml"),
35 ))
36}
37
38pub(crate) fn load_yaml(root: &Path, path: &Path) -> Result<yaml::Node, Vec<Diagnostic>> {
39 let label = relative_label(root, path);
40 let source = fs::read_to_string(path).map_err(|error| {
41 vec![Diagnostic::error(
42 "AS1008",
43 format!("cannot read `{label}`: {error}"),
44 synthetic_span(&label),
45 )]
46 })?;
47 yaml::parse(&label, &source).map_err(|error| vec![error])
48}
49
50pub(crate) fn resolve_include(
51 root: &Path,
52 include: &Located<String>,
53) -> Result<PathBuf, Diagnostic> {
54 let declared = Path::new(&include.value);
55 if declared.is_absolute() {
56 return Err(Diagnostic::error(
57 "AS1010",
58 "include paths must be relative to the project root",
59 include.span.clone(),
60 ));
61 }
62 let canonical = fs::canonicalize(root.join(declared)).map_err(|error| {
63 Diagnostic::error(
64 "AS1008",
65 format!("cannot access include `{}`: {error}", include.value),
66 include.span.clone(),
67 )
68 })?;
69 if !canonical.starts_with(root) {
70 return Err(Diagnostic::error(
71 "AS1010",
72 format!("include `{}` escapes the project root", include.value),
73 include.span.clone(),
74 ));
75 }
76 if !canonical.is_file() {
77 return Err(Diagnostic::error(
78 "AS1008",
79 format!("include `{}` is not a file", include.value),
80 include.span.clone(),
81 ));
82 }
83 Ok(canonical)
84}
85
86fn relative_label(root: &Path, path: &Path) -> String {
87 path.strip_prefix(root)
88 .unwrap_or(path)
89 .components()
90 .map(|component| component.as_os_str().to_string_lossy())
91 .collect::<Vec<_>>()
92 .join("/")
93}
94
95pub(crate) fn synthetic_span(file: &str) -> SourceSpan {
96 SourceSpan {
97 file: file.to_owned(),
98 start: 0,
99 end: 0,
100 line: 1,
101 column: 1,
102 end_line: 1,
103 end_column: 1,
104 }
105}