morphir_extension_sdk/
source.rs1use crate::{CompileRequest, SourceSet};
19use percent_encoding::percent_decode_str;
20use std::collections::BTreeSet;
21use url::Url;
22
23#[derive(Debug, thiserror::Error)]
25#[error("{0}")]
26pub struct SourceContextError(String);
27
28#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct SourceRoot(String);
31
32impl SourceRoot {
33 pub fn parse(value: &str) -> Result<Self, SourceContextError> {
35 let value = normalize(value)?;
36 if !absolute(&value) {
37 return Err(SourceContextError("sources.root must be absolute".into()));
38 }
39 Ok(Self(value))
40 }
41
42 pub fn as_str(&self) -> &str {
44 &self.0
45 }
46}
47
48#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct SourcePath(String);
51
52impl SourcePath {
53 pub fn as_str(&self) -> &str {
55 &self.0
56 }
57}
58
59impl SourceSet {
60 pub fn root(&self) -> Result<Option<SourceRoot>, SourceContextError> {
62 self.root.as_deref().map(SourceRoot::parse).transpose()
63 }
64}
65
66impl SourceSet {
67 pub fn source_paths(&self) -> Result<Vec<SourcePath>, SourceContextError> {
73 let root = self.root()?;
74 let mut seen = BTreeSet::new();
75 self.documents
76 .iter()
77 .map(|document| {
78 let normalized = normalize(&document.uri)?;
79 let relative = if absolute(&normalized) {
80 match &root {
81 Some(root) => normalized
82 .strip_prefix(&format!(
83 "{}/",
84 root.as_str().strip_suffix('/').unwrap_or(root.as_str())
85 ))
86 .ok_or_else(|| {
87 SourceContextError("Source document is outside sources.root".into())
88 })?,
89 None if self.documents.len() == 1 => {
90 normalized.rsplit('/').next().unwrap_or("")
91 }
92 None => {
93 return Err(SourceContextError(
94 "Absolute source URIs require sources.root for multiple modules"
95 .into(),
96 ));
97 }
98 }
99 } else {
100 &normalized
101 };
102 if relative.is_empty() || relative.split('/').any(str::is_empty) {
103 return Err(SourceContextError(
104 "Source document must identify a nonempty relative file path".into(),
105 ));
106 }
107 if !seen.insert(relative.to_owned()) {
108 return Err(SourceContextError(format!(
109 "Duplicate source document identity: {relative}"
110 )));
111 }
112 Ok(SourcePath(relative.to_owned()))
113 })
114 .collect()
115 }
116}
117
118impl CompileRequest {
119 pub fn source_paths(&self) -> Result<Vec<SourcePath>, SourceContextError> {
121 self.sources.source_paths()
122 }
123}
124
125fn absolute(value: &str) -> bool {
126 value.starts_with('/') || value.contains(':')
127}
128
129fn normalize(value: &str) -> Result<String, SourceContextError> {
130 let raw = value
131 .split(['?', '#'])
132 .next()
133 .unwrap_or(value)
134 .replace('\\', "/");
135 decode_path(&raw)?;
137 let windows_drive =
138 raw.as_bytes().get(1) == Some(&b':') && raw.as_bytes().get(2) == Some(&b'/');
139 if !windows_drive && raw.contains(':') {
140 let url = Url::parse(&raw)
141 .map_err(|error| SourceContextError(format!("Invalid source URI: {error}")))?;
142 if url.cannot_be_a_base() {
143 return Err(SourceContextError(
144 "Source URI must have a hierarchical path".into(),
145 ));
146 }
147 Ok(format!(
148 "{}://{}{}",
149 url.scheme(),
150 url.authority(),
151 decode_path(url.path())?
152 ))
153 } else {
154 decode_path(&raw)
155 }
156}
157
158fn decode_path(path: &str) -> Result<String, SourceContextError> {
159 for (index, byte) in path.bytes().enumerate() {
160 if byte == b'%'
161 && !path
162 .as_bytes()
163 .get(index + 1..index + 3)
164 .is_some_and(|digits| digits.iter().all(u8::is_ascii_hexdigit))
165 {
166 return Err(SourceContextError(
167 "Source path contains invalid percent encoding".into(),
168 ));
169 }
170 }
171 path.split('/')
172 .map(|segment| {
173 let decoded = percent_decode_str(segment).decode_utf8().map_err(|_| {
174 SourceContextError("Source path contains invalid UTF-8 encoding".into())
175 })?;
176 if matches!(decoded.as_ref(), "." | "..") || decoded.contains(['/', '\\', '\0']) {
177 return Err(SourceContextError(
178 "Source path contains a dot segment or encoded separator".into(),
179 ));
180 }
181 Ok(decoded.into_owned())
182 })
183 .collect::<Result<Vec<_>, _>>()
184 .map(|parts| parts.join("/"))
185}