tabnas-css 0.5.16

Parse CSS into a reworkcss-style abstract syntax tree.
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
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
/* Copyright (c) 2025 Richard Rodger, MIT License */

//! The AST value model: [`Node`], an insertion-ordered map with a `type`
//! discriminator, and [`Value`], what a node field can hold.
//!
//! The TypeScript port returns plain JavaScript objects and the Go port
//! returns `map[string]any`. The engine's own value, [`tabnas::Value`], is
//! what the plugin form returns too, but [`Css::parse`](crate::Css::parse)
//! returns this one, for two reasons: every traversal of it is iterative, so
//! a tree of any depth can be dropped, cloned, compared, printed and written
//! as JSON, where the engine's recurses once per level; and it keeps
//! JavaScript's `undefined` (below). Insertion order is preserved because the
//! AST is usually read back as JSON and `{"type": …}` first reads better than
//! a sorted map — the conformance runners compare key sets, not key order,
//! so nothing depends on it.
//!
//! [`Value::Undefined`] is the one non-obvious variant. It is JavaScript's
//! `undefined`: a key that EXISTS in insertion order but is absent from the
//! serialised JSON. The canonical port writes `node.position = { start, end:
//! undefined }` at construction and fills `end` in later, so a node whose end
//! is never recorded (a declaration with an empty value, say) serialises as
//! `{"start":…}` with no `end` at all. Emitting `null` there instead would be
//! a different AST.

use std::fmt;
use std::fmt::Write as _;
use std::sync::Arc;

use tabnas::Value as Engine;

/// A value held by an AST node field.
///
/// Every traversal of a value is ITERATIVE: dropping, cloning, comparing,
/// writing it as JSON and formatting it for [`std::fmt::Debug`]. An AST is as
/// deep as the CSS that produced it, so a derived implementation of any of
/// them would recurse once per level and abort the process on nothing worse
/// than untrusted input. None of them is derived, for that reason.
pub enum Value {
    /// A key that exists but serialises to nothing (JavaScript `undefined`).
    Undefined,
    /// JSON `null`.
    Null,
    /// JSON `true` / `false`.
    Bool(bool),
    /// A JSON number. Integral values serialise without a decimal point.
    Num(f64),
    /// A JSON string.
    Str(String),
    /// A JSON array.
    List(Vec<Value>),
    /// A nested AST node (a JSON object).
    Node(Node),
}

impl Value {
    /// The string held here, if this is a [`Value::Str`].
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Value::Str(s) => Some(s),
            _ => None,
        }
    }

    /// The node held here, if this is a [`Value::Node`].
    pub fn as_node(&self) -> Option<&Node> {
        match self {
            Value::Node(n) => Some(n),
            _ => None,
        }
    }

    /// The list held here, if this is a [`Value::List`].
    pub fn as_list(&self) -> Option<&[Value]> {
        match self {
            Value::List(l) => Some(l),
            _ => None,
        }
    }

    /// This value as JSON. `Undefined` renders as `null` at the top level and
    /// inside an array — only an object KEY can be dropped entirely, which is
    /// what JavaScript's `JSON.stringify` does too.
    pub fn to_json(&self) -> String {
        let mut out = String::new();
        write_json(self, &mut out);
        out
    }
}

impl From<&str> for Value {
    fn from(s: &str) -> Self {
        Value::Str(s.to_string())
    }
}

impl From<String> for Value {
    fn from(s: String) -> Self {
        Value::Str(s)
    }
}

impl From<Node> for Value {
    fn from(n: Node) -> Self {
        Value::Node(n)
    }
}

/// An AST node: an insertion-ordered string-keyed map.
///
/// Like [`Value`], every traversal of it is iterative rather than derived.
#[derive(Default)]
pub struct Node {
    entries: Vec<(String, Value)>,
}

impl Node {
    /// An empty node.
    pub fn new() -> Self {
        Node {
            entries: Vec::new(),
        }
    }

    /// The node's `type` discriminator, if it has one.
    pub fn node_type(&self) -> Option<&str> {
        self.get("type").and_then(Value::as_str)
    }

    /// The value at `key`, if the key is present.
    pub fn get(&self, key: &str) -> Option<&Value> {
        self.entries.iter().find(|(k, _)| k == key).map(|(_, v)| v)
    }

    /// A mutable reference to the value at `key`, if the key is present.
    pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
        self.entries
            .iter_mut()
            .find(|(k, _)| k == key)
            .map(|(_, v)| v)
    }

    /// Set `key`, keeping its existing position when it is already present
    /// (as assigning to a JavaScript object property does).
    pub fn set(&mut self, key: impl Into<String>, value: impl Into<Value>) {
        let key = key.into();
        let value = value.into();
        match self.get_mut(&key) {
            Some(slot) => *slot = value,
            None => self.entries.push((key, value)),
        }
    }

    /// Append to the list at `key`, creating the list if it is absent.
    pub fn push_to(&mut self, key: &str, value: Value) {
        match self.get_mut(key) {
            Some(Value::List(list)) => list.push(value),
            Some(slot) => *slot = Value::List(vec![value]),
            None => self
                .entries
                .push((key.to_string(), Value::List(vec![value]))),
        }
    }

    /// The entries, in insertion order.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
        self.entries.iter().map(|(k, v)| (k.as_str(), v))
    }

    /// How many keys the node holds, `Undefined` ones included.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the node holds no keys at all.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// This node as JSON. Keys holding [`Value::Undefined`] are omitted.
    pub fn to_json(&self) -> String {
        let mut out = String::new();
        write_steps(vec![Emit::Node(self)], &mut out, Mode::Json);
        out
    }
}

/// Dismantle a node iteratively when it is dropped.
///
/// An AST is as deep as the CSS that produced it, and a derived drop would
/// recurse once per level — so a stylesheet nested a few thousand rules deep
/// would abort the process, on nothing worse than untrusted input, at the
/// moment the tree went out of scope. The engine keeps its own rule stack
/// for the same reason; this is the other half of that promise.
impl Drop for Node {
    fn drop(&mut self) {
        let mut pending: Vec<Value> = self.entries.drain(..).map(|(_, v)| v).collect();
        while let Some(value) = pending.pop() {
            match value {
                Value::List(items) => pending.extend(items),
                // `node` is emptied here, so its own drop finds nothing left
                // to do and does not recurse.
                Value::Node(mut node) => {
                    pending.extend(node.entries.drain(..).map(|(_, v)| v));
                }
                _ => {}
            }
        }
    }
}

/// What [`write_steps`] is producing.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Mode {
    /// JSON: an `Undefined` key is dropped, as `JSON.stringify` drops a key
    /// whose value is `undefined`.
    Json,
    /// A debug view: an `Undefined` key is kept and shown, because the point
    /// of the debug view is to show what is there.
    Debug,
}

/// One step of the iterative writer.
enum Emit<'a> {
    /// Write this value (pushing more steps for a node or a list).
    Value(&'a Value),
    /// Write this node — the same work as `Value(Value::Node(..))`, for a
    /// node that is not wrapped in a [`Value`].
    Node(&'a Node),
    /// Write this object key and the `:` after it.
    Key(&'a str),
    /// Write this punctuation verbatim.
    Raw(&'static str),
}

/// Write a value as JSON, iteratively.
///
/// Iterative for the same reason [`Node`]'s drop is: recursing once per
/// nesting level turns a deeply nested stylesheet into a stack overflow, and
/// serialising the AST is the most ordinary thing a caller does with it.
fn write_json(root: &Value, out: &mut String) {
    write_steps(vec![Emit::Value(root)], out, Mode::Json)
}

fn write_steps(mut steps: Vec<Emit<'_>>, out: &mut String, mode: Mode) {
    while let Some(step) = steps.pop() {
        match step {
            Emit::Raw(text) => out.push_str(text),
            Emit::Key(key) => {
                write_json_string(key, out);
                out.push(':');
            }
            Emit::Value(Value::Node(node)) | Emit::Node(node) => {
                out.push('{');
                steps.push(Emit::Raw("}"));
                let entries: Vec<(&str, &Value)> = node
                    .iter()
                    .filter(|(_, v)| Mode::Debug == mode || !matches!(v, Value::Undefined))
                    .collect();
                // Pushed in reverse so they come back off the stack in order.
                for (i, (key, value)) in entries.iter().enumerate().rev() {
                    steps.push(Emit::Value(value));
                    steps.push(Emit::Key(key));
                    if 0 < i {
                        steps.push(Emit::Raw(","));
                    }
                }
            }
            Emit::Value(Value::List(items)) => {
                out.push('[');
                steps.push(Emit::Raw("]"));
                for (i, item) in items.iter().enumerate().rev() {
                    steps.push(Emit::Value(item));
                    if 0 < i {
                        steps.push(Emit::Raw(","));
                    }
                }
            }
            Emit::Value(Value::Undefined) => out.push_str(match mode {
                Mode::Json => "null",
                Mode::Debug => "undefined",
            }),
            Emit::Value(Value::Null) => out.push_str("null"),
            Emit::Value(Value::Bool(b)) => out.push_str(if *b { "true" } else { "false" }),
            Emit::Value(Value::Num(n)) => write_num(*n, out),
            Emit::Value(Value::Str(s)) => write_json_string(s, out),
        }
    }
}

/// The debug view is the JSON, with `Undefined` keys shown rather than
/// dropped.
///
/// Not derived, and not a struct-shaped `{:#?}` dump. A derived formatter
/// recurses once per nesting level, so `format!("{ast:?}")` on a stylesheet a
/// few thousand rules deep aborts the process — on an AST whose parse, drop
/// and serialisation are all depth-safe, and in the one operation a caller
/// reaches for while debugging. This shares the iterative writer instead.
impl fmt::Debug for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut out = String::new();
        write_steps(vec![Emit::Value(self)], &mut out, Mode::Debug);
        f.write_str(&out)
    }
}

impl fmt::Debug for Node {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut out = String::new();
        write_steps(vec![Emit::Node(self)], &mut out, Mode::Debug);
        f.write_str(&out)
    }
}

/// One step of the iterative deep clone.
enum CloneStep<'a> {
    /// Clone this value, pushing more steps for a node or a list.
    Enter(&'a Value),
    /// Take the last `n` cloned values off the output and make a node of
    /// them, under this node's keys.
    CloseNode(&'a Node),
    /// Take the last `n` cloned values off the output and make a list.
    CloseList(usize),
}

/// A deep clone, iteratively.
///
/// A derived `Clone` recurses once per nesting level. Cloning a parsed AST is
/// an ordinary thing to do, so it is depth-safe here like everything else.
fn clone_value(root: &Value) -> Value {
    let mut steps = vec![CloneStep::Enter(root)];
    let mut done: Vec<Value> = Vec::new();
    while let Some(step) = steps.pop() {
        match step {
            // Children are pushed after the close step, so they pop first and
            // land on `done` in order, before the close reads them back.
            CloneStep::Enter(Value::Node(node)) => {
                steps.push(CloneStep::CloseNode(node));
                for (_, value) in node.entries.iter().rev() {
                    steps.push(CloneStep::Enter(value));
                }
            }
            CloneStep::Enter(Value::List(items)) => {
                steps.push(CloneStep::CloseList(items.len()));
                for item in items.iter().rev() {
                    steps.push(CloneStep::Enter(item));
                }
            }
            CloneStep::Enter(leaf) => done.push(match leaf {
                Value::Undefined => Value::Undefined,
                Value::Null => Value::Null,
                Value::Bool(b) => Value::Bool(*b),
                Value::Num(n) => Value::Num(*n),
                Value::Str(s) => Value::Str(s.clone()),
                // Handled by the arms above.
                Value::List(_) | Value::Node(_) => unreachable!(),
            }),
            CloneStep::CloseNode(node) => {
                let values = done.split_off(done.len() - node.entries.len());
                let entries = node
                    .entries
                    .iter()
                    .map(|(k, _)| k.clone())
                    .zip(values)
                    .collect();
                done.push(Value::Node(Node { entries }));
            }
            CloneStep::CloseList(n) => {
                let items = done.split_off(done.len() - n);
                done.push(Value::List(items));
            }
        }
    }
    done.pop().expect("the clone produced no value")
}

impl Clone for Value {
    fn clone(&self) -> Value {
        clone_value(self)
    }
}

impl Clone for Node {
    fn clone(&self) -> Node {
        let mut out = Node::new();
        // One level by hand, then the iterative walk for each field, so that
        // cloning a node never wraps it in a temporary Value.
        for (key, value) in &self.entries {
            out.entries.push((key.clone(), clone_value(value)));
        }
        out
    }
}

/// An equality walk, iteratively, for the same reason as the rest.
fn values_eq(a: &Value, b: &Value) -> bool {
    let mut pending: Vec<(&Value, &Value)> = vec![(a, b)];
    while let Some((a, b)) = pending.pop() {
        match (a, b) {
            (Value::Undefined, Value::Undefined) | (Value::Null, Value::Null) => {}
            (Value::Bool(a), Value::Bool(b)) if a == b => {}
            (Value::Num(a), Value::Num(b)) if a == b => {}
            (Value::Str(a), Value::Str(b)) if a == b => {}
            (Value::List(a), Value::List(b)) if a.len() == b.len() => {
                pending.extend(a.iter().zip(b.iter()));
            }
            (Value::Node(a), Value::Node(b)) if a.entries.len() == b.entries.len() => {
                for ((ak, av), (bk, bv)) in a.entries.iter().zip(b.entries.iter()) {
                    if ak != bk {
                        return false;
                    }
                    pending.push((av, bv));
                }
            }
            _ => return false,
        }
    }
    true
}

impl PartialEq for Value {
    fn eq(&self, other: &Value) -> bool {
        values_eq(self, other)
    }
}

impl PartialEq for Node {
    fn eq(&self, other: &Node) -> bool {
        self.entries.len() == other.entries.len()
            && self
                .entries
                .iter()
                .zip(other.entries.iter())
                .all(|((ak, _), (bk, _))| ak == bk)
            && self
                .entries
                .iter()
                .zip(other.entries.iter())
                .all(|((_, av), (_, bv))| values_eq(av, bv))
    }
}

/// Write a JSON number. Integral values lose the `.0` Rust would print, so
/// a line number reads as `2` and not `2.0`.
fn write_num(n: f64, out: &mut String) {
    if n.is_finite() && n == n.trunc() && n.abs() < 1e15 {
        let _ = write!(out, "{}", n as i64);
    } else if n.is_finite() {
        let _ = write!(out, "{}", n);
    } else {
        // JSON has no infinity or NaN; JavaScript's JSON.stringify writes
        // null for both.
        out.push_str("null");
    }
}

/// Write a JSON string literal, escaping exactly what `JSON.stringify` does.
fn write_json_string(s: &str, out: &mut String) {
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '\u{08}' => out.push_str("\\b"),
            '\u{0c}' => out.push_str("\\f"),
            c if (c as u32) < 0x20 => {
                let _ = write!(out, "\\u{:04x}", c as u32);
            }
            c => out.push(c),
        }
    }
    out.push('"');
}

impl Value {
    /// An engine value as this crate's, field for field.
    ///
    /// RECURSIVE, so only for values whose depth this crate controls: the
    /// grammar document read from the embedded text. A parse result goes
    /// through [`Value::from_arena`] instead.
    pub(crate) fn from_engine(value: &Engine) -> Value {
        match value {
            Engine::Array(items) => Value::List(items.iter().map(Value::from_engine).collect()),
            Engine::Object(fields) => {
                let mut node = Node::new();
                for (key, field) in fields.iter() {
                    node.set(key.clone(), Value::from_engine(field));
                }
                Value::Node(node)
            }
            scalar => Value::from_scalar(scalar),
        }
    }

    fn from_scalar(value: &Engine) -> Value {
        match value {
            Engine::String(s) => Value::Str(s.clone()),
            Engine::Number(n) => Value::Num(*n),
            Engine::Bool(b) => Value::Bool(*b),
            Engine::Null => Value::Null,
            _ => Value::Undefined,
        }
    }

    /// A parse result from the plugin's node store as the tree it describes.
    ///
    /// [`Css::parse`](crate::Css::parse) runs the grammar with each node kept
    /// as one flat record in a per-parse list, and a child list holding the
    /// ids of the children (`rules`, `declarations`, `keyframes`), so the
    /// engine never holds a nested value it would drop or copy by recursion.
    /// Every child's constructor runs after its parent's, so a child's id is
    /// always greater than its parent's: walking the records from the last to
    /// the first finds each child already built, and moves it into place. No
    /// step recurses, whatever the depth.
    ///
    /// A record's `position` has an `end` only once one was recorded; here an
    /// absent `end` becomes [`Value::Undefined`], the key the canonical port
    /// writes at construction and fills in later.
    ///
    /// The engine's `emptyResult` for `""` arrives as an object rather than a
    /// list, and is converted as it is: an empty stylesheet with no position,
    /// as in the canonical port.
    pub(crate) fn from_arena(value: Engine) -> Value {
        match value {
            Engine::Array(records) => {
                let records = Arc::try_unwrap(records).unwrap_or_else(|shared| (*shared).clone());
                let mut built: Vec<Option<Value>> = Vec::with_capacity(records.len());
                built.resize_with(records.len(), || None);
                for (id, record) in records.into_iter().enumerate().rev() {
                    let mut node = Node::new();
                    if let Engine::Object(fields) = record {
                        for (key, field) in fields.iter() {
                            let field = match field {
                                Engine::Array(items) => Value::List(
                                    items
                                        .iter()
                                        .map(|item| match item {
                                            Engine::Number(child) => built
                                                .get_mut(*child as usize)
                                                .and_then(Option::take)
                                                .unwrap_or(Value::Null),
                                            other => Value::from_scalar(other),
                                        })
                                        .collect(),
                                ),
                                Engine::Object(_) if "position" == key => position(field),
                                other => Value::from_scalar(other),
                            };
                            node.set(key.clone(), field);
                        }
                    }
                    built[id] = Some(Value::Node(node));
                }
                built
                    .first_mut()
                    .and_then(Option::take)
                    .unwrap_or(Value::Undefined)
            }
            Engine::Object(fields) => {
                let mut node = Node::new();
                for (key, field) in fields.iter() {
                    let field = match field {
                        Engine::Array(items) => {
                            Value::List(items.iter().map(Value::from_scalar).collect())
                        }
                        other => Value::from_scalar(other),
                    };
                    node.set(key.clone(), field);
                }
                Value::Node(node)
            }
            other => Value::from_scalar(&other),
        }
    }
}

/// A record's `position`, `{start, end}`, with an unrecorded `end` as
/// [`Value::Undefined`].
fn position(value: &Engine) -> Value {
    let mut out = Node::new();
    let fields = match value {
        Engine::Object(fields) => Some(fields),
        _ => None,
    };
    for key in ["start", "end"] {
        match fields.and_then(|fields| fields.get(key)) {
            Some(Engine::Object(point)) => {
                let mut at = Node::new();
                for (name, n) in point.iter() {
                    at.set(name.clone(), Value::from_scalar(n));
                }
                out.set(key, Value::Node(at));
            }
            _ => out.set(key, Value::Undefined),
        }
    }
    Value::Node(out)
}