lima 0.9.0

Lima frontmatter parser — LIMA Is Metadata Annotation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Core §15.8 flow collections: `[...]` sequences and `{...}` mappings.
//! Mirrors `js/src/flow.ts`. Generic over [`Builder`] — see `scalars.rs`'s
//! module doc.

use crate::chars::is_trim_whitespace;
use crate::errors::{LimaDiagnosticCode as Code, LimaError};
use crate::normalize::{check_duplicate_key, check_key_length};
use crate::scalars::{
    closing_quote_index, is_valid_key, parse_quoted_or_typed, parse_scalar_value, separator_index,
    strip_key_quotes,
};
use crate::value::{Builder, ReferenceSource};

/// Maps a byte offset in the decoded container `val` to the corresponding
/// offset in the physical container `raw`. The two differ only by `\#` → `#`
/// collapses outside quoted strings (FR-5 keeps `\#` inside quotes). A `#` in
/// `val` outside a quote is such a collapse where `raw` has `\#` at that
/// place; any other `#` — one after text, which Core 1.3 §4 keeps — is
/// written as it is. `#`, `\`, `"`, `'` are ASCII, so byte scanning is safe.
fn raw_offset_of(raw: &str, val: &str, val_offset: usize) -> usize {
    let (rb, vb) = (raw.as_bytes(), val.as_bytes());
    let mut ri = 0usize;
    let mut vi = 0usize;
    let mut quote = 0u8;
    while vi < val_offset {
        let c = vb[vi];
        if quote != 0 {
            if c == b'\\' {
                vi += 2;
                ri += 2;
                continue;
            }
            if c == quote {
                quote = 0;
            }
        } else if c == b'"' || c == b'\'' {
            quote = c;
        } else if c == b'#' && rb.get(ri) == Some(&b'\\') {
            vi += 1;
            ri += 2; // '#' in the decoded container <= '\#' in raw
            continue;
        }
        vi += 1;
        ri += 1;
    }
    debug_assert!(ri <= rb.len());
    ri
}

/// `ReferenceSource` for a flow element spanning bytes `[start, end)` in the
/// decoded container `val` — the container column plus the codepoint distance
/// to the element's start in the physical text, plus the physical element
/// slice as `raw`, so a token's reported position (§2.4) and §5 ordering are
/// correct even when an earlier `\#` widened the source. `source.raw` is the
/// physical container (equal to `val` when the value carried no `\#`).
fn element_source(
    source: Option<&ReferenceSource>,
    val: &str,
    start: usize,
    end: usize,
) -> Option<ReferenceSource> {
    source.map(|s| {
        let raw = s.raw.as_deref().unwrap_or(val);
        let rs = raw_offset_of(raw, val, start);
        let re = raw_offset_of(raw, val, end);
        ReferenceSource {
            col: s.col + raw[..rs].chars().count(),
            raw: Some(raw[rs..re].to_string()),
            line: s.line,
            // A flow collection is one physical line, so the container's
            // leading-tab adjustment applies to every element.
            tab_adjust: s.tab_adjust.clone(),
        }
    })
}

fn trim_start_at(source: &str, mut start: usize, end: usize) -> usize {
    while start < end {
        let ch = source[start..end].chars().next().unwrap();
        if !is_trim_whitespace(ch) {
            break;
        }
        start += ch.len_utf8();
    }
    start
}

fn trim_end_at(source: &str, start: usize, mut end: usize) -> usize {
    while end > start {
        let ch = source[start..end].chars().next_back().unwrap();
        if !is_trim_whitespace(ch) {
            break;
        }
        end -= ch.len_utf8();
    }
    end
}

/// Stateful comma-item cursor over a flow container's original string.
/// Byte-level scanning is safe here (not just for ASCII fast paths): every
/// delimiter this loop matches on (`"`, `'`, `[`, `{`, `]`, `}`, `,`, `\`)
/// is ASCII, and no continuation byte of a multi-byte UTF-8 sequence can
/// equal an ASCII byte value, so scanning raw bytes can't misfire inside
/// non-ASCII content.
struct FlowCursor<'a> {
    source: &'a str,
    end: usize,
    next_start: usize,
    item_start: usize,
    item_end: usize,
    /// The item's end before trimming: its comma, or the end of the container.
    item_raw_end: usize,
    done: bool,
}

impl<'a> FlowCursor<'a> {
    fn new(source: &'a str, start: usize, end: usize) -> Self {
        Self {
            source,
            end,
            next_start: start,
            item_start: 0,
            item_end: 0,
            item_raw_end: 0,
            done: false,
        }
    }

    fn next(&mut self) -> bool {
        if self.done {
            return false;
        }
        let b = self.source.as_bytes();
        let mut quote: u8 = 0;
        let mut depth: i32 = 0;
        let mut pos = self.next_start;
        while pos < self.end {
            let code = b[pos];
            if quote != 0 {
                if code == b'\\' {
                    pos += 1;
                } else if code == quote {
                    quote = 0;
                }
            } else if code == b'"' || code == b'\'' {
                quote = code;
            } else if code == b'[' || code == b'{' {
                depth += 1;
            } else if code == b']' || code == b'}' {
                depth -= 1;
            } else if code == b',' && depth == 0 {
                break;
            }
            pos += 1;
        }
        self.item_start = trim_start_at(self.source, self.next_start, pos);
        self.item_end = trim_end_at(self.source, self.item_start, pos);
        self.item_raw_end = pos;
        if pos < self.end {
            self.next_start = pos + 1;
        } else {
            self.done = true;
        }
        true
    }

    fn is_last(&self) -> bool {
        self.done
    }
}

fn is_nested_flow_construct(item: &str) -> bool {
    let b = item.as_bytes();
    matches!(
        (b.first(), b.last()),
        (Some(b'['), Some(b']')) | (Some(b'{'), Some(b'}'))
    )
}

/// `None` = `val` isn't `[...]`-shaped at all (caller falls back to scalar
/// parsing); `Some(items)` on success. Errors are always hard failures
/// (never a `None` fallback), matching the TS source exactly.
pub fn parse_flow_sequence<B: Builder>(
    val: &str,
    strict: bool,
    line: u32,
    check_duplicates: bool,
) -> Result<Option<Vec<B::Value>>, LimaError> {
    if check_duplicates {
        parse_flow_sequence_checked::<B, true>(val, strict, line, None)
    } else {
        parse_flow_sequence_checked::<B, false>(val, strict, line, None)
    }
}

/// `source` is the flow container's own physical position; each element's
/// tokens are anchored at the container column plus the element's offset
/// within it (References 2.0 §5).
pub(crate) fn parse_flow_sequence_checked<B: Builder, const CHECK_DUPLICATES: bool>(
    val: &str,
    strict: bool,
    line: u32,
    source: Option<ReferenceSource>,
) -> Result<Option<Vec<B::Value>>, LimaError> {
    let b = val.as_bytes();
    if b.first() != Some(&b'[') || b.last() != Some(&b']') {
        return Ok(None);
    }
    let inner_start = trim_start_at(val, 1, val.len() - 1);
    let inner_end = trim_end_at(val, inner_start, val.len() - 1);
    if inner_start == inner_end {
        return Ok(Some(Vec::new()));
    }

    let mut items = Vec::new();
    let mut cursor = FlowCursor::new(val, inner_start, inner_end);
    let mut item_count = 0u32;
    while cursor.next() {
        let (start, end) = (cursor.item_start, cursor.item_end);
        item_count += 1;
        if start == end && !strict && cursor.is_last() && item_count > 1 {
            break;
        }
        let item = &val[start..end];
        if item.is_empty() {
            if strict {
                return Err(LimaError::new(
                    Code::InvalidFlowSyntax,
                    line,
                    format!("Lima: empty element in flow sequence at line {line}"),
                ));
            }
            items.push(B::v_null(line));
            continue;
        }
        let ib = item.as_bytes();
        if ib[0] == b'[' && *ib.last().unwrap() == b']' {
            return Err(LimaError::new(
                Code::InvalidFlowSyntax,
                line,
                format!("Lima: nested flow sequence not permitted at line {line}: \"{item}\""),
            ));
        }
        if ib[0] == b'{' && *ib.last().unwrap() == b'}' {
            if let Some(nested) = parse_flow_mapping_checked::<B, CHECK_DUPLICATES>(
                item,
                strict,
                line,
                element_source(source.as_ref(), val, start, end),
            )? {
                items.push(nested);
                continue;
            }
        }
        items.push(parse_quoted_or_typed::<B>(
            item,
            strict,
            line,
            element_source(source.as_ref(), val, start, end),
        )?);
    }
    Ok(Some(items))
}

/// Index of the key/value separator within a flow-mapping item — the first
/// colon followed by a space or a tab that is not inside a quoted key (§5.1,
/// §7.5). `end` is the item's end before trimming, so `{k: }` has a
/// separator (Core 1.3 §7.5). `None` when the item has no separator (or its
/// quoted key is never closed).
fn flow_item_separator(val: &str, start: usize, end: usize) -> Option<usize> {
    let b = val.as_bytes();
    let mut scan = start;
    if b.get(start) == Some(&b'"') || b.get(start) == Some(&b'\'') {
        // §5.2: a single-quoted key is literal, so its first `'` closes.
        let close = closing_quote_index(&val[start..end], false)?;
        scan = start + close + 1;
    }
    separator_index(&val[scan..end]).map(|p| p + scan)
}

/// `None` = `val` isn't `{...}`-shaped, or (non-strict only) a malformed
/// item inside it means the whole thing falls back to scalar parsing.
pub fn parse_flow_mapping<B: Builder>(
    val: &str,
    strict: bool,
    line: u32,
    check_duplicates: bool,
) -> Result<Option<B::Value>, LimaError> {
    if check_duplicates {
        parse_flow_mapping_checked::<B, true>(val, strict, line, None)
    } else {
        parse_flow_mapping_checked::<B, false>(val, strict, line, None)
    }
}

pub(crate) fn parse_flow_mapping_checked<B: Builder, const CHECK_DUPLICATES: bool>(
    val: &str,
    strict: bool,
    line: u32,
    source: Option<ReferenceSource>,
) -> Result<Option<B::Value>, LimaError> {
    let b = val.as_bytes();
    if b.first() != Some(&b'{') || b.last() != Some(&b'}') {
        return Ok(None);
    }
    let inner_start = trim_start_at(val, 1, val.len() - 1);
    let inner_end = trim_end_at(val, inner_start, val.len() - 1);
    let mut entries: B::Mapping = B::m_create();
    if inner_start == inner_end {
        return Ok(Some(B::v_mapping(entries, line)));
    }

    // the items end at the closing brace, so the last one keeps the
    // whitespace its separator may need (§7.5)
    let mut cursor = FlowCursor::new(val, inner_start, val.len() - 1);
    while cursor.next() {
        let (item_start, item_end) = (cursor.item_start, cursor.item_end);
        let item = &val[item_start..item_end];
        if item.is_empty() {
            if strict {
                return Err(LimaError::new(
                    Code::InvalidFlowSyntax,
                    line,
                    format!("Lima: empty element in flow mapping at line {line}"),
                ));
            }
            continue;
        }
        let malformed = || -> Result<Option<B::Value>, LimaError> {
            if strict {
                Err(LimaError::new(
                    Code::InvalidFlowSyntax, line,
                    format!("Lima: invalid flow mapping item (missing \": \") at line {line}: \"{item}\""),
                ))
            } else {
                Ok(None)
            }
        };
        let Some(colon_pos) = flow_item_separator(val, item_start, cursor.item_raw_end) else {
            return malformed();
        };

        let key_start = trim_start_at(val, item_start, colon_pos);
        let key_end = trim_end_at(val, key_start, colon_pos);
        let key_raw = &val[key_start..key_end];
        if !is_valid_key(key_raw) {
            // §5.1: not a usable key — the item is skipped in both modes
            // (§10's strict list is closed and does not cover this),
            // the same as at the top level.
            continue;
        }
        let key = strip_key_quotes(key_raw, strict, line)?;
        check_key_length(&key, line)?;
        if CHECK_DUPLICATES {
            check_duplicate_key(B::m_has_key(&entries, &key), &key, line, strict)?;
        }

        let value_start = trim_start_at(val, (colon_pos + 2).min(item_end), item_end);
        let value_end = trim_end_at(val, value_start, item_end);
        let raw_val = &val[value_start..value_end];
        if is_nested_flow_construct(raw_val) {
            return Err(LimaError::new(
                Code::InvalidFlowSyntax,
                line,
                format!("Lima: invalid flow nesting at line {line}: \"{raw_val}\""),
            ));
        }
        let v = parse_quoted_or_typed::<B>(
            raw_val,
            strict,
            line,
            element_source(source.as_ref(), val, value_start, value_end),
        )?;
        B::m_set(&mut entries, key, v);
    }
    Ok(Some(B::v_mapping(entries, line)))
}

/// Parses a value that may be a flow collection, without probing both flow
/// parsers for ordinary scalars.
pub fn parse_flow_or_scalar_value<B: Builder>(
    raw: &str,
    strict: bool,
    line: u32,
    check_duplicates: bool,
) -> Result<B::Value, LimaError> {
    if check_duplicates {
        parse_flow_or_scalar_value_checked::<B, true>(raw, strict, line, None)
    } else {
        parse_flow_or_scalar_value_checked::<B, false>(raw, strict, line, None)
    }
}

pub(crate) fn parse_flow_or_scalar_value_checked<B: Builder, const CHECK_DUPLICATES: bool>(
    raw: &str,
    strict: bool,
    line: u32,
    source: Option<ReferenceSource>,
) -> Result<B::Value, LimaError> {
    match raw.as_bytes().first() {
        Some(b'[') => {
            match parse_flow_sequence_checked::<B, CHECK_DUPLICATES>(
                raw,
                strict,
                line,
                source.clone(),
            )? {
                Some(seq) => Ok(B::v_array(seq, line)),
                None => parse_scalar_value::<B>(raw, strict, line, source),
            }
        }
        Some(b'{') => {
            match parse_flow_mapping_checked::<B, CHECK_DUPLICATES>(
                raw,
                strict,
                line,
                source.clone(),
            )? {
                Some(map) => Ok(map),
                None => parse_scalar_value::<B>(raw, strict, line, source),
            }
        }
        _ => parse_quoted_or_typed::<B>(raw, strict, line, source),
    }
}