Skip to main content

artifactize_tools/artf/
syntax.rs

1//! Scanner and reversible masker for `.artf` profile alias expressions (`!alias`, `!alias(...)`).
2//!
3//! Standard TOML has no `!` token outside strings and comments, so masking value-position alias
4//! invocations into unique quoted strings lets both `toml` and `toml_edit` parse, validate,
5//! canonicalize, and losslessly edit `.artf` files while keeping exact source spans.
6
7use std::ops::Range;
8
9/// Length of a TOML multi-line string delimiter (`"""` or `'''`).
10const TRIPLE_QUOTE_LEN: usize = 3;
11/// Maximum consecutive quotes that can close a TOML multi-line string (two content quotes + three).
12const MAX_CLOSING_QUOTE_RUN: usize = 5;
13/// Base sentinel prefix for placeholder strings; disambiguated if present in source text.
14const PLACEHOLDER_BASE: &str = "__artf_alias_";
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct AliasInvocation {
18    /// Byte span of `!name` or `!name(...)` in the original source.
19    pub span: Range<usize>,
20    /// Raw alias name immediately following `!`.
21    pub name: String,
22    /// Byte span of `name` in the original source.
23    pub name_span: Range<usize>,
24    /// Byte span strictly inside `(...)` in the original source when parentheses are present.
25    pub overrides_span: Option<Range<usize>>,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct AliasSyntaxError {
30    pub offset: usize,
31    pub message: String,
32}
33
34#[derive(Debug, Clone)]
35pub struct Masked {
36    /// Valid TOML with each value-position `!alias` / `!alias(...)` replaced by a unique string.
37    pub toml: String,
38    prefix: String,
39    invocations: Vec<AliasInvocation>,
40    spans: Vec<(Range<usize>, Range<usize>)>,
41}
42
43impl Masked {
44    pub fn invocations(&self) -> &[AliasInvocation] {
45        &self.invocations
46    }
47
48    /// Return the invocation index if `value` is a placeholder emitted by [`mask`].
49    pub fn invocation_index(&self, value: &str) -> Option<usize> {
50        let rest = value.strip_prefix(&self.prefix)?;
51        let digits = rest.strip_suffix("__")?;
52        let index: usize = digits.parse().ok()?;
53        (index < self.invocations.len()).then_some(index)
54    }
55
56    /// Map a byte offset in [`Self::toml`] back to its byte offset in the original source.
57    pub fn original_offset(&self, masked_offset: usize) -> usize {
58        let mut delta: isize = 0;
59        for (masked, original) in &self.spans {
60            if masked_offset < masked.start {
61                break;
62            }
63            if masked_offset < masked.end {
64                return original.start;
65            }
66            delta += original.len() as isize - masked.len() as isize;
67        }
68        (masked_offset as isize + delta).max(0) as usize
69    }
70
71    /// Restore each placeholder in `edited` back to its exact original slice from `original_source`.
72    pub fn unmask(&self, edited: &str, original_source: &str) -> String {
73        self.unmask_with(edited, |_, invocation| {
74            original_source[invocation.span.clone()].to_owned()
75        })
76    }
77
78    /// Replace each placeholder string literal in `serialized` using `replacement`.
79    pub fn unmask_with(
80        &self,
81        serialized: &str,
82        replacement: impl Fn(usize, &AliasInvocation) -> String,
83    ) -> String {
84        if self.invocations.is_empty() {
85            return serialized.to_owned();
86        }
87        let mut output = serialized.to_owned();
88        for (index, invocation) in self.invocations.iter().enumerate() {
89            let quoted = format!("\"{}{index}__\"", self.prefix);
90            let value = replacement(index, invocation);
91            output = output.replace(&quoted, &value);
92        }
93        output
94    }
95}
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98enum Container {
99    Array,
100    InlineTable,
101}
102
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104enum Position {
105    Key,
106    Value,
107}
108
109/// Scan `source` for value-position `!alias` and `!alias(...)` expressions and mask them into
110/// collision-free TOML string literals.
111pub fn mask(source: &str) -> Result<Masked, AliasSyntaxError> {
112    let invocations = scan(source)?;
113    if invocations.is_empty() {
114        return Ok(Masked {
115            toml: source.to_owned(),
116            prefix: PLACEHOLDER_BASE.to_owned(),
117            invocations,
118            spans: Vec::new(),
119        });
120    }
121    let prefix = unique_prefix(source);
122    let mut toml = String::with_capacity(source.len());
123    let mut spans = Vec::with_capacity(invocations.len());
124    let mut cursor = 0;
125    for (index, invocation) in invocations.iter().enumerate() {
126        toml.push_str(&source[cursor..invocation.span.start]);
127        let start = toml.len();
128        toml.push('"');
129        toml.push_str(&prefix);
130        toml.push_str(&index.to_string());
131        toml.push_str("__\"");
132        let end = toml.len();
133        spans.push((start..end, invocation.span.clone()));
134        cursor = invocation.span.end;
135    }
136    toml.push_str(&source[cursor..]);
137    Ok(Masked {
138        toml,
139        prefix,
140        invocations,
141        spans,
142    })
143}
144
145fn unique_prefix(source: &str) -> String {
146    if !source.contains(PLACEHOLDER_BASE) {
147        return PLACEHOLDER_BASE.to_owned();
148    }
149    let mut nonce = 1_u64;
150    loop {
151        let candidate = format!("{PLACEHOLDER_BASE}{nonce}_");
152        if !source.contains(&candidate) {
153            return candidate;
154        }
155        nonce += 1;
156    }
157}
158
159fn scan(source: &str) -> Result<Vec<AliasInvocation>, AliasSyntaxError> {
160    let bytes = source.as_bytes();
161    let mut i = 0;
162    let mut stack = Vec::new();
163    let mut position = Position::Key;
164    let mut invocations = Vec::new();
165
166    while i < bytes.len() {
167        match bytes[i] {
168            b' ' | b'\t' | b'\r' => {
169                i += 1;
170            }
171            b'\n' => {
172                if stack.is_empty() {
173                    position = Position::Key;
174                }
175                i += 1;
176            }
177            b'#' => {
178                i = skip_comment(bytes, i);
179            }
180            b'"' | b'\'' => {
181                i = skip_string(bytes, i);
182                if position == Position::Value {
183                    position = Position::Key;
184                }
185            }
186            b'[' if position == Position::Key && stack.is_empty() => {
187                i = skip_table_header(bytes, i);
188            }
189            b'[' if position == Position::Value => {
190                stack.push(Container::Array);
191                position = Position::Value;
192                i += 1;
193            }
194            b'{' if position == Position::Value => {
195                stack.push(Container::InlineTable);
196                position = Position::Key;
197                i += 1;
198            }
199            b']' => {
200                if stack.last() == Some(&Container::Array) {
201                    stack.pop();
202                }
203                position = Position::Key;
204                i += 1;
205            }
206            b'}' => {
207                if stack.last() == Some(&Container::InlineTable) {
208                    stack.pop();
209                }
210                position = Position::Key;
211                i += 1;
212            }
213            b'=' if position == Position::Key => {
214                position = Position::Value;
215                i += 1;
216            }
217            b',' => {
218                position = if stack.last() == Some(&Container::Array) {
219                    Position::Value
220                } else {
221                    Position::Key
222                };
223                i += 1;
224            }
225            b'!' if position == Position::Value => {
226                let (invocation, next) = parse_alias(source, i)?;
227                invocations.push(invocation);
228                position = Position::Key;
229                i = next;
230            }
231            _ if position == Position::Value => {
232                i = skip_scalar(bytes, i);
233                position = Position::Key;
234            }
235            _ => {
236                i += 1;
237            }
238        }
239    }
240    Ok(invocations)
241}
242
243fn parse_alias(source: &str, bang: usize) -> Result<(AliasInvocation, usize), AliasSyntaxError> {
244    let bytes = source.as_bytes();
245    let name_start = bang + 1;
246    let mut name_end = name_start;
247    while name_end < bytes.len() && is_alias_byte(bytes[name_end]) {
248        name_end += 1;
249    }
250    if name_end == name_start {
251        return Err(AliasSyntaxError {
252            offset: bang,
253            message: "Expected a profile alias name after `!`.".into(),
254        });
255    }
256    let name = source[name_start..name_end].to_owned();
257    let name_span = name_start..name_end;
258
259    let mut lookahead = name_end;
260    while lookahead < bytes.len() && matches!(bytes[lookahead], b' ' | b'\t') {
261        lookahead += 1;
262    }
263    if bytes.get(lookahead) == Some(&b'(') {
264        let open = lookahead;
265        let overrides_start = open + 1;
266        let close = find_closing_paren(bytes, open)?;
267        return Ok((
268            AliasInvocation {
269                span: bang..close + 1,
270                name,
271                name_span,
272                overrides_span: Some(overrides_start..close),
273            },
274            close + 1,
275        ));
276    }
277    Ok((
278        AliasInvocation {
279            span: bang..name_end,
280            name,
281            name_span,
282            overrides_span: None,
283        },
284        name_end,
285    ))
286}
287
288fn find_closing_paren(bytes: &[u8], open: usize) -> Result<usize, AliasSyntaxError> {
289    let mut i = open + 1;
290    let mut paren_depth: usize = 1;
291    let mut brace_depth: usize = 0;
292    while i < bytes.len() {
293        match bytes[i] {
294            b'#' => i = skip_comment(bytes, i),
295            b'"' | b'\'' => i = skip_string(bytes, i),
296            b'{' => {
297                brace_depth += 1;
298                i += 1;
299            }
300            b'}' => {
301                if brace_depth == 0 {
302                    return Err(AliasSyntaxError {
303                        offset: i,
304                        message: "Unexpected `}` in profile alias override.".into(),
305                    });
306                }
307                brace_depth -= 1;
308                i += 1;
309            }
310            b'(' => {
311                paren_depth += 1;
312                i += 1;
313            }
314            b')' => {
315                paren_depth -= 1;
316                if paren_depth == 0 {
317                    return Ok(i);
318                }
319                i += 1;
320            }
321            _ => i += 1,
322        }
323    }
324    Err(AliasSyntaxError {
325        offset: open,
326        message: "Unclosed `(` in profile alias override.".into(),
327    })
328}
329
330fn is_alias_byte(byte: u8) -> bool {
331    byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')
332}
333
334fn skip_comment(bytes: &[u8], mut i: usize) -> usize {
335    while i < bytes.len() && bytes[i] != b'\n' {
336        i += 1;
337    }
338    i
339}
340
341fn skip_string(bytes: &[u8], i: usize) -> usize {
342    let quote = bytes[i];
343    let multiline = bytes.get(i..i + TRIPLE_QUOTE_LEN) == Some(&[quote; TRIPLE_QUOTE_LEN]);
344    if multiline {
345        skip_multiline_string(bytes, i + TRIPLE_QUOTE_LEN, quote)
346    } else {
347        skip_single_line_string(bytes, i + 1, quote)
348    }
349}
350
351fn skip_single_line_string(bytes: &[u8], mut i: usize, quote: u8) -> usize {
352    while i < bytes.len() {
353        let byte = bytes[i];
354        if quote == b'"' && byte == b'\\' {
355            i = (i + 2).min(bytes.len());
356            continue;
357        }
358        if byte == quote {
359            return i + 1;
360        }
361        if byte == b'\n' {
362            return i;
363        }
364        i += 1;
365    }
366    i
367}
368
369fn skip_multiline_string(bytes: &[u8], mut i: usize, quote: u8) -> usize {
370    while i < bytes.len() {
371        let byte = bytes[i];
372        if quote == b'"' && byte == b'\\' {
373            i = (i + 2).min(bytes.len());
374            continue;
375        }
376        if byte == quote {
377            let mut run = 0;
378            while i + run < bytes.len() && bytes[i + run] == quote {
379                run += 1;
380            }
381            if run >= TRIPLE_QUOTE_LEN {
382                return i + run.min(MAX_CLOSING_QUOTE_RUN);
383            }
384            i += run;
385            continue;
386        }
387        i += 1;
388    }
389    i
390}
391
392fn skip_table_header(bytes: &[u8], mut i: usize) -> usize {
393    let double = bytes.get(i..i + 2) == Some(b"[[");
394    i += if double { 2 } else { 1 };
395    while i < bytes.len() {
396        match bytes[i] {
397            b'"' | b'\'' => i = skip_string(bytes, i),
398            b'\n' => return i,
399            b']' => {
400                if double {
401                    if bytes.get(i..i + 2) == Some(b"]]") {
402                        return i + 2;
403                    }
404                    i += 1;
405                } else {
406                    return i + 1;
407                }
408            }
409            _ => i += 1,
410        }
411    }
412    i
413}
414
415fn skip_scalar(bytes: &[u8], mut i: usize) -> usize {
416    while i < bytes.len() {
417        if matches!(
418            bytes[i],
419            b' ' | b'\t' | b'\r' | b'\n' | b'#' | b',' | b']' | b'}' | b'='
420        ) {
421            break;
422        }
423        i += 1;
424    }
425    i
426}