Skip to main content

morphir_extension_sdk/
source.rs

1//! Source identities within one compilation unit. These operations perform no I/O.
2//!
3//! ```
4//! use morphir_extension_sdk::CompileRequest;
5//! let request: CompileRequest = serde_json::from_value(serde_json::json!({
6//!     "languageId": "python",
7//!     "package": {"name": "acme/example", "exposedModules": ["domain.models"]},
8//!     "sources": {
9//!         "root": "file:///project/src",
10//!         "documents": [{"uri": "file:///project/src/domain/models.py", "languageId": "python",
11//!                        "version": 1, "text": ""}]
12//!     },
13//!     "options": {"irVersion": "4", "typesOnly": false}
14//! })).unwrap();
15//! assert_eq!(request.source_paths().unwrap()[0].as_str(), "domain/models.py");
16//! ```
17
18use crate::{CompileRequest, SourceSet};
19use percent_encoding::percent_decode_str;
20use std::collections::BTreeSet;
21use url::Url;
22
23/// Invalid source context supplied at the MEP boundary.
24#[derive(Debug, thiserror::Error)]
25#[error("{0}")]
26pub struct SourceContextError(String);
27
28/// Absolute location against which a compilation's document identities are resolved.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct SourceRoot(String);
31
32impl SourceRoot {
33    /// Parse an absolute hierarchical URI or legacy absolute filesystem path.
34    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    /// The normalized location, without query or fragment metadata.
43    pub fn as_str(&self) -> &str {
44        &self.0
45    }
46}
47
48/// A nonempty relative document path within its compilation unit.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct SourcePath(String);
51
52impl SourcePath {
53    /// Return the decoded, slash-separated path, including its file extension.
54    pub fn as_str(&self) -> &str {
55        &self.0
56    }
57}
58
59impl SourceSet {
60    /// Validate the root, if one was supplied.
61    pub fn root(&self) -> Result<Option<SourceRoot>, SourceContextError> {
62        self.root.as_deref().map(SourceRoot::parse).transpose()
63    }
64}
65
66impl SourceSet {
67    /// Resolve and validate source identities in document order.
68    ///
69    /// Relative paths retain their nesting. Multiple absolute documents require
70    /// a root; one absolute document without a root retains the legacy basename
71    /// behavior. Original document URIs remain unchanged for diagnostics.
72    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    /// Resolve the submitted source set using the shared source identity rules.
120    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    // URL parsing erases dot segments, so reject them before parsing.
136    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}