scah-query-ir 0.0.21

Internal query IR used by the scah selector and macro crates.
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
use super::SelectorParseError;
use super::query::{Query, QuerySection, QuerySectionId, TransitionId};
use super::transition::Transition;

/// Controls which pieces of content to capture for matched elements.
///
/// When an element matches a CSS selector, scah can optionally capture its
/// **inner HTML** (the raw markup between the opening and closing tags) and/or
/// its **text content** (the concatenated, whitespace-trimmed text nodes).
///
/// Use the convenience constructors [`Save::all`], [`Save::none`],
/// [`Save::only_inner_html`], and [`Save::only_text_content`] to create
/// common configurations.
///
/// # Example
///
/// ```rust
/// use scah_query_ir::Save;
///
/// // Capture everything
/// let save = Save::all();
/// assert!(save.inner_html);
/// assert!(save.text_content);
///
/// // Capture only text content (lighter weight)
/// let save = Save::only_text_content();
/// assert!(!save.inner_html);
/// assert!(save.text_content);
/// ```
#[derive(PartialEq, Debug, Default, Clone, Copy)]
pub struct Save {
    /// When `true`, the raw HTML between the element's opening and closing
    /// tags is stored as [`Element::inner_html`](crate::Element::inner_html).
    pub inner_html: bool,
    /// When `true`, the concatenated text content of the element is stored
    /// and retrievable via [`Element::text_content()`](crate::Element::text_content).
    pub text_content: bool,
}

impl Save {
    /// Capture only the raw inner HTML of matched elements.
    pub fn only_inner_html() -> Self {
        Self {
            inner_html: true,
            text_content: false,
        }
    }

    /// Capture only the text content of matched elements.
    pub fn only_text_content() -> Self {
        Self {
            inner_html: false,
            text_content: true,
        }
    }

    /// Capture both inner HTML and text content.
    pub fn all() -> Self {
        Self {
            inner_html: true,
            text_content: true,
        }
    }

    /// Capture neither inner HTML nor text content.
    ///
    /// The matched element's tag name, id, class, and attributes are still
    /// stored; only the heavier content extraction is skipped.
    pub fn none() -> Self {
        Self {
            inner_html: false,
            text_content: false,
        }
    }
}

/// Whether a query section should match **all** occurrences or only the
/// **first** one.
///
/// Using [`SelectionKind::First`] enables an early-exit optimisation:
/// once the first match is found (and its content captured), the parser
/// can skip the remaining document for that query branch.
#[derive(PartialEq, Debug, Clone, Copy)]
pub enum SelectionKind {
    /// Match every occurrence of the selector.
    All,
    /// Match only the first occurrence, enabling early exit.
    First,
}

/// An in-progress query being assembled via a builder pattern.
///
/// You typically don't construct a `QueryBuilder` directly; instead,
/// start with [`Query::all`](crate::Query::all) or
/// [`Query::first`](crate::Query::first) and then chain further
/// selectors with [`.all()`](QueryBuilder::all),
/// [`.first()`](QueryBuilder::first), and [`.then()`](QueryBuilder::then).
/// Finalise with [`.build()`](QueryBuilder::build) to produce a [`Query`].
///
/// # Example
///
/// ```rust
/// use scah_query_ir::{Query, Save};
///
/// let query = Query::all("main > section", Save::all())?
///     .then(|ctx| Ok([
///         ctx.all("> a[href]", Save::all())?,
///         ctx.all("div a", Save::only_text_content())?,
///     ]))?
///     .build();
/// # Ok::<(), scah_query_ir::SelectorParseError>(())
/// ```
#[derive(Debug, Clone)]
pub struct QueryBuilder<'query> {
    /// Internal automaton transitions (compiled selector segments).
    pub states: Vec<Transition<'query>>,
    /// Internal ordered list of query sections.
    pub selection: Vec<QuerySection<'query>>,
}

impl<'query> QueryBuilder<'query> {
    pub fn all(mut self, query: &'query str, save: Save) -> Result<Self, SelectorParseError> {
        assert!(!self.selection.is_empty());

        let current_state_len = self.states.len();
        let mut states = Transition::generate_transitions_from_string(query)?;

        let parent_index = QuerySectionId(self.selection.len() - 1);
        let range = TransitionId(current_state_len)..TransitionId(current_state_len + states.len());
        self.selection.push(QuerySection::new(
            query,
            save,
            SelectionKind::All,
            range,
            Some(parent_index),
        ));

        self.states.append(&mut states);

        Ok(self)
    }

    /// Append a child selector that matches **all** occurrences.
    ///
    /// The new selector is scoped to elements that already matched
    /// the previous selector in the chain.
    ///
    pub fn first(mut self, query: &'query str, save: Save) -> Result<Self, SelectorParseError> {
        assert!(!self.selection.is_empty());

        let current_state_len = self.states.len();
        let mut states = Transition::generate_transitions_from_string(query)?;

        let parent_index = QuerySectionId(self.selection.len() - 1);
        let range = TransitionId(current_state_len)..TransitionId(current_state_len + states.len());
        self.selection.push(QuerySection::new(
            query,
            save,
            SelectionKind::First,
            range,
            Some(parent_index),
        ));

        self.states.append(&mut states);

        Ok(self)
    }

    /// Append a child selector that matches only the **first** occurrence.
    ///
    /// Enables early-exit optimisation for this branch of the query tree.
    ///
    pub fn append(&mut self, parent: QuerySectionId, mut other: Self) {
        let state_length = self.states.len();
        let selection_length = self.selection.len();

        let mut last_sibling: Option<QuerySectionId> = {
            if parent.index() + 1 == self.selection.len() {
                None
            } else {
                let mut sibling_index = QuerySectionId(parent.index() + 1);
                while self.selection[sibling_index.index()].next_sibling.is_some() {
                    sibling_index = self.selection[sibling_index.index()].next_sibling.unwrap();
                }

                Some(sibling_index)
            }
        };
        for index in 0..other.selection.len() {
            let query = &mut other.selection[index];
            query.range.start = TransitionId(query.range.start.index() + state_length);
            query.range.end = TransitionId(query.range.end.index() + state_length);
            if let Some(next_sibling) = query.next_sibling {
                query.next_sibling = Some(QuerySectionId(next_sibling.index() + selection_length));
            }

            if let Some(idx) = query.parent {
                query.parent = Some(QuerySectionId(idx.index() + selection_length));
            } else {
                query.parent = Some(parent);

                let current_index = QuerySectionId(selection_length + index);
                last_sibling = match last_sibling {
                    Some(sibling) => {
                        if sibling.index() < selection_length {
                            self.selection[sibling.index()].next_sibling = Some(current_index);
                        } else {
                            other.selection[sibling.index() - selection_length].next_sibling =
                                Some(current_index);
                        }
                        Some(current_index)
                    }
                    None => Some(current_index),
                };
            }
        }
        self.states.append(&mut other.states);
        self.selection.append(&mut other.selection);
    }

    /// Branch into multiple child queries using a closure.
    ///
    /// The closure receives a [`QueryFactory`] that can create new
    /// sub-queries. Each sub-query is scoped to run only within elements
    /// matched by the current (most recently added) selector.
    ///
    /// This is the key mechanism for **structured querying**; extracting
    /// hierarchical data relationships in a single streaming pass.
    ///
    /// # Example
    ///
    /// ```rust
    /// use scah_query_ir::{Query, Save};
    ///
    /// let query = Query::all("article", Save::none())?
    ///     .then(|article| Ok([
    ///         article.first("h1", Save::only_text_content())?,
    ///         article.all("a[href]", Save::all())?,
    ///     ]))?
    ///     .build();
    /// # Ok::<(), scah_query_ir::SelectorParseError>(())
    /// ```
    pub fn then<F, I>(mut self, func: F) -> Result<Self, SelectorParseError>
    where
        F: FnOnce(QueryFactory) -> Result<I, SelectorParseError>,
        I: IntoIterator<Item = Self>,
    {
        let factory = QueryFactory {};
        let children = func(factory)?;

        let current_index = QuerySectionId(self.selection.len() - 1);
        for child in children {
            self.append(current_index, child);
        }
        Ok(self)
    }

    fn exit_at_section(&self) -> Option<QuerySectionId> {
        // returns the position in the selection tree where it can early exit
        // TODO: I should add a required flag for QuerySections, so that the first selection is nulled
        //  -> Basicly you can't return the first section without a perticular section behind added
        //  -> If you come back to the section without saving the required section,
        //      then you delete the saved data and you start over.

        fn search_for_single_exit_section(
            index: QuerySectionId,
            list: &[QuerySection<'_>],
        ) -> Option<QuerySectionId> {
            // If you have a section with MULTIPLE children that can early exit,
            //   then this parent node will become the exit section
            if index.index() >= list.len() {
                return None;
            }
            let section = &list[index.index()];
            let stop_here = match &section.kind {
                //BUG: you can only early exit when the ALL of them have been found, thus the parent must be awaited for
                SelectionKind::All => return None,

                // This is it need's to find the </{element}> to get either inner_html or text_content
                SelectionKind::First => section.save != Save::none(),
            };
            if stop_here {
                return Some(index);
            }

            let mut child = QuerySectionId(index.index() + 1);
            if child.index() >= list.len() {
                return Some(index);
            }

            let mut child_response: Option<QuerySectionId> = None;
            if let Some(parent) = list[child.index()].parent
                && parent == index
            {
                loop {
                    child_response = match child_response {
                        None => search_for_single_exit_section(child, list),
                        Some(_) => {
                            // If their's more than one child that can early exit then
                            // the parent is chosen
                            return Some(index);
                        }
                    };

                    if let Some(sibling) = list[child.index()].next_sibling {
                        child = sibling;
                    } else {
                        break;
                    }
                }
            }

            if child_response.is_some() {
                return child_response;
            }
            Some(index)
        }

        search_for_single_exit_section(QuerySectionId(0), &self.selection)
    }
}

impl<'query> QueryBuilder<'query> {
    /// Finalise the builder and produce a compiled [`Query`].
    ///
    /// This computes early-exit optimisation metadata and converts the
    /// internal vectors into boxed slices. After calling `build`, pass
    /// the resulting `Query` to [`parse`](crate::parse).
    pub fn build(self) -> Query<'query> {
        let exit_at_section_end = self.exit_at_section();
        let states_box = self.states.into_boxed_slice();
        let query_box = self.selection.into_boxed_slice();
        Query {
            states: states_box,
            queries: query_box,
            exit_at_section_end,
        }
    }
}

/// A factory for creating child [`QueryBuilder`]s inside a
/// [`QueryBuilder::then`] closure.
///
/// You never construct this directly; it is provided as the argument to
/// the closure passed to `.then()`.
pub struct QueryFactory {}
impl<'query> QueryFactory {
    /// Create a child query that matches **all** occurrences of the selector.
    pub fn all(
        &self,
        query: &'query str,
        save: Save,
    ) -> Result<QueryBuilder<'query>, SelectorParseError> {
        Query::all(query, save)
    }

    /// Create a child query that matches only the **first** occurrence.
    pub fn first(
        &self,
        query: &'query str,
        save: Save,
    ) -> Result<QueryBuilder<'query>, SelectorParseError> {
        Query::first(query, save)
    }
}

#[cfg(test)]
mod tests {
    use crate::{ClassSelections, Query, QuerySectionId, Save, SelectionKind};

    #[test]
    fn test_builder_with_class_chaining() {
        let query = Query::all("a.blue.exit", Save::all()).unwrap().build();
        assert_eq!(
            query.states[0].predicate.classes,
            ClassSelections::from_static(&["blue", "exit"])
        );
    }

    #[test]
    fn test_early_exit() {
        let query = Query::all("a", Save::all()).unwrap();
        assert_eq!(query.exit_at_section(), None);

        let query = Query::all("a", Save::none()).unwrap();
        assert_eq!(query.exit_at_section(), None);

        let query = Query::first("a", Save::all()).unwrap();
        assert_eq!(query.exit_at_section(), Some(QuerySectionId(0)));

        let query = Query::first("a", Save::none()).unwrap();
        assert_eq!(query.exit_at_section(), Some(QuerySectionId(0)));

        let query = Query::all("p", Save::all())
            .unwrap()
            .first("a", Save::all())
            .unwrap();
        assert_eq!(query.exit_at_section(), None);

        let query = Query::first("p", Save::all())
            .unwrap()
            .all("a", Save::all())
            .unwrap();
        assert_eq!(query.exit_at_section(), Some(QuerySectionId(0)));

        let query = Query::first("p", Save::all())
            .unwrap()
            .first("a", Save::all())
            .unwrap();
        assert_eq!(query.exit_at_section(), Some(QuerySectionId(0)));

        let query = Query::first("p", Save::none())
            .unwrap()
            .first("a", Save::none())
            .unwrap();
        assert_eq!(query.exit_at_section(), Some(QuerySectionId(1)));
    }

    #[test]
    fn test_invalid_selectors_fail_to_build() {
        let invalid = [
            "",
            "a > ",
            ".",
            "#",
            " a ~ b",
            "a + b",
            "a[]",
            "*",
            "a[123=\"321\"]",
        ];

        for selector in invalid {
            assert!(Query::all(selector, Save::none()).is_err(), "{selector}");
        }
    }

    #[test]
    fn test_then_with_all_and_first() {
        let query = Query::all("article", Save::none())
            .unwrap()
            .then(|article| {
                Ok([
                    article.all("a[href]", Save::all())?,
                    article.first("h1", Save::only_text_content())?,
                ])
            })
            .unwrap()
            .build();

        assert_eq!(query.queries.len(), 3);
        assert_eq!(query.queries[1].source, "a[href]");
        assert_eq!(query.queries[2].source, "h1");
    }

    #[test]
    fn test_then_propagates_invalid_selector_from_callback() {
        let error = Query::all("article", Save::none())
            .unwrap()
            .then(|article| {
                Ok([
                    article.all("a[href]", Save::all())?,
                    article.first("a + b", Save::only_text_content())?,
                ])
            })
            .unwrap_err();

        assert_eq!(error.message(), "unsupported combinator '+'");
    }

    #[test]
    fn test_then_builds_sibling_links_in_callback_order() {
        let query = Query::all("article", Save::none())
            .unwrap()
            .then(|article| {
                Ok([
                    article.all("a[href]", Save::all())?,
                    article.first("h1", Save::only_text_content())?,
                    article.all("p", Save::none())?,
                ])
            })
            .unwrap()
            .build();

        assert_eq!(query.queries.len(), 4);
        assert_eq!(query.queries[1].parent, Some(QuerySectionId(0)));
        assert_eq!(query.queries[2].parent, Some(QuerySectionId(0)));
        assert_eq!(query.queries[3].parent, Some(QuerySectionId(0)));
        assert_eq!(query.queries[1].next_sibling, Some(QuerySectionId(2)));
        assert_eq!(query.queries[2].next_sibling, Some(QuerySectionId(3)));
        assert_eq!(query.queries[3].next_sibling, None);
        assert_eq!(query.queries[1].kind, SelectionKind::All);
        assert_eq!(query.queries[2].kind, SelectionKind::First);
        assert_eq!(query.queries[3].kind, SelectionKind::All);
    }

    #[test]
    fn test_nested_then_supports_all_and_first() {
        let query = Query::all("article", Save::none())
            .unwrap()
            .then(|article| {
                Ok([article.all("section", Save::none())?.then(|section| {
                    Ok([
                        section.first("h2", Save::only_text_content())?,
                        section.all("a[href]", Save::all())?,
                    ])
                })?])
            })
            .unwrap()
            .build();

        assert_eq!(query.queries.len(), 4);
        assert_eq!(query.queries[1].source, "section");
        assert_eq!(query.queries[2].source, "h2");
        assert_eq!(query.queries[3].source, "a[href]");
        assert_eq!(query.queries[2].parent, Some(QuerySectionId(1)));
        assert_eq!(query.queries[3].parent, Some(QuerySectionId(1)));
        assert_eq!(query.queries[2].next_sibling, Some(QuerySectionId(3)));
    }

    #[test]
    fn test_then_returns_error_without_partial_append() {
        let builder = Query::all("article", Save::none())
            .unwrap()
            .then(|article| {
                let first = article.all("section", Save::none())?;
                let second = article.first("a + b", Save::all());
                match second {
                    Ok(second) => Ok([first, second]),
                    Err(err) => Err(err),
                }
            });

        assert!(builder.is_err());
        let error = builder.unwrap_err();
        assert_eq!(error.message(), "unsupported combinator '+'");
    }
}