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                    // Did we forget to move on from the last tfs and there's
687                    // overlap?
688                    // NOTE: If the rest of the logic works, this should never
689                    // happen.
690                    log::debug!("Missed Skip");
691                    continue;
692                } else {
693                    // This means that the current lexed element spans across
694                    // multiple templated file slices.
695
696                    log::debug!("Consuming whole spanning literal",);
697
698                    // This almost certainly means there's a templated element
699                    // in the middle of a whole lexed element.
700
701                    // What we do here depends on whether we're allowed to split
702                    // lexed elements. This is basically only true if it's whitespace.
703                    // NOTE: We should probably make this configurable on the
704                    // matcher object, but for now we're going to look for the
705                    // name of the lexer.
706                    if element.matcher.name == "whitespace" {
707                        if stashed_source_idx.is_some() {
708                            panic!("Found literal whitespace with stashed idx!")
709                        }
710
711                        let incremental_length =
712                            tfs.templated_slice.end - element.template_slice.start;
713
714                        let source_slice_start = element.template_slice.start as isize
715                            + consumed_element_length as isize
716                            + tfs_offset;
717                        let source_slice_start =
718                            source_slice_start.try_into().unwrap_or_else(|_| {
719                                panic!("Cannot convert {source_slice_start} to usize")
720                            });
721                        let source_slice_end =
722                            source_slice_start as isize + incremental_length as isize;
723                        let source_slice_end = source_slice_end.try_into().unwrap_or_else(|_| {
724                            panic!("Cannot convert {source_slice_end} to usize")
725                        });
726
727                        result.push(element.to_segment(
728                            PositionMarker::new(
729                                source_slice_start..source_slice_end,
730                                element.template_slice.clone(),
731                                templated_file.clone(),
732                                None,
733                                None,
734                            ),
735                            offset_slice(consumed_element_length, incremental_length).into(),
736                        ));
737                    } else {
738                        // We can't split it. We're going to end up yielding a segment
739                        // which spans multiple slices. Stash the type, and if we haven't
740                        // set the start yet, stash it too.
741                        log::debug!("Spilling over literal slice.");
742                        if stashed_source_idx.is_none() {
743                            stashed_source_idx = (element.template_slice.start + idx).into();
744                            log::debug!("Stashing a source start. {stashed_source_idx:?}");
745                            continue;
746                        }
747                    }
748                }
749            } else if matches!(tfs.slice_type.as_str(), "templated" | "block_start") {
750                // Found a templated slice. Does it have length in the templated file?
751                // If it doesn't, then we'll pick it up next.
752                if !is_zero_slice(&tfs.templated_slice) {
753                    // If it's a block_start. Append to the block stack.
754                    // NOTE: This is rare, but call blocks do occasionally
755                    // have length (and so don't get picked up by
756                    // _handle_zero_length_slice)
757                    if tfs.slice_type == "block_start" {
758                        unimplemented!()
759                        // block_stack.enter(tfs.source_slice)
760                    }
761
762                    // Is our current element totally contained in this slice?
763                    if element.template_slice.end <= tfs.templated_slice.end {
764                        log::debug!("Contained templated slice.");
765                        // Yes it is. Add lexed element with source slices as the whole
766                        // span of the source slice for the file slice.
767                        // If we've got an existing stashed source start, use that
768                        // as the start of the source slice.
769                        let slice_start = if let Some(stashed_source_idx) = stashed_source_idx {
770                            stashed_source_idx
771                        } else {
772                            tfs.source_slice.start + consumed_element_length
773                        };
774
775                        result.push(element.to_segment(
776                            PositionMarker::new(
777                                slice_start..tfs.source_slice.end,
778                                element.template_slice.clone(),
779                                templated_file.clone(),
780                                None,
781                                None,
782                            ),
783                            Some(consumed_element_length..element.raw.len()),
784                        ));
785
786                        // If it was an exact match, consume the templated element too.
787                        if element.template_slice.end == tfs.templated_slice.end {
788                            tfs_idx += 1
789                        }
790                        // Carry on to the next lexed element
791                        break;
792                    } else {
793                        // We've got an element which extends beyond this templated slice.
794                        // This means that a _single_ lexed element claims both some
795                        // templated elements and some non-templated elements. That could
796                        // include all kinds of things (and from here we don't know what
797                        // else is yet to come, comments, blocks, literals etc...).
798
799                        // In the `literal` version of this code we would consider
800                        // splitting the literal element here, but in the templated
801                        // side we don't. That's because the way that templated tokens
802                        // are lexed, means that they should arrive "pre-split".
803
804                        // Stash the source idx for later when we do make a segment.
805                        if stashed_source_idx.is_none() {
806                            stashed_source_idx = Some(tfs.source_slice.start);
807                            continue;
808                        }
809                        // Move on to the next template slice
810                        continue;
811                    }
812                }
813            }
814            panic!("Unable to process slice: {tfs:?}");
815        }
816    }
817    result
818}
819
820#[cfg(test)]
821mod tests {
822    use super::*;
823
824    /// Assert that a matcher does or doesn't work on a string.
825    ///
826    /// The optional `matchstring` argument, which can optionally
827    /// be None, allows to either test positive matching of a
828    /// particular string or negative matching (that it explicitly)
829    /// doesn't match.
830    fn assert_matches(in_string: &str, matcher: &Matcher, match_string: Option<&str>) {
831        let res = matcher.matches(in_string);
832        if let Some(match_string) = match_string {
833            assert_eq!(res.forward_string, &in_string[match_string.len()..]);
834            assert_eq!(res.elements.len(), 1);
835            assert_eq!(res.elements[0].text, match_string);
836        } else {
837            assert_eq!(res.forward_string, in_string);
838            assert_eq!(res.elements.len(), 0);
839        }
840    }
841
842    #[test]
843    fn test_parser_lexer_trim_post_subdivide() {
844        let matcher: Vec<Matcher> = vec![
845            Matcher::legacy(
846                "function_script_terminator",
847                |_| true,
848                r";\s+(?!\*)\/(?!\*)|\s+(?!\*)\/(?!\*)",
849                SyntaxKind::StatementTerminator,
850            )
851            .subdivider(Pattern::string("semicolon", ";", SyntaxKind::Semicolon))
852            .post_subdivide(Pattern::legacy(
853                "newline",
854                |_| true,
855                r"(\n|\r\n)+",
856                SyntaxKind::Newline,
857            )),
858        ];
859
860        let res = Lexer::new(&matcher).lex_match(";\n/\n");
861        assert_eq!(res.elements[0].text, ";");
862        assert_eq!(res.elements[1].text, "\n");
863        assert_eq!(res.elements[2].text, "/");
864        assert_eq!(res.elements.len(), 3);
865    }
866
867    /// Test the RegexLexer.
868    #[test]
869    fn test_parser_lexer_regex() {
870        let tests = &[
871            ("fsaljk", "f", "f"),
872            ("fsaljk", r"f", "f"),
873            ("fsaljk", r"[fas]*", "fsa"),
874            // Matching whitespace segments
875            ("   \t   fsaljk", r"[^\S\r\n]*", "   \t   "),
876            // Matching whitespace segments (with a newline)
877            ("   \t \n  fsaljk", r"[^\S\r\n]*", "   \t "),
878            // Matching quotes containing stuff
879            (
880                "'something boring'   \t \n  fsaljk",
881                r"'[^']*'",
882                "'something boring'",
883            ),
884            (
885                "' something exciting \t\n '   \t \n  fsaljk",
886                r"'[^']*'",
887                "' something exciting \t\n '",
888            ),
889        ];
890
891        for (raw, reg, res) in tests {
892            let matcher = Matcher::legacy("test", |_| true, reg, SyntaxKind::Word);
893
894            assert_matches(raw, &matcher, Some(res));
895        }
896    }
897
898    /// Test the lexer string
899    #[test]
900    fn test_parser_lexer_string() {
901        let matcher = Matcher::string("dot", ".", SyntaxKind::Dot);
902
903        assert_matches(".fsaljk", &matcher, Some("."));
904        assert_matches("fsaljk", &matcher, None);
905    }
906
907    /// Test the RepeatedMultiMatcher
908    #[test]
909    fn test_parser_lexer_lex_match() {
910        let matchers: Vec<Matcher> = vec![
911            Matcher::string("dot", ".", SyntaxKind::Dot),
912            Matcher::regex("test", "#[^#]*#", SyntaxKind::Dash),
913        ];
914
915        let res = Lexer::new(&matchers).lex_match("..#..#..#");
916
917        assert_eq!(res.forward_string, "#");
918        assert_eq!(res.elements.len(), 5);
919        assert_eq!(res.elements[2].text, "#..#");
920    }
921}