sqruff_lib_core/parser/
lexer.rs

1use std::borrow::Cow;
2use std::fmt::Debug;
3use std::ops::Range;
4use std::str::Chars;
5
6use super::markers::PositionMarker;
7use super::segments::{ErasedSegment, SegmentBuilder, Tables};
8use crate::dialects::Dialect;
9use crate::dialects::syntax::SyntaxKind;
10use crate::errors::SQLLexError;
11use crate::slice_helpers::{is_zero_slice, offset_slice};
12use crate::templaters::TemplatedFile;
13
14/// An element matched during lexing.
15#[derive(Debug, Clone)]
16pub struct Element<'a> {
17    name: &'static str,
18    text: Cow<'a, str>,
19    syntax_kind: SyntaxKind,
20}
21
22impl<'a> Element<'a> {
23    fn new(name: &'static str, syntax_kind: SyntaxKind, text: impl Into<Cow<'a, str>>) -> Self {
24        Self {
25            name,
26            syntax_kind,
27            text: text.into(),
28        }
29    }
30}
31
32/// A LexedElement, bundled with it's position in the templated file.
33#[derive(Debug)]
34pub struct TemplateElement<'a> {
35    raw: Cow<'a, str>,
36    template_slice: Range<usize>,
37    matcher: Info,
38}
39
40#[derive(Debug)]
41struct Info {
42    name: &'static str,
43    syntax_kind: SyntaxKind,
44}
45
46impl<'a> TemplateElement<'a> {
47    /// Make a TemplateElement from a LexedElement.
48    pub fn from_element(element: Element<'a>, template_slice: Range<usize>) -> Self {
49        TemplateElement {
50            raw: element.text,
51            template_slice,
52            matcher: Info {
53                name: element.name,
54                syntax_kind: element.syntax_kind,
55            },
56        }
57    }
58
59    pub fn to_segment(
60        &self,
61        pos_marker: PositionMarker,
62        subslice: Option<Range<usize>>,
63    ) -> ErasedSegment {
64        let slice = subslice.map_or_else(|| self.raw.as_ref(), |slice| &self.raw[slice]);
65        SegmentBuilder::token(0, slice, self.matcher.syntax_kind)
66            .with_position(pos_marker)
67            .finish()
68    }
69}
70
71/// A class to hold matches from the lexer.
72#[derive(Debug)]
73pub struct Match<'a> {
74    pub forward_string: &'a str,
75    pub elements: Vec<Element<'a>>,
76}
77
78#[derive(Debug, Clone)]
79pub struct Matcher {
80    pattern: Pattern,
81    subdivider: Option<Pattern>,
82    trim_post_subdivide: Option<Pattern>,
83}
84
85impl Matcher {
86    pub const fn new(pattern: Pattern) -> Self {
87        Self {
88            pattern,
89            subdivider: None,
90            trim_post_subdivide: None,
91        }
92    }
93
94    pub const fn string(
95        name: &'static str,
96        pattern: &'static str,
97        syntax_kind: SyntaxKind,
98    ) -> Self {
99        Self::new(Pattern::string(name, pattern, syntax_kind))
100    }
101
102    #[track_caller]
103    pub fn regex(name: &'static str, pattern: &'static str, syntax_kind: SyntaxKind) -> Self {
104        Self::new(Pattern::regex(name, pattern, syntax_kind))
105    }
106
107    pub fn native(name: &'static str, f: fn(&mut Cursor) -> bool, syntax_kind: SyntaxKind) -> Self {
108        Self::new(Pattern::native(name, f, syntax_kind))
109    }
110
111    #[track_caller]
112    pub fn legacy(
113        name: &'static str,
114        starts_with: fn(&str) -> bool,
115        pattern: &'static str,
116        syntax_kind: SyntaxKind,
117    ) -> Self {
118        Self::new(Pattern::legacy(name, starts_with, pattern, syntax_kind))
119    }
120
121    pub fn subdivider(mut self, subdivider: Pattern) -> Self {
122        assert!(matches!(
123            self.pattern.kind,
124            SearchPatternKind::Legacy(_, _) | SearchPatternKind::Native(_)
125        ));
126        self.subdivider = Some(subdivider);
127        self
128    }
129
130    pub fn post_subdivide(mut self, trim_post_subdivide: Pattern) -> Self {
131        assert!(matches!(
132            self.pattern.kind,
133            SearchPatternKind::Legacy(_, _) | SearchPatternKind::Native(_)
134        ));
135        self.trim_post_subdivide = Some(trim_post_subdivide);
136        self
137    }
138
139    pub fn name(&self) -> &'static str {
140        self.pattern.name
141    }
142
143    #[track_caller]
144    pub fn matches<'a>(&self, forward_string: &'a str) -> Match<'a> {
145        match self.pattern.matches(forward_string) {
146            Some(matched) => {
147                let new_elements = self.subdivide(matched, self.pattern.syntax_kind);
148
149                Match {
150                    forward_string: &forward_string[matched.len()..],
151                    elements: new_elements,
152                }
153            }
154            None => Match {
155                forward_string,
156                elements: Vec::new(),
157            },
158        }
159    }
160
161    fn subdivide<'a>(&self, matched: &'a str, matched_kind: SyntaxKind) -> Vec<Element<'a>> {
162        match &self.subdivider {
163            Some(subdivider) => {
164                let mut elem_buff = Vec::new();
165                let mut str_buff = matched;
166
167                while !str_buff.is_empty() {
168                    let Some(div_pos) = subdivider.search(str_buff) else {
169                        let mut trimmed_elems = self.trim_match(str_buff);
170                        elem_buff.append(&mut trimmed_elems);
171                        break;
172                    };
173
174                    let mut trimmed_elems = self.trim_match(&str_buff[..div_pos.start]);
175                    let div_elem = Element::new(
176                        subdivider.name,
177                        subdivider.syntax_kind,
178                        &str_buff[div_pos.start..div_pos.end],
179                    );
180
181                    elem_buff.append(&mut trimmed_elems);
182                    elem_buff.push(div_elem);
183
184                    str_buff = &str_buff[div_pos.end..];
185                }
186
187                elem_buff
188            }
189            None => {
190                vec![Element::new(self.name(), matched_kind, matched)]
191            }
192        }
193    }
194
195    fn trim_match<'a>(&self, matched_str: &'a str) -> Vec<Element<'a>> {
196        let Some(trim_post_subdivide) = &self.trim_post_subdivide else {
197            return Vec::new();
198        };
199
200        let mk_element = |text| {
201            Element::new(
202                trim_post_subdivide.name,
203                trim_post_subdivide.syntax_kind,
204                text,
205            )
206        };
207
208        let mut elem_buff = Vec::new();
209        let mut content_buff = String::new();
210        let mut str_buff = matched_str;
211
212        while !str_buff.is_empty() {
213            let Some(trim_pos) = trim_post_subdivide.search(str_buff) else {
214                break;
215            };
216
217            let start = trim_pos.start;
218            let end = trim_pos.end;
219
220            if start == 0 {
221                elem_buff.push(mk_element(&str_buff[..end]));
222                str_buff = str_buff[end..].into();
223            } else if end == str_buff.len() {
224                let raw = format!("{}{}", content_buff, &str_buff[..start]);
225
226                elem_buff.push(Element::new(
227                    trim_post_subdivide.name,
228                    trim_post_subdivide.syntax_kind,
229                    raw,
230                ));
231                elem_buff.push(mk_element(&str_buff[start..end]));
232
233                content_buff.clear();
234                str_buff = "";
235            } else {
236                content_buff.push_str(&str_buff[..end]);
237                str_buff = &str_buff[end..];
238            }
239        }
240
241        if !content_buff.is_empty() || !str_buff.is_empty() {
242            let raw = format!("{content_buff}{str_buff}");
243            elem_buff.push(Element::new(
244                self.pattern.name,
245                self.pattern.syntax_kind,
246                raw,
247            ));
248        }
249
250        elem_buff
251    }
252}
253
254#[derive(Debug, Clone)]
255pub struct Pattern {
256    name: &'static str,
257    syntax_kind: SyntaxKind,
258    kind: SearchPatternKind,
259}
260
261#[derive(Debug, Clone)]
262pub enum SearchPatternKind {
263    String(&'static str),
264    Regex(&'static str),
265    Native(fn(&mut Cursor) -> bool),
266    Legacy(fn(&str) -> bool, fancy_regex::Regex),
267}
268
269impl Pattern {
270    pub const fn string(
271        name: &'static str,
272        template: &'static str,
273        syntax_kind: SyntaxKind,
274    ) -> Self {
275        Self {
276            name,
277            syntax_kind,
278            kind: SearchPatternKind::String(template),
279        }
280    }
281
282    #[track_caller]
283    pub fn regex(name: &'static str, regex: &'static str, syntax_kind: SyntaxKind) -> Self {
284        #[cfg(debug_assertions)]
285        if regex_automata::dfa::regex::Regex::new(regex).is_err() {
286            panic!("Invalid regex pattern: {}", std::panic::Location::caller());
287        }
288
289        Self {
290            name,
291            syntax_kind,
292            kind: SearchPatternKind::Regex(regex),
293        }
294    }
295
296    pub fn native(name: &'static str, f: fn(&mut Cursor) -> bool, syntax_kind: SyntaxKind) -> Self {
297        Self {
298            name,
299            syntax_kind,
300            kind: SearchPatternKind::Native(f),
301        }
302    }
303
304    pub fn legacy(
305        name: &'static str,
306        starts_with: fn(&str) -> bool,
307        regex: &'static str,
308        syntax_kind: SyntaxKind,
309    ) -> Self {
310        let regex = format!("^{regex}");
311        Self {
312            name,
313            syntax_kind,
314            kind: SearchPatternKind::Legacy(starts_with, fancy_regex::Regex::new(&regex).unwrap()),
315        }
316    }
317
318    fn matches<'a>(&self, forward_string: &'a str) -> Option<&'a str> {
319        match self.kind {
320            SearchPatternKind::String(template) => {
321                if forward_string.starts_with(template) {
322                    return Some(template);
323                }
324            }
325            SearchPatternKind::Legacy(f, ref template) => {
326                if !f(forward_string) {
327                    return None;
328                }
329
330                if let Ok(Some(matched)) = template.find(forward_string)
331                    && matched.start() == 0
332                {
333                    return Some(matched.as_str());
334                }
335            }
336            SearchPatternKind::Native(f) => {
337                let mut cursor = Cursor::new(forward_string);
338                return f(&mut cursor).then(|| cursor.lexed());
339            }
340            _ => unreachable!(),
341        };
342
343        None
344    }
345
346    fn search(&self, forward_string: &str) -> Option<Range<usize>> {
347        match &self.kind {
348            SearchPatternKind::String(template) => forward_string
349                .find(template)
350                .map(|start| start..start + template.len()),
351            SearchPatternKind::Legacy(_, template) => {
352                if let Ok(Some(matched)) = template.find(forward_string) {
353                    return Some(matched.range());
354                }
355                None
356            }
357            _ => unreachable!("{:?}", self.kind),
358        }
359    }
360}
361
362pub struct Cursor<'text> {
363    text: &'text str,
364    chars: Chars<'text>,
365}
366
367impl<'text> Cursor<'text> {
368    const EOF: char = '\0';
369
370    fn new(text: &'text str) -> Self {
371        Self {
372            text,
373            chars: text.chars(),
374        }
375    }
376
377    pub fn peek(&self) -> char {
378        self.chars.clone().next().unwrap_or(Self::EOF)
379    }
380
381    pub fn shift(&mut self) -> char {
382        self.chars.next().unwrap_or(Self::EOF)
383    }
384
385    pub fn shift_while(&mut self, f: impl Fn(char) -> bool + Copy) {
386        while self.peek() != Self::EOF && f(self.peek()) {
387            self.shift();
388        }
389    }
390
391    fn lexed(&self) -> &'text str {
392        let len = self.text.len() - self.chars.as_str().len();
393        &self.text[..len]
394    }
395}
396
397/// The Lexer class actually does the lexing step.
398#[derive(Debug, Clone)]
399pub struct Lexer {
400    syntax_map: Vec<(&'static str, SyntaxKind)>,
401    regex: regex_automata::meta::Regex,
402    matchers: Vec<Matcher>,
403    last_resort_lexer: Matcher,
404}
405
406impl<'a> From<&'a Dialect> for Lexer {
407    fn from(dialect: &'a Dialect) -> Self {
408        Lexer::new(dialect.lexer_matchers())
409    }
410}
411
412impl Lexer {
413    /// Create a new lexer.
414    pub(crate) fn new(lexer_matchers: &[Matcher]) -> Self {
415        let mut patterns = Vec::new();
416        let mut syntax_map = Vec::new();
417        let mut matchers = Vec::new();
418
419        for matcher in lexer_matchers {
420            match matcher.pattern.kind {
421                SearchPatternKind::String(pattern) | SearchPatternKind::Regex(pattern) => {
422                    let pattern = if matches!(matcher.pattern.kind, SearchPatternKind::String(_)) {
423                        fancy_regex::escape(pattern)
424                    } else {
425                        pattern.into()
426                    };
427
428                    patterns.push(pattern);
429                    syntax_map.push((matcher.pattern.name, matcher.pattern.syntax_kind));
430                }
431                SearchPatternKind::Legacy(_, _) | SearchPatternKind::Native(_) => {
432                    matchers.push(matcher.clone());
433                }
434            }
435        }
436
437        Lexer {
438            syntax_map,
439            matchers,
440            regex: regex_automata::meta::Regex::new_many(&patterns).unwrap(),
441            last_resort_lexer: Matcher::legacy(
442                "<unlexable>",
443                |_| true,
444                r"[^\t\n.]*",
445                SyntaxKind::Unlexable,
446            ),
447        }
448    }
449
450    pub fn lex(
451        &self,
452        tables: &Tables,
453        template: impl Into<TemplatedFile>,
454    ) -> (Vec<ErasedSegment>, Vec<SQLLexError>) {
455        let template = template.into();
456        let mut str_buff = template.templated_str.as_deref().unwrap();
457
458        // Lex the string to get a tuple of LexedElement
459        let mut element_buffer: Vec<Element> = Vec::new();
460
461        loop {
462            let mut res = self.lex_match(str_buff);
463            element_buffer.append(&mut res.elements);
464
465            if res.forward_string.is_empty() {
466                break;
467            }
468
469            // If we STILL can't match, then just panic out.
470            let mut resort_res = self.last_resort_lexer.matches(str_buff);
471            if !resort_res.elements.is_empty() {
472                break;
473            }
474
475            str_buff = resort_res.forward_string;
476            element_buffer.append(&mut resort_res.elements);
477        }
478
479        // Map tuple LexedElement to list of TemplateElement.
480        // This adds the template_slice to the object.
481        let templated_buffer = Lexer::map_template_slices(element_buffer, &template);
482        // Turn lexed elements into segments.
483        let mut segments = self.elements_to_segments(templated_buffer, &template);
484
485        for seg in &mut segments {
486            seg.get_mut().set_id(tables.next_id())
487        }
488
489        (segments, Vec::new())
490    }
491
492    /// Generate any lexing errors for any un-lex-ables.
493    ///
494    /// TODO: Taking in an iterator, also can make the typing better than use
495    /// unwrap.
496    #[allow(dead_code)]
497    fn violations_from_segments(segments: Vec<ErasedSegment>) -> Vec<SQLLexError> {
498        segments
499            .into_iter()
500            .filter(|s| s.is_type(SyntaxKind::Unlexable))
501            .map(|s| {
502                SQLLexError::new(
503                    format!(
504                        "Unable to lex characters: {}",
505                        s.raw().chars().take(10).collect::<String>()
506                    ),
507                    s.get_position_marker().unwrap().clone(),
508                )
509            })
510            .collect()
511    }
512
513    /// Iteratively match strings using the selection of sub-matchers.
514    fn lex_match<'b>(&self, mut forward_string: &'b str) -> Match<'b> {
515        let mut elem_buff = Vec::new();
516
517        'main: loop {
518            if forward_string.is_empty() {
519                return Match {
520                    forward_string,
521                    elements: elem_buff,
522                };
523            }
524
525            for matcher in &self.matchers {
526                let mut match_result = matcher.matches(forward_string);
527
528                if !match_result.elements.is_empty() {
529                    elem_buff.append(&mut match_result.elements);
530                    forward_string = match_result.forward_string;
531                    continue 'main;
532                }
533            }
534
535            let input =
536                regex_automata::Input::new(forward_string).anchored(regex_automata::Anchored::Yes);
537
538            if let Some(match_) = self.regex.find(input) {
539                let (name, kind) = self.syntax_map[match_.pattern().as_usize()];
540
541                elem_buff.push(Element::new(
542                    name,
543                    kind,
544                    &forward_string[match_.start()..match_.end()],
545                ));
546                forward_string = &forward_string[match_.end()..];
547
548                continue 'main;
549            }
550
551            return Match {
552                forward_string,
553                elements: elem_buff,
554            };
555        }
556    }
557
558    /// Create a tuple of TemplateElement from a tuple of LexedElement.
559    ///
560    /// This adds slices in the templated file to the original lexed
561    /// elements. We'll need this to work out the position in the source
562    /// file.
563    /// TODO Can this vec be turned into an iterator and return iterator to make
564    /// lazy?
565    fn map_template_slices<'b>(
566        elements: Vec<Element<'b>>,
567        template: &TemplatedFile,
568    ) -> Vec<TemplateElement<'b>> {
569        let mut idx = 0;
570        let mut templated_buff: Vec<TemplateElement> = Vec::with_capacity(elements.len());
571
572        for element in elements {
573            let template_slice = offset_slice(idx, element.text.len());
574            idx += element.text.len();
575
576            let templated_string = template.templated();
577            if templated_string[template_slice.clone()] != element.text {
578                panic!(
579                    "Template and lexed elements do not match. This should never happen {:?} != \
580                     {:?}",
581                    element.text, &templated_string[template_slice]
582                );
583            }
584
585            templated_buff.push(TemplateElement::from_element(element, template_slice));
586        }
587
588        templated_buff
589    }
590
591    /// Convert a tuple of lexed elements into a tuple of segments.
592    fn elements_to_segments(
593        &self,
594        elements: Vec<TemplateElement>,
595        templated_file: &TemplatedFile,
596    ) -> Vec<ErasedSegment> {
597        let mut segments = iter_segments(elements, templated_file);
598
599        // Add an end of file marker
600        let position_maker = match segments.last() {
601            Some(segment) => segment.get_position_marker().unwrap().end_point_marker(),
602            None => PositionMarker::from_point(0, 0, templated_file.clone(), None, None),
603        };
604
605        segments.push(
606            SegmentBuilder::token(0, "", SyntaxKind::EndOfFile)
607                .with_position(position_maker)
608                .finish(),
609        );
610
611        segments
612    }
613}
614
615fn iter_segments(
616    lexed_elements: Vec<TemplateElement>,
617    templated_file: &TemplatedFile,
618) -> Vec<ErasedSegment> {
619    let mut result: Vec<ErasedSegment> = Vec::with_capacity(lexed_elements.len());
620    // An index to track where we've got to in the templated file.
621    let mut tfs_idx = 0;
622    // We keep a map of previous block locations in case they re-occur.
623    // let block_stack = BlockTracker()
624    let templated_file_slices = &templated_file.sliced_file;
625
626    // Now work out source slices, and add in template placeholders.
627    for element in lexed_elements {
628        let consumed_element_length = 0;
629        let mut stashed_source_idx = None;
630
631        for (idx, tfs) in templated_file_slices
632            .iter()
633            .skip(tfs_idx)
634            .enumerate()
635            .map(|(i, tfs)| (i + tfs_idx, tfs))
636        {
637            // Is it a zero slice?
638            if is_zero_slice(&tfs.templated_slice) {
639                let _slice = if idx + 1 < templated_file_slices.len() {
640                    templated_file_slices[idx + 1].clone().into()
641                } else {
642                    None
643                };
644
645                continue;
646            }
647
648            if tfs.slice_type == "literal" {
649                let tfs_offset =
650                    (tfs.source_slice.start as isize) - (tfs.templated_slice.start as isize);
651
652                // NOTE: Greater than OR EQUAL, to include the case of it matching
653                // length exactly.
654                if element.template_slice.end <= tfs.templated_slice.end {
655                    let slice_start = stashed_source_idx.unwrap_or_else(|| {
656                        let sum = element.template_slice.start as isize
657                            + consumed_element_length as isize
658                            + tfs_offset;
659                        if sum < 0 {
660                            panic!("Slice start is negative: {sum}");
661                        }
662                        sum.try_into()
663                            .unwrap_or_else(|_| panic!("Cannot convert {sum} to usize"))
664                    });
665
666                    let source_slice_end =
667                        (element.template_slice.end as isize + tfs_offset) as usize;
668                    result.push(element.to_segment(
669                        PositionMarker::new(
670                            slice_start..source_slice_end,
671                            element.template_slice.clone(),
672                            templated_file.clone(),
673                            None,
674                            None,
675                        ),
676                        Some(consumed_element_length..element.raw.len()),
677                    ));
678
679                    // If it was an exact match, consume the templated element too.
680                    if element.template_slice.end == tfs.templated_slice.end {
681                        tfs_idx += 1
682                    }
683                    // In any case, we're done with this element. Move on
684                    break;
685                } else if element.template_slice.start >= tfs.templated_slice.end {
686                    // Element starts at or after this slice ends - skip to next slice.
687                    // This can happen when zero-length slices exist (e.g., stripped
688                    // whitespace from Jinja comments like {#- ... #}).
689                    log::debug!("Element starts at or after slice end, skipping");
690                    continue;
691                } else {
692                    // This means that the current lexed element spans across
693                    // multiple templated file slices.
694
695                    log::debug!("Consuming whole spanning literal",);
696
697                    // This almost certainly means there's a templated element
698                    // in the middle of a whole lexed element.
699
700                    // What we do here depends on whether we're allowed to split
701                    // lexed elements. This is basically only true if it's whitespace.
702                    // NOTE: We should probably make this configurable on the
703                    // matcher object, but for now we're going to look for the
704                    // name of the lexer.
705                    if element.matcher.name == "whitespace" {
706                        if stashed_source_idx.is_some() {
707                            panic!("Found literal whitespace with stashed idx!")
708                        }
709
710                        let incremental_length =
711                            tfs.templated_slice.end - element.template_slice.start;
712
713                        let source_slice_start = element.template_slice.start as isize
714                            + consumed_element_length as isize
715                            + tfs_offset;
716                        let source_slice_start =
717                            source_slice_start.try_into().unwrap_or_else(|_| {
718                                panic!("Cannot convert {source_slice_start} to usize")
719                            });
720                        let source_slice_end =
721                            source_slice_start as isize + incremental_length as isize;
722                        let source_slice_end = source_slice_end.try_into().unwrap_or_else(|_| {
723                            panic!("Cannot convert {source_slice_end} to usize")
724                        });
725
726                        result.push(element.to_segment(
727                            PositionMarker::new(
728                                source_slice_start..source_slice_end,
729                                element.template_slice.clone(),
730                                templated_file.clone(),
731                                None,
732                                None,
733                            ),
734                            offset_slice(consumed_element_length, incremental_length).into(),
735                        ));
736                        // Continue to the next slice to process remaining whitespace
737                        continue;
738                    } else {
739                        // We can't split it. We're going to end up yielding a segment
740                        // which spans multiple slices. Stash the type, and if we haven't
741                        // set the start yet, stash it too.
742                        log::debug!("Spilling over literal slice.");
743                        if stashed_source_idx.is_none() {
744                            stashed_source_idx = (element.template_slice.start + idx).into();
745                            log::debug!("Stashing a source start. {stashed_source_idx:?}");
746                        }
747                        // Continue to next slice regardless of whether we stashed
748                        continue;
749                    }
750                }
751            } else if matches!(tfs.slice_type.as_str(), "templated" | "block_start") {
752                // Found a templated slice. Does it have length in the templated file?
753                // If it doesn't, then we'll pick it up next.
754                if !is_zero_slice(&tfs.templated_slice) {
755                    // If it's a block_start. Append to the block stack.
756                    // NOTE: This is rare, but call blocks do occasionally
757                    // have length (and so don't get picked up by
758                    // _handle_zero_length_slice)
759                    if tfs.slice_type == "block_start" {
760                        unimplemented!()
761                        // block_stack.enter(tfs.source_slice)
762                    }
763
764                    // Is our current element totally contained in this slice?
765                    if element.template_slice.end <= tfs.templated_slice.end {
766                        log::debug!("Contained templated slice.");
767                        // Yes it is. Add lexed element with source slices as the whole
768                        // span of the source slice for the file slice.
769                        // If we've got an existing stashed source start, use that
770                        // as the start of the source slice.
771                        let slice_start = if let Some(stashed_source_idx) = stashed_source_idx {
772                            stashed_source_idx
773                        } else {
774                            tfs.source_slice.start + consumed_element_length
775                        };
776
777                        result.push(element.to_segment(
778                            PositionMarker::new(
779                                slice_start..tfs.source_slice.end,
780                                element.template_slice.clone(),
781                                templated_file.clone(),
782                                None,
783                                None,
784                            ),
785                            Some(consumed_element_length..element.raw.len()),
786                        ));
787
788                        // If it was an exact match, consume the templated element too.
789                        if element.template_slice.end == tfs.templated_slice.end {
790                            tfs_idx += 1
791                        }
792                        // Carry on to the next lexed element
793                        break;
794                    } else {
795                        // We've got an element which extends beyond this templated slice.
796                        // This means that a _single_ lexed element claims both some
797                        // templated elements and some non-templated elements. That could
798                        // include all kinds of things (and from here we don't know what
799                        // else is yet to come, comments, blocks, literals etc...).
800
801                        // In the `literal` version of this code we would consider
802                        // splitting the literal element here, but in the templated
803                        // side we don't. That's because the way that templated tokens
804                        // are lexed, means that they should arrive "pre-split".
805
806                        // Stash the source idx for later when we do make a segment.
807                        if stashed_source_idx.is_none() {
808                            stashed_source_idx = Some(tfs.source_slice.start);
809                            continue;
810                        }
811                        // Move on to the next template slice
812                        continue;
813                    }
814                }
815            }
816            panic!("Unable to process slice: {tfs:?}");
817        }
818    }
819    result
820}
821
822#[cfg(test)]
823mod tests {
824    use super::*;
825
826    /// Assert that a matcher does or doesn't work on a string.
827    ///
828    /// The optional `matchstring` argument, which can optionally
829    /// be None, allows to either test positive matching of a
830    /// particular string or negative matching (that it explicitly)
831    /// doesn't match.
832    fn assert_matches(in_string: &str, matcher: &Matcher, match_string: Option<&str>) {
833        let res = matcher.matches(in_string);
834        if let Some(match_string) = match_string {
835            assert_eq!(res.forward_string, &in_string[match_string.len()..]);
836            assert_eq!(res.elements.len(), 1);
837            assert_eq!(res.elements[0].text, match_string);
838        } else {
839            assert_eq!(res.forward_string, in_string);
840            assert_eq!(res.elements.len(), 0);
841        }
842    }
843
844    #[test]
845    fn test_parser_lexer_trim_post_subdivide() {
846        let matcher: Vec<Matcher> = vec![
847            Matcher::legacy(
848                "function_script_terminator",
849                |_| true,
850                r";\s+(?!\*)\/(?!\*)|\s+(?!\*)\/(?!\*)",
851                SyntaxKind::StatementTerminator,
852            )
853            .subdivider(Pattern::string("semicolon", ";", SyntaxKind::Semicolon))
854            .post_subdivide(Pattern::legacy(
855                "newline",
856                |_| true,
857                r"(\n|\r\n)+",
858                SyntaxKind::Newline,
859            )),
860        ];
861
862        let res = Lexer::new(&matcher).lex_match(";\n/\n");
863        assert_eq!(res.elements[0].text, ";");
864        assert_eq!(res.elements[1].text, "\n");
865        assert_eq!(res.elements[2].text, "/");
866        assert_eq!(res.elements.len(), 3);
867    }
868
869    /// Test the RegexLexer.
870    #[test]
871    fn test_parser_lexer_regex() {
872        let tests = &[
873            ("fsaljk", "f", "f"),
874            ("fsaljk", r"f", "f"),
875            ("fsaljk", r"[fas]*", "fsa"),
876            // Matching whitespace segments
877            ("   \t   fsaljk", r"[^\S\r\n]*", "   \t   "),
878            // Matching whitespace segments (with a newline)
879            ("   \t \n  fsaljk", r"[^\S\r\n]*", "   \t "),
880            // Matching quotes containing stuff
881            (
882                "'something boring'   \t \n  fsaljk",
883                r"'[^']*'",
884                "'something boring'",
885            ),
886            (
887                "' something exciting \t\n '   \t \n  fsaljk",
888                r"'[^']*'",
889                "' something exciting \t\n '",
890            ),
891        ];
892
893        for (raw, reg, res) in tests {
894            let matcher = Matcher::legacy("test", |_| true, reg, SyntaxKind::Word);
895
896            assert_matches(raw, &matcher, Some(res));
897        }
898    }
899
900    /// Test the lexer string
901    #[test]
902    fn test_parser_lexer_string() {
903        let matcher = Matcher::string("dot", ".", SyntaxKind::Dot);
904
905        assert_matches(".fsaljk", &matcher, Some("."));
906        assert_matches("fsaljk", &matcher, None);
907    }
908
909    /// Test the RepeatedMultiMatcher
910    #[test]
911    fn test_parser_lexer_lex_match() {
912        let matchers: Vec<Matcher> = vec![
913            Matcher::string("dot", ".", SyntaxKind::Dot),
914            Matcher::regex("test", "#[^#]*#", SyntaxKind::Dash),
915        ];
916
917        let res = Lexer::new(&matchers).lex_match("..#..#..#");
918
919        assert_eq!(res.forward_string, "#");
920        assert_eq!(res.elements.len(), 5);
921        assert_eq!(res.elements[2].text, "#..#");
922    }
923}