mittens-query 0.6.0

CSS and Meow Meow query parsers and a host-neutral tree evaluator
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
//! MMQ — Meow Meow Query selector syntax.
//!
//! MMQ MVP grammar:
//!
//! ```text
//! query    := sequence ("," sequence)*
//! sequence := compound (combinator compound)*
//! combinator := whitespace | ">"
//! compound := simple+
//! simple   := "*" | "#" ident | type_ident | "[" attr "]"
//! attr     := ident ("=" (quoted_string | ident_or_number))?
//! ```
//!
//! Differences from CSS syntax:
//! - `#name` selects by component **label** (`SimpleSelector::Name`), not by Id.
//!   The engine's component graph has no separate id concept distinct from label.
//! - No class selector (`.foo`) in MVP — the engine has no class concept.
//!
//! Example: `T#hero`, `#left_hand`, `Renderable#bg`, `T > R`, `#root T`.

use std::collections::HashMap;
use std::sync::Arc;

use crate::ast::{
    AttributeSelector, Combinator, CompoundSelector, QueryAst, SelectorSegment, SelectorSequence,
    SimpleSelector,
};
use crate::{QueryParseError, QuerySyntax};

/// MMQ parser with per-instance AST cache.
///
/// Repeated `parse(s)` calls with the same `s` are amortized to one
/// `Arc::clone` after the first. ASTs are pure functions of the input —
/// the cache never goes stale; it grows monotonically.
#[derive(Default)]
pub struct MmqQuerySyntax {
    cache: HashMap<String, Arc<QueryAst>>,
}

impl MmqQuerySyntax {
    pub fn new() -> Self {
        Self::default()
    }
}

impl QuerySyntax for MmqQuerySyntax {
    fn parse(&mut self, input: &str) -> Result<Arc<QueryAst>, QueryParseError> {
        if let Some(ast) = self.cache.get(input) {
            return Ok(ast.clone());
        }
        let ast = Arc::new(Parser::new(input).parse_query()?);
        self.cache.insert(input.to_string(), ast.clone());
        Ok(ast)
    }
}

struct Parser<'a> {
    input: &'a str,
    pos: usize,
}

impl<'a> Parser<'a> {
    fn new(input: &'a str) -> Self {
        Self { input, pos: 0 }
    }

    fn parse_query(&mut self) -> Result<QueryAst, QueryParseError> {
        let mut selector_groups = Vec::new();

        loop {
            self.skip_whitespace();
            if self.is_eof() {
                break;
            }

            selector_groups.push(self.parse_selector_sequence()?);
            self.skip_whitespace();

            if self.peek_char() == Some(',') {
                self.bump_char();
                continue;
            }

            break;
        }

        if selector_groups.is_empty() {
            return Err(self.err("empty query"));
        }

        Ok(QueryAst { selector_groups })
    }

    fn parse_selector_sequence(&mut self) -> Result<SelectorSequence, QueryParseError> {
        let mut segments = Vec::new();
        let first = self.parse_compound_selector()?;
        segments.push(SelectorSegment {
            combinator: None,
            compound: first,
        });

        loop {
            let saw_ws = self.skip_whitespace();
            let combinator = match self.peek_char() {
                Some('>') => {
                    self.bump_char();
                    self.skip_whitespace();
                    Some(Combinator::Child)
                }
                Some(',') | None => break,
                _ if saw_ws => Some(Combinator::Descendant),
                _ => None,
            };

            let Some(combinator) = combinator else {
                break;
            };

            let compound = self.parse_compound_selector()?;
            segments.push(SelectorSegment {
                combinator: Some(combinator),
                compound,
            });
        }

        Ok(SelectorSequence { segments })
    }

    fn parse_compound_selector(&mut self) -> Result<CompoundSelector, QueryParseError> {
        let mut simple_selectors = Vec::new();

        loop {
            match self.peek_char() {
                Some('*') => {
                    self.bump_char();
                    simple_selectors.push(SimpleSelector::Universal);
                }
                Some('#') => {
                    self.bump_char();
                    let ident = self.parse_identifier()?;
                    simple_selectors.push(SimpleSelector::Name(ident));
                }
                Some('@') => {
                    self.bump_char();
                    // Currently only `@uuid:<hex+hyphens>` is recognized.
                    let scheme = self.parse_identifier()?;
                    if scheme != "uuid" {
                        return Err(self.err(format!(
                            "unknown @-selector scheme '{}', expected 'uuid'",
                            scheme
                        )));
                    }
                    self.expect_char(':')?;
                    let guid = self.parse_guid_literal()?;
                    simple_selectors.push(SimpleSelector::Guid(guid));
                }
                Some('[') => {
                    simple_selectors
                        .push(SimpleSelector::Attribute(self.parse_attribute_selector()?));
                }
                Some(ch) if is_ident_start(ch) => {
                    let ident = self.parse_identifier()?;
                    simple_selectors.push(SimpleSelector::Type(ident));
                }
                _ => break,
            }
        }

        if simple_selectors.is_empty() {
            return Err(self.err("expected selector"));
        }

        Ok(CompoundSelector { simple_selectors })
    }

    fn parse_attribute_selector(&mut self) -> Result<AttributeSelector, QueryParseError> {
        self.expect_char('[')?;
        self.skip_whitespace();
        let name = self.parse_identifier()?;
        self.skip_whitespace();

        let value = if self.peek_char() == Some('=') {
            self.bump_char();
            self.skip_whitespace();
            Some(self.parse_attribute_value()?)
        } else {
            None
        };

        self.skip_whitespace();
        self.expect_char(']')?;

        Ok(AttributeSelector { name, value })
    }

    fn parse_attribute_value(&mut self) -> Result<String, QueryParseError> {
        match self.peek_char() {
            Some('\'') | Some('"') => self.parse_quoted_string(),
            Some(ch) if is_ident_start(ch) || ch.is_ascii_digit() => {
                self.parse_identifier_or_number()
            }
            _ => Err(self.err("expected attribute value")),
        }
    }

    fn parse_quoted_string(&mut self) -> Result<String, QueryParseError> {
        let quote = self
            .bump_char()
            .ok_or_else(|| self.err("expected string quote"))?;
        let start = self.pos;
        while let Some(ch) = self.peek_char() {
            if ch == quote {
                let value = self.input[start..self.pos].to_string();
                self.bump_char();
                return Ok(value);
            }
            self.bump_char();
        }
        Err(self.err("unterminated string"))
    }

    fn parse_identifier_or_number(&mut self) -> Result<String, QueryParseError> {
        let start = self.pos;
        while let Some(ch) = self.peek_char() {
            if is_ident_continue(ch) || ch.is_ascii_digit() {
                self.bump_char();
            } else {
                break;
            }
        }

        if start == self.pos {
            return Err(self.err("expected identifier"));
        }

        Ok(self.input[start..self.pos].to_string())
    }

    fn parse_guid_literal(&mut self) -> Result<String, QueryParseError> {
        let start = self.pos;
        while let Some(ch) = self.peek_char() {
            if ch.is_ascii_hexdigit() || ch == '-' {
                self.bump_char();
            } else {
                break;
            }
        }
        if start == self.pos {
            return Err(self.err("expected guid literal"));
        }
        Ok(self.input[start..self.pos].to_string())
    }

    fn parse_identifier(&mut self) -> Result<String, QueryParseError> {
        let Some(ch) = self.peek_char() else {
            return Err(self.err("expected identifier"));
        };
        if !is_ident_start(ch) {
            return Err(self.err("expected identifier"));
        }

        let start = self.pos;
        self.bump_char();
        while let Some(next) = self.peek_char() {
            if is_ident_continue(next) {
                self.bump_char();
            } else {
                break;
            }
        }

        Ok(self.input[start..self.pos].to_string())
    }

    fn expect_char(&mut self, expected: char) -> Result<(), QueryParseError> {
        match self.bump_char() {
            Some(ch) if ch == expected => Ok(()),
            _ => Err(self.err(format!("expected '{}'", expected))),
        }
    }

    fn skip_whitespace(&mut self) -> bool {
        let start = self.pos;
        while matches!(self.peek_char(), Some(ch) if ch.is_whitespace()) {
            self.bump_char();
        }
        self.pos > start
    }

    fn peek_char(&self) -> Option<char> {
        self.input[self.pos..].chars().next()
    }

    fn bump_char(&mut self) -> Option<char> {
        let ch = self.peek_char()?;
        self.pos += ch.len_utf8();
        Some(ch)
    }

    fn is_eof(&self) -> bool {
        self.pos >= self.input.len()
    }

    fn err(&self, message: impl Into<String>) -> QueryParseError {
        QueryParseError::new(message, self.pos)
    }
}

fn is_ident_start(ch: char) -> bool {
    ch.is_ascii_alphabetic() || ch == '_' || ch == '-'
}

fn is_ident_continue(ch: char) -> bool {
    is_ident_start(ch) || ch.is_ascii_digit()
}

#[cfg(test)]
mod tests {
    use super::MmqQuerySyntax;
    use crate::QuerySyntax;
    use crate::ast::{Combinator, SimpleSelector};
    use std::sync::Arc;

    #[test]
    fn parses_name_selector() {
        let mut p = MmqQuerySyntax::new();
        let ast = p.parse("#hero").expect("parse");
        let seg = &ast.selector_groups[0].segments[0];
        assert_eq!(seg.combinator, None);
        match &seg.compound.simple_selectors[0] {
            SimpleSelector::Name(n) => assert_eq!(n, "hero"),
            other => panic!("expected name, got {:?}", other),
        }
    }

    #[test]
    fn parses_type_selector() {
        let mut p = MmqQuerySyntax::new();
        let ast = p.parse("Transform").expect("parse");
        match &ast.selector_groups[0].segments[0].compound.simple_selectors[0] {
            SimpleSelector::Type(t) => assert_eq!(t, "Transform"),
            other => panic!("expected type, got {:?}", other),
        }
    }

    #[test]
    fn parses_type_hash_name_compound() {
        let mut p = MmqQuerySyntax::new();
        let ast = p.parse("T#hero").expect("parse");
        let simples = &ast.selector_groups[0].segments[0].compound.simple_selectors;
        assert_eq!(simples.len(), 2);
        assert!(matches!(&simples[0], SimpleSelector::Type(t) if t == "T"));
        assert!(matches!(&simples[1], SimpleSelector::Name(n) if n == "hero"));
    }

    #[test]
    fn parses_attribute_name_selector_back_compat() {
        let mut p = MmqQuerySyntax::new();
        let ast = p.parse("[name='LeftHand']").expect("parse");
        match &ast.selector_groups[0].segments[0].compound.simple_selectors[0] {
            SimpleSelector::Attribute(a) => {
                assert_eq!(a.name, "name");
                assert_eq!(a.value.as_deref(), Some("LeftHand"));
            }
            other => panic!("expected attribute, got {:?}", other),
        }
    }

    #[test]
    fn parses_descendant_and_child_combinators() {
        let mut p = MmqQuerySyntax::new();
        let ast = p.parse("#root > T C").expect("parse");
        let segs = &ast.selector_groups[0].segments;
        assert_eq!(segs.len(), 3);
        assert_eq!(segs[0].combinator, None);
        assert_eq!(segs[1].combinator, Some(Combinator::Child));
        assert_eq!(segs[2].combinator, Some(Combinator::Descendant));
    }

    #[test]
    fn parses_multi_selector_groups() {
        let mut p = MmqQuerySyntax::new();
        let ast = p.parse("T, R").expect("parse");
        assert_eq!(ast.selector_groups.len(), 2);
    }

    #[test]
    fn parses_guid_selector() {
        let mut p = MmqQuerySyntax::new();
        let ast = p
            .parse("@uuid:8c4f3e72-1234-5678-9abc-def012345678")
            .expect("parse");
        match &ast.selector_groups[0].segments[0].compound.simple_selectors[0] {
            SimpleSelector::Guid(g) => {
                assert_eq!(g, "8c4f3e72-1234-5678-9abc-def012345678")
            }
            other => panic!("expected guid, got {:?}", other),
        }
    }

    #[test]
    fn guid_selector_rejects_unknown_scheme() {
        let mut p = MmqQuerySyntax::new();
        assert!(p.parse("@oid:1234").is_err());
    }

    #[test]
    fn cache_returns_same_arc_for_same_input() {
        let mut p = MmqQuerySyntax::new();
        let a = p.parse("#hero").expect("parse");
        let b = p.parse("#hero").expect("parse");
        assert!(Arc::ptr_eq(&a, &b));
    }
}