|
| 1 | +import {ExternalTokenizer} from "@lezer/lr" |
| 2 | +import {Regex, divideOp} from "./syntax.grammar.terms" |
| 3 | + |
| 4 | +// ============================================================ |
| 5 | +// Regex / Division external tokenizer (#7) |
| 6 | +// |
| 7 | +// `/` is ambiguous: regex literal or division operator. |
| 8 | +// This tokenizer handles both: |
| 9 | +// |
| 10 | +// 1. Try to match /pattern/flags (regex) |
| 11 | +// 2. If the parser state allows Regex AND the pattern is valid, emit Regex |
| 12 | +// 3. Otherwise emit divideOp (aliased to ArithOp) for division |
| 13 | +// |
| 14 | +// The parser state determines which is valid: |
| 15 | +// - At expression-start (after =, (, [, ,, operator): Regex is valid |
| 16 | +// - After a value (identifier, number, ), ]): only divideOp is valid |
| 17 | +// ============================================================ |
| 18 | + |
| 19 | +export const regexTokenizer = new ExternalTokenizer((input, stack) => { |
| 20 | + if (input.next !== 47 /* '/' */) return |
| 21 | + |
| 22 | + // Try to match a regex pattern |
| 23 | + let pos = 1 |
| 24 | + let isRegex = true |
| 25 | + while (true) { |
| 26 | + const ch = input.peek(pos) |
| 27 | + if (ch === -1 || ch === 10 /* \n */ || ch === 13 /* \r */) { isRegex = false; break } |
| 28 | + if (ch === 92 /* \\ */) { |
| 29 | + pos++ |
| 30 | + // Check the escaped char isn't newline/EOF |
| 31 | + const next = input.peek(pos) |
| 32 | + if (next === -1 || next === 10 || next === 13) { isRegex = false; break } |
| 33 | + pos++ |
| 34 | + continue |
| 35 | + } |
| 36 | + if (ch === 47 /* '/' */) { pos++; break } |
| 37 | + pos++ |
| 38 | + } |
| 39 | + |
| 40 | + if (isRegex) { |
| 41 | + // Consume optional flags: i, m, x, o, u, s, n |
| 42 | + while (true) { |
| 43 | + const ch = input.peek(pos) |
| 44 | + if (ch === 105 || ch === 109 || ch === 120 || ch === 111 || |
| 45 | + ch === 117 || ch === 115 || ch === 110) { |
| 46 | + pos++ |
| 47 | + } else { |
| 48 | + break |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + if (stack.canShift(Regex)) { |
| 53 | + input.acceptToken(Regex, pos) |
| 54 | + return |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + // Fall back to division |
| 59 | + if (stack.canShift(divideOp)) { |
| 60 | + input.acceptToken(divideOp, 1) |
| 61 | + } |
| 62 | +}) |
0 commit comments