1use std::sync::OnceLock;
10
11use regex::Regex;
12
13use super::decimal::Decimal;
14use super::diagnostics::{ErrorKind, Result, TranslationError};
15use super::frontend_rules::{
16 UnicodeEscape, accept_control_parenthesis, accept_statement_brace, decode_unicode_escape,
17 read_rust_number_bounds, read_rust_source_line_break_end, read_rust_string_continuation_end,
18 regular_expression_end, start_regular_expression,
19};
20use super::javascript_line_terminator_rules::accept_java_script_line_terminator;
21use super::js_number::js_number_literal;
22use super::{Language, Span};
23
24mod cooked_strings;
25mod number_rules;
26mod raw_strings;
27mod source_whitespace;
28mod unicode_escapes;
29
30#[derive(Clone, Debug, Default, PartialEq, Eq)]
32pub struct Source {
33 units: Vec<u16>,
34}
35
36impl Source {
37 #[must_use]
38 pub fn new(text: &str) -> Self {
39 Self {
40 units: text.encode_utf16().collect(),
41 }
42 }
43
44 #[must_use]
45 pub const fn len(&self) -> usize {
46 self.units.len()
47 }
48
49 #[must_use]
50 pub const fn is_empty(&self) -> bool {
51 self.units.is_empty()
52 }
53
54 #[must_use]
55 pub fn units(&self) -> &[u16] {
56 &self.units
57 }
58
59 #[must_use]
61 pub fn at(&self, index: usize) -> Option<u16> {
62 self.units.get(index).copied()
63 }
64
65 #[must_use]
67 pub fn char_at(&self, index: usize) -> Option<char> {
68 self.at(index)
69 .and_then(|unit| char::from_u32(u32::from(unit)))
70 }
71
72 #[must_use]
74 pub fn is_char(&self, index: usize, ch: char) -> bool {
75 self.char_at(index) == Some(ch)
76 }
77
78 #[must_use]
79 pub fn starts_with(&self, pattern: &str, index: usize) -> bool {
80 pattern
81 .encode_utf16()
82 .enumerate()
83 .all(|(offset, unit)| self.at(index + offset) == Some(unit))
84 }
85
86 #[must_use]
88 pub fn slice(&self, start: usize, end: usize) -> String {
89 let end = end.min(self.units.len());
90 let start = start.min(end);
91 String::from_utf16_lossy(&self.units[start..end])
92 }
93
94 #[must_use]
96 pub fn index_of(&self, pattern: &str, from: usize) -> Option<usize> {
97 (from..self.units.len()).find(|&index| self.starts_with(pattern, index))
98 }
99
100 #[must_use]
103 pub fn code_point_text(&self, index: usize) -> String {
104 let high = self.units[index];
105 if (0xD800..0xDC00).contains(&high)
106 && let Some(low) = self.at(index + 1)
107 && (0xDC00..0xE000).contains(&low)
108 {
109 return String::from_utf16_lossy(&self.units[index..index + 2]);
110 }
111 String::from_utf16_lossy(&self.units[index..=index])
112 }
113}
114
115#[derive(Clone, Copy, Debug, PartialEq, Eq)]
116pub enum TokenKind {
117 Number,
118 Identifier,
119 Macro,
120 Punct,
121 RegularExpression,
122 String,
123 Character,
124 ByteCharacter,
125 Interpolation,
126 Template,
127 Eof,
128}
129
130#[derive(Clone, Debug, PartialEq, Eq)]
132pub struct TemplateExpression {
133 pub source: String,
134 pub offset: usize,
135}
136
137#[derive(Clone, Debug, PartialEq, Eq)]
138pub struct TemplatePart {
139 pub text: String,
140 pub expression: Option<TemplateExpression>,
141}
142
143#[derive(Clone, Debug, PartialEq, Eq)]
144pub struct Token {
145 pub kind: TokenKind,
146 pub value: String,
147 pub suffix: String,
149 pub floating: bool,
151 pub raw: String,
152 pub start: usize,
153 pub end: usize,
154 pub parts: Vec<TemplatePart>,
155 pub line: usize,
157 pub col: usize,
158 pub first: bool,
159}
160
161impl Token {
162 const fn new(kind: TokenKind, value: String, raw: String, start: usize, end: usize) -> Self {
163 Self {
164 kind,
165 value,
166 suffix: String::new(),
167 floating: false,
168 raw,
169 start,
170 end,
171 parts: Vec::new(),
172 line: 0,
173 col: 0,
174 first: false,
175 }
176 }
177
178 #[must_use]
179 pub const fn span(&self) -> Span {
180 Span {
181 start: self.start,
182 end: self.end,
183 }
184 }
185}
186
187#[derive(Clone, Debug, PartialEq, Eq)]
188pub struct Comment {
189 pub text: String,
190 pub start: usize,
191 pub end: usize,
192}
193
194#[derive(Clone, Debug)]
195pub struct Tokens {
196 pub tokens: Vec<Token>,
197 pub comments: Vec<Comment>,
198}
199
200fn operators(language: Language) -> Vec<&'static str> {
201 let mut list: Vec<&'static str> = match language {
202 Language::JavaScript => vec![
203 ">>>=", "===", "!==", "...", "**=", "<<=", ">>=", ">>>", "&&=", "||=", "??=", "**",
204 "&&", "||", "==", "!=", "<=", ">=", "=>", "+=", "-=", "*=", "/=", "%=", "&=", "|=",
205 "^=", "++", "--", "??", "?.", "<<", ">>",
206 ],
207 Language::Rust => vec![
208 "..=", "::", "->", "=>", "==", "!=", "<=", ">=", "&&", "||", "+=", "-=", "*=", "/=",
209 "%=", "..",
210 ],
211 Language::Lean => vec![
212 ":=", "++", "->", "=>", "==", "!=", "<=", ">=", "&&", "||", "<;>", "<|", "|>", "::",
213 "..", "←", "→", "∀", "∧", "≤", "≥", "≠", "×",
214 ],
215 Language::Rocq => vec![
216 ":=", "=>", "->", "<->", "<=?", "<?", "=?", "<=", ">=", "<>", "/\\", "\\/", "&&", "||",
217 "++", "::", "%",
218 ],
219 };
220 list.sort_by_key(|operator| std::cmp::Reverse(operator.encode_utf16().count()));
223 list
224}
225
226struct CommentSyntax {
227 line: Option<&'static str>,
228 open: &'static str,
229 close: &'static str,
230 nested: bool,
231}
232
233const fn comment_syntax(language: Language) -> CommentSyntax {
234 match language {
235 Language::JavaScript => CommentSyntax {
236 line: Some("//"),
237 open: "/*",
238 close: "*/",
239 nested: false,
240 },
241 Language::Rust => CommentSyntax {
242 line: Some("//"),
243 open: "/*",
244 close: "*/",
245 nested: true,
246 },
247 Language::Lean => CommentSyntax {
248 line: Some("--"),
249 open: "/-",
250 close: "-/",
251 nested: true,
252 },
253 Language::Rocq => CommentSyntax {
254 line: None,
255 open: "(*",
256 close: "*)",
257 nested: true,
258 },
259 }
260}
261
262#[must_use]
264pub const fn is_js_space(unit: u16) -> bool {
265 matches!(
266 unit,
267 0x09..=0x0D
268 | 0x20
269 | 0xA0
270 | 0x1680
271 | 0x2000..=0x200A
272 | 0x2028
273 | 0x2029
274 | 0x202F
275 | 0x205F
276 | 0x3000
277 | 0xFEFF
278 )
279}
280
281fn letter_regex() -> &'static Regex {
282 static LETTER: OnceLock<Regex> = OnceLock::new();
283 LETTER.get_or_init(|| Regex::new(r"^\p{L}$").expect("letter class"))
284}
285
286fn letter_or_number_regex() -> &'static Regex {
287 static LETTER: OnceLock<Regex> = OnceLock::new();
288 LETTER.get_or_init(|| Regex::new(r"^[\p{L}\p{N}]$").expect("letter or number class"))
289}
290
291const LEAN_SYMBOLS: &str = "∀→∧≤≥≠λ×";
292
293fn unicode_test(unit: Option<u16>, regex: &Regex) -> bool {
294 unit.and_then(|unit| char::from_u32(u32::from(unit)))
295 .is_some_and(|ch| !LEAN_SYMBOLS.contains(ch) && regex.is_match(ch.encode_utf8(&mut [0; 4])))
296}
297
298fn is_identifier_start(unit: Option<u16>, language: Language) -> bool {
299 let Some(value) = unit else { return false };
300 if u8::try_from(value).is_ok_and(|byte| byte.is_ascii_alphabetic() || byte == b'_') {
301 return true;
302 }
303 if language == Language::JavaScript && value == u16::from(b'$') {
304 return true;
305 }
306 matches!(language, Language::Lean | Language::Rocq) && unicode_test(unit, letter_regex())
307}
308
309fn is_identifier_part(unit: Option<u16>, language: Language) -> bool {
310 let Some(value) = unit else { return false };
311 if u8::try_from(value).is_ok_and(|byte| byte.is_ascii_alphanumeric() || byte == b'_') {
312 return true;
313 }
314 let is = |ch: u8| value == u16::from(ch);
315 if language == Language::JavaScript && is(b'$') {
316 return true;
317 }
318 if language == Language::Rocq && is(b'\'') {
319 return true;
320 }
321 if language == Language::Lean && (is(b'\'') || is(b'!') || is(b'?')) {
322 return true;
323 }
324 matches!(language, Language::Lean | Language::Rocq)
325 && unicode_test(unit, letter_or_number_regex())
326}
327
328const fn span(start: usize, end: usize) -> Span {
329 Span { start, end }
330}
331
332pub fn tokenize(text: &str, language: Language) -> Result<Tokens> {
339 tokenize_source(&Source::new(text), language)
340}
341
342pub fn tokenize_source(source: &Source, language: Language) -> Result<Tokens> {
348 tokenize_region(source, language, 0, false, &mut None)
349}
350
351fn tokenize_region(
354 source: &Source,
355 language: Language,
356 start: usize,
357 braced: bool,
358 units: &mut Option<Vec<f64>>,
359) -> Result<Tokens> {
360 let operators = operators(language);
361 let comments = comment_syntax(language);
362 let mut tokens: Vec<Token> = Vec::new();
363 let mut comment_list = Vec::new();
364 let mut scopes = Vec::new();
367 let mut statement_blocks = Vec::new();
368 let mut closed = false;
369 let mut declaration_body = false;
370 let mut depth = 0usize;
371 let mut index = start;
372 while index < source.len() {
373 let unit = source.units[index];
374 if braced && source.is_char(index, '}') && depth == 0 {
375 break;
376 }
377 let whitespace = if language == Language::Rust {
378 source_whitespace::accept_rust_source_whitespace(f64::from(unit))
379 || source_whitespace::accept_rust_source_byte_order_mark(
380 f64::from(unit),
381 index == 0,
382 )
383 } else {
384 is_js_space(unit)
385 };
386 if whitespace {
387 index += 1;
388 continue;
389 }
390 if let Some(line) = comments.line
391 && source.starts_with(line, index)
392 {
393 let stop = if language == Language::JavaScript {
394 source.units[index..]
395 .iter()
396 .position(|unit| accept_java_script_line_terminator(f64::from(*unit)))
397 .map_or(source.len(), |offset| index + offset)
398 } else {
399 source.index_of("\n", index).unwrap_or(source.len())
400 };
401 comment_list.push(Comment {
402 text: source.slice(index, stop),
403 start: index,
404 end: stop,
405 });
406 index = stop;
407 continue;
408 }
409 if source.starts_with(comments.open, index) {
410 let stop = block_comment_end(source, index, &comments)?;
411 comment_list.push(Comment {
412 text: source.slice(index, stop),
413 start: index,
414 end: stop,
415 });
416 index = stop;
417 continue;
418 }
419 let start = index;
420 let ch = source.char_at(index);
421 if language == Language::JavaScript && ch == Some('/') {
422 let previous = tokens.last();
423 let kind = previous.map_or("", |token| match token.kind {
424 TokenKind::Identifier => "identifier",
425 TokenKind::Punct => "punct",
426 _ => "other",
427 });
428 let kind = if tokens
429 .iter()
430 .rev()
431 .nth(1)
432 .is_some_and(|token| token.value == "." || token.value == "?.")
433 {
434 "member"
435 } else {
436 kind
437 };
438 let value = previous.map_or("", |token| token.value.as_str());
439 if closed || start_regular_expression(kind, value) {
440 let units = units.get_or_insert_with(|| {
441 source.units().iter().map(|unit| f64::from(*unit)).collect()
442 });
443 #[allow(clippy::cast_precision_loss)]
444 let end = regular_expression_end(units, index as f64);
445 if end < 0.0 {
446 return Err(TranslationError::syntax(
447 "unterminated regular expression literal",
448 Some(span(start, source.len())),
449 ));
450 }
451 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
452 let end = end as usize;
453 tokens.push(Token::new(
454 TokenKind::RegularExpression,
455 "/".to_owned(),
456 source.slice(index, end),
457 start,
458 end,
459 ));
460 index = end;
461 closed = false;
462 continue;
463 }
464 }
465 let control_closed = closed;
466 closed = false;
467 if language == Language::JavaScript && ch == Some('`') {
468 let token = template_token(source, index, units)?;
469 index = token.end;
470 tokens.push(token);
471 continue;
472 }
473 if language == Language::Rust
474 && ch == Some('r')
475 && let Some(token) = raw_string_token(source, index, units)?
476 {
477 index = token.end;
478 tokens.push(token);
479 continue;
480 }
481 if language == Language::Rust
482 && (ch == Some('\'') || (ch == Some('b') && source.is_char(index + 1, '\'')))
483 && let Some(token) = rust_character_token(source, index, units)?
484 {
485 index = token.end;
486 tokens.push(token);
487 continue;
488 }
489 if ch == Some('"') || (language == Language::JavaScript && ch == Some('\'')) {
490 let token = string_token(source, index, language, units)?;
491 index = token.end;
492 tokens.push(token);
493 continue;
494 }
495 if language == Language::Lean && source.starts_with("s!\"", index) {
496 let mut token = string_token(source, index + 2, language, units)?;
497 token.kind = TokenKind::Interpolation;
498 token.start = start;
499 token.raw = source.slice(start, token.end);
500 index = token.end;
501 tokens.push(token);
502 continue;
503 }
504 if language == Language::JavaScript
505 && (ch.is_some_and(|ch| ch.is_ascii_digit())
506 || (ch == Some('.')
507 && source
508 .char_at(index + 1)
509 .is_some_and(|ch| ch.is_ascii_digit())))
510 {
511 let token = javascript_number(source, index)?;
512 index = token.end;
513 tokens.push(token);
514 continue;
515 }
516 if ch.is_some_and(|ch| ch.is_ascii_digit()) {
517 if language == Language::Rust {
518 let token = rust_number(source, index, units)?;
519 index = token.end;
520 tokens.push(token);
521 continue;
522 }
523 let mut stop = index;
524 while source
525 .char_at(stop)
526 .is_some_and(|ch| ch.is_ascii_digit() || ch == '_')
527 {
528 stop += 1;
529 }
530 let digits_end = stop;
531 if source
532 .char_at(stop)
533 .is_some_and(|ch| ch.is_ascii_lowercase())
534 {
535 stop += 1;
536 while source
537 .char_at(stop)
538 .is_some_and(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit())
539 {
540 stop += 1;
541 }
542 }
543 let raw = source.slice(start, stop);
544 let digits = source.slice(start, digits_end);
545 if digits.ends_with('_') {
546 return Err(TranslationError::syntax(
547 format!("malformed number {raw}"),
548 Some(span(start, stop)),
549 ));
550 }
551 let mut token =
552 Token::new(TokenKind::Number, digits.replace('_', ""), raw, start, stop);
553 token.suffix = source.slice(digits_end, stop);
554 tokens.push(token);
555 index = stop;
556 continue;
557 }
558 if is_identifier_start(Some(unit), language) {
559 let mut stop = index + 1;
560 loop {
561 while stop < source.len() && is_identifier_part(source.at(stop), language) {
562 stop += 1;
563 }
564 let qualified = matches!(language, Language::Lean | Language::Rocq)
566 && source.is_char(stop, '.')
567 && stop + 1 < source.len()
568 && is_identifier_start(source.at(stop + 1), language);
569 if !qualified {
570 break;
571 }
572 stop += 2;
573 }
574 if language == Language::Rust
575 && source.is_char(stop, '!')
576 && !source.is_char(stop + 1, '=')
577 {
578 tokens.push(Token::new(
579 TokenKind::Macro,
580 source.slice(index, stop),
581 source.slice(index, stop + 1),
582 start,
583 stop + 1,
584 ));
585 index = stop + 1;
586 continue;
587 }
588 let value = source.slice(index, stop);
589 tokens.push(Token::new(
590 TokenKind::Identifier,
591 value.clone(),
592 value,
593 start,
594 stop,
595 ));
596 index = stop;
597 continue;
598 }
599 let text = operators
600 .iter()
601 .find(|operator| source.starts_with(operator, index))
602 .map_or_else(
603 || source.code_point_text(index),
604 |operator| (*operator).to_owned(),
605 );
606 let length = text.encode_utf16().count();
607 if braced && text == "{" {
608 depth += 1;
609 }
610 if braced && text == "}" {
611 depth -= 1;
612 }
613 if language == Language::JavaScript {
614 if text == "(" {
615 let qualified = tokens
616 .iter()
617 .rev()
618 .nth(1)
619 .is_some_and(|token| token.value == "." || token.value == "?.");
620 let declaration = tokens
621 .iter()
622 .rev()
623 .nth(1)
624 .is_some_and(|token| token.value == "function")
625 && (tokens.len() == 2
626 || tokens.iter().rev().nth(2).is_some_and(|token| {
627 matches!(token.value.as_str(), ";" | "{" | "}" | "export" | "async")
628 }));
629 let control = tokens.last().is_some_and(|token| {
630 let kind = if token.kind == TokenKind::Identifier {
631 "identifier"
632 } else {
633 "other"
634 };
635 accept_control_parenthesis(kind, &token.value, qualified)
636 });
637 scopes.push((control, declaration));
638 }
639 if text == ")" {
640 let (control, declaration) = scopes.pop().unwrap_or((false, false));
641 closed = control;
642 declaration_body = declaration;
643 } else if text == "{" {
644 let kind =
645 tokens.last().map_or(
646 if braced { "expression" } else { "" },
647 |token| match token.kind {
648 TokenKind::Identifier => "identifier",
649 TokenKind::Punct => "punct",
650 _ => "other",
651 },
652 );
653 let value = tokens.last().map_or("", |token| token.value.as_str());
654 statement_blocks.push(accept_statement_brace(
655 kind,
656 value,
657 control_closed,
658 declaration_body,
659 ));
660 declaration_body = false;
661 } else if text == "}" {
662 closed = statement_blocks.pop().unwrap_or(false);
663 } else {
664 declaration_body = false;
665 }
666 }
667 tokens.push(Token::new(
668 TokenKind::Punct,
669 text.clone(),
670 text,
671 start,
672 start + length,
673 ));
674 index += length;
675 }
676 tokens.push(Token::new(
677 TokenKind::Eof,
678 String::new(),
679 String::new(),
680 index,
681 index,
682 ));
683 Ok(Tokens {
684 tokens,
685 comments: comment_list,
686 })
687}
688
689include!("lexer/literals.rs");
690
691#[must_use]
693pub fn describe(token: &Token) -> String {
694 if token.kind == TokenKind::Eof {
695 "end of input".to_owned()
696 } else {
697 json_string(&token.raw)
698 }
699}
700
701#[must_use]
703pub fn json_string(text: &str) -> String {
704 serde_json::to_string(text).unwrap_or_default()
705}