about summary refs log tree commit diff stats
path: root/js/baba-yaga/src/legacy/lexer-optimized.js
blob: 0d4dc518c179e79cfb411e59720957bb4b9e7179 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
// lexer-optimized.js - High-performance regex-based lexer

import { LexError, ErrorHelpers } from './error.js';

const tokenTypes = {
  IDENTIFIER: 'IDENTIFIER',
  TYPE: 'TYPE',
  NUMBER: 'NUMBER',
  STRING: 'STRING',
  ARROW: 'ARROW',
  COLON: 'COLON',
  SEMICOLON: 'SEMICOLON',
  COMMA: 'COMMA',
  KEYWORD: 'KEYWORD',
  OPERATOR: 'OPERATOR',
  LPAREN: 'LPAREN',
  RPAREN: 'RPAREN',
  DOT: 'DOT',
  LBRACKET: 'LBRACKET',
  RBRACKET: 'RBRACKET',
  LBRACE: 'LBRACE',
  RBRACE: 'RBRACE',
  EOF: 'EOF',
};

const keywords = new Set(['when', 'is', 'then', 'if', 'Ok', 'Err', 'true', 'false', 'PI', 'INFINITY', 'and', 'or', 'xor']);
const types = new Set(['Int', 'String', 'Result', 'Float', 'Number', 'List', 'Table', 'Bool']);

/**
 * Token pattern definitions with regex and processing functions
 */
const TOKEN_PATTERNS = [
  // Whitespace (skip)
  {
    name: 'WHITESPACE',
    regex: /^[ \t\r]+/,
    skip: true
  },
  
  // Newlines (track line numbers) - handled by advance function
  {
    name: 'NEWLINE',
    regex: /^\n/,
    skip: true
  },
  
  // Comments (skip)
  {
    name: 'COMMENT',
    regex: /^\/\/.*$/m,
    skip: true
  },
  
  // Multi-character operators (order matters - longest first)
  {
    name: 'ARROW',
    regex: /^->/,
    type: tokenTypes.ARROW
  },
  
  {
    name: 'STRING_CONCAT',
    regex: /^\.\./,
    type: tokenTypes.OPERATOR,
    value: '..'
  },
  
  {
    name: 'COMPARISON_OPS',
    regex: /^(>=|<=|!=)/,
    type: tokenTypes.OPERATOR
  },
  
  // Numbers (including negative numbers in appropriate contexts)
  {
    name: 'NUMBER',
    regex: /^-?\d+(\.\d+)?/,
    type: tokenTypes.NUMBER,
    process: (match, lexer) => {
      const value = parseFloat(match[0]);
      const isFloat = match[0].includes('.');
      return {
        type: tokenTypes.NUMBER,
        value,
        isFloat,
        originalString: match[0]
      };
    }
  },
  
  // Strings with escape sequence handling
  {
    name: 'STRING',
    regex: /^"((?:[^"\\]|\\.)*)"/,
    type: tokenTypes.STRING,
    process: (match, lexer) => {
      const rawString = match[1];
      const processedString = rawString
        .replace(/\\n/g, '\n')
        .replace(/\\t/g, '\t')
        .replace(/\\r/g, '\r')
        .replace(/\\\\/g, '\\')
        .replace(/\\"/g, '"');
      
      return {
        type: tokenTypes.STRING,
        value: processedString
      };
    }
  },
  
  // Identifiers, keywords, and types
  {
    name: 'IDENTIFIER',
    regex: /^[a-zA-Z_][a-zA-Z0-9_]*/,
    process: (match, lexer) => {
      const value = match[0];
      
      if (keywords.has(value)) {
        return {
          type: tokenTypes.KEYWORD,
          value
        };
      } else if (types.has(value)) {
        return {
          type: tokenTypes.TYPE,
          value
        };
      } else {
        return {
          type: tokenTypes.IDENTIFIER,
          value
        };
      }
    }
  },
  
  // Single character operators
  {
    name: 'SINGLE_CHAR_OPS',
    regex: /^[+\-*/%=><]/,
    type: tokenTypes.OPERATOR
  },
  
  // Punctuation
  {
    name: 'PUNCTUATION',
    regex: /^[()[\]{}:;,.]/,
    process: (match, lexer) => {
      const char = match[0];
      const typeMap = {
        '(': tokenTypes.LPAREN,
        ')': tokenTypes.RPAREN,
        '[': tokenTypes.LBRACKET,
        ']': tokenTypes.RBRACKET,
        '{': tokenTypes.LBRACE,
        '}': tokenTypes.RBRACE,
        ':': tokenTypes.COLON,
        ';': tokenTypes.SEMICOLON,
        ',': tokenTypes.COMMA,
        '.': tokenTypes.DOT
      };
      
      return {
        type: typeMap[char],
        value: char
      };
    }
  }
];

/**
 * High-performance regex-based lexer
 */
function createOptimizedLexer(input) {
  let position = 0;
  let line = 1;
  let column = 1;
  
  // Pre-compile all regexes for better performance
  const compiledPatterns = TOKEN_PATTERNS.map(pattern => ({
    ...pattern,
    compiledRegex: pattern.regex
  }));

  function getCurrentLocation() {
    return { line, column };
  }

  function advance(length) {
    for (let i = 0; i < length; i++) {
      if (input[position + i] === '\n') {
        line++;
        column = 1;
      } else {
        column++;
      }
    }
    position += length;
  }

  function nextToken() {
    if (position >= input.length) {
      return {
        type: tokenTypes.EOF,
        value: '',
        line,
        column
      };
    }

    const remaining = input.slice(position);
    const startLocation = getCurrentLocation();

    // Try each pattern in order
    for (const pattern of compiledPatterns) {
      const match = remaining.match(pattern.compiledRegex);
      
      if (match) {
        const matchedText = match[0];
        const tokenLength = matchedText.length;
        
        // Handle special patterns that affect lexer state
        if (pattern.onMatch) {
          pattern.onMatch({ line, column });
        }
        
        advance(tokenLength);
        
        // Skip tokens that should be ignored
        if (pattern.skip) {
          return nextToken();
        }
        
        // Create the token
        let token;
        
        if (pattern.process) {
          token = pattern.process(match, this);
        } else {
          token = {
            type: pattern.type,
            value: pattern.value || matchedText
          };
        }
        
        // Add location information
        token.line = startLocation.line;
        token.column = startLocation.column;
        
        return token;
      }
    }

    // No pattern matched - handle error
    const char = remaining[0];
    const suggestions = [];
    
    // Common character mistakes
    if (char === '"' || char === '"') {
      suggestions.push('Use straight quotes " instead of curly quotes');
    } else if (char === '–' || char === '—') {
      suggestions.push('Use regular minus - or arrow -> instead of em/en dash');
    } else if (/[^\x00-\x7F]/.test(char)) {
      suggestions.push('Use only ASCII characters in Baba Yaga code');
    } else {
      suggestions.push(`Character "${char}" is not valid in Baba Yaga syntax`);
    }
    
    throw new LexError(
      `Unexpected character: ${JSON.stringify(char)}`,
      { line, column, length: 1 },
      input,
      suggestions
    );
  }

  function allTokens() {
    const tokens = [];
    let token;
    
    do {
      token = nextToken();
      tokens.push(token);
    } while (token.type !== tokenTypes.EOF);
    
    return tokens;
  }

  return {
    allTokens,
    nextToken
  };
}

/**
 * Performance comparison utility
 */
async function createLexerWithFallback(input, useOptimized = true) {
  if (useOptimized) {
    try {
      return createOptimizedLexer(input);
    } catch (error) {
      // If optimized lexer fails, fall back to original
      console.warn('Falling back to original lexer:', error.message);
      const { createLexer } = await import('./lexer.js');
      return createLexer(input);
    }
  } else {
    const { createLexer } = await import('./lexer.js');
    return createLexer(input);
  }
}

/**
 * Benchmark function to compare lexer performance
 */
async function benchmarkLexers(input, iterations = 1000) {
  console.log(`Benchmarking lexers with ${iterations} iterations...`);
  
  // Warm up
  for (let i = 0; i < 10; i++) {
    createOptimizedLexer(input).allTokens();
  }
  
  // Benchmark optimized lexer
  const optimizedStart = performance.now();
  for (let i = 0; i < iterations; i++) {
    createOptimizedLexer(input).allTokens();
  }
  const optimizedTime = performance.now() - optimizedStart;
  
  // Benchmark original lexer
  const { createLexer } = await import('./lexer.js');
  const originalStart = performance.now();
  for (let i = 0; i < iterations; i++) {
    createLexer(input).allTokens();
  }
  const originalTime = performance.now() - originalStart;
  
  console.log(`Original lexer: ${originalTime.toFixed(2)}ms`);
  console.log(`Optimized lexer: ${optimizedTime.toFixed(2)}ms`);
  console.log(`Speedup: ${(originalTime / optimizedTime).toFixed(2)}x`);
  
  return {
    originalTime,
    optimizedTime,
    speedup: originalTime / optimizedTime
  };
}

export { 
  createOptimizedLexer,
  createLexerWithFallback,
  benchmarkLexers,
  tokenTypes 
};