-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArduinoParser.js
More file actions
4768 lines (4169 loc) · 208 KB
/
ArduinoParser.js
File metadata and controls
4768 lines (4169 loc) · 208 KB
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
// Load debug logger for performance optimization (Node.js only)
let conditionalLog = (verbose, ...args) => { if (verbose) console.log(...args); };
if (typeof require !== 'undefined') {
try {
const debugLogger = require('../../../src/javascript/utils/debug-logger.js');
conditionalLog = debugLogger.conditionalLog;
} catch (e) {
// Fallback to simple implementation if debug logger not found
}
}
/**
* ArduinoParser - Comprehensive Arduino/C++ Parser with Integrated Preprocessing and Platform Emulation
*
* A complete Arduino/C++ code parser with built-in preprocessor and platform emulation.
* Combines parsing, macro expansion, conditional compilation, and platform-specific defines.
*
* USAGE:
* // Basic parsing with default ESP32 platform
* const ast = parse(code);
*
* // Parsing with specific platform
* const ast = parse(code, { platform: 'ARDUINO_UNO' });
*
* // Class-based approach
* const parser = new Parser(code, { platform: 'ESP32_NANO' });
* const ast = parser.parse();
*
* FEATURES:
* ✅ Complete Arduino/C++ language support
* ✅ Integrated preprocessor with macro expansion
* ✅ Platform emulation (ESP32 Nano, Arduino Uno)
* ✅ Library auto-activation from #include directives
* ✅ Conditional compilation (#ifdef, #ifndef, #if)
* ✅ Function-like and simple macro substitution
* ✅ Enhanced error handling and recovery
* ✅ Universal Node.js and browser compatibility
*
* Architecture: Code → Platform Context → Preprocessor → Parser → Clean AST
*
* CHANGELOG v5.3.0:
* + FILESYSTEM REORGANIZATION: Extracted as independent library from monolithic structure
* + Fixed CompactAST import path after extraction (../../CompactAST/src/CompactAST.js)
* + Maintained complete compatibility with Node.js and browser environments
* + Enhanced browser export pattern for standalone library usage
* + TESTED: All parser test harnesses work correctly with new structure
*
* CHANGELOG v5.2.0:
* + CRITICAL FIX: CompactAST export mapping for ternary expressions
* + Fixed 'TernaryExpressionNode' → 'TernaryExpression' mapping for cross-platform compatibility
* + Ensures JavaScript ↔ C++ ternary expression parity in CompactAST format
* + MERGED: platform_emulation.js and preprocessor.js into single file
* + Added simplified API with platform string support
* + Maintained full backward compatibility
* + Updated to support both class and function-based APIs
* + Enhanced documentation and examples
*/
// =============================================================================
// PARSER CONSTANTS AND CONFIGURATION
// =============================================================================
const PARSER_VERSION = "6.0.0";
const PLATFORM_EMULATION_VERSION = '1.0.0';
const PREPROCESSOR_VERSION = '1.2.0';
// Import CompactAST library
let exportCompactAST;
try {
if (typeof require !== 'undefined') {
// Node.js environment
const compactAST = require('../../CompactAST/src/CompactAST.js');
exportCompactAST = compactAST.exportCompactAST;
} else if (typeof window !== 'undefined' && window.CompactAST) {
// Browser environment - use CompactAST namespace
exportCompactAST = window.CompactAST.exportCompactAST;
}
} catch (error) {
// CompactAST not available - library will work without binary export (Node.js only)
if (typeof require !== 'undefined') {
console.warn('CompactAST library not found - binary export disabled');
}
}
// =============================================================================
// PLATFORM EMULATION SYSTEM (integrated from platform_emulation.js)
// =============================================================================
/**
* ESP32 Nano Platform Definition
*/
const ESP32_NANO_PLATFORM = {
name: 'ESP32_NANO',
displayName: 'Arduino Nano ESP32',
defines: {
'ESP32': '1', 'ARDUINO_NANO_ESP32': '1', 'ARDUINO': '2030100', 'ARDUINO_ESP32_NANO': '1',
'ESP32_S3': '1', 'NORA_W106': '1', 'WIFI_SUPPORT': '1', 'BLUETOOTH_SUPPORT': '1',
'BLE_SUPPORT': '1', 'USB_C_SUPPORT': '1', 'FLASH_SIZE': '16777216', 'RAM_SIZE': '524288',
'PSRAM_SIZE': '8388608', 'OPERATING_VOLTAGE': '3300', 'MAX_PIN_CURRENT': '40',
'VIN_MIN': '5000', 'VIN_MAX': '18000'
},
pins: {
'D0': 0, 'D1': 1, 'D2': 2, 'D3': 3, 'D4': 4, 'D5': 5, 'D6': 6, 'D7': 7, 'D8': 8,
'D9': 9, 'D10': 10, 'D11': 11, 'D12': 12, 'D13': 13, 'A0': 14, 'A1': 15, 'A2': 16,
'A3': 17, 'A4': 18, 'A5': 19, 'A6': 20, 'A7': 21, 'LED_BUILTIN': 13, 'LED_RED': 46,
'LED_GREEN': 45, 'LED_BLUE': 44, 'SDA': 18, 'SCL': 19, 'MOSI': 11, 'MISO': 12,
'SCK': 13, 'SS': 10, 'TX': 1, 'RX': 0, 'VIN': -1, 'VBUS': -2, 'V3V3': -3, 'GND': -4
},
pinCapabilities: {
pwm: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
analog: [14, 15, 16, 17, 18, 19, 20, 21],
digital: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
i2c: [18, 19], spi: [10, 11, 12, 13], serial: [0, 1]
},
libraries: ['WiFi', 'WiFiClient', 'WiFiServer', 'WiFiUDP', 'BluetoothSerial', 'BLE', 'Wire',
'SPI', 'Servo', 'Stepper', 'EEPROM', 'SD', 'Adafruit_NeoPixel', 'FastLED', 'ArduinoJson',
'PubSubClient', 'HTTPClient', 'WebServer', 'Update', 'Preferences'],
clocks: { 'CPU_FREQ': '240000000', 'APB_FREQ': '80000000', 'XTAL_FREQ': '40000000' },
memory: { 'FLASH_START': '0x10000', 'RAM_START': '0x3FC88000', 'PSRAM_START': '0x3F800000' }
};
const ARDUINO_UNO_PLATFORM = {
name: 'ARDUINO_UNO', displayName: 'Arduino Uno',
defines: { 'ARDUINO_AVR_UNO': '1', 'ARDUINO': '2030100', 'ATMEGA328P': '1' },
pins: {
'D0': 0, 'D1': 1, 'D2': 2, 'D3': 3, 'D4': 4, 'D5': 5, 'D6': 6, 'D7': 7, 'D8': 8,
'D9': 9, 'D10': 10, 'D11': 11, 'D12': 12, 'D13': 13, 'A0': 14, 'A1': 15, 'A2': 16,
'A3': 17, 'A4': 18, 'A5': 19, 'LED_BUILTIN': 13, 'SDA': 18, 'SCL': 19, 'MOSI': 11,
'MISO': 12, 'SCK': 13, 'SS': 10, 'TX': 1, 'RX': 0
},
pinCapabilities: {
pwm: [3, 5, 6, 9, 10, 11], analog: [14, 15, 16, 17, 18, 19],
digital: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
i2c: [18, 19], spi: [10, 11, 12, 13], serial: [0, 1]
},
libraries: ['SoftwareSerial', 'Wire', 'SPI', 'Servo', 'Stepper', 'EEPROM', 'LiquidCrystal', 'SD'],
clocks: { 'CPU_FREQ': '16000000' }
};
class PlatformEmulation {
constructor(platformName = 'ESP32_NANO') {
this.version = PLATFORM_EMULATION_VERSION;
this.currentPlatform = null;
this.availablePlatforms = { 'ESP32_NANO': ESP32_NANO_PLATFORM, 'ARDUINO_UNO': ARDUINO_UNO_PLATFORM };
this.setPlatform(platformName);
}
setPlatform(platformName) {
if (!this.availablePlatforms[platformName]) {
throw new Error(`Platform '${platformName}' not supported. Available: ${Object.keys(this.availablePlatforms).join(', ')}`);
}
this.currentPlatform = this.availablePlatforms[platformName];
return this.currentPlatform;
}
getDefines() { return { ...this.currentPlatform.defines }; }
getPin(pinName) { return this.currentPlatform.pins[pinName] || null; }
pinSupports(pin, capability) { const caps = this.currentPlatform.pinCapabilities[capability]; return caps && caps.includes(pin); }
getLibraries() { return [...this.currentPlatform.libraries]; }
hasLibrary(libraryName) { return this.currentPlatform.libraries.includes(libraryName); }
getPlatformInfo() {
return {
name: this.currentPlatform.name, displayName: this.currentPlatform.displayName,
defines: Object.keys(this.currentPlatform.defines).length, pins: Object.keys(this.currentPlatform.pins).length,
libraries: this.currentPlatform.libraries.length, capabilities: Object.keys(this.currentPlatform.pinCapabilities)
};
}
}
// =============================================================================
// ARDUINO PREPROCESSOR SYSTEM (integrated from preprocessor.js)
// =============================================================================
const LIBRARY_INCLUDES = {
'Adafruit_NeoPixel.h': { library: 'Adafruit_NeoPixel', constants: { 'NEO_GRB': '0x52', 'NEO_RGB': '0x20', 'NEO_RGBW': '0x28', 'NEO_KHZ800': '0x0000', 'NEO_KHZ400': '0x0100' }, activate: true },
'Servo.h': { library: 'Servo', constants: {}, activate: true },
'SPI.h': { library: 'SPI', constants: { 'MSBFIRST': '1', 'LSBFIRST': '0', 'SPI_MODE0': '0', 'SPI_MODE1': '1', 'SPI_MODE2': '2', 'SPI_MODE3': '3' }, activate: true },
'Wire.h': { library: 'Wire', constants: {}, activate: true },
'EEPROM.h': { library: 'EEPROM', constants: {}, activate: true },
'avr/power.h': { constants: { 'clock_div_1': '0x00', 'clock_div_2': '0x01', 'clock_div_4': '0x02', 'clock_div_8': '0x03', 'clock_div_16': '0x04', 'clock_div_32': '0x05', 'clock_div_64': '0x06', 'clock_div_128': '0x07', 'clock_div_256': '0x08' } },
'Arduino.h': { constants: { 'HIGH': '1', 'LOW': '0', 'INPUT': '0', 'OUTPUT': '1', 'INPUT_PULLUP': '2', 'LED_BUILTIN': '13' } }
};
class ArduinoPreprocessor {
constructor(options = {}) {
this.options = { verbose: options.verbose || false, debug: options.debug || false, platformDefines: options.platformDefines || ['ARDUINO', '__AVR__'], platformContext: options.platformContext || null, ...options };
this.macros = new Map(); this.functionMacros = new Map(); this.activeLibraries = new Set(); this.libraryConstants = new Map(); this.conditionalStack = [];
this.initializeDefaultMacros();
}
initializeDefaultMacros() {
this.macros.set('HIGH', '1'); this.macros.set('LOW', '0'); this.macros.set('INPUT', '0'); this.macros.set('OUTPUT', '1'); this.macros.set('INPUT_PULLUP', '2'); this.macros.set('LED_BUILTIN', '13'); this.macros.set('PI', '3.14159');
if (this.options.platformContext) {
const platformDefines = this.options.platformContext.getDefines();
Object.entries(platformDefines).forEach(([key, value]) => { this.macros.set(key, String(value)); });
} else {
this.macros.set('ARDUINO_ARCH_AVR', '1'); this.macros.set('F_CPU', '16000000UL'); this.macros.set('ARDUINO_API_VERSION', '10001');
this.macros.set('MOSI', '11'); this.macros.set('MISO', '12'); this.macros.set('SCK', '13');
this.options.platformDefines.forEach(define => { this.macros.set(define, '1'); });
}
}
preprocess(sourceCode) {
try {
let processedCode = this.processIncludes(sourceCode);
processedCode = this.processDefines(processedCode); processedCode = this.processConditionals(processedCode); processedCode = this.performMacroSubstitution(processedCode);
return { processedCode, activeLibraries: Array.from(this.activeLibraries), libraryConstants: Object.fromEntries(this.libraryConstants), macros: Object.fromEntries(this.macros), functionMacros: Object.fromEntries(this.functionMacros) };
} catch (error) {
return { processedCode: sourceCode, activeLibraries: [], libraryConstants: {}, macros: Object.fromEntries(this.macros), functionMacros: {}, error: error.message };
}
}
processIncludes(code) { const includeRegex = /#include\s*[<"]([^>"]+)[>"]/g; let processedCode = code; let match; includeRegex.lastIndex = 0; while ((match = includeRegex.exec(code)) !== null) { const includeFile = match[1]; const fullInclude = match[0]; if (LIBRARY_INCLUDES[includeFile]) { const config = LIBRARY_INCLUDES[includeFile]; if (config.activate && config.library) { this.activeLibraries.add(config.library); } Object.entries(config.constants || {}).forEach(([name, value]) => { this.macros.set(name, value); this.libraryConstants.set(name, value); }); } processedCode = processedCode.replace(fullInclude, ''); } return processedCode; }
processDefines(code) { const lines = code.split('\n'); const processedLines = []; for (let i = 0; i < lines.length; i++) { const line = lines[i]; const trimmed = line.trim(); if (trimmed.startsWith('#define')) { this.processDefineDirective(trimmed); } else if (trimmed.startsWith('#undef')) { this.processUndefDirective(trimmed); } else { processedLines.push(line); } } return processedLines.join('\n'); }
processDefineDirective(defineLine) { const content = defineLine.substring(7).trim(); const functionMacroMatch = content.match(/^([A-Z_][A-Z0-9_]*)\s*\(([^)]*)\)\s+(.+)$/i); if (functionMacroMatch) { const name = functionMacroMatch[1]; const paramsStr = functionMacroMatch[2].trim(); const body = functionMacroMatch[3].trim(); const params = paramsStr ? paramsStr.split(',').map(p => p.trim()) : []; this.functionMacros.set(name, { params: params, body: body }); } else { const parts = content.match(/^([A-Z_][A-Z0-9_]*)\s+(.+)$/i); if (parts) { const name = parts[1]; const value = parts[2].trim(); this.macros.set(name, value); } else { const nameMatch = content.match(/^([A-Z_][A-Z0-9_]*)$/i); if (nameMatch) { const name = nameMatch[1]; this.macros.set(name, '1'); } } } }
processUndefDirective(undefLine) { const macroName = undefLine.substring(6).trim(); if (this.macros.has(macroName)) { this.macros.delete(macroName); } if (this.functionMacros.has(macroName)) { this.functionMacros.delete(macroName); } }
processConditionals(code) { const lines = code.split('\n'); const processedLines = []; let skipLines = false; let conditionalDepth = 0; for (let i = 0; i < lines.length; i++) { const line = lines[i]; const trimmed = line.trim(); if (trimmed.startsWith('#ifdef')) { const macro = trimmed.substring(6).trim(); conditionalDepth++; skipLines = !this.macros.has(macro); } else if (trimmed.startsWith('#ifndef')) { const macro = trimmed.substring(7).trim(); conditionalDepth++; skipLines = this.macros.has(macro); } else if (trimmed.startsWith('#endif')) { conditionalDepth--; if (conditionalDepth === 0) { skipLines = false; } } else if (trimmed.startsWith('#else')) { skipLines = !skipLines; } else if (trimmed.startsWith('#if ')) { const expression = trimmed.substring(3).trim(); conditionalDepth++; try { let evalExpression = expression; evalExpression = evalExpression.replace(/defined\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)/g, (match, macroName) => { return this.macros.has(macroName) ? '1' : '0'; }); for (const [macro, value] of this.macros) { const regex = new RegExp(`\\b${macro}\\b`, 'g'); evalExpression = evalExpression.replace(regex, value); } evalExpression = evalExpression.replace(/\b[A-Za-z_][A-Za-z0-9_]*\b/g, (match) => { if (/^[0-9]/.test(match) || ['&&', '||', '==', '!=', '>', '<', '>=', '<='].includes(match)) { return match; } return '0'; }); const result = eval(evalExpression); skipLines = !result; } catch (error) { skipLines = false; } } else { if (!skipLines) { processedLines.push(line); } } } return processedLines.join('\n'); }
performMacroSubstitution(code) { let substitutedCode = code; for (const [macroName, macroValue] of this.macros) { const regex = new RegExp(`\\b${macroName}\\b`, 'g'); substitutedCode = substitutedCode.replace(regex, macroValue); } for (const [macroName, macroInfo] of this.functionMacros) { const { params, body } = macroInfo; const regex = new RegExp(`\\b${macroName}\\s*\\(([^)]*)\\)`, 'g'); substitutedCode = substitutedCode.replace(regex, (match, argsStr) => { const args = argsStr ? argsStr.split(',').map(arg => arg.trim()) : []; let expandedBody = body; for (let i = 0; i < params.length && i < args.length; i++) { const paramRegex = new RegExp(`\\b${params[i]}\\b`, 'g'); expandedBody = expandedBody.replace(paramRegex, args[i]); } return expandedBody; }); } return substitutedCode; }
getStats() { return { version: PREPROCESSOR_VERSION, macros: this.macros.size, functionMacros: this.functionMacros.size, activeLibraries: this.activeLibraries.size, libraryConstants: this.libraryConstants.size }; }
}
// Import Arduino Preprocessor - now available internally
function getArduinoPreprocessor() { return ArduinoPreprocessor; }
// =============================================================================
// KEYWORD MAPPINGS - Maps source code keywords to token types
// =============================================================================
const KEYWORDS = {
// Primitive data types
'void': 'VOID', 'int': 'INT', 'long': 'LONG', 'float': 'FLOAT', 'double': 'DOUBLE',
'char': 'CHAR', 'short': 'SHORT', 'bool': 'BOOL', 'boolean': 'BOOLEAN', 'byte': 'BYTE',
'size_t': 'SIZE_T', 'word': 'WORD', 'unsigned': 'UNSIGNED', 'signed': 'SIGNED',
// Arduino-specific types and classes
'String': 'STRING', 'Servo': 'SERVO', 'LiquidCrystal': 'LIQUID_CRYSTAL',
// Standard integer types (stdint.h)
'uint8_t': 'UINT8_T', 'int8_t': 'INT8_T', 'uint16_t': 'UINT16_T', 'int16_t': 'INT16_T',
'uint32_t': 'UINT32_T', 'int32_t': 'INT32_T', 'uint64_t': 'UINT64_T', 'int64_t': 'INT64_T',
// Storage class specifiers
'const': 'CONST', 'static': 'STATIC', 'volatile': 'VOLATILE', 'extern': 'EXTERN',
'PROGMEM': 'PROGMEM', // Arduino-specific: store data in flash memory
// Structure and type keywords
'struct': 'STRUCT', 'typedef': 'TYPEDEF', 'enum': 'ENUM', 'union': 'UNION',
'class': 'CLASS', 'template': 'TEMPLATE', 'typename': 'TYPENAME', 'auto': 'AUTO',
// Access specifiers
'public': 'PUBLIC', 'private': 'PRIVATE', 'protected': 'PROTECTED',
// C++ specifiers and keywords
'virtual': 'VIRTUAL', 'override': 'OVERRIDE', 'final': 'FINAL',
'constexpr': 'CONSTEXPR', 'decltype': 'DECLTYPE', 'explicit': 'EXPLICIT',
'mutable': 'MUTABLE', 'inline': 'INLINE', 'noexcept': 'NOEXCEPT',
'nullptr': 'NULLPTR', 'friend': 'FRIEND', 'operator': 'OPERATOR',
'new': 'NEW', 'delete': 'DELETE',
'static_cast': 'STATIC_CAST', 'dynamic_cast': 'DYNAMIC_CAST', 'const_cast': 'CONST_CAST', 'reinterpret_cast': 'REINTERPRET_CAST',
'namespace': 'NAMESPACE', 'using': 'USING',
// Control flow keywords
'if': 'IF', 'else': 'ELSE', 'for': 'FOR', 'while': 'WHILE', 'do': 'DO',
'return': 'RETURN', 'break': 'BREAK', 'continue': 'CONTINUE',
'switch': 'SWITCH', 'case': 'CASE', 'default': 'DEFAULT', 'goto': 'GOTO',
// Literal values
'true': 'TRUE', 'false': 'FALSE', 'NULL': 'NULL',
// Arduino constants
'HIGH': 'HIGH', 'LOW': 'LOW', 'INPUT': 'INPUT', 'OUTPUT': 'OUTPUT',
'INPUT_PULLUP': 'INPUT_PULLUP', 'INPUT_PULLDOWN': 'INPUT_PULLDOWN',
'OUTPUT_OPENDRAIN': 'OUTPUT_OPENDRAIN', 'LED_BUILTIN': 'LED_BUILTIN',
// Number format specifiers
'HEX': 'HEX', 'DEC': 'DEC', 'OCT': 'OCT', 'BIN': 'BIN',
// Operators and special keywords
'sizeof': 'SIZEOF',
// Arduino built-in functions
'digitalRead': 'ARDUINO_FUNC', 'digitalWrite': 'ARDUINO_FUNC', 'pinMode': 'ARDUINO_FUNC',
'analogRead': 'ARDUINO_FUNC', 'analogWrite': 'ARDUINO_FUNC', 'analogReference': 'ARDUINO_FUNC',
'analogReadResolution': 'ARDUINO_FUNC', 'analogWriteResolution': 'ARDUINO_FUNC',
'tone': 'ARDUINO_FUNC', 'noTone': 'ARDUINO_FUNC', 'pulseIn': 'ARDUINO_FUNC', 'pulseInLong': 'ARDUINO_FUNC',
'shiftIn': 'ARDUINO_FUNC', 'shiftOut': 'ARDUINO_FUNC',
'delay': 'ARDUINO_FUNC', 'delayMicroseconds': 'ARDUINO_FUNC', 'millis': 'ARDUINO_FUNC', 'micros': 'ARDUINO_FUNC',
'map': 'ARDUINO_FUNC', 'constrain': 'ARDUINO_FUNC', 'min': 'ARDUINO_FUNC', 'max': 'ARDUINO_FUNC',
'abs': 'ARDUINO_FUNC', 'sq': 'ARDUINO_FUNC', 'sqrt': 'ARDUINO_FUNC', 'pow': 'ARDUINO_FUNC',
'sin': 'ARDUINO_FUNC', 'cos': 'ARDUINO_FUNC', 'tan': 'ARDUINO_FUNC',
'random': 'ARDUINO_FUNC', 'randomSeed': 'ARDUINO_FUNC',
'attachInterrupt': 'ARDUINO_FUNC', 'detachInterrupt': 'ARDUINO_FUNC',
'interrupts': 'ARDUINO_FUNC', 'noInterrupts': 'ARDUINO_FUNC'
};
// =============================================================================
// CENTRALIZED TYPE MANAGEMENT SYSTEM - Comprehensive type classification
// =============================================================================
// Type categories for systematic and consistent type checking
const TYPE_CATEGORIES = {
// Fundamental C/C++ types
FUNDAMENTAL: ['INT', 'CHAR', 'FLOAT', 'DOUBLE', 'VOID', 'BOOL', 'BOOLEAN'],
// Standard library types (stddef.h, stdint.h, etc.)
STDLIB: ['SIZE_T', 'PTRDIFF_T', 'WCHAR_T'],
// Fixed-width integer types (stdint.h)
FIXED_WIDTH: ['UINT8_T', 'INT8_T', 'UINT16_T', 'INT16_T', 'UINT32_T', 'INT32_T', 'UINT64_T', 'INT64_T'],
// Arduino-specific types
ARDUINO: ['STRING', 'BYTE', 'WORD', 'SERVO', 'LIQUID_CRYSTAL'],
// Type modifiers and storage classes
MODIFIERS: ['CONST', 'VOLATILE', 'STATIC', 'EXTERN', 'UNSIGNED', 'SIGNED'],
// Additional type keywords
EXTENDED: ['LONG', 'SHORT', 'AUTO'],
// C++ specific specifiers
CXX_SPECIFIERS: ['VIRTUAL', 'OVERRIDE', 'FINAL', 'CONSTEXPR', 'EXPLICIT', 'MUTABLE', 'INLINE']
};
// Flatten all type categories for quick lookup
const ALL_TYPES = Object.values(TYPE_CATEGORIES).flat();
/**
* Centralized type checking function - replaces all hardcoded type arrays
* @param {string} tokenType - The token type to check
* @param {string} context - The parsing context ('declaration', 'cast', 'parameter', 'any')
* @returns {boolean} True if the token is a valid type in the given context
*/
function isValidType(tokenType, context = 'any') {
// Always include identifiers as potential custom types
if (tokenType === 'IDENTIFIER') return true;
// Check if it's a known type
const isKnownType = ALL_TYPES.includes(tokenType);
switch (context) {
case 'declaration':
// Variable declarations - all types except some C++ specifiers
return isKnownType && !TYPE_CATEGORIES.CXX_SPECIFIERS.includes(tokenType);
case 'cast':
// Cast expressions - fundamental types + stdlib + fixed-width + arduino + type modifiers
return TYPE_CATEGORIES.FUNDAMENTAL.includes(tokenType) ||
TYPE_CATEGORIES.STDLIB.includes(tokenType) ||
TYPE_CATEGORIES.FIXED_WIDTH.includes(tokenType) ||
TYPE_CATEGORIES.ARDUINO.includes(tokenType) ||
TYPE_CATEGORIES.EXTENDED.includes(tokenType) ||
['UNSIGNED', 'SIGNED', 'CONST', 'VOLATILE'].includes(tokenType) || // Allow type modifiers for multi-word casts
tokenType === 'IDENTIFIER';
case 'parameter':
// Function parameters - all types
return isKnownType;
case 'any':
default:
// General type checking - all types
return isKnownType;
}
}
/**
* Check if a token is a type modifier (const, volatile, etc.)
* @param {string} tokenType - The token type to check
* @returns {boolean} True if the token is a type modifier
*/
function isTypeModifier(tokenType) {
return TYPE_CATEGORIES.MODIFIERS.includes(tokenType);
}
/**
* Check if a token is a storage class specifier
* @param {string} tokenType - The token type to check
* @returns {boolean} True if the token is a storage class specifier
*/
function isStorageClass(tokenType) {
return ['STATIC', 'EXTERN', 'VOLATILE'].includes(tokenType);
}
// =============================================================================
// OPERATOR PRECEDENCE TABLE - Defines operator parsing priority (higher = more precedence)
// =============================================================================
const PRECEDENCE = {
'COMMA': 0, // Lowest precedence
'OR': 1,
'AND': 2,
'BITWISE_OR': 3,
'BITWISE_XOR': 4,
'BITWISE_AND': 5,
'AMPERSAND': 5, // Bitwise AND (same precedence as BITWISE_AND)
'EQ': 6, 'NEQ': 6,
'LT': 7, 'GT': 7, 'LTE': 7, 'GTE': 7,
'LSHIFT': 8, 'RSHIFT': 8,
'PLUS': 9, 'MINUS': 9,
'MUL': 10, 'DIV': 10, 'MOD': 10,
// Unary operators handled separately
};
/**
* Arduino/C++ Parser class for parsing Arduino source code into Abstract Syntax Trees
*
* @class Parser
* @description Comprehensive parser supporting Arduino/C++ syntax including:
* - Function definitions and declarations
* - Variable declarations with all C++ types
* - Control structures (if/else, for, while, switch)
* - Classes and constructors
* - Expressions and operators
* - Arduino-specific constants and functions
*/
class Parser {
/**
* Creates a new Parser instance
*
* @param {string} code - The Arduino/C++ source code to parse
* @param {Object} options - Parser configuration options
* @param {boolean} options.verbose - Enable verbose output and analysis
* @param {boolean} options.throwOnError - Throw errors instead of graceful recovery
*/
constructor(code, options = {}) {
this.code = code;
this.options = options;
this.position = 0;
this.currentChar = this.code[this.position];
this.line = 1;
this.column = 1;
this.currentToken = null;
this.peekToken = null;
this.peekToken2 = null;
// Prime the tokens
this.advanceToken();
this.advanceToken();
this.advanceToken();
}
// Advance the parser's position
advance() {
if (this.currentChar === '\n') {
this.line++;
this.column = 1;
} else {
this.column++;
}
this.position++;
this.currentChar = this.position < this.code.length ? this.code[this.position] : null;
}
// A version of eat that consumes a character, not a token
eatChar(char) {
if (this.currentChar === char) {
this.advance();
} else {
throw new Error(`Lexer Error on line ${this.line}, column ${this.column}: Expected character '${char}' but found '${this.currentChar || 'EOF'}'`);
}
}
// Look at the next character without consuming it
peek() {
const peekPos = this.position + 1;
return peekPos < this.code.length ? this.code[peekPos] : null;
}
// Advance the tokens, maintaining the lookahead buffer
advanceToken() {
this.currentToken = this.peekToken;
this.peekToken = this.peekToken2;
this.peekToken2 = this.getNextToken();
}
// Consume a token of a specific type
eat(tokenType) {
if (this.currentToken.type === tokenType) {
this.advanceToken();
} else {
// Special handling for SEMICOLON with problematic tokens
if (tokenType === 'SEMICOLON' && ['PRIVATE', 'PUBLIC', 'PROTECTED', 'RETURN'].includes(this.currentToken.type)) {
// Skip the problematic token and continue
this.advanceToken();
// Try to find the next semicolon or give up gracefully
while (this.currentToken.type !== 'EOF' &&
this.currentToken.type !== 'SEMICOLON' &&
this.currentToken.type !== 'RBRACE') {
this.advanceToken();
}
if (this.currentToken.type === 'SEMICOLON') {
this.advanceToken(); // consume the semicolon we found
}
return; // Successfully recovered
}
const { line, column } = this.currentToken;
throw new Error(`Parsing Error on line ${line}, column ${column}: Expected token type '${tokenType}' but found '${this.currentToken.type}' (value: '${this.currentToken.value}')`);
}
}
// Skip over any whitespace
skipWhitespace() {
while (this.currentChar !== null && /\s/.test(this.currentChar)) {
this.advance();
}
}
// Skip over comments
skipComments() {
if (this.currentChar === '/' && this.peek() === '/') {
while (this.currentChar !== null && this.currentChar !== '\n') {
this.advance();
}
return true;
}
if (this.currentChar === '/' && this.peek() === '*') {
this.advance(); // consume /
this.advance(); // consume *
while (this.currentChar !== null && !(this.currentChar === '*' && this.peek() === '/')) {
this.advance();
}
this.eatChar('*');
this.eatChar('/');
return true;
}
return false;
}
// Parse a string literal
stringLiteral() {
let result = '';
const startLine = this.line;
const startColumn = this.column;
this.eatChar('"'); // consume opening "
// Enhanced parsing for HTML-friendly strings
const webFriendlyMode = this.options.webFriendlyMode || false;
while (this.currentChar !== null && this.currentChar !== '"') {
if (this.currentChar === '\\') {
this.advance(); // consume backslash
if (this.currentChar !== null) {
// Handle escape sequences - enhanced for web content
switch (this.currentChar) {
case 'n': result += '\n'; break;
case 't': result += '\t'; break;
case 'r': result += '\r'; break;
case '\\': result += '\\'; break;
case '"': result += '"'; break;
case "'": result += "'"; break;
case '/': result += '/'; break; // Common in HTML/URLs
case 'b': result += '\b'; break; // Backspace
case 'f': result += '\f'; break; // Form feed
case 'v': result += '\v'; break; // Vertical tab
case '\n':
// Line continuation: backslash followed by newline
// The newline is consumed but not added to the string
this.advance(); // consume the newline
continue; // Continue loop without adding anything to result
case '\r':
// Handle Windows-style line endings for line continuation
this.advance(); // consume the \r
if (this.currentChar === '\n') {
this.advance(); // consume the \n as well
}
continue; // Continue loop without adding anything to result
default:
// In web-friendly mode, be more permissive with escape sequences
if (webFriendlyMode) {
result += this.currentChar;
} else {
result += this.currentChar;
}
break;
}
this.advance();
}
} else if (this.currentChar === '\n') {
// Handle multi-line strings better - common in HTML
if (webFriendlyMode) {
result += this.currentChar;
this.advance();
} else {
// Standard C++ doesn't allow unescaped newlines in strings
throw new Error(`Lexer Error on line ${this.line}, column ${this.column}: Unescaped newline in string literal`);
}
} else {
result += this.currentChar;
this.advance();
}
}
// Enhanced error handling for unterminated strings
if (this.currentChar !== '"') {
if (webFriendlyMode) {
// In web-friendly mode, try to recover gracefully
if (this.options && this.options.verbose) {
console.warn(`Warning: Unterminated string literal starting at line ${startLine}, column ${startColumn}. Attempting recovery.`);
}
return { type: 'STRING_LITERAL', value: result, unterminated: true };
} else {
throw new Error(`Lexer Error on line ${startLine}, column ${startColumn}: Expected character '"' but found 'EOF'`);
}
}
this.eatChar('"'); // consume closing "
return { type: 'STRING_LITERAL', value: result };
}
// Parse a C++11 raw string literal: R"delimiter(content)delimiter"
rawStringLiteral() {
const startLine = this.line;
const startColumn = this.column;
// Consume 'R"'
this.advance(); // consume 'R'
this.advance(); // consume '"'
// Parse the delimiter (up to 16 characters, until we hit '(')
let delimiter = '';
while (this.currentChar !== null && this.currentChar !== '(' && delimiter.length < 16) {
delimiter += this.currentChar;
this.advance();
}
if (this.currentChar !== '(') {
throw new Error(`Lexer Error on line ${this.line}, column ${this.column}: Expected '(' in raw string literal`);
}
this.advance(); // consume '('
// Parse the content until we find ')delimiter"'
let content = '';
const endPattern = ')' + delimiter + '"';
let matchIndex = 0;
while (this.currentChar !== null) {
if (this.currentChar === endPattern[matchIndex]) {
matchIndex++;
if (matchIndex === endPattern.length) {
// Found complete end pattern - already consumed by loop advance
break;
}
} else {
// If we were partially matching, add the partial match to content
if (matchIndex > 0) {
content += endPattern.substring(0, matchIndex);
matchIndex = 0;
}
// Add current character to content if it's not starting a new match
if (this.currentChar !== endPattern[0]) {
content += this.currentChar;
} else {
matchIndex = 1; // Start matching from the first character
}
}
this.advance();
}
if (matchIndex < endPattern.length) {
// Handle unterminated raw string
const webFriendlyMode = this.options && this.options.webFriendlyMode;
if (webFriendlyMode) {
if (this.options && this.options.verbose) {
console.warn(`Warning: Unterminated raw string literal starting at line ${startLine}, column ${startColumn}. Expected closing pattern: ${endPattern}`);
}
return { type: 'STRING_LITERAL', value: content, unterminated: true, rawString: true, delimiter: delimiter };
} else {
throw new Error(`Lexer Error on line ${startLine}, column ${startColumn}: Unterminated raw string literal. Expected closing pattern: ${endPattern}`);
}
}
return { type: 'STRING_LITERAL', value: content, rawString: true, delimiter: delimiter };
}
// Parse a character literal
charLiteral() {
this.eatChar("'"); // consume opening '
let result = '';
// Handle potentially multi-character sequences in char literals
while (this.currentChar !== "'" && this.currentChar !== null) {
if (this.currentChar === '\\') {
this.advance(); // consume backslash
// Handle escape sequences
switch (this.currentChar) {
case 'n': result += '\n'; break;
case 't': result += '\t'; break;
case 'r': result += '\r'; break;
case '\\': result += '\\'; break;
case "'": result += "'"; break;
case '"': result += '"'; break;
case '0': result += '\0'; break; // null character
case 'b': result += '\b'; break; // backspace
case 'f': result += '\f'; break; // form feed
case 'v': result += '\v'; break; // vertical tab
default: result += this.currentChar; break;
}
this.advance();
} else {
result += this.currentChar;
this.advance();
}
}
this.eatChar("'"); // consume closing '
// For standard character literals, should be single character
// But we'll allow multi-character for Arduino compatibility
return { type: 'CHAR_LITERAL', value: result };
}
// 4. Updated number() method to handle octal, binary, and scientific notation
number() {
let result = '';
// Check for hex prefix
if (this.currentChar === '0' && (this.peek() === 'x' || this.peek() === 'X')) {
result += this.currentChar; // '0'
this.advance();
result += this.currentChar; // 'x'
this.advance();
while (this.currentChar !== null && /[0-9a-fA-F]/.test(this.currentChar)) {
result += this.currentChar;
this.advance();
}
// Handle numeric suffixes for hex
let suffix = '';
while (this.currentChar !== null && /[LlUu]/.test(this.currentChar)) {
suffix += this.currentChar;
this.advance();
}
return { type: 'HEX_NUMBER', value: parseInt(result, 16), suffix: suffix };
}
// Check for octal prefix (0 followed by digits)
if (this.currentChar === '0' && /[0-7]/.test(this.peek())) {
result += this.currentChar; // '0'
this.advance();
while (this.currentChar !== null && /[0-7]/.test(this.currentChar)) {
result += this.currentChar;
this.advance();
}
// Handle numeric suffixes for octal
let suffix = '';
while (this.currentChar !== null && /[LlUu]/.test(this.currentChar)) {
suffix += this.currentChar;
this.advance();
}
return { type: 'OCTAL_NUMBER', value: parseInt(result, 8), suffix: suffix };
}
// Check for binary prefix
if (this.currentChar === '0' && (this.peek() === 'b' || this.peek() === 'B')) {
result += this.currentChar; // '0'
this.advance();
result += this.currentChar; // 'b'
this.advance();
while (this.currentChar !== null && /[01]/.test(this.currentChar)) {
result += this.currentChar;
this.advance();
}
// Handle numeric suffixes for binary
let suffix = '';
while (this.currentChar !== null && /[LlUu]/.test(this.currentChar)) {
suffix += this.currentChar;
this.advance();
}
return { type: 'BINARY_NUMBER', value: parseInt(result.substring(2), 2), suffix: suffix }; // Use substring to parse
}
// Parse regular numbers
while (this.currentChar !== null && /\d/.test(this.currentChar)) {
result += this.currentChar;
this.advance();
}
// Handle floating point numbers
if (this.currentChar === '.' && this.peek() && /\d/.test(this.peek())) {
result += '.';
this.advance();
while (this.currentChar !== null && /\d/.test(this.currentChar)) {
result += this.currentChar;
this.advance();
}
// Handle scientific notation
if (this.currentChar === 'e' || this.currentChar === 'E') {
result += this.currentChar;
this.advance();
if (this.currentChar === '+' || this.currentChar === '-') {
result += this.currentChar;
this.advance();
}
while (this.currentChar !== null && /\d/.test(this.currentChar)) {
result += this.currentChar;
this.advance();
}
}
// Handle numeric suffixes for floating point numbers
let suffix = '';
while (this.currentChar !== null && /[LlUufF]/.test(this.currentChar)) {
suffix += this.currentChar;
this.advance();
}
return { type: 'FLOAT_NUMBER', value: parseFloat(result), suffix: suffix };
}
// Handle numeric suffixes (L, U, LL, UL, f, F, etc.)
let suffix = '';
while (this.currentChar !== null && /[LlUufF]/.test(this.currentChar)) {
suffix += this.currentChar;
this.advance();
}
if (suffix) {
// If suffix contains 'f' or 'F', treat as float
if (/[fF]/.test(suffix)) {
return { type: 'FLOAT_NUMBER', value: parseFloat(result), suffix: suffix };
} else {
return { type: 'NUMBER', value: Number(result), suffix: suffix };
}
}
return { type: 'NUMBER', value: Number(result) };
}
// Parse floating point numbers that start with a dot (e.g., .5)
floatFromDot() {
let result = '';
if (this.currentChar === '.') {
result += '.';
this.advance();
while (this.currentChar !== null && /\d/.test(this.currentChar)) {
result += this.currentChar;
this.advance();
}
// Handle numeric suffixes for floating point numbers starting with dot
let suffix = '';
while (this.currentChar !== null && /[LlUufF]/.test(this.currentChar)) {
suffix += this.currentChar;
this.advance();
}
return { type: 'FLOAT_NUMBER', value: parseFloat(result), suffix: suffix };
}
return { type: 'DOT', value: '.' };
}
// Parse an identifier or keyword
identifier() {
let result = '';
while (this.currentChar !== null && /[a-zA-Z0-9_]/.test(this.currentChar)) {
result += this.currentChar;
this.advance();
}
// Check if Arduino function recognition is disabled
// Use hasOwnProperty to avoid prototype pollution (toString, valueOf, etc.)
let tokenType = (KEYWORDS.hasOwnProperty(result) ? KEYWORDS[result] : null) || 'IDENTIFIER';
if (!this.options.recognizeArduinoFunctions && tokenType === 'ARDUINO_FUNC') {
tokenType = 'IDENTIFIER';
}
return { type: tokenType, value: result };
}
// The on-demand lexer
getNextToken() {
while (this.currentChar !== null) {
const line = this.line;
const column = this.column;
if (/\s/.test(this.currentChar)) {
this.skipWhitespace();
continue;
}
if (this.currentChar === '/' && (this.peek() === '/' || this.peek() === '*')) {
this.skipComments();
continue;
}
// Preprocessor directives (#) should not appear in preprocessed code
if (this.currentChar === '#') {
throw new Error(`Unexpected preprocessor directive at line ${line}, column ${column}. All preprocessor directives should be handled before parsing.`);
}
if (this.currentChar === '"') {
return { ...this.stringLiteral(), line, column };
}
if (this.currentChar === "'") {
return { ...this.charLiteral(), line, column };
}
// 3. Added new multi-character operators
// Handle multi-character operators first
if (this.currentChar === '=' && this.peek() === '=') {
this.advance(); this.advance();
return { type: 'EQ', value: '==', line, column };
}
if (this.currentChar === '!' && this.peek() === '=') {
this.advance(); this.advance();
return { type: 'NEQ', value: '!=', line, column };
}
if (this.currentChar === '<' && this.peek() === '=') {
this.advance(); this.advance();
return { type: 'LTE', value: '<=', line, column };
}
if (this.currentChar === '>' && this.peek() === '=') {
this.advance(); this.advance();
return { type: 'GTE', value: '>=', line, column };
}
if (this.currentChar === '&' && this.peek() === '&') {
this.advance(); this.advance();
return { type: 'AND', value: '&&', line, column };
}
if (this.currentChar === '|' && this.peek() === '|') {
this.advance(); this.advance();
return { type: 'OR', value: '||', line, column };
}
if (this.currentChar === '+' && this.peek() === '=') {
this.advance(); this.advance();
return { type: 'PLUS_ASSIGN', value: '+=', line, column };
}
if (this.currentChar === '-' && this.peek() === '=') {
this.advance(); this.advance();
return { type: 'MINUS_ASSIGN', value: '-=', line, column };
}
if (this.currentChar === '+' && this.peek() === '+') {
this.advance(); this.advance();
return { type: 'PLUS_PLUS', value: '++', line, column };
}
if (this.currentChar === '-' && this.peek() === '-') {
this.advance(); this.advance();
return { type: 'MINUS_MINUS', value: '--', line, column };
}
// Handle shift assignment operators BEFORE regular shift operators
if (this.currentChar === '<' && this.peek() === '<') {
// Look ahead to see if this is <<=
const savedPos = this.position;
const savedChar = this.currentChar;
const savedLine = this.line;
const savedColumn = this.column;
this.advance(); this.advance(); // Skip <<
if (this.currentChar === '=') {
this.advance(); // Skip =
return { type: 'LSHIFT_ASSIGN', value: '<<=', line, column };
} else {
// Restore position for regular << handling
this.position = savedPos;
this.currentChar = savedChar;
this.line = savedLine;
this.column = savedColumn;
// Now handle regular <<
this.advance(); this.advance();
return { type: 'LSHIFT', value: '<<', line, column };
}
}
if (this.currentChar === '>' && this.peek() === '>') {
// Look ahead to see if this is >>=
const savedPos = this.position;
const savedChar = this.currentChar;
const savedLine = this.line;
const savedColumn = this.column;
this.advance(); this.advance(); // Skip >>
if (this.currentChar === '=') {
this.advance(); // Skip =
return { type: 'RSHIFT_ASSIGN', value: '>>=', line, column };
} else {
// Restore position for regular >> handling
this.position = savedPos;
this.currentChar = savedChar;
this.line = savedLine;
this.column = savedColumn;
// Now handle regular >>
this.advance(); this.advance();
return { type: 'RSHIFT', value: '>>', line, column };
}
}
if (this.currentChar === '*' && this.peek() === '=') { this.advance(); this.advance(); return { type: 'MUL_ASSIGN', value: '*=', line, column }; }
if (this.currentChar === '/' && this.peek() === '=') { this.advance(); this.advance(); return { type: 'DIV_ASSIGN', value: '/=', line, column }; }
if (this.currentChar === '%' && this.peek() === '=') { this.advance(); this.advance(); return { type: 'MOD_ASSIGN', value: '%=', line, column }; }
if (this.currentChar === '&' && this.peek() === '=') { this.advance(); this.advance(); return { type: 'AND_ASSIGN', value: '&=', line, column }; }
if (this.currentChar === '|' && this.peek() === '=') { this.advance(); this.advance(); return { type: 'OR_ASSIGN', value: '|=', line, column }; }
if (this.currentChar === '^' && this.peek() === '=') { this.advance(); this.advance(); return { type: 'XOR_ASSIGN', value: '^=', line, column }; }
if (this.currentChar === '-' && this.peek() === '>') { this.advance(); this.advance(); return { type: 'ARROW', value: '->', line, column }; }