polycomp 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/parser.rs ADDED
@@ -0,0 +1,2605 @@
1
+ use crate::ast::*;
2
+ use crate::diagnostics::{Diagnostic, PolyError, Span};
3
+
4
+ #[derive(Debug, Clone, PartialEq)]
5
+ enum TokKind {
6
+ Ident(String),
7
+ Int(i64),
8
+ Float(f64),
9
+ Str(String),
10
+ Newline,
11
+ Indent,
12
+ Dedent,
13
+ LParen,
14
+ RParen,
15
+ LBrace,
16
+ RBrace,
17
+ LBracket,
18
+ RBracket,
19
+ Comma,
20
+ Colon,
21
+ ColonColon,
22
+ Semi,
23
+ Dot,
24
+ DotDot,
25
+ DotDotEq,
26
+ Arrow,
27
+ FatArrow,
28
+ Question,
29
+ Plus,
30
+ Minus,
31
+ Star,
32
+ Slash,
33
+ SlashSlash,
34
+ Percent,
35
+ PlusPlus,
36
+ MinusMinus,
37
+ Eq,
38
+ PlusEq,
39
+ MinusEq,
40
+ StarEq,
41
+ SlashEq,
42
+ PercentEq,
43
+ EqEq,
44
+ EqEqEq,
45
+ BangEq,
46
+ BangEqEq,
47
+ Lt,
48
+ Le,
49
+ Gt,
50
+ Ge,
51
+ Amp,
52
+ AmpAmp,
53
+ Pipe,
54
+ PipePipe,
55
+ Caret,
56
+ Tilde,
57
+ Bang,
58
+ Shl,
59
+ Shr,
60
+ Eof,
61
+ }
62
+
63
+ #[derive(Debug, Clone)]
64
+ struct Tok {
65
+ kind: TokKind,
66
+ span: Span,
67
+ }
68
+
69
+ struct Lexer<'a> {
70
+ file_id: usize,
71
+ lang: Language,
72
+ src: &'a str,
73
+ bytes: &'a [u8],
74
+ pos: usize,
75
+ line: u32,
76
+ line_start: usize,
77
+ directives: Vec<ImportDecl>,
78
+ }
79
+
80
+ impl<'a> Lexer<'a> {
81
+ fn new(file_id: usize, lang: Language, src: &'a str) -> Self {
82
+ Self {
83
+ file_id,
84
+ lang,
85
+ src,
86
+ bytes: src.as_bytes(),
87
+ pos: 0,
88
+ line: 1,
89
+ line_start: 0,
90
+ directives: Vec::new(),
91
+ }
92
+ }
93
+
94
+ fn make_span(&self, start: usize, end: usize, line: u32, col: u32) -> Span {
95
+ Span {
96
+ file_id: self.file_id,
97
+ start,
98
+ end,
99
+ line,
100
+ col,
101
+ }
102
+ }
103
+
104
+ fn current_col(&self) -> u32 {
105
+ (self.pos - self.line_start + 1) as u32
106
+ }
107
+
108
+ fn peek(&self) -> Option<u8> {
109
+ self.bytes.get(self.pos).copied()
110
+ }
111
+
112
+ fn peek_at(&self, offset: usize) -> Option<u8> {
113
+ self.bytes.get(self.pos + offset).copied()
114
+ }
115
+
116
+ fn advance(&mut self) -> Option<u8> {
117
+ let b = self.peek()?;
118
+ self.pos += 1;
119
+ if b == b'\n' {
120
+ self.line += 1;
121
+ self.line_start = self.pos;
122
+ }
123
+ Some(b)
124
+ }
125
+
126
+ fn parse_comment_directive(&mut self, text: &str, span: Span) {
127
+ let trimmed = text.trim();
128
+ if let Some(rest) = trimmed.strip_prefix("polycomp") {
129
+ let rest = rest.trim();
130
+ if let Some(path_raw) = rest.strip_prefix("require") {
131
+ let spec = unquote(path_raw.trim());
132
+ if !spec.is_empty() {
133
+ self.directives.push(ImportDecl {
134
+ module_specifier: spec,
135
+ kind: ImportKind::Wildcard,
136
+ span,
137
+ });
138
+ }
139
+ } else if let Some(imp_rest) = rest.strip_prefix("import") {
140
+ if let Some((left, right)) = imp_rest.split_once(" from ") {
141
+ let mod_spec = unquote(right.trim());
142
+ let items = parse_directive_item_list(left, span);
143
+ if !mod_spec.is_empty() && !items.is_empty() {
144
+ self.directives.push(ImportDecl {
145
+ module_specifier: mod_spec,
146
+ kind: ImportKind::Named { items },
147
+ span,
148
+ });
149
+ }
150
+ } else {
151
+ for part in imp_rest.split(',') {
152
+ let part = part.trim();
153
+ if let Some((m, a)) = part.split_once(" as ") {
154
+ self.directives.push(ImportDecl {
155
+ module_specifier: unquote(m.trim()),
156
+ kind: ImportKind::Namespace {
157
+ alias: a.trim().to_string(),
158
+ },
159
+ span,
160
+ });
161
+ } else if !part.is_empty() {
162
+ let spec = unquote(part);
163
+ let alias = default_alias_for_spec(&spec);
164
+ self.directives.push(ImportDecl {
165
+ module_specifier: spec,
166
+ kind: ImportKind::Namespace { alias },
167
+ span,
168
+ });
169
+ }
170
+ }
171
+ }
172
+ }
173
+ }
174
+ }
175
+
176
+ fn tokenize(mut self) -> Result<(Vec<Tok>, Vec<ImportDecl>), PolyError> {
177
+ let mut tokens = Vec::new();
178
+ let mut indent_stack: Vec<usize> = vec![0];
179
+ let mut paren_depth: usize = 0;
180
+ let mut at_line_start = true;
181
+
182
+ while let Some(b) = self.peek() {
183
+ if at_line_start && self.lang == Language::Python && paren_depth == 0 {
184
+ let line_begin = self.pos;
185
+ let mut indent = 0usize;
186
+ while let Some(wb) = self.peek() {
187
+ match wb {
188
+ b' ' => {
189
+ indent += 1;
190
+ self.advance();
191
+ }
192
+ b'\t' => {
193
+ indent += 4;
194
+ self.advance();
195
+ }
196
+ b'\r' => {
197
+ self.advance();
198
+ }
199
+ _ => break,
200
+ }
201
+ }
202
+
203
+ match self.peek() {
204
+ None => break,
205
+ Some(b'\n') => {
206
+ self.advance();
207
+ continue;
208
+ }
209
+ Some(b'#') => {
210
+ let c_start = self.pos;
211
+ let c_line = self.line;
212
+ let c_col = self.current_col();
213
+ self.advance();
214
+ let text_start = self.pos;
215
+ while let Some(cb) = self.peek() {
216
+ if cb == b'\n' {
217
+ break;
218
+ }
219
+ self.advance();
220
+ }
221
+ let comment = &self.src[text_start..self.pos];
222
+ let span = self.make_span(c_start, self.pos, c_line, c_col);
223
+ self.parse_comment_directive(comment, span);
224
+ if self.peek() == Some(b'\n') {
225
+ self.advance();
226
+ }
227
+ continue;
228
+ }
229
+ _ => {}
230
+ }
231
+
232
+ let top = *indent_stack.last().unwrap_or(&0);
233
+ if indent > top {
234
+ indent_stack.push(indent);
235
+ tokens.push(Tok {
236
+ kind: TokKind::Indent,
237
+ span: self.make_span(line_begin, self.pos, self.line, 1),
238
+ });
239
+ } else if indent < top {
240
+ while let Some(&prev) = indent_stack.last() {
241
+ if prev == indent {
242
+ break;
243
+ }
244
+ if prev < indent {
245
+ return Err(PolyError::spanned(
246
+ "E0101",
247
+ "inconsistent Python indentation level",
248
+ self.make_span(line_begin, self.pos, self.line, 1),
249
+ ));
250
+ }
251
+ indent_stack.pop();
252
+ tokens.push(Tok {
253
+ kind: TokKind::Dedent,
254
+ span: self.make_span(line_begin, self.pos, self.line, 1),
255
+ });
256
+ }
257
+ }
258
+ at_line_start = false;
259
+ continue;
260
+ }
261
+
262
+ if b == b' ' || b == b'\t' || b == b'\r' {
263
+ self.advance();
264
+ continue;
265
+ }
266
+
267
+ if b == b'\n' {
268
+ let s = self.pos;
269
+ let line = self.line;
270
+ let col = self.current_col();
271
+ self.advance();
272
+ if self.lang == Language::Python && paren_depth == 0 {
273
+ let emit = tokens
274
+ .last()
275
+ .is_some_and(|t| !matches!(t.kind, TokKind::Newline | TokKind::Indent));
276
+ if emit {
277
+ tokens.push(Tok {
278
+ kind: TokKind::Newline,
279
+ span: self.make_span(s, self.pos, line, col),
280
+ });
281
+ }
282
+ }
283
+ at_line_start = true;
284
+ continue;
285
+ }
286
+ at_line_start = false;
287
+
288
+ if b == b'#' {
289
+ let c_start = self.pos;
290
+ let c_line = self.line;
291
+ let c_col = self.current_col();
292
+ self.advance();
293
+ let text_start = self.pos;
294
+ while let Some(cb) = self.peek() {
295
+ if cb == b'\n' {
296
+ break;
297
+ }
298
+ self.advance();
299
+ }
300
+ let raw_text = self.src[text_start..self.pos].trim();
301
+ let span = self.make_span(c_start, self.pos, c_line, c_col);
302
+ if self.lang == Language::C {
303
+ if let Some(inc) = raw_text.strip_prefix("include") {
304
+ let inc = inc.trim();
305
+ if inc.starts_with('"') && inc.ends_with('"') && inc.len() >= 2 {
306
+ self.directives.push(ImportDecl {
307
+ module_specifier: inc[1..inc.len() - 1].to_string(),
308
+ kind: ImportKind::Wildcard,
309
+ span,
310
+ });
311
+ }
312
+ } else {
313
+ self.parse_comment_directive(raw_text, span);
314
+ }
315
+ } else {
316
+ self.parse_comment_directive(raw_text, span);
317
+ }
318
+ continue;
319
+ }
320
+
321
+ if b == b'/' && self.peek_at(1) == Some(b'/') {
322
+ let c_start = self.pos;
323
+ let c_line = self.line;
324
+ let c_col = self.current_col();
325
+ self.advance();
326
+ self.advance();
327
+ let text_start = self.pos;
328
+ while let Some(cb) = self.peek() {
329
+ if cb == b'\n' {
330
+ break;
331
+ }
332
+ self.advance();
333
+ }
334
+ let span = self.make_span(c_start, self.pos, c_line, c_col);
335
+ let comment = &self.src[text_start..self.pos];
336
+ self.parse_comment_directive(comment, span);
337
+ continue;
338
+ }
339
+
340
+ if b == b'/' && self.peek_at(1) == Some(b'*') {
341
+ let c_start = self.pos;
342
+ let c_line = self.line;
343
+ let c_col = self.current_col();
344
+ self.advance();
345
+ self.advance();
346
+ let mut closed = false;
347
+ while let Some(cb) = self.peek() {
348
+ if cb == b'*' && self.peek_at(1) == Some(b'/') {
349
+ self.advance();
350
+ self.advance();
351
+ closed = true;
352
+ break;
353
+ }
354
+ self.advance();
355
+ }
356
+ if !closed {
357
+ return Err(PolyError::spanned(
358
+ "E0102",
359
+ "unterminated block comment",
360
+ self.make_span(c_start, self.pos, c_line, c_col),
361
+ ));
362
+ }
363
+ continue;
364
+ }
365
+
366
+ let start = self.pos;
367
+ let line = self.line;
368
+ let col = self.current_col();
369
+
370
+ if b == b'"' || b == b'\'' || b == b'`' {
371
+ let quote = b;
372
+ self.advance();
373
+ let mut s = String::new();
374
+ let mut closed = false;
375
+ while let Some(cb) = self.peek() {
376
+ if cb == quote {
377
+ self.advance();
378
+ closed = true;
379
+ break;
380
+ }
381
+ if cb == b'\\' {
382
+ self.advance();
383
+ match self.advance() {
384
+ Some(b'n') => s.push('\n'),
385
+ Some(b't') => s.push('\t'),
386
+ Some(b'r') => s.push('\r'),
387
+ Some(b'0') => s.push('\0'),
388
+ Some(b'\\') => s.push('\\'),
389
+ Some(b'"') => s.push('"'),
390
+ Some(b'\'') => s.push('\''),
391
+ Some(other) => s.push(other as char),
392
+ None => break,
393
+ }
394
+ } else {
395
+ let ch = self.src[self.pos..].chars().next().unwrap();
396
+ for _ in 0..ch.len_utf8() {
397
+ self.advance();
398
+ }
399
+ s.push(ch);
400
+ }
401
+ }
402
+ if !closed {
403
+ return Err(PolyError::spanned(
404
+ "E0103",
405
+ "unterminated string literal",
406
+ self.make_span(start, self.pos, line, col),
407
+ ));
408
+ }
409
+ tokens.push(Tok {
410
+ kind: TokKind::Str(s),
411
+ span: self.make_span(start, self.pos, line, col),
412
+ });
413
+ continue;
414
+ }
415
+
416
+ if b.is_ascii_digit() {
417
+ if b == b'0' && matches!(self.peek_at(1), Some(b'x' | b'X' | b'b' | b'B')) {
418
+ let prefix = self.peek_at(1).unwrap();
419
+ self.advance();
420
+ self.advance();
421
+ let d_start = self.pos;
422
+ while let Some(db) = self.peek() {
423
+ if db.is_ascii_hexdigit() || db == b'_' {
424
+ self.advance();
425
+ } else {
426
+ break;
427
+ }
428
+ }
429
+ let clean: String = self.src[d_start..self.pos]
430
+ .chars()
431
+ .filter(|&c| c != '_')
432
+ .collect();
433
+ let radix = if prefix == b'x' || prefix == b'X' { 16 } else { 2 };
434
+ let val = i64::from_str_radix(&clean, radix).map_err(|_| {
435
+ PolyError::spanned(
436
+ "E0104",
437
+ "invalid integer literal",
438
+ self.make_span(start, self.pos, line, col),
439
+ )
440
+ })?;
441
+ tokens.push(Tok {
442
+ kind: TokKind::Int(val),
443
+ span: self.make_span(start, self.pos, line, col),
444
+ });
445
+ continue;
446
+ }
447
+
448
+ let mut is_float = false;
449
+ while let Some(db) = self.peek() {
450
+ if db.is_ascii_digit() || db == b'_' {
451
+ self.advance();
452
+ } else if db == b'.' && self.peek_at(1).is_some_and(|n| n.is_ascii_digit()) {
453
+ is_float = true;
454
+ self.advance();
455
+ } else if (db == b'e' || db == b'E') && !is_float {
456
+ is_float = true;
457
+ self.advance();
458
+ if matches!(self.peek(), Some(b'+' | b'-')) {
459
+ self.advance();
460
+ }
461
+ } else if (db == b'e' || db == b'E') && is_float {
462
+ self.advance();
463
+ if matches!(self.peek(), Some(b'+' | b'-')) {
464
+ self.advance();
465
+ }
466
+ } else {
467
+ break;
468
+ }
469
+ }
470
+ let clean: String = self.src[start..self.pos]
471
+ .chars()
472
+ .filter(|&c| c != '_')
473
+ .collect();
474
+ let span = self.make_span(start, self.pos, line, col);
475
+ if is_float {
476
+ let val: f64 = clean.parse().map_err(|_| {
477
+ PolyError::spanned("E0104", "invalid float literal", span)
478
+ })?;
479
+ tokens.push(Tok {
480
+ kind: TokKind::Float(val),
481
+ span,
482
+ });
483
+ } else {
484
+ let val: i64 = clean.parse().map_err(|_| {
485
+ PolyError::spanned("E0104", "invalid integer literal", span)
486
+ })?;
487
+ tokens.push(Tok {
488
+ kind: TokKind::Int(val),
489
+ span,
490
+ });
491
+ }
492
+ continue;
493
+ }
494
+
495
+ if b.is_ascii_alphabetic() || b == b'_' {
496
+ while let Some(ib) = self.peek() {
497
+ if ib.is_ascii_alphanumeric() || ib == b'_' {
498
+ self.advance();
499
+ } else {
500
+ break;
501
+ }
502
+ }
503
+ let ident = self.src[start..self.pos].to_string();
504
+ tokens.push(Tok {
505
+ kind: TokKind::Ident(ident),
506
+ span: self.make_span(start, self.pos, line, col),
507
+ });
508
+ continue;
509
+ }
510
+
511
+ let kind = match (b, self.peek_at(1), self.peek_at(2)) {
512
+ (b'.', Some(b'.'), Some(b'=')) => {
513
+ self.advance();
514
+ self.advance();
515
+ self.advance();
516
+ TokKind::DotDotEq
517
+ }
518
+ (b'=', Some(b'='), Some(b'=')) => {
519
+ self.advance();
520
+ self.advance();
521
+ self.advance();
522
+ TokKind::EqEqEq
523
+ }
524
+ (b'!', Some(b'='), Some(b'=')) => {
525
+ self.advance();
526
+ self.advance();
527
+ self.advance();
528
+ TokKind::BangEqEq
529
+ }
530
+ (b':', Some(b':'), _) => {
531
+ self.advance();
532
+ self.advance();
533
+ TokKind::ColonColon
534
+ }
535
+ (b'.', Some(b'.'), _) => {
536
+ self.advance();
537
+ self.advance();
538
+ TokKind::DotDot
539
+ }
540
+ (b'-', Some(b'>'), _) => {
541
+ self.advance();
542
+ self.advance();
543
+ TokKind::Arrow
544
+ }
545
+ (b'=', Some(b'>'), _) => {
546
+ self.advance();
547
+ self.advance();
548
+ TokKind::FatArrow
549
+ }
550
+ (b'/', Some(b'/'), _) => {
551
+ self.advance();
552
+ self.advance();
553
+ TokKind::SlashSlash
554
+ }
555
+ (b'+', Some(b'+'), _) => {
556
+ self.advance();
557
+ self.advance();
558
+ TokKind::PlusPlus
559
+ }
560
+ (b'-', Some(b'-'), _) => {
561
+ self.advance();
562
+ self.advance();
563
+ TokKind::MinusMinus
564
+ }
565
+ (b'+', Some(b'='), _) => {
566
+ self.advance();
567
+ self.advance();
568
+ TokKind::PlusEq
569
+ }
570
+ (b'-', Some(b'='), _) => {
571
+ self.advance();
572
+ self.advance();
573
+ TokKind::MinusEq
574
+ }
575
+ (b'*', Some(b'='), _) => {
576
+ self.advance();
577
+ self.advance();
578
+ TokKind::StarEq
579
+ }
580
+ (b'/', Some(b'='), _) => {
581
+ self.advance();
582
+ self.advance();
583
+ TokKind::SlashEq
584
+ }
585
+ (b'%', Some(b'='), _) => {
586
+ self.advance();
587
+ self.advance();
588
+ TokKind::PercentEq
589
+ }
590
+ (b'=', Some(b'='), _) => {
591
+ self.advance();
592
+ self.advance();
593
+ TokKind::EqEq
594
+ }
595
+ (b'!', Some(b'='), _) => {
596
+ self.advance();
597
+ self.advance();
598
+ TokKind::BangEq
599
+ }
600
+ (b'<', Some(b'='), _) => {
601
+ self.advance();
602
+ self.advance();
603
+ TokKind::Le
604
+ }
605
+ (b'>', Some(b'='), _) => {
606
+ self.advance();
607
+ self.advance();
608
+ TokKind::Ge
609
+ }
610
+ (b'<', Some(b'<'), _) => {
611
+ self.advance();
612
+ self.advance();
613
+ TokKind::Shl
614
+ }
615
+ (b'>', Some(b'>'), _) => {
616
+ self.advance();
617
+ self.advance();
618
+ TokKind::Shr
619
+ }
620
+ (b'&', Some(b'&'), _) => {
621
+ self.advance();
622
+ self.advance();
623
+ TokKind::AmpAmp
624
+ }
625
+ (b'|', Some(b'|'), _) => {
626
+ self.advance();
627
+ self.advance();
628
+ TokKind::PipePipe
629
+ }
630
+ (b'(', _, _) => {
631
+ self.advance();
632
+ paren_depth += 1;
633
+ TokKind::LParen
634
+ }
635
+ (b')', _, _) => {
636
+ self.advance();
637
+ paren_depth = paren_depth.saturating_sub(1);
638
+ TokKind::RParen
639
+ }
640
+ (b'[', _, _) => {
641
+ self.advance();
642
+ paren_depth += 1;
643
+ TokKind::LBracket
644
+ }
645
+ (b']', _, _) => {
646
+ self.advance();
647
+ paren_depth = paren_depth.saturating_sub(1);
648
+ TokKind::RBracket
649
+ }
650
+ (b'{', _, _) => {
651
+ self.advance();
652
+ if self.lang == Language::Python {
653
+ paren_depth += 1;
654
+ }
655
+ TokKind::LBrace
656
+ }
657
+ (b'}', _, _) => {
658
+ self.advance();
659
+ if self.lang == Language::Python {
660
+ paren_depth = paren_depth.saturating_sub(1);
661
+ }
662
+ TokKind::RBrace
663
+ }
664
+ (b',', _, _) => {
665
+ self.advance();
666
+ TokKind::Comma
667
+ }
668
+ (b':', _, _) => {
669
+ self.advance();
670
+ TokKind::Colon
671
+ }
672
+ (b';', _, _) => {
673
+ self.advance();
674
+ TokKind::Semi
675
+ }
676
+ (b'.', _, _) => {
677
+ self.advance();
678
+ TokKind::Dot
679
+ }
680
+ (b'?', _, _) => {
681
+ self.advance();
682
+ TokKind::Question
683
+ }
684
+ (b'+', _, _) => {
685
+ self.advance();
686
+ TokKind::Plus
687
+ }
688
+ (b'-', _, _) => {
689
+ self.advance();
690
+ TokKind::Minus
691
+ }
692
+ (b'*', _, _) => {
693
+ self.advance();
694
+ TokKind::Star
695
+ }
696
+ (b'/', _, _) => {
697
+ self.advance();
698
+ TokKind::Slash
699
+ }
700
+ (b'%', _, _) => {
701
+ self.advance();
702
+ TokKind::Percent
703
+ }
704
+ (b'=', _, _) => {
705
+ self.advance();
706
+ TokKind::Eq
707
+ }
708
+ (b'<', _, _) => {
709
+ self.advance();
710
+ TokKind::Lt
711
+ }
712
+ (b'>', _, _) => {
713
+ self.advance();
714
+ TokKind::Gt
715
+ }
716
+ (b'&', _, _) => {
717
+ self.advance();
718
+ TokKind::Amp
719
+ }
720
+ (b'|', _, _) => {
721
+ self.advance();
722
+ TokKind::Pipe
723
+ }
724
+ (b'^', _, _) => {
725
+ self.advance();
726
+ TokKind::Caret
727
+ }
728
+ (b'~', _, _) => {
729
+ self.advance();
730
+ TokKind::Tilde
731
+ }
732
+ (b'!', _, _) => {
733
+ self.advance();
734
+ TokKind::Bang
735
+ }
736
+ other => {
737
+ return Err(PolyError::spanned(
738
+ "E0105",
739
+ format!("unexpected character '{}'", other.0 as char),
740
+ self.make_span(start, self.pos + 1, line, col),
741
+ ));
742
+ }
743
+ };
744
+
745
+ tokens.push(Tok {
746
+ kind,
747
+ span: self.make_span(start, self.pos, line, col),
748
+ });
749
+ }
750
+
751
+ if self.lang == Language::Python {
752
+ let eof_span = self.make_span(self.pos, self.pos, self.line, self.current_col());
753
+ if tokens
754
+ .last()
755
+ .is_some_and(|t| !matches!(t.kind, TokKind::Newline | TokKind::Dedent))
756
+ {
757
+ tokens.push(Tok {
758
+ kind: TokKind::Newline,
759
+ span: eof_span,
760
+ });
761
+ }
762
+ while indent_stack.len() > 1 {
763
+ indent_stack.pop();
764
+ tokens.push(Tok {
765
+ kind: TokKind::Dedent,
766
+ span: eof_span,
767
+ });
768
+ }
769
+ }
770
+
771
+ tokens.push(Tok {
772
+ kind: TokKind::Eof,
773
+ span: self.make_span(self.pos, self.pos, self.line, self.current_col()),
774
+ });
775
+
776
+ Ok((tokens, self.directives))
777
+ }
778
+ }
779
+
780
+ fn unquote(s: &str) -> String {
781
+ let s = s.trim();
782
+ if s.len() >= 2
783
+ && ((s.starts_with('"') && s.ends_with('"'))
784
+ || (s.starts_with('\'') && s.ends_with('\'')))
785
+ {
786
+ s[1..s.len() - 1].to_string()
787
+ } else {
788
+ s.to_string()
789
+ }
790
+ }
791
+
792
+ fn default_alias_for_spec(spec: &str) -> String {
793
+ let stripped = spec.trim_end_matches(&['/', '\\'][..]);
794
+ let base = stripped.rsplit(&['/', '\\'][..]).next().unwrap_or(stripped);
795
+ base.split('.').next().unwrap_or(base).to_string()
796
+ }
797
+
798
+ fn parse_directive_item_list(raw: &str, span: Span) -> Vec<ImportItem> {
799
+ let raw = raw.trim().trim_start_matches('{').trim_end_matches('}');
800
+ let mut items = Vec::new();
801
+ for part in raw.split(',') {
802
+ let p = part.trim();
803
+ if p.is_empty() {
804
+ continue;
805
+ }
806
+ if let Some((orig, alias)) = p.split_once(" as ") {
807
+ items.push(ImportItem {
808
+ name: orig.trim().to_string(),
809
+ alias: alias.trim().to_string(),
810
+ span,
811
+ });
812
+ } else {
813
+ items.push(ImportItem {
814
+ name: p.to_string(),
815
+ alias: p.to_string(),
816
+ span,
817
+ });
818
+ }
819
+ }
820
+ items
821
+ }
822
+
823
+ struct Parser {
824
+ lang: Language,
825
+ tokens: Vec<Tok>,
826
+ pos: usize,
827
+ struct_names: Vec<String>,
828
+ anon_counter: usize,
829
+ extra_functions: Vec<FunctionDecl>,
830
+ }
831
+
832
+ impl Parser {
833
+ fn new(lang: Language, tokens: Vec<Tok>) -> Self {
834
+ Self {
835
+ lang,
836
+ tokens,
837
+ pos: 0,
838
+ struct_names: Vec::new(),
839
+ anon_counter: 0,
840
+ extra_functions: Vec::new(),
841
+ }
842
+ }
843
+
844
+ fn peek(&self) -> &Tok {
845
+ self.tokens
846
+ .get(self.pos)
847
+ .unwrap_or_else(|| self.tokens.last().unwrap())
848
+ }
849
+
850
+ fn peek_n(&self, n: usize) -> &Tok {
851
+ self.tokens
852
+ .get(self.pos + n)
853
+ .unwrap_or_else(|| self.tokens.last().unwrap())
854
+ }
855
+
856
+ fn advance(&mut self) -> Tok {
857
+ let t = self.peek().clone();
858
+ if self.pos + 1 < self.tokens.len() {
859
+ self.pos += 1;
860
+ }
861
+ t
862
+ }
863
+
864
+ fn at(&self, kind: &TokKind) -> bool {
865
+ &self.peek().kind == kind
866
+ }
867
+
868
+ fn at_ident(&self, kw: &str) -> bool {
869
+ matches!(&self.peek().kind, TokKind::Ident(s) if s == kw)
870
+ }
871
+
872
+ fn eat(&mut self, kind: &TokKind) -> bool {
873
+ if self.at(kind) {
874
+ self.advance();
875
+ true
876
+ } else {
877
+ false
878
+ }
879
+ }
880
+
881
+ fn eat_ident(&mut self, kw: &str) -> bool {
882
+ if self.at_ident(kw) {
883
+ self.advance();
884
+ true
885
+ } else {
886
+ false
887
+ }
888
+ }
889
+
890
+ fn expect(&mut self, kind: &TokKind, desc: &str) -> Result<Tok, PolyError> {
891
+ if self.at(kind) {
892
+ Ok(self.advance())
893
+ } else {
894
+ let t = self.peek();
895
+ Err(PolyError::spanned(
896
+ "E0110",
897
+ format!("expected {desc}, found {:?}", t.kind),
898
+ t.span,
899
+ ))
900
+ }
901
+ }
902
+
903
+ fn expect_ident(&mut self, desc: &str) -> Result<(String, Span), PolyError> {
904
+ let t = self.peek().clone();
905
+ match t.kind {
906
+ TokKind::Ident(name) => {
907
+ self.advance();
908
+ Ok((name, t.span))
909
+ }
910
+ _ => Err(PolyError::spanned(
911
+ "E0111",
912
+ format!("expected {desc}, found {:?}", t.kind),
913
+ t.span,
914
+ )),
915
+ }
916
+ }
917
+
918
+ fn skip_newlines(&mut self) {
919
+ while self.eat(&TokKind::Newline) {}
920
+ }
921
+
922
+ fn eat_stmt_end(&mut self) {
923
+ if self.lang == Language::Python {
924
+ let _ = self.eat(&TokKind::Semi);
925
+ while self.eat(&TokKind::Newline) {}
926
+ } else {
927
+ while self.eat(&TokKind::Semi) || self.eat(&TokKind::Newline) {}
928
+ }
929
+ }
930
+
931
+ fn is_c_type_start(&self) -> bool {
932
+ match &self.peek().kind {
933
+ TokKind::Ident(s) => {
934
+ matches!(
935
+ s.as_str(),
936
+ "void"
937
+ | "int"
938
+ | "long"
939
+ | "short"
940
+ | "char"
941
+ | "float"
942
+ | "double"
943
+ | "bool"
944
+ | "unsigned"
945
+ | "signed"
946
+ | "size_t"
947
+ | "int64_t"
948
+ | "uint64_t"
949
+ | "int32_t"
950
+ | "const"
951
+ | "struct"
952
+ ) || self.struct_names.contains(s)
953
+ }
954
+ _ => false,
955
+ }
956
+ }
957
+
958
+ fn parse_type_hint_str(s: &str) -> TypeHint {
959
+ match s {
960
+ "void" | "()" | "None" => TypeHint::Void,
961
+ "bool" => TypeHint::Bool,
962
+ "int" | "i8" | "i16" | "i32" | "i64" | "isize" | "u8" | "u16" | "u32" | "u64"
963
+ | "usize" | "long" | "short" | "int64_t" | "int32_t" | "uint64_t" | "size_t" => {
964
+ TypeHint::Int
965
+ }
966
+ "float" | "double" | "f32" | "f64" | "number" => TypeHint::Float,
967
+ "str" | "String" | "string" | "char" => TypeHint::Str,
968
+ _ => TypeHint::Unknown,
969
+ }
970
+ }
971
+
972
+ fn parse_c_type(&mut self) -> Result<TypeHint, PolyError> {
973
+ let mut base = TypeHint::Unknown;
974
+ let mut saw_any = false;
975
+ while let TokKind::Ident(kw) = &self.peek().kind {
976
+ let k = kw.clone();
977
+ if matches!(k.as_str(), "const" | "unsigned" | "signed" | "struct") {
978
+ self.advance();
979
+ saw_any = true;
980
+ if k == "unsigned" && !self.is_c_type_start() {
981
+ base = TypeHint::Int;
982
+ }
983
+ continue;
984
+ }
985
+ let mapped = Self::parse_type_hint_str(&k);
986
+ if mapped != TypeHint::Unknown || self.struct_names.contains(&k) {
987
+ self.advance();
988
+ saw_any = true;
989
+ if k == "char" && self.at(&TokKind::Star) {
990
+ base = TypeHint::Str;
991
+ } else {
992
+ base = mapped;
993
+ }
994
+ break;
995
+ } else {
996
+ break;
997
+ }
998
+ }
999
+ while self.eat(&TokKind::Star) {
1000
+ if base == TypeHint::Unknown {
1001
+ base = TypeHint::Int;
1002
+ }
1003
+ }
1004
+ if !saw_any {
1005
+ let t = self.peek();
1006
+ return Err(PolyError::spanned("E0112", "expected C type", t.span));
1007
+ }
1008
+ Ok(base)
1009
+ }
1010
+
1011
+ fn parse_rust_or_py_type(&mut self) -> Result<TypeHint, PolyError> {
1012
+ if self.eat(&TokKind::LParen) {
1013
+ self.expect(&TokKind::RParen, "')'")?;
1014
+ return Ok(TypeHint::Void);
1015
+ }
1016
+ if self.eat(&TokKind::Amp) {
1017
+ let _ = self.eat_ident("mut");
1018
+ let (name, _) = self.expect_ident("type name")?;
1019
+ return Ok(Self::parse_type_hint_str(&name));
1020
+ }
1021
+ let (name, _) = self.expect_ident("type name")?;
1022
+ Ok(Self::parse_type_hint_str(&name))
1023
+ }
1024
+
1025
+ fn parse_module(
1026
+ &mut self,
1027
+ directives: Vec<ImportDecl>,
1028
+ ) -> Result<ModuleAst, PolyError> {
1029
+ let mut imports = directives;
1030
+ let mut structs = Vec::new();
1031
+ let mut functions = Vec::new();
1032
+ let mut top_level = Vec::new();
1033
+
1034
+ self.skip_newlines();
1035
+ while !self.at(&TokKind::Eof) {
1036
+ if self.at_ident("import") || self.at_ident("from") || self.at_ident("use") {
1037
+ let mut decls = self.parse_import_decl()?;
1038
+ imports.append(&mut decls);
1039
+ self.eat_stmt_end();
1040
+ continue;
1041
+ }
1042
+
1043
+ if self.lang == Language::Rust && self.at_ident("mod") {
1044
+ let start = self.peek().span;
1045
+ self.advance();
1046
+ let (name, _) = self.expect_ident("module name")?;
1047
+ self.eat_stmt_end();
1048
+ imports.push(ImportDecl {
1049
+ module_specifier: name.clone(),
1050
+ kind: ImportKind::Namespace { alias: name },
1051
+ span: start,
1052
+ });
1053
+ continue;
1054
+ }
1055
+
1056
+ let exported = if self.eat_ident("export") {
1057
+ let _ = self.eat_ident("default");
1058
+ true
1059
+ } else {
1060
+ self.eat_ident("pub")
1061
+ };
1062
+
1063
+ if self.at_ident("import") || self.at_ident("from") || self.at_ident("use") {
1064
+ let mut decls = self.parse_import_decl()?;
1065
+ imports.append(&mut decls);
1066
+ self.eat_stmt_end();
1067
+ continue;
1068
+ }
1069
+
1070
+ if self.at_ident("fn")
1071
+ || self.at_ident("def")
1072
+ || self.at_ident("function")
1073
+ {
1074
+ let f = self.parse_function(exported)?;
1075
+ functions.push(f);
1076
+ self.skip_newlines();
1077
+ continue;
1078
+ }
1079
+
1080
+ if self.at_ident("struct") || self.at_ident("class") {
1081
+ if self.lang == Language::C
1082
+ && matches!(&self.peek_n(1).kind, TokKind::Ident(_))
1083
+ && !matches!(&self.peek_n(2).kind, TokKind::LBrace)
1084
+ {
1085
+ if let Some(f) = self.try_parse_c_top_level()? {
1086
+ functions.push(f);
1087
+ }
1088
+ self.skip_newlines();
1089
+ continue;
1090
+ }
1091
+ let s = self.parse_struct_or_class()?;
1092
+ self.struct_names.push(s.name.clone());
1093
+ structs.push(s);
1094
+ self.skip_newlines();
1095
+ continue;
1096
+ }
1097
+
1098
+ if self.lang == Language::Rust && self.at_ident("impl") {
1099
+ self.advance();
1100
+ let (struct_name, _) = self.expect_ident("struct name")?;
1101
+ self.expect(&TokKind::LBrace, "'{'")?;
1102
+ let mut methods = Vec::new();
1103
+ while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
1104
+ let is_pub = self.eat_ident("pub");
1105
+ let mut m = self.parse_function(is_pub)?;
1106
+ m.name = format!("{struct_name}::{}", m.name);
1107
+ methods.push(m);
1108
+ }
1109
+ self.expect(&TokKind::RBrace, "'}'")?;
1110
+ functions.extend(methods);
1111
+ continue;
1112
+ }
1113
+
1114
+ if self.lang == Language::C && self.is_c_type_start() {
1115
+ if let Some(f) = self.try_parse_c_top_level()? {
1116
+ functions.push(f);
1117
+ self.skip_newlines();
1118
+ continue;
1119
+ }
1120
+ let s = self.parse_stmt()?;
1121
+ top_level.push(s);
1122
+ self.skip_newlines();
1123
+ continue;
1124
+ }
1125
+
1126
+ let stmt = self.parse_stmt()?;
1127
+ top_level.push(stmt);
1128
+ self.skip_newlines();
1129
+ }
1130
+
1131
+ functions.append(&mut self.extra_functions);
1132
+
1133
+ Ok(ModuleAst {
1134
+ language: self.lang,
1135
+ imports,
1136
+ structs,
1137
+ functions,
1138
+ top_level,
1139
+ })
1140
+ }
1141
+
1142
+ fn parse_module_specifier_tok(&mut self) -> Result<(String, Span), PolyError> {
1143
+ let t = self.peek().clone();
1144
+ match t.kind {
1145
+ TokKind::Str(s) => {
1146
+ self.advance();
1147
+ Ok((s, t.span))
1148
+ }
1149
+ TokKind::Ident(first) => {
1150
+ self.advance();
1151
+ let mut spec = first;
1152
+ while self.eat(&TokKind::Dot) || self.eat(&TokKind::ColonColon) {
1153
+ if let TokKind::Ident(seg) = &self.peek().kind {
1154
+ spec.push('/');
1155
+ spec.push_str(seg);
1156
+ self.advance();
1157
+ } else {
1158
+ break;
1159
+ }
1160
+ }
1161
+ Ok((spec, t.span))
1162
+ }
1163
+ TokKind::Dot => {
1164
+ self.advance();
1165
+ let mut spec = String::from("./");
1166
+ while matches!(
1167
+ &self.peek().kind,
1168
+ TokKind::Ident(_) | TokKind::Dot | TokKind::Slash
1169
+ ) {
1170
+ match &self.peek().kind {
1171
+ TokKind::Ident(seg) => {
1172
+ spec.push_str(seg);
1173
+ self.advance();
1174
+ }
1175
+ TokKind::Dot => {
1176
+ spec.push('.');
1177
+ self.advance();
1178
+ }
1179
+ TokKind::Slash => {
1180
+ spec.push('/');
1181
+ self.advance();
1182
+ }
1183
+ _ => break,
1184
+ }
1185
+ }
1186
+ Ok((spec, t.span))
1187
+ }
1188
+ _ => Err(PolyError::spanned(
1189
+ "E0113",
1190
+ "expected module path or name",
1191
+ t.span,
1192
+ )),
1193
+ }
1194
+ }
1195
+
1196
+ fn parse_import_decl(&mut self) -> Result<Vec<ImportDecl>, PolyError> {
1197
+ let start = self.peek().span;
1198
+ if self.eat_ident("from") {
1199
+ let (mod_spec, _) = self.parse_module_specifier_tok()?;
1200
+ if !self.eat_ident("import") {
1201
+ return Err(PolyError::spanned(
1202
+ "E0114",
1203
+ "expected 'import' after module in 'from ... import ...'",
1204
+ self.peek().span,
1205
+ ));
1206
+ }
1207
+ if self.eat(&TokKind::Star) {
1208
+ return Ok(vec![ImportDecl {
1209
+ module_specifier: mod_spec,
1210
+ kind: ImportKind::Wildcard,
1211
+ span: start,
1212
+ }]);
1213
+ }
1214
+ let paren = self.eat(&TokKind::LParen);
1215
+ let mut items = Vec::new();
1216
+ loop {
1217
+ if paren && self.at(&TokKind::RParen) {
1218
+ break;
1219
+ }
1220
+ let (name, item_span) = self.expect_ident("imported symbol")?;
1221
+ let alias = if self.eat_ident("as") {
1222
+ self.expect_ident("import alias")?.0
1223
+ } else {
1224
+ name.clone()
1225
+ };
1226
+ items.push(ImportItem {
1227
+ name,
1228
+ alias,
1229
+ span: item_span,
1230
+ });
1231
+ if !self.eat(&TokKind::Comma) {
1232
+ break;
1233
+ }
1234
+ }
1235
+ if paren {
1236
+ self.expect(&TokKind::RParen, "')'")?;
1237
+ }
1238
+ return Ok(vec![ImportDecl {
1239
+ module_specifier: mod_spec,
1240
+ kind: ImportKind::Named { items },
1241
+ span: start,
1242
+ }]);
1243
+ }
1244
+
1245
+ if self.eat_ident("use") {
1246
+ let mut segments = Vec::new();
1247
+ let mut prefix = String::new();
1248
+ if self.eat(&TokKind::Dot) {
1249
+ let _ = self.eat(&TokKind::Slash);
1250
+ prefix = "./".to_string();
1251
+ }
1252
+ let (first, _) = self.expect_ident("module path")?;
1253
+ if first != "crate" && first != "self" {
1254
+ segments.push(first);
1255
+ }
1256
+ let mut named_items: Option<Vec<ImportItem>> = None;
1257
+ let mut wildcard = false;
1258
+ let mut single_alias: Option<String> = None;
1259
+
1260
+ while self.eat(&TokKind::ColonColon) {
1261
+ if self.eat(&TokKind::Star) {
1262
+ wildcard = true;
1263
+ break;
1264
+ }
1265
+ if self.eat(&TokKind::LBrace) {
1266
+ let mut items = Vec::new();
1267
+ while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
1268
+ let (name, ispan) = self.expect_ident("imported symbol")?;
1269
+ let alias = if self.eat_ident("as") {
1270
+ self.expect_ident("alias")?.0
1271
+ } else {
1272
+ name.clone()
1273
+ };
1274
+ items.push(ImportItem {
1275
+ name,
1276
+ alias,
1277
+ span: ispan,
1278
+ });
1279
+ if !self.eat(&TokKind::Comma) {
1280
+ break;
1281
+ }
1282
+ }
1283
+ self.expect(&TokKind::RBrace, "'}'")?;
1284
+ named_items = Some(items);
1285
+ break;
1286
+ }
1287
+ let (seg, _) = self.expect_ident("path segment")?;
1288
+ segments.push(seg);
1289
+ }
1290
+
1291
+ if named_items.is_none() && !wildcard && self.eat_ident("as") {
1292
+ single_alias = Some(self.expect_ident("alias")?.0);
1293
+ }
1294
+
1295
+ if let Some(items) = named_items {
1296
+ let mod_spec = format!("{prefix}{}", segments.join("/"));
1297
+ return Ok(vec![ImportDecl {
1298
+ module_specifier: mod_spec,
1299
+ kind: ImportKind::Named { items },
1300
+ span: start,
1301
+ }]);
1302
+ }
1303
+ if wildcard {
1304
+ let mod_spec = format!("{prefix}{}", segments.join("/"));
1305
+ return Ok(vec![ImportDecl {
1306
+ module_specifier: mod_spec,
1307
+ kind: ImportKind::Wildcard,
1308
+ span: start,
1309
+ }]);
1310
+ }
1311
+ if segments.len() >= 2 && single_alias.is_none() {
1312
+ let sym = segments.pop().unwrap();
1313
+ let mod_spec = format!("{prefix}{}", segments.join("/"));
1314
+ return Ok(vec![ImportDecl {
1315
+ module_specifier: mod_spec,
1316
+ kind: ImportKind::Named {
1317
+ items: vec![ImportItem {
1318
+ name: sym.clone(),
1319
+ alias: sym,
1320
+ span: start,
1321
+ }],
1322
+ },
1323
+ span: start,
1324
+ }]);
1325
+ }
1326
+ let mod_spec = format!("{prefix}{}", segments.join("/"));
1327
+ let alias = single_alias.unwrap_or_else(|| default_alias_for_spec(&mod_spec));
1328
+ return Ok(vec![ImportDecl {
1329
+ module_specifier: mod_spec,
1330
+ kind: ImportKind::Namespace { alias },
1331
+ span: start,
1332
+ }]);
1333
+ }
1334
+
1335
+ // `import ...`
1336
+ self.expect_ident("'import'")?;
1337
+
1338
+ if let TokKind::Str(spec) = &self.peek().kind {
1339
+ let spec = spec.clone();
1340
+ self.advance();
1341
+ return Ok(vec![ImportDecl {
1342
+ module_specifier: spec,
1343
+ kind: ImportKind::Wildcard,
1344
+ span: start,
1345
+ }]);
1346
+ }
1347
+
1348
+ if self.eat(&TokKind::Star) {
1349
+ if !self.eat_ident("as") {
1350
+ return Err(PolyError::spanned(
1351
+ "E0115",
1352
+ "expected 'as' after 'import *'",
1353
+ self.peek().span,
1354
+ ));
1355
+ }
1356
+ let (alias, _) = self.expect_ident("namespace alias")?;
1357
+ if !self.eat_ident("from") {
1358
+ return Err(PolyError::spanned(
1359
+ "E0115",
1360
+ "expected 'from' in 'import * as ... from ...'",
1361
+ self.peek().span,
1362
+ ));
1363
+ }
1364
+ let (mod_spec, _) = self.parse_module_specifier_tok()?;
1365
+ return Ok(vec![ImportDecl {
1366
+ module_specifier: mod_spec,
1367
+ kind: ImportKind::Namespace { alias },
1368
+ span: start,
1369
+ }]);
1370
+ }
1371
+
1372
+ if self.eat(&TokKind::LBrace) {
1373
+ let items = self.parse_braced_import_items()?;
1374
+ if !self.eat_ident("from") {
1375
+ return Err(PolyError::spanned(
1376
+ "E0115",
1377
+ "expected 'from' after import list",
1378
+ self.peek().span,
1379
+ ));
1380
+ }
1381
+ let (mod_spec, _) = self.parse_module_specifier_tok()?;
1382
+ return Ok(vec![ImportDecl {
1383
+ module_specifier: mod_spec,
1384
+ kind: ImportKind::Named { items },
1385
+ span: start,
1386
+ }]);
1387
+ }
1388
+
1389
+ // Handles:
1390
+ // import mod
1391
+ // import mod as alias
1392
+ // import a, b as c
1393
+ // import x, y, z from module
1394
+ // import mod, { x, y } from "module"
1395
+ let mut first_entries: Vec<(String, Option<String>, Span)> = Vec::new();
1396
+ let mut braced_tail: Option<Vec<ImportItem>> = None;
1397
+
1398
+ loop {
1399
+ let (name, ispan) = self.expect_ident("module or symbol name")?;
1400
+ let alias = if self.eat_ident("as") {
1401
+ Some(self.expect_ident("alias")?.0)
1402
+ } else {
1403
+ None
1404
+ };
1405
+ first_entries.push((name, alias, ispan));
1406
+ if self.eat(&TokKind::Comma) {
1407
+ if self.eat(&TokKind::LBrace) {
1408
+ braced_tail = Some(self.parse_braced_import_items()?);
1409
+ break;
1410
+ }
1411
+ continue;
1412
+ }
1413
+ break;
1414
+ }
1415
+
1416
+ if self.eat_ident("from") {
1417
+ let (mod_spec, _) = self.parse_module_specifier_tok()?;
1418
+ let mut decls = Vec::new();
1419
+ if let Some(items) = braced_tail {
1420
+ if let Some((ns_name, ns_alias, _)) = first_entries.first() {
1421
+ decls.push(ImportDecl {
1422
+ module_specifier: mod_spec.clone(),
1423
+ kind: ImportKind::Namespace {
1424
+ alias: ns_alias.clone().unwrap_or_else(|| ns_name.clone()),
1425
+ },
1426
+ span: start,
1427
+ });
1428
+ }
1429
+ decls.push(ImportDecl {
1430
+ module_specifier: mod_spec,
1431
+ kind: ImportKind::Named { items },
1432
+ span: start,
1433
+ });
1434
+ return Ok(decls);
1435
+ }
1436
+ if first_entries.len() == 1 && first_entries[0].1.is_none() && self.lang == Language::JavaScript {
1437
+ // In JS, `import foo from "./mod.js"` can be default/namespace or named; treat single unbraced as Named OR Namespace fallback?
1438
+ // Wait: in `import x,y,z from module` it's always Named items!
1439
+ let (name, alias, ispan) = first_entries.remove(0);
1440
+ let alias = alias.unwrap_or_else(|| name.clone());
1441
+ return Ok(vec![ImportDecl {
1442
+ module_specifier: mod_spec,
1443
+ kind: ImportKind::Named {
1444
+ items: vec![ImportItem {
1445
+ name,
1446
+ alias,
1447
+ span: ispan,
1448
+ }],
1449
+ },
1450
+ span: start,
1451
+ }]);
1452
+ }
1453
+ let items = first_entries
1454
+ .into_iter()
1455
+ .map(|(name, alias, ispan)| ImportItem {
1456
+ alias: alias.unwrap_or_else(|| name.clone()),
1457
+ name,
1458
+ span: ispan,
1459
+ })
1460
+ .collect();
1461
+ return Ok(vec![ImportDecl {
1462
+ module_specifier: mod_spec,
1463
+ kind: ImportKind::Named { items },
1464
+ span: start,
1465
+ }]);
1466
+ }
1467
+
1468
+ // Plain `import mod1, mod2 as m2`
1469
+ let decls = first_entries
1470
+ .into_iter()
1471
+ .map(|(mod_spec, alias, ispan)| ImportDecl {
1472
+ kind: ImportKind::Namespace {
1473
+ alias: alias.unwrap_or_else(|| default_alias_for_spec(&mod_spec)),
1474
+ },
1475
+ module_specifier: mod_spec,
1476
+ span: ispan,
1477
+ })
1478
+ .collect();
1479
+ Ok(decls)
1480
+ }
1481
+
1482
+ fn parse_braced_import_items(&mut self) -> Result<Vec<ImportItem>, PolyError> {
1483
+ let mut items = Vec::new();
1484
+ while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
1485
+ let (name, ispan) = self.expect_ident("imported symbol")?;
1486
+ let alias = if self.eat_ident("as") {
1487
+ self.expect_ident("alias")?.0
1488
+ } else {
1489
+ name.clone()
1490
+ };
1491
+ items.push(ImportItem {
1492
+ name,
1493
+ alias,
1494
+ span: ispan,
1495
+ });
1496
+ if !self.eat(&TokKind::Comma) {
1497
+ break;
1498
+ }
1499
+ }
1500
+ self.expect(&TokKind::RBrace, "'}'")?;
1501
+ Ok(items)
1502
+ }
1503
+
1504
+ fn try_parse_c_top_level(&mut self) -> Result<Option<FunctionDecl>, PolyError> {
1505
+ let save = self.pos;
1506
+ let ret_ty = self.parse_c_type()?;
1507
+ if let TokKind::Ident(name) = &self.peek().kind {
1508
+ let fn_name = name.clone();
1509
+ let fn_span = self.peek().span;
1510
+ self.advance();
1511
+ if self.eat(&TokKind::LParen) {
1512
+ let params = self.parse_c_params()?;
1513
+ self.expect(&TokKind::RParen, "')'")?;
1514
+ if self.eat(&TokKind::Semi) {
1515
+ // Forward prototype; return a no-op or skip? Return None only if var decl; for prototype re-loop cleanly!
1516
+ return Ok(None);
1517
+ }
1518
+ let body = self.parse_brace_block()?;
1519
+ return Ok(Some(FunctionDecl {
1520
+ name: fn_name,
1521
+ params,
1522
+ return_type: ret_ty,
1523
+ body,
1524
+ is_exported: true,
1525
+ span: fn_span,
1526
+ }));
1527
+ }
1528
+ }
1529
+ self.pos = save;
1530
+ Ok(None)
1531
+ }
1532
+
1533
+ fn parse_c_params(&mut self) -> Result<Vec<Param>, PolyError> {
1534
+ let mut params = Vec::new();
1535
+ if self.at_ident("void") && self.peek_n(1).kind == TokKind::RParen {
1536
+ self.advance();
1537
+ return Ok(params);
1538
+ }
1539
+ while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
1540
+ let ty = if self.is_c_type_start() {
1541
+ self.parse_c_type()?
1542
+ } else {
1543
+ TypeHint::Unknown
1544
+ };
1545
+ let (name, span) = self.expect_ident("parameter name")?;
1546
+ if self.eat(&TokKind::LBracket) {
1547
+ let _ = self.eat(&TokKind::RBracket);
1548
+ }
1549
+ params.push(Param { name, ty, span });
1550
+ if !self.eat(&TokKind::Comma) {
1551
+ break;
1552
+ }
1553
+ }
1554
+ Ok(params)
1555
+ }
1556
+
1557
+
1558
+ fn parse_function(&mut self, _exported: bool) -> Result<FunctionDecl, PolyError> {
1559
+ let start_span = self.advance().span;
1560
+ let (name, _) = self.expect_ident("function name")?;
1561
+ self.expect(&TokKind::LParen, "'('")?;
1562
+ let mut params = Vec::new();
1563
+ while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
1564
+ if self.eat_ident("mut") {}
1565
+ let (pname, pspan) = self.expect_ident("parameter name")?;
1566
+ let ty = if self.eat(&TokKind::Colon) {
1567
+ self.parse_rust_or_py_type()?
1568
+ } else {
1569
+ TypeHint::Unknown
1570
+ };
1571
+ if self.eat(&TokKind::Eq) {
1572
+ // Skip optional default expr in signature
1573
+ let _ = self.parse_expr()?;
1574
+ }
1575
+ if pname != "self" || !params.is_empty() {
1576
+ params.push(Param {
1577
+ name: pname,
1578
+ ty,
1579
+ span: pspan,
1580
+ });
1581
+ } else {
1582
+ params.push(Param {
1583
+ name: pname,
1584
+ ty,
1585
+ span: pspan,
1586
+ });
1587
+ }
1588
+ if !self.eat(&TokKind::Comma) {
1589
+ break;
1590
+ }
1591
+ }
1592
+ self.expect(&TokKind::RParen, "')'")?;
1593
+
1594
+ let mut return_type = TypeHint::Unknown;
1595
+ if self.eat(&TokKind::Arrow) {
1596
+ return_type = self.parse_rust_or_py_type()?;
1597
+ } else if self.lang != Language::Python && self.eat(&TokKind::Colon) {
1598
+ return_type = self.parse_rust_or_py_type()?;
1599
+ }
1600
+
1601
+ let mut body = if self.lang == Language::Python {
1602
+ self.expect(&TokKind::Colon, "':'")?;
1603
+ self.parse_py_suite()?
1604
+ } else {
1605
+ self.parse_brace_block()?
1606
+ };
1607
+
1608
+ // Rust implicit tail expression return
1609
+ if self.lang == Language::Rust
1610
+ && return_type != TypeHint::Void
1611
+ && let Some(last) = body.pop()
1612
+ {
1613
+ match last {
1614
+ Stmt::ExprStmt(expr, sp) => {
1615
+ body.push(Stmt::Return(Some(expr), sp));
1616
+ }
1617
+ other => body.push(other),
1618
+ }
1619
+ }
1620
+ Ok(FunctionDecl {
1621
+ name,
1622
+ params,
1623
+ return_type,
1624
+ body,
1625
+ is_exported: true,
1626
+ span: start_span,
1627
+ })
1628
+ }
1629
+
1630
+ fn parse_struct_or_class(&mut self) -> Result<StructDecl, PolyError> {
1631
+ let start_span = self.advance().span;
1632
+ let (name, _) = self.expect_ident("struct/class name")?;
1633
+ let mut fields = Vec::new();
1634
+ let mut methods = Vec::new();
1635
+
1636
+ if self.lang == Language::Python {
1637
+ self.expect(&TokKind::Colon, "':'")?;
1638
+ self.skip_newlines();
1639
+ self.expect(&TokKind::Indent, "indented class body")?;
1640
+ while !self.at(&TokKind::Dedent) && !self.at(&TokKind::Eof) {
1641
+ self.skip_newlines();
1642
+ if self.at(&TokKind::Dedent) || self.at(&TokKind::Eof) {
1643
+ break;
1644
+ }
1645
+ if self.at_ident("def") {
1646
+ let mut m = self.parse_function(true)?;
1647
+ let short = m.name.clone();
1648
+ m.name = format!("{name}::{short}");
1649
+ methods.push(m);
1650
+ } else if self.eat_ident("pass") {
1651
+ self.eat_stmt_end();
1652
+ } else {
1653
+ let _ = self.parse_stmt()?;
1654
+ }
1655
+ }
1656
+ let _ = self.eat(&TokKind::Dedent);
1657
+ } else {
1658
+ self.expect(&TokKind::LBrace, "'{'")?;
1659
+ while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
1660
+ if self.at_ident("fn") || self.at_ident("function") {
1661
+ let mut m = self.parse_function(true)?;
1662
+ m.name = format!("{name}::{}", m.name);
1663
+ methods.push(m);
1664
+ continue;
1665
+ }
1666
+ if self.lang == Language::JavaScript
1667
+ && matches!(&self.peek().kind, TokKind::Ident(_))
1668
+ && self.peek_n(1).kind == TokKind::LParen
1669
+ {
1670
+ let (mname, mspan) = self.expect_ident("method name")?;
1671
+ self.expect(&TokKind::LParen, "'('")?;
1672
+ let mut params = vec![Param {
1673
+ name: "this".to_string(),
1674
+ ty: TypeHint::Unknown,
1675
+ span: mspan,
1676
+ }];
1677
+ while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
1678
+ let (pn, ps) = self.expect_ident("param")?;
1679
+ params.push(Param {
1680
+ name: pn,
1681
+ ty: TypeHint::Unknown,
1682
+ span: ps,
1683
+ });
1684
+ if !self.eat(&TokKind::Comma) {
1685
+ break;
1686
+ }
1687
+ }
1688
+ self.expect(&TokKind::RParen, "')'")?;
1689
+ let body = self.parse_brace_block()?;
1690
+ methods.push(FunctionDecl {
1691
+ name: format!("{name}::{mname}"),
1692
+ params,
1693
+ return_type: TypeHint::Unknown,
1694
+ body,
1695
+ is_exported: true,
1696
+ span: mspan,
1697
+ });
1698
+ continue;
1699
+ }
1700
+ if self.lang == Language::C && self.is_c_type_start() {
1701
+ let fty = self.parse_c_type()?;
1702
+ let (fname, _) = self.expect_ident("field name")?;
1703
+ self.eat(&TokKind::Semi);
1704
+ fields.push((fname, fty));
1705
+ continue;
1706
+ }
1707
+ let _ = self.eat_ident("pub");
1708
+ let (fname, _) = self.expect_ident("field name")?;
1709
+ let fty = if self.eat(&TokKind::Colon) {
1710
+ self.parse_rust_or_py_type()?
1711
+ } else {
1712
+ TypeHint::Unknown
1713
+ };
1714
+ fields.push((fname, fty));
1715
+ let _ = self.eat(&TokKind::Comma) || self.eat(&TokKind::Semi);
1716
+ }
1717
+ self.expect(&TokKind::RBrace, "'}'")?;
1718
+ let _ = self.eat(&TokKind::Semi);
1719
+ }
1720
+
1721
+ Ok(StructDecl {
1722
+ name,
1723
+ fields,
1724
+ methods,
1725
+ span: start_span,
1726
+ })
1727
+ }
1728
+
1729
+ fn parse_py_suite(&mut self) -> Result<Vec<Stmt>, PolyError> {
1730
+ if self.eat(&TokKind::Newline) {
1731
+ self.skip_newlines();
1732
+ self.expect(&TokKind::Indent, "indented block")?;
1733
+ let mut stmts = Vec::new();
1734
+ while !self.at(&TokKind::Dedent) && !self.at(&TokKind::Eof) {
1735
+ self.skip_newlines();
1736
+ if self.at(&TokKind::Dedent) || self.at(&TokKind::Eof) {
1737
+ break;
1738
+ }
1739
+ stmts.push(self.parse_stmt()?);
1740
+ }
1741
+ let _ = self.eat(&TokKind::Dedent);
1742
+ Ok(stmts)
1743
+ } else {
1744
+ // Single-line suite: `if cond: return x`
1745
+ let s = self.parse_stmt()?;
1746
+ Ok(vec![s])
1747
+ }
1748
+ }
1749
+
1750
+ fn parse_brace_block(&mut self) -> Result<Vec<Stmt>, PolyError> {
1751
+ self.expect(&TokKind::LBrace, "'{'")?;
1752
+ let mut stmts = Vec::new();
1753
+ self.skip_newlines();
1754
+ while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
1755
+ stmts.push(self.parse_stmt()?);
1756
+ self.skip_newlines();
1757
+ }
1758
+ self.expect(&TokKind::RBrace, "'}'")?;
1759
+ Ok(stmts)
1760
+ }
1761
+
1762
+ fn parse_stmt(&mut self) -> Result<Stmt, PolyError> {
1763
+ self.skip_newlines();
1764
+ let sp = self.peek().span;
1765
+
1766
+ if self.at(&TokKind::LBrace) {
1767
+ let body = self.parse_brace_block()?;
1768
+ return Ok(Stmt::Block(body, sp));
1769
+ }
1770
+
1771
+ if self.eat_ident("pass") {
1772
+ self.eat_stmt_end();
1773
+ return Ok(Stmt::Block(Vec::new(), sp));
1774
+ }
1775
+
1776
+ if self.eat_ident("break") {
1777
+ self.eat_stmt_end();
1778
+ return Ok(Stmt::Break(sp));
1779
+ }
1780
+
1781
+ if self.eat_ident("continue") {
1782
+ self.eat_stmt_end();
1783
+ return Ok(Stmt::Continue(sp));
1784
+ }
1785
+
1786
+ if self.eat_ident("return") {
1787
+ let val = if self.at(&TokKind::Semi)
1788
+ || self.at(&TokKind::Newline)
1789
+ || self.at(&TokKind::RBrace)
1790
+ || self.at(&TokKind::Dedent)
1791
+ || self.at(&TokKind::Eof)
1792
+ {
1793
+ None
1794
+ } else {
1795
+ Some(self.parse_expr()?)
1796
+ };
1797
+ self.eat_stmt_end();
1798
+ return Ok(Stmt::Return(val, sp));
1799
+ }
1800
+
1801
+ if self.eat_ident("if") {
1802
+ return self.parse_if_stmt(sp);
1803
+ }
1804
+
1805
+ if self.eat_ident("while") {
1806
+ let cond = if self.lang == Language::Python {
1807
+ self.parse_expr_no_struct()?
1808
+ } else if self.at(&TokKind::LParen) {
1809
+ self.advance();
1810
+ let e = self.parse_expr()?;
1811
+ self.expect(&TokKind::RParen, "')'")?;
1812
+ e
1813
+ } else {
1814
+ self.parse_expr_no_struct()?
1815
+ };
1816
+ let body = if self.lang == Language::Python {
1817
+ self.expect(&TokKind::Colon, "':'")?;
1818
+ self.parse_py_suite()?
1819
+ } else {
1820
+ self.parse_brace_block()?
1821
+ };
1822
+ return Ok(Stmt::While {
1823
+ cond,
1824
+ body,
1825
+ span: sp,
1826
+ });
1827
+ }
1828
+
1829
+ if self.eat_ident("loop") {
1830
+ let body = self.parse_brace_block()?;
1831
+ return Ok(Stmt::While {
1832
+ cond: Expr::Bool(true, sp),
1833
+ body,
1834
+ span: sp,
1835
+ });
1836
+ }
1837
+
1838
+ if self.eat_ident("for") {
1839
+ return self.parse_for_stmt(sp);
1840
+ }
1841
+
1842
+ // `let [mut] x [: ty] = expr;` / `const x = expr;` / `var x = expr;`
1843
+ if self.at_ident("let") || self.at_ident("const") || self.at_ident("var") {
1844
+ let kw = match &self.peek().kind {
1845
+ TokKind::Ident(s) => s.clone(),
1846
+ _ => unreachable!(),
1847
+ };
1848
+ let is_fn_scoped = kw == "var";
1849
+ self.advance();
1850
+ let _ = self.eat_ident("mut");
1851
+ let (name, _) = self.expect_ident("variable name")?;
1852
+ let ty = if self.eat(&TokKind::Colon) {
1853
+ self.parse_rust_or_py_type()?
1854
+ } else {
1855
+ TypeHint::Unknown
1856
+ };
1857
+ let init = if self.eat(&TokKind::Eq) {
1858
+ Some(self.parse_expr()?)
1859
+ } else {
1860
+ None
1861
+ };
1862
+ self.eat_stmt_end();
1863
+ return Ok(Stmt::VarDecl {
1864
+ name,
1865
+ ty,
1866
+ init,
1867
+ is_function_scoped: is_fn_scoped,
1868
+ span: sp,
1869
+ });
1870
+ }
1871
+
1872
+ // C typed local declaration: `double final_cost = ...;`
1873
+ if self.lang == Language::C && self.is_c_type_start() {
1874
+ let ty = self.parse_c_type()?;
1875
+ let (name, _) = self.expect_ident("variable name")?;
1876
+ if self.eat(&TokKind::LBracket) {
1877
+ while !self.at(&TokKind::RBracket) && !self.at(&TokKind::Eof) {
1878
+ self.advance();
1879
+ }
1880
+ self.expect(&TokKind::RBracket, "']'")?;
1881
+ }
1882
+ let init = if self.eat(&TokKind::Eq) {
1883
+ Some(self.parse_expr()?)
1884
+ } else {
1885
+ None
1886
+ };
1887
+ self.eat_stmt_end();
1888
+ return Ok(Stmt::VarDecl {
1889
+ name,
1890
+ ty,
1891
+ init,
1892
+ is_function_scoped: false,
1893
+ span: sp,
1894
+ });
1895
+ }
1896
+
1897
+ // Python typed variable `x: int = 10`
1898
+ if self.lang == Language::Python
1899
+ && matches!(&self.peek().kind, TokKind::Ident(_))
1900
+ && self.peek_n(1).kind == TokKind::Colon
1901
+ {
1902
+ let (name, _) = self.expect_ident("variable name")?;
1903
+ self.advance(); // ':'
1904
+ let ty = self.parse_rust_or_py_type()?;
1905
+ let init = if self.eat(&TokKind::Eq) {
1906
+ Some(self.parse_expr()?)
1907
+ } else {
1908
+ None
1909
+ };
1910
+ self.eat_stmt_end();
1911
+ return Ok(Stmt::VarDecl {
1912
+ name,
1913
+ ty,
1914
+ init,
1915
+ is_function_scoped: true,
1916
+ span: sp,
1917
+ });
1918
+ }
1919
+
1920
+ // Expression or assignment
1921
+ let lhs = self.parse_expr()?;
1922
+ let compound = if self.eat(&TokKind::Eq) {
1923
+ Some(None)
1924
+ } else if self.eat(&TokKind::PlusEq) {
1925
+ Some(Some(BinOp::Add))
1926
+ } else if self.eat(&TokKind::MinusEq) {
1927
+ Some(Some(BinOp::Sub))
1928
+ } else if self.eat(&TokKind::StarEq) {
1929
+ Some(Some(BinOp::Mul))
1930
+ } else if self.eat(&TokKind::SlashEq) {
1931
+ Some(Some(BinOp::Div))
1932
+ } else if self.eat(&TokKind::PercentEq) {
1933
+ Some(Some(BinOp::Mod))
1934
+ } else {
1935
+ None
1936
+ };
1937
+
1938
+ if let Some(op) = compound {
1939
+ let val = self.parse_expr()?;
1940
+ self.eat_stmt_end();
1941
+ let target = match lhs {
1942
+ Expr::Var(name, _) => {
1943
+ if self.lang == Language::Python && op.is_none() {
1944
+ return Ok(Stmt::VarDecl {
1945
+ name,
1946
+ ty: TypeHint::Unknown,
1947
+ init: Some(val),
1948
+ is_function_scoped: true,
1949
+ span: sp,
1950
+ });
1951
+ }
1952
+ AssignTarget::Var(name)
1953
+ }
1954
+ Expr::Member { object, field, .. } => AssignTarget::Field(object, field),
1955
+ Expr::Index { object, index, .. } => AssignTarget::Index(object, index),
1956
+ other => {
1957
+ return Err(PolyError::spanned(
1958
+ "E0116",
1959
+ "invalid assignment target",
1960
+ other.span(),
1961
+ ));
1962
+ }
1963
+ };
1964
+ return Ok(Stmt::Assign {
1965
+ target,
1966
+ op,
1967
+ value: val,
1968
+ span: sp,
1969
+ });
1970
+ }
1971
+
1972
+ // In Rust, a statement without `;` at the end of a block is an expression statement (handled by `parse_function` tail-return!).
1973
+ self.eat_stmt_end();
1974
+ Ok(Stmt::ExprStmt(lhs, sp))
1975
+ }
1976
+
1977
+ fn parse_if_stmt(&mut self, sp: Span) -> Result<Stmt, PolyError> {
1978
+ let cond = if self.lang == Language::Python {
1979
+ self.parse_expr_no_struct()?
1980
+ } else if self.at(&TokKind::LParen) {
1981
+ self.advance();
1982
+ let e = self.parse_expr()?;
1983
+ self.expect(&TokKind::RParen, "')'")?;
1984
+ e
1985
+ } else {
1986
+ self.parse_expr_no_struct()?
1987
+ };
1988
+
1989
+ let then_body = if self.lang == Language::Python {
1990
+ self.expect(&TokKind::Colon, "':'")?;
1991
+ self.parse_py_suite()?
1992
+ } else {
1993
+ self.parse_brace_block()?
1994
+ };
1995
+
1996
+ let mut else_body = Vec::new();
1997
+ if self.lang == Language::Python {
1998
+ self.skip_newlines();
1999
+ if self.eat_ident("elif") {
2000
+ let nested = self.parse_if_stmt(self.peek().span)?;
2001
+ else_body.push(nested);
2002
+ } else if self.eat_ident("else") {
2003
+ self.expect(&TokKind::Colon, "':'")?;
2004
+ else_body = self.parse_py_suite()?;
2005
+ }
2006
+ } else if self.eat_ident("else") {
2007
+ if self.eat_ident("if") {
2008
+ else_body.push(self.parse_if_stmt(self.peek().span)?);
2009
+ } else {
2010
+ else_body = self.parse_brace_block()?;
2011
+ }
2012
+ }
2013
+
2014
+ Ok(Stmt::If {
2015
+ cond,
2016
+ then_body,
2017
+ else_body,
2018
+ span: sp,
2019
+ })
2020
+ }
2021
+
2022
+ fn parse_for_stmt(&mut self, sp: Span) -> Result<Stmt, PolyError> {
2023
+ if self.lang == Language::Python {
2024
+ let (var, _) = self.expect_ident("loop variable")?;
2025
+ if !self.eat_ident("in") {
2026
+ return Err(PolyError::spanned(
2027
+ "E0117",
2028
+ "expected 'in' in Python for-loop",
2029
+ self.peek().span,
2030
+ ));
2031
+ }
2032
+ if self.at_ident("range") && self.peek_n(1).kind == TokKind::LParen {
2033
+ self.advance();
2034
+ self.advance();
2035
+ let mut args = Vec::new();
2036
+ while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
2037
+ args.push(self.parse_expr()?);
2038
+ if !self.eat(&TokKind::Comma) {
2039
+ break;
2040
+ }
2041
+ }
2042
+ self.expect(&TokKind::RParen, "')'")?;
2043
+ self.expect(&TokKind::Colon, "':'")?;
2044
+ let body = self.parse_py_suite()?;
2045
+ let (start, end, step) = match args.len() {
2046
+ 1 => (Expr::Int(0, sp), args.remove(0), None),
2047
+ 2 => (args.remove(0), args.remove(0), None),
2048
+ 3 => (args.remove(0), args.remove(0), Some(args.remove(0))),
2049
+ _ => {
2050
+ return Err(PolyError::spanned(
2051
+ "E0118",
2052
+ "range() takes 1 to 3 arguments",
2053
+ sp,
2054
+ ));
2055
+ }
2056
+ };
2057
+ return Ok(Stmt::ForRange {
2058
+ var,
2059
+ start,
2060
+ end,
2061
+ inclusive: false,
2062
+ step,
2063
+ body,
2064
+ span: sp,
2065
+ });
2066
+ }
2067
+ let iter = self.parse_expr_no_struct()?;
2068
+ self.expect(&TokKind::Colon, "':'")?;
2069
+ let body = self.parse_py_suite()?;
2070
+ return Ok(Stmt::ForIn {
2071
+ var,
2072
+ iter,
2073
+ body,
2074
+ span: sp,
2075
+ });
2076
+ }
2077
+
2078
+ if self.lang == Language::Rust {
2079
+ let (var, _) = self.expect_ident("loop variable")?;
2080
+ if !self.eat_ident("in") {
2081
+ return Err(PolyError::spanned(
2082
+ "E0117",
2083
+ "expected 'in' in Rust for-loop",
2084
+ self.peek().span,
2085
+ ));
2086
+ }
2087
+ let start = self.parse_expr_no_struct()?;
2088
+ if self.eat(&TokKind::DotDotEq) {
2089
+ let end = self.parse_expr_no_struct()?;
2090
+ let body = self.parse_brace_block()?;
2091
+ return Ok(Stmt::ForRange {
2092
+ var,
2093
+ start,
2094
+ end,
2095
+ inclusive: true,
2096
+ step: None,
2097
+ body,
2098
+ span: sp,
2099
+ });
2100
+ } else if self.eat(&TokKind::DotDot) {
2101
+ let end = self.parse_expr_no_struct()?;
2102
+ let body = self.parse_brace_block()?;
2103
+ return Ok(Stmt::ForRange {
2104
+ var,
2105
+ start,
2106
+ end,
2107
+ inclusive: false,
2108
+ step: None,
2109
+ body,
2110
+ span: sp,
2111
+ });
2112
+ }
2113
+ let body = self.parse_brace_block()?;
2114
+ return Ok(Stmt::ForIn {
2115
+ var,
2116
+ iter: start,
2117
+ body,
2118
+ span: sp,
2119
+ });
2120
+ }
2121
+
2122
+ // C / JS `for (init; cond; step)` or `for (let x of arr)`
2123
+ self.expect(&TokKind::LParen, "'('")?;
2124
+ if (self.at_ident("let") || self.at_ident("const") || self.at_ident("var"))
2125
+ && matches!(&self.peek_n(1).kind, TokKind::Ident(_))
2126
+ && matches!(&self.peek_n(2).kind, TokKind::Ident(s) if s == "of")
2127
+ {
2128
+ self.advance();
2129
+ let (var, _) = self.expect_ident("loop variable")?;
2130
+ self.advance(); // 'of'
2131
+ let iter = self.parse_expr()?;
2132
+ self.expect(&TokKind::RParen, "')'")?;
2133
+ let body = self.parse_brace_block()?;
2134
+ return Ok(Stmt::ForIn {
2135
+ var,
2136
+ iter,
2137
+ body,
2138
+ span: sp,
2139
+ });
2140
+ }
2141
+
2142
+ let mut stmts = Vec::new();
2143
+ if !self.eat(&TokKind::Semi) {
2144
+ let init = self.parse_stmt()?;
2145
+ stmts.push(init);
2146
+ }
2147
+ let cond = if !self.at(&TokKind::Semi) {
2148
+ self.parse_expr()?
2149
+ } else {
2150
+ Expr::Bool(true, sp)
2151
+ };
2152
+ self.expect(&TokKind::Semi, "';'")?;
2153
+ let step_stmt = if !self.at(&TokKind::RParen) {
2154
+ Some(self.parse_stmt_inline()?)
2155
+ } else {
2156
+ None
2157
+ };
2158
+ self.expect(&TokKind::RParen, "')'")?;
2159
+ let mut body = self.parse_brace_block()?;
2160
+ if let Some(step) = step_stmt {
2161
+ body.push(step);
2162
+ }
2163
+ stmts.push(Stmt::While {
2164
+ cond,
2165
+ body,
2166
+ span: sp,
2167
+ });
2168
+ Ok(Stmt::Block(stmts, sp))
2169
+ }
2170
+
2171
+ fn parse_stmt_inline(&mut self) -> Result<Stmt, PolyError> {
2172
+ let sp = self.peek().span;
2173
+ let lhs = self.parse_expr()?;
2174
+ let op = if self.eat(&TokKind::Eq) {
2175
+ Some(None)
2176
+ } else if self.eat(&TokKind::PlusEq) {
2177
+ Some(Some(BinOp::Add))
2178
+ } else if self.eat(&TokKind::MinusEq) {
2179
+ Some(Some(BinOp::Sub))
2180
+ } else if self.eat(&TokKind::StarEq) {
2181
+ Some(Some(BinOp::Mul))
2182
+ } else if self.eat(&TokKind::SlashEq) {
2183
+ Some(Some(BinOp::Div))
2184
+ } else {
2185
+ None
2186
+ };
2187
+ if let Some(op) = op {
2188
+ let value = self.parse_expr()?;
2189
+ let target = match lhs {
2190
+ Expr::Var(n, _) => AssignTarget::Var(n),
2191
+ Expr::Member { object, field, .. } => AssignTarget::Field(object, field),
2192
+ Expr::Index { object, index, .. } => AssignTarget::Index(object, index),
2193
+ other => {
2194
+ return Err(PolyError::spanned(
2195
+ "E0116",
2196
+ "invalid assignment target",
2197
+ other.span(),
2198
+ ));
2199
+ }
2200
+ };
2201
+ Ok(Stmt::Assign {
2202
+ target,
2203
+ op,
2204
+ value,
2205
+ span: sp,
2206
+ })
2207
+ } else {
2208
+ Ok(Stmt::ExprStmt(lhs, sp))
2209
+ }
2210
+ }
2211
+
2212
+ fn parse_expr(&mut self) -> Result<Expr, PolyError> {
2213
+ self.parse_expr_bp(0, true)
2214
+ }
2215
+
2216
+ fn parse_expr_no_struct(&mut self) -> Result<Expr, PolyError> {
2217
+ self.parse_expr_bp(0, false)
2218
+ }
2219
+
2220
+ fn parse_expr_bp(&mut self, min_bp: u8, allow_struct_lit: bool) -> Result<Expr, PolyError> {
2221
+ let mut lhs = self.parse_prefix(allow_struct_lit)?;
2222
+ lhs = self.parse_postfix(lhs, allow_struct_lit)?;
2223
+
2224
+ loop {
2225
+ // Python ternary: `a if cond else b`
2226
+ if self.lang == Language::Python && min_bp <= 1 && self.eat_ident("if") {
2227
+ let cond = self.parse_expr_bp(0, allow_struct_lit)?;
2228
+ if !self.eat_ident("else") {
2229
+ return Err(PolyError::spanned(
2230
+ "E0119",
2231
+ "expected 'else' in conditional expression",
2232
+ self.peek().span,
2233
+ ));
2234
+ }
2235
+ let else_expr = self.parse_expr_bp(0, allow_struct_lit)?;
2236
+ let sp = lhs.span().merge(else_expr.span());
2237
+ lhs = Expr::Ternary {
2238
+ cond: Box::new(cond),
2239
+ then_expr: Box::new(lhs),
2240
+ else_expr: Box::new(else_expr),
2241
+ span: sp,
2242
+ };
2243
+ continue;
2244
+ }
2245
+
2246
+ // C / JS ternary: `cond ? a : b`
2247
+ if self.lang != Language::Python && min_bp <= 1 && self.eat(&TokKind::Question) {
2248
+ let then_expr = self.parse_expr()?;
2249
+ self.expect(&TokKind::Colon, "':'")?;
2250
+ let else_expr = self.parse_expr_bp(1, allow_struct_lit)?;
2251
+ let sp = lhs.span().merge(else_expr.span());
2252
+ lhs = Expr::Ternary {
2253
+ cond: Box::new(lhs),
2254
+ then_expr: Box::new(then_expr),
2255
+ else_expr: Box::new(else_expr),
2256
+ span: sp,
2257
+ };
2258
+ continue;
2259
+ }
2260
+
2261
+ // Rust/C explicit cast `expr as f64`
2262
+ if self.eat_ident("as") {
2263
+ let _ = self.parse_rust_or_py_type()?;
2264
+ continue;
2265
+ }
2266
+
2267
+ let Some((op, l_bp, r_bp)) = self.infix_bp() else {
2268
+ break;
2269
+ };
2270
+ if l_bp < min_bp {
2271
+ break;
2272
+ }
2273
+ self.advance();
2274
+ let rhs = self.parse_expr_bp(r_bp, allow_struct_lit)?;
2275
+ let sp = lhs.span().merge(rhs.span());
2276
+ lhs = Expr::Binary(op, Box::new(lhs), Box::new(rhs), sp);
2277
+ }
2278
+
2279
+ Ok(lhs)
2280
+ }
2281
+
2282
+ fn infix_bp(&self) -> Option<(BinOp, u8, u8)> {
2283
+ match &self.peek().kind {
2284
+ TokKind::PipePipe => Some((BinOp::Or, 2, 3)),
2285
+ TokKind::Ident(s) if s == "or" => Some((BinOp::Or, 2, 3)),
2286
+ TokKind::AmpAmp => Some((BinOp::And, 4, 5)),
2287
+ TokKind::Ident(s) if s == "and" => Some((BinOp::And, 4, 5)),
2288
+ TokKind::Pipe => Some((BinOp::BitOr, 6, 7)),
2289
+ TokKind::Caret => Some((BinOp::BitXor, 8, 9)),
2290
+ TokKind::Amp => Some((BinOp::BitAnd, 10, 11)),
2291
+ TokKind::EqEq | TokKind::EqEqEq => Some((BinOp::Eq, 12, 13)),
2292
+ TokKind::BangEq | TokKind::BangEqEq => Some((BinOp::Ne, 12, 13)),
2293
+ TokKind::Lt => Some((BinOp::Lt, 14, 15)),
2294
+ TokKind::Le => Some((BinOp::Le, 14, 15)),
2295
+ TokKind::Gt => Some((BinOp::Gt, 14, 15)),
2296
+ TokKind::Ge => Some((BinOp::Ge, 14, 15)),
2297
+ TokKind::Shl => Some((BinOp::Shl, 16, 17)),
2298
+ TokKind::Shr => Some((BinOp::Shr, 16, 17)),
2299
+ TokKind::Plus => Some((BinOp::Add, 18, 19)),
2300
+ TokKind::Minus => Some((BinOp::Sub, 18, 19)),
2301
+ TokKind::Star => Some((BinOp::Mul, 20, 21)),
2302
+ TokKind::Slash => Some((BinOp::Div, 20, 21)),
2303
+ TokKind::SlashSlash => Some((BinOp::FloorDiv, 20, 21)),
2304
+ TokKind::Percent => Some((BinOp::Mod, 20, 21)),
2305
+ _ => None,
2306
+ }
2307
+ }
2308
+
2309
+ fn parse_prefix(&mut self, allow_struct_lit: bool) -> Result<Expr, PolyError> {
2310
+ let t = self.peek().clone();
2311
+ match t.kind {
2312
+ TokKind::Minus => {
2313
+ self.advance();
2314
+ let inner = self.parse_expr_bp(22, allow_struct_lit)?;
2315
+ let sp = t.span.merge(inner.span());
2316
+ Ok(Expr::Unary(UnaryOp::Neg, Box::new(inner), sp))
2317
+ }
2318
+ TokKind::Plus => {
2319
+ self.advance();
2320
+ self.parse_expr_bp(22, allow_struct_lit)
2321
+ }
2322
+ TokKind::Bang => {
2323
+ self.advance();
2324
+ let inner = self.parse_expr_bp(22, allow_struct_lit)?;
2325
+ let sp = t.span.merge(inner.span());
2326
+ Ok(Expr::Unary(UnaryOp::Not, Box::new(inner), sp))
2327
+ }
2328
+ TokKind::Tilde => {
2329
+ self.advance();
2330
+ let inner = self.parse_expr_bp(22, allow_struct_lit)?;
2331
+ let sp = t.span.merge(inner.span());
2332
+ Ok(Expr::Unary(UnaryOp::BitNot, Box::new(inner), sp))
2333
+ }
2334
+ TokKind::Ident(ref s) if s == "not" => {
2335
+ self.advance();
2336
+ let inner = self.parse_expr_bp(22, allow_struct_lit)?;
2337
+ let sp = t.span.merge(inner.span());
2338
+ Ok(Expr::Unary(UnaryOp::Not, Box::new(inner), sp))
2339
+ }
2340
+ TokKind::PlusPlus | TokKind::MinusMinus => {
2341
+ let inc = t.kind == TokKind::PlusPlus;
2342
+ self.advance();
2343
+ let (name, nspan) = self.expect_ident("variable")?;
2344
+ Ok(Expr::Update {
2345
+ name,
2346
+ inc,
2347
+ prefix: true,
2348
+ span: t.span.merge(nspan),
2349
+ })
2350
+ }
2351
+ TokKind::Int(v) => {
2352
+ self.advance();
2353
+ Ok(Expr::Int(v, t.span))
2354
+ }
2355
+ TokKind::Float(v) => {
2356
+ self.advance();
2357
+ Ok(Expr::Float(v, t.span))
2358
+ }
2359
+ TokKind::Str(s) => {
2360
+ self.advance();
2361
+ Ok(Expr::Str(s, t.span))
2362
+ }
2363
+ TokKind::LParen => {
2364
+ self.advance();
2365
+ if self.lang == Language::C
2366
+ && self.is_c_type_start()
2367
+ && self.peek_n(1).kind == TokKind::RParen
2368
+ {
2369
+ let _ = self.parse_c_type()?;
2370
+ self.expect(&TokKind::RParen, "')'")?;
2371
+ return self.parse_expr_bp(22, allow_struct_lit);
2372
+ }
2373
+ let e = self.parse_expr()?;
2374
+ self.expect(&TokKind::RParen, "')'")?;
2375
+ Ok(e)
2376
+ }
2377
+ TokKind::LBracket => {
2378
+ self.advance();
2379
+ let mut items = Vec::new();
2380
+ while !self.at(&TokKind::RBracket) && !self.at(&TokKind::Eof) {
2381
+ items.push(self.parse_expr()?);
2382
+ if !self.eat(&TokKind::Comma) {
2383
+ break;
2384
+ }
2385
+ }
2386
+ let end = self.expect(&TokKind::RBracket, "']'")?;
2387
+ Ok(Expr::Array(items, t.span.merge(end.span)))
2388
+ }
2389
+ TokKind::LBrace => {
2390
+ self.advance();
2391
+ let mut fields = Vec::new();
2392
+ while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
2393
+ let key = match &self.peek().kind {
2394
+ TokKind::Ident(k) | TokKind::Str(k) => {
2395
+ let k = k.clone();
2396
+ self.advance();
2397
+ k
2398
+ }
2399
+ _ => {
2400
+ return Err(PolyError::spanned(
2401
+ "E0120",
2402
+ "expected object literal field key",
2403
+ self.peek().span,
2404
+ ));
2405
+ }
2406
+ };
2407
+ self.expect(&TokKind::Colon, "':'")?;
2408
+ let val = self.parse_expr()?;
2409
+ fields.push((key, val));
2410
+ if !self.eat(&TokKind::Comma) {
2411
+ break;
2412
+ }
2413
+ }
2414
+ let end = self.expect(&TokKind::RBrace, "'}'")?;
2415
+ Ok(Expr::ObjectLit(None, fields, t.span.merge(end.span)))
2416
+ }
2417
+ TokKind::Ident(ref s) if matches!(s.as_str(), "None" | "null" | "nil" | "undefined") => {
2418
+ self.advance();
2419
+ Ok(Expr::Nil(t.span))
2420
+ }
2421
+ TokKind::Ident(ref s) if matches!(s.as_str(), "true" | "True") => {
2422
+ self.advance();
2423
+ Ok(Expr::Bool(true, t.span))
2424
+ }
2425
+ TokKind::Ident(ref s) if matches!(s.as_str(), "false" | "False") => {
2426
+ self.advance();
2427
+ Ok(Expr::Bool(false, t.span))
2428
+ }
2429
+ TokKind::Ident(ref s) if s == "new" => {
2430
+ self.advance();
2431
+ let (cls, _) = self.expect_ident("class name")?;
2432
+ let mut args = Vec::new();
2433
+ if self.eat(&TokKind::LParen) {
2434
+ while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
2435
+ args.push(self.parse_expr()?);
2436
+ if !self.eat(&TokKind::Comma) {
2437
+ break;
2438
+ }
2439
+ }
2440
+ self.expect(&TokKind::RParen, "')'")?;
2441
+ }
2442
+ let mut fields = Vec::new();
2443
+ for (idx, a) in args.into_iter().enumerate() {
2444
+ fields.push((format!("_{idx}"), a));
2445
+ }
2446
+ Ok(Expr::ObjectLit(Some(cls), fields, t.span))
2447
+ }
2448
+ TokKind::Ident(ref s) if s == "lambda" && self.lang == Language::Python => {
2449
+ self.advance();
2450
+ let mut params = Vec::new();
2451
+ while !self.at(&TokKind::Colon) && !self.at(&TokKind::Eof) {
2452
+ let (pn, ps) = self.expect_ident("lambda param")?;
2453
+ params.push(Param {
2454
+ name: pn,
2455
+ ty: TypeHint::Unknown,
2456
+ span: ps,
2457
+ });
2458
+ if !self.eat(&TokKind::Comma) {
2459
+ break;
2460
+ }
2461
+ }
2462
+ self.expect(&TokKind::Colon, "':'")?;
2463
+ let body_expr = self.parse_expr()?;
2464
+ let sp = t.span.merge(body_expr.span());
2465
+ let name = self.fresh_anon_name();
2466
+ self.extra_functions.push(FunctionDecl {
2467
+ name: name.clone(),
2468
+ params,
2469
+ return_type: TypeHint::Unknown,
2470
+ body: vec![Stmt::Return(Some(body_expr), sp)],
2471
+ is_exported: false,
2472
+ span: sp,
2473
+ });
2474
+ Ok(Expr::Var(name, sp))
2475
+ }
2476
+ TokKind::Ident(name) => {
2477
+ self.advance();
2478
+ if allow_struct_lit
2479
+ && self.lang == Language::Rust
2480
+ && self.struct_names.contains(&name)
2481
+ && self.eat(&TokKind::LBrace)
2482
+ {
2483
+ let mut fields = Vec::new();
2484
+ while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
2485
+ let (k, _) = self.expect_ident("field name")?;
2486
+ self.expect(&TokKind::Colon, "':'")?;
2487
+ let v = self.parse_expr()?;
2488
+ fields.push((k, v));
2489
+ if !self.eat(&TokKind::Comma) {
2490
+ break;
2491
+ }
2492
+ }
2493
+ let end = self.expect(&TokKind::RBrace, "'}'")?;
2494
+ return Ok(Expr::ObjectLit(
2495
+ Some(name),
2496
+ fields,
2497
+ t.span.merge(end.span),
2498
+ ));
2499
+ }
2500
+ Ok(Expr::Var(name, t.span))
2501
+ }
2502
+ other => Err(PolyError::spanned(
2503
+ "E0121",
2504
+ format!("unexpected token {:?} in expression", other),
2505
+ t.span,
2506
+ )),
2507
+ }
2508
+ }
2509
+
2510
+ fn fresh_anon_name(&mut self) -> String {
2511
+ let id = self.anon_counter;
2512
+ self.anon_counter += 1;
2513
+ format!("__lambda_{id}")
2514
+ }
2515
+
2516
+ fn parse_postfix(&mut self, mut expr: Expr, _allow_struct_lit: bool) -> Result<Expr, PolyError> {
2517
+ loop {
2518
+ if self.eat(&TokKind::LParen) {
2519
+ let mut args = Vec::new();
2520
+ while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
2521
+ args.push(self.parse_expr()?);
2522
+ if !self.eat(&TokKind::Comma) {
2523
+ break;
2524
+ }
2525
+ }
2526
+ let end = self.expect(&TokKind::RParen, "')'")?;
2527
+ let sp = expr.span().merge(end.span);
2528
+ expr = Expr::Call {
2529
+ callee: Box::new(expr),
2530
+ args,
2531
+ span: sp,
2532
+ };
2533
+ } else if self.eat(&TokKind::Dot) || self.eat(&TokKind::ColonColon) {
2534
+ let (field, fspan) = self.expect_ident("member name")?;
2535
+ let sp = expr.span().merge(fspan);
2536
+ expr = Expr::Member {
2537
+ object: Box::new(expr),
2538
+ field,
2539
+ span: sp,
2540
+ };
2541
+ } else if self.eat(&TokKind::LBracket) {
2542
+ let idx = self.parse_expr()?;
2543
+ let end = self.expect(&TokKind::RBracket, "']'")?;
2544
+ let sp = expr.span().merge(end.span);
2545
+ expr = Expr::Index {
2546
+ object: Box::new(expr),
2547
+ index: Box::new(idx),
2548
+ span: sp,
2549
+ };
2550
+ } else if self.eat(&TokKind::PlusPlus) {
2551
+ let sp = expr.span();
2552
+ if let Expr::Var(name, _) = expr {
2553
+ expr = Expr::Update {
2554
+ name,
2555
+ inc: true,
2556
+ prefix: false,
2557
+ span: sp,
2558
+ };
2559
+ } else {
2560
+ return Err(PolyError::spanned(
2561
+ "E0122",
2562
+ "'++' target must be a variable",
2563
+ sp,
2564
+ ));
2565
+ }
2566
+ } else if self.eat(&TokKind::MinusMinus) {
2567
+ let sp = expr.span();
2568
+ if let Expr::Var(name, _) = expr {
2569
+ expr = Expr::Update {
2570
+ name,
2571
+ inc: false,
2572
+ prefix: false,
2573
+ span: sp,
2574
+ };
2575
+ } else {
2576
+ return Err(PolyError::spanned(
2577
+ "E0122",
2578
+ "'--' target must be a variable",
2579
+ sp,
2580
+ ));
2581
+ }
2582
+ } else {
2583
+ break;
2584
+ }
2585
+ }
2586
+ Ok(expr)
2587
+ }
2588
+ }
2589
+
2590
+ pub fn parse_module(
2591
+ file_id: usize,
2592
+ language: Language,
2593
+ source: &str,
2594
+ ) -> Result<ModuleAst, PolyError> {
2595
+ let lexer = Lexer::new(file_id, language, source);
2596
+ let (tokens, directives) = lexer.tokenize().map_err(|mut err| {
2597
+ if err.diagnostics.is_empty() {
2598
+ err.diagnostics
2599
+ .push(Diagnostic::error("E0100", "lexing error"));
2600
+ }
2601
+ err
2602
+ })?;
2603
+ let mut parser = Parser::new(language, tokens);
2604
+ parser.parse_module(directives)
2605
+ }