rsconstruct 0.9.129

Rust based fast build system
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! svglint's `valid` rule: fast-xml-parser 5.10.1's `XMLValidator.validate`
//! with its default options (no boolean attributes, no unpaired tags),
//! ported statement for statement. It is a single pass over the text that
//! stops at the first problem and names it the way fast-xml-parser does;
//! svglint prints that message and nothing else, so the message text is
//! what matters here.
//!
//! The scan runs over UTF-16 code units, as the JavaScript does, so that
//! the one message carrying a position ("opened in line L, col C") counts
//! columns the same way.

const LT: u16 = b'<' as u16;
const GT: u16 = b'>' as u16;
const SLASH: u16 = b'/' as u16;
const BANG: u16 = b'!' as u16;
const QUESTION: u16 = b'?' as u16;
const AMP: u16 = b'&' as u16;
const SEMI: u16 = b';' as u16;
const HASH: u16 = b'#' as u16;
const EQ: u16 = b'=' as u16;
const DQ: u16 = b'"' as u16;
const SQ: u16 = b'\'' as u16;
const SPACE: u16 = b' ' as u16;

/// Validate `source`; `None` when it is well-formed, otherwise the message
/// fast-xml-parser reports.
pub fn validate(source: &str) -> Option<String> {
    let mut data: Vec<u16> = source.encode_utf16().collect();
    if data.first() == Some(&0xFEFF) {
        data.remove(0);
    }
    Validator { x: data }.run()
}

struct Validator {
    x: Vec<u16>,
}

struct OpenTag {
    name: String,
    start: usize,
}

/// A position in the text the way `getLineNumberForPosition` computes it:
/// 1-based line and column, columns in UTF-16 units.
fn line_col(x: &[u16], index: usize) -> (usize, usize) {
    let before = &x[..index.min(x.len())];
    let mut line = 1;
    let mut col_start = 0;
    let mut i = 0;
    while i < before.len() {
        if before[i] == u16::from(b'\n') {
            line += 1;
            col_start = i + 1;
        } else if before[i] == u16::from(b'\r') && before.get(i + 1) == Some(&u16::from(b'\n')) {
            line += 1;
            i += 1;
            col_start = i + 1;
        }
        i += 1;
    }
    (line, before.len() - col_start + 1)
}

const fn is_ws(c: u16) -> bool {
    c == SPACE || c == b'\t' as u16 || c == b'\n' as u16 || c == b'\r' as u16
}

/// JavaScript's `\s` and `String.prototype.trim` whitespace.
const fn is_js_space(c: u16) -> bool {
    matches!(
        c,
        0x09..=0x0D | 0x20 | 0xA0 | 0x1680 | 0x2000..=0x200A | 0x2028 | 0x2029 | 0x202F | 0x205F | 0x3000 | 0xFEFF
    )
}

fn utf16(units: &[u16]) -> String {
    String::from_utf16_lossy(units)
}

fn trim(units: &[u16]) -> &[u16] {
    let start = units
        .iter()
        .position(|&c| !is_js_space(c))
        .unwrap_or(units.len());
    let end = units
        .iter()
        .rposition(|&c| !is_js_space(c))
        .map_or(start, |p| p + 1);
    &units[start..end.max(start)]
}

/// fast-xml-parser's `isName`: XML Name characters within the BMP.
fn is_name(name: &str) -> bool {
    let mut chars = name.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    is_name_start(first) && chars.all(is_name_char)
}

fn is_name_start(c: char) -> bool {
    let u = c as u32;
    c == ':'
        || c.is_ascii_alphabetic()
        || c == '_'
        || (0xC0..=0xD6).contains(&u)
        || (0xD8..=0xF6).contains(&u)
        || (0xF8..=0x2FF).contains(&u)
        || (0x370..=0x37D).contains(&u)
        || (0x37F..=0x1FFF).contains(&u)
        || (0x200C..=0x200D).contains(&u)
        || (0x2070..=0x218F).contains(&u)
        || (0x2C00..=0x2FEF).contains(&u)
        || (0x3001..=0xD7FF).contains(&u)
        || (0xF900..=0xFDCF).contains(&u)
        || (0xFDF0..=0xFFFD).contains(&u)
}

fn is_name_char(c: char) -> bool {
    let u = c as u32;
    is_name_start(c)
        || c == '-'
        || c == '.'
        || c.is_ascii_digit()
        || u == 0xB7
        || (0x300..=0x36F).contains(&u)
        || (0x203F..=0x2040).contains(&u)
}

fn json_string(s: &str) -> String {
    serde_json::to_string(s).unwrap_or_else(|_| format!("{s:?}"))
}

impl Validator {
    fn at(&self, i: usize) -> Option<u16> {
        self.x.get(i).copied()
    }

    fn run(&self) -> Option<String> {
        let x = &self.x;
        let len = x.len();
        let mut tags: Vec<OpenTag> = Vec::new();
        let mut tag_found = false;
        let mut reached_root = false;
        let mut i = 0usize;
        while i < len {
            if x[i] == LT && self.at(i + 1) == Some(QUESTION) {
                i += 2;
                i = match self.read_pi(i) {
                    Ok(i) => i,
                    Err(msg) => return Some(msg),
                };
            } else if x[i] == LT {
                let tag_start = i;
                i += 1;
                if self.at(i) == Some(BANG) {
                    i = self.read_comment_and_cdata(i);
                    i += 1;
                    continue;
                }
                let mut closing = false;
                if self.at(i) == Some(SLASH) {
                    closing = true;
                    i += 1;
                }
                let name_start = i;
                while i < len
                    && x[i] != GT
                    && x[i] != SPACE
                    && x[i] != u16::from(b'\t')
                    && x[i] != u16::from(b'\n')
                    && x[i] != u16::from(b'\r')
                {
                    i += 1;
                }
                let mut name_units = trim(&x[name_start..i]).to_vec();
                if name_units.last() == Some(&SLASH) {
                    name_units.pop();
                    i -= 1;
                }
                let tag_name = utf16(&name_units);
                if !is_name(&tag_name) {
                    if trim(&name_units).is_empty() {
                        return Some("Invalid space after '<'.".to_string());
                    }
                    return Some(format!("Tag '{tag_name}' is an invalid name."));
                }
                let Some((mut attr_str, after, tag_closed)) = self.read_attribute_str(i) else {
                    return Some(format!("Attributes for '{tag_name}' have open quote."));
                };
                i = after;
                if attr_str.last() == Some(&SLASH) {
                    attr_str.pop();
                    if let Some(msg) = validate_attribute_string(&attr_str) {
                        return Some(msg);
                    }
                    tag_found = true;
                } else if closing {
                    if !tag_closed {
                        return Some(format!(
                            "Closing tag '{tag_name}' doesn't have proper closing."
                        ));
                    } else if !trim(&attr_str).is_empty() {
                        return Some(format!(
                            "Closing tag '{tag_name}' can't have attributes or invalid starting."
                        ));
                    } else if tags.is_empty() {
                        return Some(format!("Closing tag '{tag_name}' has not been opened."));
                    }
                    let open = tags.pop().unwrap_or(OpenTag {
                        name: String::new(),
                        start: 0,
                    });
                    if tag_name != open.name {
                        let (line, col) = line_col(x, open.start);
                        return Some(format!(
                            "Expected closing tag '{}' (opened in line {line}, col {col}) instead of closing tag '{tag_name}'.",
                            open.name
                        ));
                    }
                    if tags.is_empty() {
                        reached_root = true;
                    }
                } else {
                    if let Some(msg) = validate_attribute_string(&attr_str) {
                        return Some(msg);
                    }
                    if reached_root {
                        return Some("Multiple possible root nodes found.".to_string());
                    }
                    tags.push(OpenTag {
                        name: tag_name,
                        start: tag_start,
                    });
                    tag_found = true;
                }

                // The text after the tag, with the comments, CDATA sections
                // and processing instructions inside it.
                i += 1;
                while i < len {
                    if x[i] == LT {
                        if self.at(i + 1) == Some(BANG) {
                            i += 1;
                            i = self.read_comment_and_cdata(i);
                            i += 1;
                            continue;
                        } else if self.at(i + 1) == Some(QUESTION) {
                            i += 1;
                            i = match self.read_pi(i) {
                                Ok(i) => i,
                                Err(msg) => return Some(msg),
                            };
                        } else {
                            break;
                        }
                    } else if x[i] == AMP {
                        let after_amp = self.validate_ampersand(i);
                        let Some(after_amp) = after_amp else {
                            return Some("char '&' is not expected.".to_string());
                        };
                        i = after_amp;
                    } else if reached_root && !is_ws(x[i]) {
                        return Some("Extra text at the end".to_string());
                    }
                    i += 1;
                }
                if self.at(i) == Some(LT) {
                    i -= 1;
                }
            } else {
                if is_ws(x[i]) {
                    i += 1;
                    continue;
                }
                return Some(format!("char '{}' is not expected.", utf16(&x[i..=i])));
            }
            i += 1;
        }

        if !tag_found {
            return Some("Start tag expected.".to_string());
        }
        if tags.len() == 1 {
            return Some(format!("Unclosed tag '{}'.", tags[0].name));
        }
        if !tags.is_empty() {
            let names: Vec<String> = tags
                .iter()
                .map(|t| format!("    {}", json_string(&t.name)))
                .collect();
            return Some(format!("Invalid '[{}]' found.", names.join(",")));
        }
        None
    }

    /// `readPI`: skip a processing instruction. `Ok(i)` is the index to
    /// continue from, `Err(msg)` a misplaced XML declaration.
    fn read_pi(&self, mut i: usize) -> Result<usize, String> {
        let start = i;
        while i < self.x.len() {
            let c = self.x[i];
            if c == QUESTION || c == SPACE {
                let name = utf16(&self.x[start..i]);
                if i > 5 && name == "xml" {
                    return Err(
                        "XML declaration allowed only at the start of the document.".to_string()
                    );
                } else if c == QUESTION && self.at(i + 1) == Some(GT) {
                    i += 1;
                    break;
                }
            }
            i += 1;
        }
        Ok(i)
    }

    /// `readCommentAndCDATA`, entered at the `!`.
    fn read_comment_and_cdata(&self, mut i: usize) -> usize {
        let x = &self.x;
        let len = x.len();
        let unit = |b: u8| u16::from(b);
        if len > i + 5 && self.at(i + 1) == Some(unit(b'-')) && self.at(i + 2) == Some(unit(b'-')) {
            i += 3;
            while i < len {
                if x[i] == unit(b'-')
                    && self.at(i + 1) == Some(unit(b'-'))
                    && self.at(i + 2) == Some(GT)
                {
                    i += 2;
                    break;
                }
                i += 1;
            }
        } else if len > i + 8 && x[i + 1..i + 8] == b"DOCTYPE".map(u16::from) {
            let mut depth = 1;
            i += 8;
            while i < len {
                if x[i] == LT {
                    depth += 1;
                } else if x[i] == GT {
                    depth -= 1;
                    if depth == 0 {
                        break;
                    }
                }
                i += 1;
            }
        } else if len > i + 9 && x[i + 1..i + 8] == b"[CDATA[".map(u16::from) {
            i += 8;
            while i < len {
                if x[i] == unit(b']')
                    && self.at(i + 1) == Some(unit(b']'))
                    && self.at(i + 2) == Some(GT)
                {
                    i += 2;
                    break;
                }
                i += 1;
            }
        }
        i
    }

    /// `readAttributeStr`: everything up to the `>` outside quotes. `None`
    /// for an unclosed quote; otherwise the text, the index of the `>` (or
    /// the end), and whether a `>` was found.
    fn read_attribute_str(&self, mut i: usize) -> Option<(Vec<u16>, usize, bool)> {
        let mut attr = Vec::new();
        let mut quote: Option<u16> = None;
        let mut closed = false;
        while i < self.x.len() {
            let c = self.x[i];
            if c == DQ || c == SQ {
                match quote {
                    None => quote = Some(c),
                    Some(q) if q == c => quote = None,
                    Some(_) => {}
                }
            } else if c == GT && quote.is_none() {
                closed = true;
                break;
            }
            attr.push(c);
            i += 1;
        }
        if quote.is_some() {
            return None;
        }
        Some((attr, i, closed))
    }

    /// `validateAmpersand`: the index of the `;` ending a reference (or the
    /// end of the text), `None` when the `&` is not a reference.
    fn validate_ampersand(&self, mut i: usize) -> Option<usize> {
        let x = &self.x;
        i += 1;
        if self.at(i) == Some(SEMI) {
            return None;
        }
        if self.at(i) == Some(HASH) {
            i += 1;
            let hex = self.at(i) == Some(u16::from(b'x'));
            if hex {
                i += 1;
            }
            while i < x.len() {
                if x[i] == SEMI {
                    return Some(i);
                }
                let ok = char::from_u32(u32::from(x[i])).is_some_and(|c| {
                    if hex {
                        c.is_ascii_hexdigit()
                    } else {
                        c.is_ascii_digit()
                    }
                });
                if !ok {
                    break;
                }
                i += 1;
            }
            return None;
        }
        let mut count = 0;
        while i < x.len() {
            let word = char::from_u32(u32::from(x[i]))
                .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_');
            if word && count < 20 {
                i += 1;
                count += 1;
                continue;
            }
            if x[i] == SEMI {
                break;
            }
            return None;
        }
        Some(i)
    }
}

/// `validateAttributeString`: the attribute text of a tag, scanned with the
/// `(\s*)([^\s=]+)(\s*=)?(\s*(['"])(([\s\S])*?)\5)?` regular expression and
/// checked match by match.
fn validate_attribute_string(attr: &[u16]) -> Option<String> {
    let mut seen: Vec<String> = Vec::new();
    for m in attr_matches(attr) {
        let name = utf16(&m.name);
        if m.leading_ws == 0 {
            return Some(format!("Attribute '{name}' has no space in starting."));
        } else if m.has_equals && !m.has_value {
            return Some(format!("Attribute '{name}' is without value."));
        } else if !m.has_equals {
            return Some(format!("boolean attribute '{name}' is not allowed."));
        }
        if !is_name(&name) {
            return Some(format!("Attribute '{name}' is an invalid name."));
        }
        if seen.contains(&name) {
            return Some(format!("Attribute '{name}' is repeated."));
        }
        seen.push(name);
    }
    None
}

struct AttrMatch {
    leading_ws: usize,
    name: Vec<u16>,
    has_equals: bool,
    has_value: bool,
}

/// The successive matches of the attribute regular expression, as a global
/// `exec` loop finds them: the leftmost position from which `\s*` reaches a
/// character that is neither whitespace nor `=` starts a match.
fn attr_matches(attr: &[u16]) -> Vec<AttrMatch> {
    let len = attr.len();
    let mut out = Vec::new();
    let mut last = 0usize;
    loop {
        // Find the leftmost start `s >= last` whose whitespace run ends at a
        // name character; a run ending at `=` or the end fails, and the
        // scan resumes after that `=`.
        let mut start = last;
        let name_start;
        loop {
            let mut r = start;
            while r < len && is_js_space(attr[r]) {
                r += 1;
            }
            if r >= len {
                return out;
            }
            if attr[r] == EQ {
                start = r + 1;
                continue;
            }
            name_start = r;
            break;
        }
        let leading_ws = name_start - start;
        let mut i = name_start;
        while i < len && !is_js_space(attr[i]) && attr[i] != EQ {
            i += 1;
        }
        let name = attr[name_start..i].to_vec();
        // `(\s*=)?`
        let mut j = i;
        while j < len && is_js_space(attr[j]) {
            j += 1;
        }
        let mut has_equals = false;
        if j < len && attr[j] == EQ {
            has_equals = true;
            i = j + 1;
        }
        // `(\s*(['"])(([\s\S])*?)\5)?`
        let mut has_value = false;
        let mut k = i;
        while k < len && is_js_space(attr[k]) {
            k += 1;
        }
        if k < len && (attr[k] == DQ || attr[k] == SQ) {
            let q = attr[k];
            if let Some(close) = attr[k + 1..].iter().position(|&c| c == q) {
                has_value = true;
                i = k + 1 + close + 1;
            }
        }
        out.push(AttrMatch {
            leading_ws,
            name,
            has_equals,
            has_value,
        });
        last = i;
    }
}