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::base::{ErasedSegment, SegmentBuilder, Tables};
8use crate::dialects::base::Dialect;
9use crate::dialects::syntax::SyntaxKind;
10use crate::errors::{SQLLexError, ValueError};
11use crate::slice_helpers::{is_zero_slice, offset_slice};
12use crate::templaters::base::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                    if matched.start() == 0 {
332                        return Some(matched.as_str());
333                    }
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
412pub enum StringOrTemplate<'a> {
413    String(&'a str),
414    Template(TemplatedFile),
415}
416
417impl Lexer {
418    /// Create a new lexer.
419    pub(crate) fn new(lexer_matchers: &[Matcher]) -> Self {
420        let mut patterns = Vec::new();
421        let mut syntax_map = Vec::new();
422        let mut matchers = Vec::new();
423
424        for matcher in lexer_matchers {
425            match matcher.pattern.kind {
426                SearchPatternKind::String(pattern) | SearchPatternKind::Regex(pattern) => {
427                    let pattern = if matches!(matcher.pattern.kind, SearchPatternKind::String(_)) {
428                        fancy_regex::escape(pattern)
429                    } else {
430                        pattern.into()
431                    };
432
433                    patterns.push(pattern);
434                    syntax_map.push((matcher.pattern.name, matcher.pattern.syntax_kind));
435                }
436                SearchPatternKind::Legacy(_, _) | SearchPatternKind::Native(_) => {
437                    matchers.push(matcher.clone());
438                }
439            }
440        }
441
442        Lexer {
443            syntax_map,
444            matchers,
445            regex: regex_automata::meta::Regex::new_many(&patterns).unwrap(),
446            last_resort_lexer: Matcher::legacy(
447                "<unlexable>",
448                |_| true,
449                r"[^\t\n.]*",
450                SyntaxKind::Unlexable,
451            ),
452        }
453    }
454
455    pub fn lex(
456        &self,
457        tables: &Tables,
458        raw: StringOrTemplate,
459    ) -> Result<(Vec<ErasedSegment>, Vec<SQLLexError>), ValueError> {
460        // Make sure we've got a string buffer and a template regardless of what was
461        // passed in.
462
463        let template;
464        let mut str_buff = match raw {
465            StringOrTemplate::String(s) => {
466                template = s.into();
467                s
468            }
469            StringOrTemplate::Template(slot) => {
470                template = slot;
471                template.templated_str.as_ref().unwrap()
472            }
473        };
474
475        // Lex the string to get a tuple of LexedElement
476        let mut element_buffer: Vec<Element> = Vec::new();
477
478        loop {
479            let mut res = self.lex_match(str_buff);
480            element_buffer.append(&mut res.elements);
481
482            if res.forward_string.is_empty() {
483                break;
484            }
485
486            // If we STILL can't match, then just panic out.
487            let mut resort_res = self.last_resort_lexer.matches(str_buff);
488            if !resort_res.elements.is_empty() {
489                break;
490            }
491
492            str_buff = resort_res.forward_string;
493            element_buffer.append(&mut resort_res.elements);
494        }
495
496        // Map tuple LexedElement to list of TemplateElement.
497        // This adds the template_slice to the object.
498        let templated_buffer = Lexer::map_template_slices(element_buffer, &template);
499        // Turn lexed elements into segments.
500        let mut segments = self.elements_to_segments(templated_buffer, &template);
501
502        for seg in &mut segments {
503            seg.get_mut().set_id(tables.next_id())
504        }
505        Ok((segments, Vec::new()))
506    }
507
508    /// Generate any lexing errors for any un-lex-ables.
509    ///
510    /// TODO: Taking in an iterator, also can make the typing better than use
511    /// unwrap.
512    #[allow(dead_code)]
513    fn violations_from_segments(segments: Vec<ErasedSegment>) -> Vec<SQLLexError> {
514        segments
515            .into_iter()
516            .filter(|s| s.is_type(SyntaxKind::Unlexable))
517            .map(|s| {
518                SQLLexError::new(
519                    format!(
520                        "Unable to lex characters: {}",
521                        s.raw().chars().take(10).collect::<String>()
522                    ),
523                    s.get_position_marker().unwrap().clone(),
524                )
525            })
526            .collect()
527    }
528
529    /// Iteratively match strings using the selection of sub-matchers.
530    fn lex_match<'b>(&self, mut forward_string: &'b str) -> Match<'b> {
531        let mut elem_buff = Vec::new();
532
533        'main: loop {
534            if forward_string.is_empty() {
535                return Match {
536                    forward_string,
537                    elements: elem_buff,
538                };
539            }
540
541            for matcher in &self.matchers {
542                let mut match_result = matcher.matches(forward_string);
543
544                if !match_result.elements.is_empty() {
545                    elem_buff.append(&mut match_result.elements);
546                    forward_string = match_result.forward_string;
547                    continue 'main;
548                }
549            }
550
551            let input =
552                regex_automata::Input::new(forward_string).anchored(regex_automata::Anchored::Yes);
553
554            if let Some(match_) = self.regex.find(input) {
555                let (name, kind) = self.syntax_map[match_.pattern().as_usize()];
556
557                elem_buff.push(Element::new(
558                    name,
559                    kind,
560                    &forward_string[match_.start()..match_.end()],
561                ));
562                forward_string = &forward_string[match_.end()..];
563
564                continue 'main;
565            }
566
567            return Match {
568                forward_string,
569                elements: elem_buff,
570            };
571        }
572    }
573
574    /// Create a tuple of TemplateElement from a tuple of LexedElement.
575    ///
576    /// This adds slices in the templated file to the original lexed
577    /// elements. We'll need this to work out the position in the source
578    /// file.
579    /// TODO Can this vec be turned into an iterator and return iterator to make
580    /// lazy?
581    fn map_template_slices<'b>(
582        elements: Vec<Element<'b>>,
583        template: &TemplatedFile,
584    ) -> Vec<TemplateElement<'b>> {
585        let mut idx = 0;
586        let mut templated_buff: Vec<TemplateElement> = Vec::with_capacity(elements.len());
587
588        for element in elements {
589            let template_slice = offset_slice(idx, element.text.len());
590            idx += element.text.len();
591
592            let templated_string = template.templated();
593            if templated_string[template_slice.clone()] != element.text {
594                panic!(
595                    "Template and lexed elements do not match. This should never happen {:?} != \
596                     {:?}",
597                    element.text, &templated_string[template_slice]
598                );
599            }
600
601            templated_buff.push(TemplateElement::from_element(element, template_slice));
602        }
603
604        templated_buff
605    }
606
607    /// Convert a tuple of lexed elements into a tuple of segments.
608    fn elements_to_segments(
609        &self,
610        elements: Vec<TemplateElement>,
611        templated_file: &TemplatedFile,
612    ) -> Vec<ErasedSegment> {
613        let mut segments = iter_segments(elements, templated_file);
614
615        // Add an end of file marker
616        let position_maker = match segments.last() {
617            Some(segment) => segment.get_position_marker().unwrap().end_point_marker(),
618            None => PositionMarker::from_point(0, 0, templated_file.clone(), None, None),
619        };
620
621        segments.push(
622            SegmentBuilder::token(0, "", SyntaxKind::EndOfFile)
623                .with_position(position_maker)
624                .finish(),
625        );
626
627        segments
628    }
629}
630
631fn iter_segments(
632    lexed_elements: Vec<TemplateElement>,
633    templated_file: &TemplatedFile,
634) -> Vec<ErasedSegment> {
635    let mut result: Vec<ErasedSegment> = Vec::with_capacity(lexed_elements.len());
636    // An index to track where we've got to in the templated file.
637    let mut tfs_idx = 0;
638    // We keep a map of previous block locations in case they re-occur.
639    // let block_stack = BlockTracker()
640    let templated_file_slices = &templated_file.sliced_file;
641
642    // Now work out source slices, and add in template placeholders.
643    for element in lexed_elements {
644        let consumed_element_length = 0;
645        let mut stashed_source_idx = None;
646
647        for (idx, tfs) in templated_file_slices
648            .iter()
649            .skip(tfs_idx)
650            .enumerate()
651            .map(|(i, tfs)| (i + tfs_idx, tfs))
652        {
653            // Is it a zero slice?
654            if is_zero_slice(&tfs.templated_slice) {
655                let _slice = if idx + 1 < templated_file_slices.len() {
656                    templated_file_slices[idx + 1].clone().into()
657                } else {
658                    None
659                };
660
661                continue;
662            }
663
664            if tfs.slice_type == "literal" {
665                let tfs_offset = tfs.source_slice.start - tfs.templated_slice.start;
666
667                // NOTE: Greater than OR EQUAL, to include the case of it matching
668                // length exactly.
669                if element.template_slice.end <= tfs.templated_slice.end {
670                    let slice_start = stashed_source_idx.unwrap_or_else(|| {
671                        element.template_slice.start + consumed_element_length + tfs_offset
672                    });
673
674                    result.push(element.to_segment(
675                        PositionMarker::new(
676                            slice_start..element.template_slice.end + tfs_offset,
677                            element.template_slice.clone(),
678                            templated_file.clone(),
679                            None,
680                            None,
681                        ),
682                        Some(consumed_element_length..element.raw.len()),
683                    ));
684
685                    // If it was an exact match, consume the templated element too.
686                    if element.template_slice.end == tfs.templated_slice.end {
687                        tfs_idx += 1
688                    }
689                    // In any case, we're done with this element. Move on
690                    break;
691                } else if element.template_slice.start == tfs.templated_slice.end {
692                    // Did we forget to move on from the last tfs and there's
693                    // overlap?
694                    // NOTE: If the rest of the logic works, this should never
695                    // happen.
696                    // lexer_logger.debug("     NOTE: Missed Skip")  # pragma: no cover
697                    continue;
698                } else {
699                    // This means that the current lexed element spans across
700                    // multiple templated file slices.
701                    // lexer_logger.debug("     Consuming whole spanning literal")
702                    // This almost certainly means there's a templated element
703                    // in the middle of a whole lexed element.
704
705                    // What we do here depends on whether we're allowed to split
706                    // lexed elements. This is basically only true if it's whitespace.
707                    // NOTE: We should probably make this configurable on the
708                    // matcher object, but for now we're going to look for the
709                    // name of the lexer.
710                    if element.matcher.name == "whitespace" {
711                        if stashed_source_idx.is_some() {
712                            panic!("Found literal whitespace with stashed idx!")
713                        }
714
715                        let incremental_length =
716                            tfs.templated_slice.end - element.template_slice.start;
717
718                        result.push(element.to_segment(
719                            PositionMarker::new(
720                                element.template_slice.start + consumed_element_length + tfs_offset
721                                    ..tfs.templated_slice.end + tfs_offset,
722                                element.template_slice.clone(),
723                                templated_file.clone(),
724                                None,
725                                None,
726                            ),
727                            offset_slice(consumed_element_length, incremental_length).into(),
728                        ));
729                    } else {
730                        // We can't split it. We're going to end up yielding a segment
731                        // which spans multiple slices. Stash the type, and if we haven't
732                        // set the start yet, stash it too.
733                        // lexer_logger.debug("     Spilling over literal slice.")
734                        if stashed_source_idx.is_none() {
735                            stashed_source_idx = (element.template_slice.start + idx).into();
736                            // lexer_logger.debug(
737                            //     "     Stashing a source start. %s", stashed_source_idx
738                            // )
739                            continue;
740                        }
741                    }
742                }
743            } else if matches!(tfs.slice_type.as_str(), "templated" | "block_start") {
744                // Found a templated slice. Does it have length in the templated file?
745                // If it doesn't, then we'll pick it up next.
746                if !is_zero_slice(&tfs.templated_slice) {
747                    // If it's a block_start. Append to the block stack.
748                    // NOTE: This is rare, but call blocks do occasionally
749                    // have length (and so don't get picked up by
750                    // _handle_zero_length_slice)
751                    if tfs.slice_type == "block_start" {
752                        unimplemented!()
753                        // block_stack.enter(tfs.source_slice)
754                    }
755
756                    // Is our current element totally contained in this slice?
757                    if element.template_slice.end <= tfs.templated_slice.end {
758                        // lexer_logger.debug("     Contained templated slice.")
759                        // Yes it is. Add lexed element with source slices as the whole
760                        // span of the source slice for the file slice.
761                        // If we've got an existing stashed source start, use that
762                        // as the start of the source slice.
763                        let slice_start = if let Some(stashed_source_idx) = stashed_source_idx {
764                            stashed_source_idx
765                        } else {
766                            tfs.source_slice.start + consumed_element_length
767                        };
768
769                        result.push(element.to_segment(
770                            PositionMarker::new(
771                                slice_start..tfs.source_slice.end,
772                                element.template_slice.clone(),
773                                templated_file.clone(),
774                                None,
775                                None,
776                            ),
777                            Some(consumed_element_length..element.raw.len()),
778                        ));
779
780                        // If it was an exact match, consume the templated element too.
781                        if element.template_slice.end == tfs.templated_slice.end {
782                            tfs_idx += 1
783                        }
784                        // Carry on to the next lexed element
785                        break;
786                    } else {
787                        // We've got an element which extends beyond this templated slice.
788                        // This means that a _single_ lexed element claims both some
789                        // templated elements and some non-templated elements. That could
790                        // include all kinds of things (and from here we don't know what
791                        // else is yet to come, comments, blocks, literals etc...).
792
793                        // In the `literal` version of this code we would consider
794                        // splitting the literal element here, but in the templated
795                        // side we don't. That's because the way that templated tokens
796                        // are lexed, means that they should arrive "pre-split".
797
798                        // Stash the source idx for later when we do make a segment.
799                        if stashed_source_idx.is_none() {
800                            stashed_source_idx = Some(tfs.source_slice.start);
801                            continue;
802                        }
803                        // Move on to the next template slice
804                        continue;
805                    }
806                }
807            }
808            panic!("Unable to process slice: {:?}", tfs);
809        }
810    }
811    result
812}
813
814#[cfg(test)]
815mod tests {
816    use super::*;
817
818    /// Assert that a matcher does or doesn't work on a string.
819    ///
820    /// The optional `matchstring` argument, which can optionally
821    /// be None, allows to either test positive matching of a
822    /// particular string or negative matching (that it explicitly)
823    /// doesn't match.
824    fn assert_matches(in_string: &str, matcher: &Matcher, match_string: Option<&str>) {
825        let res = matcher.matches(in_string);
826        if let Some(match_string) = match_string {
827            assert_eq!(res.forward_string, &in_string[match_string.len()..]);
828            assert_eq!(res.elements.len(), 1);
829            assert_eq!(res.elements[0].text, match_string);
830        } else {
831            assert_eq!(res.forward_string, in_string);
832            assert_eq!(res.elements.len(), 0);
833        }
834    }
835
836    #[test]
837    fn test_parser_lexer_trim_post_subdivide() {
838        let matcher: Vec<Matcher> = vec![
839            Matcher::legacy(
840                "function_script_terminator",
841                |_| true,
842                r";\s+(?!\*)\/(?!\*)|\s+(?!\*)\/(?!\*)",
843                SyntaxKind::StatementTerminator,
844            )
845            .subdivider(Pattern::string("semicolon", ";", SyntaxKind::Semicolon))
846            .post_subdivide(Pattern::legacy(
847                "newline",
848                |_| true,
849                r"(\n|\r\n)+",
850                SyntaxKind::Newline,
851            )),
852        ];
853
854        let res = Lexer::new(&matcher).lex_match(";\n/\n");
855        assert_eq!(res.elements[0].text, ";");
856        assert_eq!(res.elements[1].text, "\n");
857        assert_eq!(res.elements[2].text, "/");
858        assert_eq!(res.elements.len(), 3);
859    }
860
861    /// Test the RegexLexer.
862    #[test]
863    fn test_parser_lexer_regex() {
864        let tests = &[
865            ("fsaljk", "f", "f"),
866            ("fsaljk", r"f", "f"),
867            ("fsaljk", r"[fas]*", "fsa"),
868            // Matching whitespace segments
869            ("   \t   fsaljk", r"[^\S\r\n]*", "   \t   "),
870            // Matching whitespace segments (with a newline)
871            ("   \t \n  fsaljk", r"[^\S\r\n]*", "   \t "),
872            // Matching quotes containing stuff
873            (
874                "'something boring'   \t \n  fsaljk",
875                r"'[^']*'",
876                "'something boring'",
877            ),
878            (
879                "' something exciting \t\n '   \t \n  fsaljk",
880                r"'[^']*'",
881                "' something exciting \t\n '",
882            ),
883        ];
884
885        for (raw, reg, res) in tests {
886            let matcher = Matcher::legacy("test", |_| true, reg, SyntaxKind::Word);
887
888            assert_matches(raw, &matcher, Some(res));
889        }
890    }
891
892    /// Test the lexer string
893    #[test]
894    fn test_parser_lexer_string() {
895        let matcher = Matcher::string("dot", ".", SyntaxKind::Dot);
896
897        assert_matches(".fsaljk", &matcher, Some("."));
898        assert_matches("fsaljk", &matcher, None);
899    }
900
901    /// Test the RepeatedMultiMatcher
902    #[test]
903    fn test_parser_lexer_lex_match() {
904        let matchers: Vec<Matcher> = vec![
905            Matcher::string("dot", ".", SyntaxKind::Dot),
906            Matcher::regex("test", "#[^#]*#", SyntaxKind::Dash),
907        ];
908
909        let res = Lexer::new(&matchers).lex_match("..#..#..#");
910
911        assert_eq!(res.forward_string, "#");
912        assert_eq!(res.elements.len(), 5);
913        assert_eq!(res.elements[2].text, "#..#");
914    }
915}