polycomp 0.0.0-stage → 0.3.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,4755 @@
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
+ Regex(String, String),
11
+ InterpStr(Vec<(bool, String, Option<String>, u32, u32)>),
12
+ Newline,
13
+ Indent,
14
+ Dedent,
15
+ LParen,
16
+ RParen,
17
+ LBrace,
18
+ RBrace,
19
+ LBracket,
20
+ RBracket,
21
+ Comma,
22
+ Colon,
23
+ ColonColon,
24
+ ColonEq,
25
+ Semi,
26
+ Dot,
27
+ DotDot,
28
+ DotDotEq,
29
+ Arrow,
30
+ FatArrow,
31
+ Question,
32
+ QuestionDot,
33
+ QuestionQuestion,
34
+ Plus,
35
+ Minus,
36
+ Star,
37
+ StarStar,
38
+ Slash,
39
+ SlashSlash,
40
+ Percent,
41
+ PlusPlus,
42
+ MinusMinus,
43
+ Eq,
44
+ PlusEq,
45
+ MinusEq,
46
+ StarEq,
47
+ SlashEq,
48
+ PercentEq,
49
+ EqEq,
50
+ EqEqEq,
51
+ BangEq,
52
+ BangEqEq,
53
+ Lt,
54
+ Le,
55
+ Gt,
56
+ Ge,
57
+ Amp,
58
+ AmpAmp,
59
+ Pipe,
60
+ PipePipe,
61
+ Caret,
62
+ Tilde,
63
+ Bang,
64
+ Shl,
65
+ Shr,
66
+ At,
67
+ Eof,
68
+ }
69
+
70
+ #[derive(Debug, Clone)]
71
+ struct Tok {
72
+ kind: TokKind,
73
+ span: Span,
74
+ }
75
+
76
+ fn can_precede_regex(tokens: &[Tok]) -> bool {
77
+ let Some(last) = tokens.last() else {
78
+ return true;
79
+ };
80
+ match &last.kind {
81
+ TokKind::LParen
82
+ | TokKind::LBracket
83
+ | TokKind::LBrace
84
+ | TokKind::Comma
85
+ | TokKind::Semi
86
+ | TokKind::Colon
87
+ | TokKind::ColonEq
88
+ | TokKind::Question
89
+ | TokKind::QuestionQuestion
90
+ | TokKind::Arrow
91
+ | TokKind::FatArrow
92
+ | TokKind::Newline
93
+ | TokKind::Eq
94
+ | TokKind::PlusEq
95
+ | TokKind::MinusEq
96
+ | TokKind::StarEq
97
+ | TokKind::SlashEq
98
+ | TokKind::PercentEq
99
+ | TokKind::Plus
100
+ | TokKind::Minus
101
+ | TokKind::Star
102
+ | TokKind::StarStar
103
+ | TokKind::Slash
104
+ | TokKind::Percent
105
+ | TokKind::EqEq
106
+ | TokKind::EqEqEq
107
+ | TokKind::BangEq
108
+ | TokKind::BangEqEq
109
+ | TokKind::Lt
110
+ | TokKind::Le
111
+ | TokKind::Gt
112
+ | TokKind::Ge
113
+ | TokKind::Amp
114
+ | TokKind::AmpAmp
115
+ | TokKind::Pipe
116
+ | TokKind::PipePipe
117
+ | TokKind::Caret
118
+ | TokKind::Tilde
119
+ | TokKind::Bang
120
+ | TokKind::Shl
121
+ | TokKind::Shr => true,
122
+ TokKind::Ident(kw) => matches!(
123
+ kw.as_str(),
124
+ "return"
125
+ | "throw"
126
+ | "case"
127
+ | "yield"
128
+ | "await"
129
+ | "typeof"
130
+ | "delete"
131
+ | "void"
132
+ | "in"
133
+ | "of"
134
+ | "else"
135
+ | "do"
136
+ | "new"
137
+ ),
138
+ _ => false,
139
+ }
140
+ }
141
+
142
+ struct Lexer<'a> {
143
+ file_id: usize,
144
+ lang: Language,
145
+ src: &'a str,
146
+ bytes: &'a [u8],
147
+ pos: usize,
148
+ line: u32,
149
+ line_start: usize,
150
+ directives: Vec<ImportDecl>,
151
+ }
152
+
153
+ impl<'a> Lexer<'a> {
154
+ fn new(file_id: usize, lang: Language, src: &'a str) -> Self {
155
+ Self {
156
+ file_id,
157
+ lang,
158
+ src,
159
+ bytes: src.as_bytes(),
160
+ pos: 0,
161
+ line: 1,
162
+ line_start: 0,
163
+ directives: Vec::new(),
164
+ }
165
+ }
166
+
167
+ fn make_span(&self, start: usize, end: usize, line: u32, col: u32) -> Span {
168
+ Span {
169
+ file_id: self.file_id,
170
+ start,
171
+ end,
172
+ line,
173
+ col,
174
+ }
175
+ }
176
+
177
+ fn current_col(&self) -> u32 {
178
+ (self.pos - self.line_start + 1) as u32
179
+ }
180
+
181
+ fn peek(&self) -> Option<u8> {
182
+ self.bytes.get(self.pos).copied()
183
+ }
184
+
185
+ fn peek_at(&self, offset: usize) -> Option<u8> {
186
+ self.bytes.get(self.pos + offset).copied()
187
+ }
188
+
189
+ fn advance(&mut self) -> Option<u8> {
190
+ let b = self.peek()?;
191
+ self.pos += 1;
192
+ if b == b'\n' {
193
+ self.line += 1;
194
+ self.line_start = self.pos;
195
+ }
196
+ Some(b)
197
+ }
198
+
199
+ fn parse_comment_directive(&mut self, text: &str, span: Span) {
200
+ let trimmed = text.trim();
201
+ if let Some(rest) = trimmed.strip_prefix("polycomp") {
202
+ let rest = rest.trim();
203
+ if let Some(path_raw) = rest.strip_prefix("require") {
204
+ let spec = unquote(path_raw.trim());
205
+ if !spec.is_empty() {
206
+ self.directives.push(ImportDecl {
207
+ module_specifier: spec,
208
+ kind: ImportKind::Wildcard,
209
+ span,
210
+ });
211
+ }
212
+ } else if let Some(imp_rest) = rest.strip_prefix("import") {
213
+ if let Some((left, right)) = imp_rest.split_once(" from ") {
214
+ let mod_spec = unquote(right.trim());
215
+ let items = parse_directive_item_list(left, span);
216
+ if !mod_spec.is_empty() && !items.is_empty() {
217
+ self.directives.push(ImportDecl {
218
+ module_specifier: mod_spec,
219
+ kind: ImportKind::Named { items },
220
+ span,
221
+ });
222
+ }
223
+ } else {
224
+ for part in imp_rest.split(',') {
225
+ let part = part.trim();
226
+ if let Some((m, a)) = part.split_once(" as ") {
227
+ self.directives.push(ImportDecl {
228
+ module_specifier: unquote(m.trim()),
229
+ kind: ImportKind::Namespace {
230
+ alias: a.trim().to_string(),
231
+ },
232
+ span,
233
+ });
234
+ } else if !part.is_empty() {
235
+ let spec = unquote(part);
236
+ let alias = default_alias_for_spec(&spec);
237
+ self.directives.push(ImportDecl {
238
+ module_specifier: spec,
239
+ kind: ImportKind::Namespace { alias },
240
+ span,
241
+ });
242
+ }
243
+ }
244
+ }
245
+ }
246
+ }
247
+ }
248
+
249
+ fn scan_escaped_char(&mut self) -> Option<char> {
250
+ match self.advance()? {
251
+ b'n' => Some('\n'),
252
+ b't' => Some('\t'),
253
+ b'r' => Some('\r'),
254
+ b'0' => Some('\0'),
255
+ b'\\' => Some('\\'),
256
+ b'"' => Some('"'),
257
+ b'\'' => Some('\''),
258
+ b'`' => Some('`'),
259
+ b'x' => {
260
+ let h1 = self.advance()? as char;
261
+ let h2 = self.advance()? as char;
262
+ let code = u8::from_str_radix(&format!("{h1}{h2}"), 16).ok()?;
263
+ Some(code as char)
264
+ }
265
+ b'u' => {
266
+ if self.peek() == Some(b'{') {
267
+ self.advance();
268
+ let mut hex = String::new();
269
+ while let Some(c) = self.peek() {
270
+ if c == b'}' {
271
+ self.advance();
272
+ break;
273
+ }
274
+ hex.push(c as char);
275
+ self.advance();
276
+ }
277
+ u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32)
278
+ } else {
279
+ let mut hex = String::new();
280
+ for _ in 0..4 {
281
+ hex.push(self.advance()? as char);
282
+ }
283
+ u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32)
284
+ }
285
+ }
286
+ other => Some(other as char),
287
+ }
288
+ }
289
+
290
+ fn scan_regular_string(&mut self, quote: u8, start: usize, line: u32, col: u32) -> Result<Tok, PolyError> {
291
+ let is_triple = self.lang == Language::Python
292
+ && self.peek() == Some(quote)
293
+ && self.peek_at(1) == Some(quote);
294
+ if is_triple {
295
+ self.advance();
296
+ self.advance();
297
+ }
298
+ let mut s = String::new();
299
+ let mut closed = false;
300
+ while let Some(cb) = self.peek() {
301
+ if is_triple {
302
+ if cb == quote && self.peek_at(1) == Some(quote) && self.peek_at(2) == Some(quote) {
303
+ self.advance();
304
+ self.advance();
305
+ self.advance();
306
+ closed = true;
307
+ break;
308
+ }
309
+ } else if cb == quote {
310
+ self.advance();
311
+ closed = true;
312
+ break;
313
+ }
314
+ if cb == b'\\' {
315
+ self.advance();
316
+ if let Some(ch) = self.scan_escaped_char() {
317
+ s.push(ch);
318
+ }
319
+ } else {
320
+ let ch = self.src[self.pos..].chars().next().unwrap();
321
+ for _ in 0..ch.len_utf8() {
322
+ self.advance();
323
+ }
324
+ s.push(ch);
325
+ }
326
+ }
327
+ if !closed {
328
+ return Err(PolyError::spanned(
329
+ "E0103",
330
+ "unterminated string literal",
331
+ self.make_span(start, self.pos, line, col),
332
+ ));
333
+ }
334
+ Ok(Tok {
335
+ kind: TokKind::Str(s),
336
+ span: self.make_span(start, self.pos, line, col),
337
+ })
338
+ }
339
+
340
+ fn scan_interp_string(
341
+ &mut self,
342
+ quote: u8,
343
+ dollar_braces: bool,
344
+ raw_mode: bool,
345
+ start: usize,
346
+ line: u32,
347
+ col: u32,
348
+ ) -> Result<Tok, PolyError> {
349
+ let mut parts: Vec<(bool, String, Option<String>, u32, u32)> = Vec::new();
350
+ let mut cur_lit = String::new();
351
+ let mut closed = false;
352
+
353
+ while let Some(b) = self.peek() {
354
+ if b == quote {
355
+ self.advance();
356
+ closed = true;
357
+ break;
358
+ }
359
+ if !raw_mode && b == b'\\' {
360
+ self.advance();
361
+ if let Some(ch) = self.scan_escaped_char() {
362
+ cur_lit.push(ch);
363
+ }
364
+ continue;
365
+ }
366
+ if raw_mode && quote == b'"' && b == b'"' && self.peek_at(1) == Some(b'"') {
367
+ self.advance();
368
+ self.advance();
369
+ cur_lit.push('"');
370
+ continue;
371
+ }
372
+ if !dollar_braces && ((b == b'{' && self.peek_at(1) == Some(b'{')) || (b == b'}' && self.peek_at(1) == Some(b'}'))) {
373
+ cur_lit.push(b as char);
374
+ self.advance();
375
+ self.advance();
376
+ continue;
377
+ }
378
+
379
+ let is_interp_start = if dollar_braces {
380
+ b == b'$' && self.peek_at(1) == Some(b'{')
381
+ } else {
382
+ b == b'{'
383
+ };
384
+
385
+ if is_interp_start {
386
+ if !cur_lit.is_empty() {
387
+ parts.push((false, std::mem::take(&mut cur_lit), None, line, col));
388
+ }
389
+ if dollar_braces {
390
+ self.advance();
391
+ }
392
+ self.advance();
393
+ let e_line = self.line;
394
+ let e_col = self.current_col();
395
+ let mut depth = 1usize;
396
+ let mut expr_raw = String::new();
397
+ while let Some(eb) = self.peek() {
398
+ if eb == b'{' {
399
+ depth += 1;
400
+ expr_raw.push('{');
401
+ self.advance();
402
+ } else if eb == b'}' {
403
+ depth -= 1;
404
+ self.advance();
405
+ if depth == 0 {
406
+ break;
407
+ }
408
+ expr_raw.push('}');
409
+ } else if eb == b'"' || eb == b'\'' {
410
+ let q = eb;
411
+ expr_raw.push(q as char);
412
+ self.advance();
413
+ while let Some(sb) = self.peek() {
414
+ if sb == b'\\' {
415
+ expr_raw.push('\\');
416
+ self.advance();
417
+ if let Some(nb) = self.advance() {
418
+ expr_raw.push(nb as char);
419
+ }
420
+ continue;
421
+ }
422
+ expr_raw.push(sb as char);
423
+ self.advance();
424
+ if sb == q {
425
+ break;
426
+ }
427
+ }
428
+ } else {
429
+ let ch = self.src[self.pos..].chars().next().unwrap();
430
+ for _ in 0..ch.len_utf8() {
431
+ self.advance();
432
+ }
433
+ expr_raw.push(ch);
434
+ }
435
+ }
436
+ let (clean_expr, fmt_spec) = if !dollar_braces {
437
+ split_interp_format(&expr_raw)
438
+ } else {
439
+ (expr_raw, None)
440
+ };
441
+ parts.push((true, clean_expr, fmt_spec, e_line, e_col));
442
+ continue;
443
+ }
444
+
445
+ let ch = self.src[self.pos..].chars().next().unwrap();
446
+ for _ in 0..ch.len_utf8() {
447
+ self.advance();
448
+ }
449
+ cur_lit.push(ch);
450
+ }
451
+
452
+ if !closed {
453
+ return Err(PolyError::spanned(
454
+ "E0103",
455
+ "unterminated interpolated string literal",
456
+ self.make_span(start, self.pos, line, col),
457
+ ));
458
+ }
459
+ if !cur_lit.is_empty() || parts.is_empty() {
460
+ parts.push((false, cur_lit, None, line, col));
461
+ }
462
+ Ok(Tok {
463
+ kind: TokKind::InterpStr(parts),
464
+ span: self.make_span(start, self.pos, line, col),
465
+ })
466
+ }
467
+
468
+ fn scan_regex_literal(&mut self, start: usize, line: u32, col: u32) -> Result<Tok, PolyError> {
469
+ self.advance();
470
+ let mut pat = String::new();
471
+ let mut in_class = false;
472
+ let mut closed = false;
473
+ while let Some(b) = self.peek() {
474
+ if b == b'\n' || b == b'\r' {
475
+ break;
476
+ }
477
+ if b == b'\\' {
478
+ pat.push('\\');
479
+ self.advance();
480
+ if let Some(nb) = self.peek()
481
+ && nb != b'\n'
482
+ && nb != b'\r'
483
+ {
484
+ let ch = self.src[self.pos..].chars().next().unwrap();
485
+ for _ in 0..ch.len_utf8() {
486
+ self.advance();
487
+ }
488
+ pat.push(ch);
489
+ }
490
+ continue;
491
+ }
492
+ if b == b'[' {
493
+ in_class = true;
494
+ pat.push('[');
495
+ self.advance();
496
+ continue;
497
+ }
498
+ if b == b']' && in_class {
499
+ in_class = false;
500
+ pat.push(']');
501
+ self.advance();
502
+ continue;
503
+ }
504
+ if b == b'/' && !in_class {
505
+ self.advance();
506
+ closed = true;
507
+ break;
508
+ }
509
+ let ch = self.src[self.pos..].chars().next().unwrap();
510
+ for _ in 0..ch.len_utf8() {
511
+ self.advance();
512
+ }
513
+ pat.push(ch);
514
+ }
515
+ if !closed {
516
+ return Err(PolyError::spanned(
517
+ "E0106",
518
+ "unterminated regular expression literal",
519
+ self.make_span(start, self.pos, line, col),
520
+ ));
521
+ }
522
+ let mut flags = String::new();
523
+ while let Some(fb) = self.peek() {
524
+ if fb.is_ascii_alphabetic() {
525
+ flags.push(fb as char);
526
+ self.advance();
527
+ } else {
528
+ break;
529
+ }
530
+ }
531
+ Ok(Tok {
532
+ kind: TokKind::Regex(pat, flags),
533
+ span: self.make_span(start, self.pos, line, col),
534
+ })
535
+ }
536
+
537
+ fn tokenize(mut self) -> Result<(Vec<Tok>, Vec<ImportDecl>), PolyError> {
538
+ let mut tokens = Vec::new();
539
+ let mut indent_stack: Vec<usize> = vec![0];
540
+ let mut paren_depth: usize = 0;
541
+ let mut at_line_start = true;
542
+
543
+ while let Some(b) = self.peek() {
544
+ if at_line_start && self.lang == Language::Python && paren_depth == 0 {
545
+ let line_begin = self.pos;
546
+ let mut indent = 0usize;
547
+ while let Some(wb) = self.peek() {
548
+ match wb {
549
+ b' ' => {
550
+ indent += 1;
551
+ self.advance();
552
+ }
553
+ b'\t' => {
554
+ indent += 4;
555
+ self.advance();
556
+ }
557
+ b'\r' => {
558
+ self.advance();
559
+ }
560
+ _ => break,
561
+ }
562
+ }
563
+
564
+ match self.peek() {
565
+ None => break,
566
+ Some(b'\n') => {
567
+ self.advance();
568
+ continue;
569
+ }
570
+ Some(b'#') => {
571
+ let c_start = self.pos;
572
+ let c_line = self.line;
573
+ let c_col = self.current_col();
574
+ self.advance();
575
+ let text_start = self.pos;
576
+ while let Some(cb) = self.peek() {
577
+ if cb == b'\n' {
578
+ break;
579
+ }
580
+ self.advance();
581
+ }
582
+ let comment = &self.src[text_start..self.pos];
583
+ let span = self.make_span(c_start, self.pos, c_line, c_col);
584
+ self.parse_comment_directive(comment, span);
585
+ if self.peek() == Some(b'\n') {
586
+ self.advance();
587
+ }
588
+ continue;
589
+ }
590
+ _ => {}
591
+ }
592
+
593
+ let top = *indent_stack.last().unwrap_or(&0);
594
+ if indent > top {
595
+ indent_stack.push(indent);
596
+ tokens.push(Tok {
597
+ kind: TokKind::Indent,
598
+ span: self.make_span(line_begin, self.pos, self.line, 1),
599
+ });
600
+ } else if indent < top {
601
+ while let Some(&prev) = indent_stack.last() {
602
+ if prev == indent {
603
+ break;
604
+ }
605
+ if prev < indent {
606
+ return Err(PolyError::spanned(
607
+ "E0101",
608
+ "inconsistent Python indentation level",
609
+ self.make_span(line_begin, self.pos, self.line, 1),
610
+ ));
611
+ }
612
+ indent_stack.pop();
613
+ tokens.push(Tok {
614
+ kind: TokKind::Dedent,
615
+ span: self.make_span(line_begin, self.pos, self.line, 1),
616
+ });
617
+ }
618
+ }
619
+ at_line_start = false;
620
+ continue;
621
+ }
622
+
623
+ if b == b' ' || b == b'\t' || b == b'\r' {
624
+ self.advance();
625
+ continue;
626
+ }
627
+
628
+ if b == b'\n' {
629
+ let s = self.pos;
630
+ let line = self.line;
631
+ let col = self.current_col();
632
+ self.advance();
633
+ if (self.lang == Language::Python || self.lang == Language::Go) && paren_depth == 0 {
634
+ let emit = tokens
635
+ .last()
636
+ .is_some_and(|t| !matches!(t.kind, TokKind::Newline | TokKind::Indent));
637
+ if emit {
638
+ tokens.push(Tok {
639
+ kind: TokKind::Newline,
640
+ span: self.make_span(s, self.pos, line, col),
641
+ });
642
+ }
643
+ }
644
+ at_line_start = true;
645
+ continue;
646
+ }
647
+ at_line_start = false;
648
+
649
+ if b == b'#' {
650
+ if self.lang == Language::Rust
651
+ && (self.peek_at(1) == Some(b'[')
652
+ || (self.peek_at(1) == Some(b'!') && self.peek_at(2) == Some(b'[')))
653
+ {
654
+ while let Some(ab) = self.peek() {
655
+ if ab == b'[' {
656
+ break;
657
+ }
658
+ self.advance();
659
+ }
660
+ let mut depth = 0usize;
661
+ while let Some(ab) = self.peek() {
662
+ if ab == b'[' {
663
+ depth += 1;
664
+ } else if ab == b']' {
665
+ depth -= 1;
666
+ self.advance();
667
+ if depth == 0 {
668
+ break;
669
+ }
670
+ continue;
671
+ }
672
+ self.advance();
673
+ }
674
+ continue;
675
+ }
676
+
677
+ let c_start = self.pos;
678
+ let c_line = self.line;
679
+ let c_col = self.current_col();
680
+ self.advance();
681
+ let text_start = self.pos;
682
+ while let Some(cb) = self.peek() {
683
+ if cb == b'\n' {
684
+ break;
685
+ }
686
+ self.advance();
687
+ }
688
+ let raw_text = self.src[text_start..self.pos].trim();
689
+ let span = self.make_span(c_start, self.pos, c_line, c_col);
690
+ if matches!(self.lang, Language::C | Language::Cpp) {
691
+ if let Some(inc) = raw_text.strip_prefix("include") {
692
+ let inc = inc.trim();
693
+ if inc.starts_with('"') && inc.ends_with('"') && inc.len() >= 2 {
694
+ self.directives.push(ImportDecl {
695
+ module_specifier: inc[1..inc.len() - 1].to_string(),
696
+ kind: ImportKind::Wildcard,
697
+ span,
698
+ });
699
+ }
700
+ } else {
701
+ self.parse_comment_directive(raw_text, span);
702
+ }
703
+ } else {
704
+ self.parse_comment_directive(raw_text, span);
705
+ }
706
+ continue;
707
+ }
708
+
709
+ if b == b'/' && self.peek_at(1) == Some(b'/') {
710
+ let c_start = self.pos;
711
+ let c_line = self.line;
712
+ let c_col = self.current_col();
713
+ self.advance();
714
+ self.advance();
715
+ let text_start = self.pos;
716
+ while let Some(cb) = self.peek() {
717
+ if cb == b'\n' {
718
+ break;
719
+ }
720
+ self.advance();
721
+ }
722
+ let span = self.make_span(c_start, self.pos, c_line, c_col);
723
+ let comment = &self.src[text_start..self.pos];
724
+ self.parse_comment_directive(comment, span);
725
+ continue;
726
+ }
727
+
728
+ if b == b'/' && self.peek_at(1) == Some(b'*') {
729
+ let c_start = self.pos;
730
+ let c_line = self.line;
731
+ let c_col = self.current_col();
732
+ self.advance();
733
+ self.advance();
734
+ let mut closed = false;
735
+ while let Some(cb) = self.peek() {
736
+ if cb == b'*' && self.peek_at(1) == Some(b'/') {
737
+ self.advance();
738
+ self.advance();
739
+ closed = true;
740
+ break;
741
+ }
742
+ self.advance();
743
+ }
744
+ if !closed {
745
+ return Err(PolyError::spanned(
746
+ "E0102",
747
+ "unterminated block comment",
748
+ self.make_span(c_start, self.pos, c_line, c_col),
749
+ ));
750
+ }
751
+ continue;
752
+ }
753
+
754
+ let start = self.pos;
755
+ let line = self.line;
756
+ let col = self.current_col();
757
+
758
+ if b == b'/'
759
+ && matches!(self.lang, Language::JavaScript | Language::TypeScript)
760
+ && can_precede_regex(&tokens)
761
+ {
762
+ tokens.push(self.scan_regex_literal(start, line, col)?);
763
+ continue;
764
+ }
765
+
766
+ if self.lang == Language::CSharp {
767
+ if (b == b'$' && self.peek_at(1) == Some(b'@') && self.peek_at(2) == Some(b'"'))
768
+ || (b == b'@' && self.peek_at(1) == Some(b'$') && self.peek_at(2) == Some(b'"'))
769
+ {
770
+ self.advance();
771
+ self.advance();
772
+ self.advance();
773
+ tokens.push(self.scan_interp_string(b'"', false, true, start, line, col)?);
774
+ continue;
775
+ }
776
+ if b == b'$' && self.peek_at(1) == Some(b'"') {
777
+ self.advance();
778
+ self.advance();
779
+ tokens.push(self.scan_interp_string(b'"', false, false, start, line, col)?);
780
+ continue;
781
+ }
782
+ if b == b'@' && self.peek_at(1) == Some(b'"') {
783
+ self.advance();
784
+ self.advance();
785
+ let mut s = String::new();
786
+ let mut closed = false;
787
+ while let Some(cb) = self.peek() {
788
+ if cb == b'"' {
789
+ self.advance();
790
+ if self.peek() == Some(b'"') {
791
+ self.advance();
792
+ s.push('"');
793
+ continue;
794
+ }
795
+ closed = true;
796
+ break;
797
+ }
798
+ let ch = self.src[self.pos..].chars().next().unwrap();
799
+ for _ in 0..ch.len_utf8() {
800
+ self.advance();
801
+ }
802
+ s.push(ch);
803
+ }
804
+ if !closed {
805
+ return Err(PolyError::spanned(
806
+ "E0103",
807
+ "unterminated verbatim string",
808
+ self.make_span(start, self.pos, line, col),
809
+ ));
810
+ }
811
+ tokens.push(Tok {
812
+ kind: TokKind::Str(s),
813
+ span: self.make_span(start, self.pos, line, col),
814
+ });
815
+ continue;
816
+ }
817
+ }
818
+
819
+ if self.lang == Language::Python {
820
+ let p0 = b.to_ascii_lowercase();
821
+ let p1 = self.peek_at(1).map(|c| c.to_ascii_lowercase());
822
+ if (p0 == b'f' || p0 == b'r') && matches!(self.peek_at(1), Some(b'"' | b'\'')) {
823
+ let q = self.peek_at(1).unwrap();
824
+ self.advance();
825
+ self.advance();
826
+ if p0 == b'f' {
827
+ tokens.push(self.scan_interp_string(q, false, false, start, line, col)?);
828
+ } else {
829
+ let mut s = String::new();
830
+ let mut closed = false;
831
+ while let Some(cb) = self.peek() {
832
+ if cb == b'\\' && self.peek_at(1) == Some(q) {
833
+ s.push('\\');
834
+ s.push(q as char);
835
+ self.advance();
836
+ self.advance();
837
+ continue;
838
+ }
839
+ if cb == q {
840
+ self.advance();
841
+ closed = true;
842
+ break;
843
+ }
844
+ let ch = self.src[self.pos..].chars().next().unwrap();
845
+ for _ in 0..ch.len_utf8() {
846
+ self.advance();
847
+ }
848
+ s.push(ch);
849
+ }
850
+ if !closed {
851
+ return Err(PolyError::spanned(
852
+ "E0103",
853
+ "unterminated raw string",
854
+ self.make_span(start, self.pos, line, col),
855
+ ));
856
+ }
857
+ tokens.push(Tok {
858
+ kind: TokKind::Str(s),
859
+ span: self.make_span(start, self.pos, line, col),
860
+ });
861
+ }
862
+ continue;
863
+ }
864
+ if ((p0 == b'r' && p1 == Some(b'f')) || (p0 == b'f' && p1 == Some(b'r')))
865
+ && matches!(self.peek_at(2), Some(b'"' | b'\''))
866
+ {
867
+ let q = self.peek_at(2).unwrap();
868
+ self.advance();
869
+ self.advance();
870
+ self.advance();
871
+ tokens.push(self.scan_interp_string(q, false, true, start, line, col)?);
872
+ continue;
873
+ }
874
+ }
875
+
876
+ if self.lang == Language::Cpp && b == b'R' && self.peek_at(1) == Some(b'"') {
877
+ self.advance();
878
+ self.advance();
879
+ let mut delim = String::new();
880
+ while let Some(db) = self.peek() {
881
+ if db == b'(' {
882
+ self.advance();
883
+ break;
884
+ }
885
+ delim.push(db as char);
886
+ self.advance();
887
+ }
888
+ let end_seq = format!("){delim}\"");
889
+ let body_start = self.pos;
890
+ if let Some(rel) = self.src[body_start..].find(&end_seq) {
891
+ let s = self.src[body_start..body_start + rel].to_string();
892
+ for _ in 0..(rel + end_seq.len()) {
893
+ self.advance();
894
+ }
895
+ tokens.push(Tok {
896
+ kind: TokKind::Str(s),
897
+ span: self.make_span(start, self.pos, line, col),
898
+ });
899
+ continue;
900
+ } else {
901
+ return Err(PolyError::spanned(
902
+ "E0103",
903
+ "unterminated C++ raw string literal",
904
+ self.make_span(start, self.pos, line, col),
905
+ ));
906
+ }
907
+ }
908
+
909
+ if self.lang == Language::Rust
910
+ && b == b'r'
911
+ && matches!(self.peek_at(1), Some(b'"' | b'#'))
912
+ {
913
+ let mut hashes = 0usize;
914
+ while self.peek_at(1 + hashes) == Some(b'#') {
915
+ hashes += 1;
916
+ }
917
+ if self.peek_at(1 + hashes) == Some(b'"') {
918
+ for _ in 0..(2 + hashes) {
919
+ self.advance();
920
+ }
921
+ let end_seq = format!("\"{}", "#".repeat(hashes));
922
+ let body_start = self.pos;
923
+ if let Some(rel) = self.src[body_start..].find(&end_seq) {
924
+ let s = self.src[body_start..body_start + rel].to_string();
925
+ for _ in 0..(rel + end_seq.len()) {
926
+ self.advance();
927
+ }
928
+ tokens.push(Tok {
929
+ kind: TokKind::Str(s),
930
+ span: self.make_span(start, self.pos, line, col),
931
+ });
932
+ continue;
933
+ }
934
+ }
935
+ }
936
+
937
+ if b == b'`' {
938
+ self.advance();
939
+ if self.lang == Language::Go {
940
+ let mut s = String::new();
941
+ let mut closed = false;
942
+ while let Some(cb) = self.peek() {
943
+ if cb == b'`' {
944
+ self.advance();
945
+ closed = true;
946
+ break;
947
+ }
948
+ let ch = self.src[self.pos..].chars().next().unwrap();
949
+ for _ in 0..ch.len_utf8() {
950
+ self.advance();
951
+ }
952
+ s.push(ch);
953
+ }
954
+ if !closed {
955
+ return Err(PolyError::spanned(
956
+ "E0103",
957
+ "unterminated Go raw string literal",
958
+ self.make_span(start, self.pos, line, col),
959
+ ));
960
+ }
961
+ tokens.push(Tok {
962
+ kind: TokKind::Str(s),
963
+ span: self.make_span(start, self.pos, line, col),
964
+ });
965
+ } else {
966
+ tokens.push(self.scan_interp_string(b'`', true, false, start, line, col)?);
967
+ }
968
+ continue;
969
+ }
970
+
971
+ if b == b'"' {
972
+ self.advance();
973
+ tokens.push(self.scan_regular_string(b'"', start, line, col)?);
974
+ continue;
975
+ }
976
+ if b == b'\'' {
977
+ if matches!(
978
+ self.lang,
979
+ Language::Python | Language::JavaScript | Language::TypeScript
980
+ ) {
981
+ self.advance();
982
+ tokens.push(self.scan_regular_string(b'\'', start, line, col)?);
983
+ continue;
984
+ }
985
+ if self.lang == Language::Rust
986
+ && self.peek_at(1).is_some_and(|c| c.is_ascii_alphabetic() || c == b'_')
987
+ && self.peek_at(2) != Some(b'\'')
988
+ {
989
+ self.advance();
990
+ while let Some(lb) = self.peek() {
991
+ if lb.is_ascii_alphanumeric() || lb == b'_' {
992
+ self.advance();
993
+ } else {
994
+ break;
995
+ }
996
+ }
997
+ continue;
998
+ }
999
+ self.advance();
1000
+ let ch = if self.peek() == Some(b'\\') {
1001
+ self.advance();
1002
+ self.scan_escaped_char().unwrap_or('\0')
1003
+ } else {
1004
+ let c = self.src[self.pos..].chars().next().unwrap_or('\0');
1005
+ for _ in 0..c.len_utf8() {
1006
+ self.advance();
1007
+ }
1008
+ c
1009
+ };
1010
+ if self.peek() != Some(b'\'') {
1011
+ return Err(PolyError::spanned(
1012
+ "E0103",
1013
+ "unterminated char literal",
1014
+ self.make_span(start, self.pos, line, col),
1015
+ ));
1016
+ }
1017
+ self.advance();
1018
+ tokens.push(Tok {
1019
+ kind: TokKind::Int(i64::from(ch as u32)),
1020
+ span: self.make_span(start, self.pos, line, col),
1021
+ });
1022
+ continue;
1023
+ }
1024
+
1025
+ if b.is_ascii_digit() {
1026
+ if b == b'0' && matches!(self.peek_at(1), Some(b'x' | b'X' | b'b' | b'B' | b'o' | b'O')) {
1027
+ let prefix = self.peek_at(1).unwrap().to_ascii_lowercase();
1028
+ self.advance();
1029
+ self.advance();
1030
+ let d_start = self.pos;
1031
+ while let Some(db) = self.peek() {
1032
+ if db.is_ascii_hexdigit() || db == b'_' || db == b'\'' {
1033
+ self.advance();
1034
+ } else {
1035
+ break;
1036
+ }
1037
+ }
1038
+ let clean: String = self.src[d_start..self.pos]
1039
+ .chars()
1040
+ .filter(|&c| c != '_' && c != '\'')
1041
+ .collect();
1042
+ let radix = match prefix {
1043
+ b'x' => 16,
1044
+ b'b' => 2,
1045
+ _ => 8,
1046
+ };
1047
+ let val = i64::from_str_radix(&clean, radix).map_err(|_| {
1048
+ PolyError::spanned(
1049
+ "E0104",
1050
+ "invalid integer literal",
1051
+ self.make_span(start, self.pos, line, col),
1052
+ )
1053
+ })?;
1054
+ consume_numeric_suffix(&mut self);
1055
+ tokens.push(Tok {
1056
+ kind: TokKind::Int(val),
1057
+ span: self.make_span(start, self.pos, line, col),
1058
+ });
1059
+ continue;
1060
+ }
1061
+
1062
+ let mut is_float = false;
1063
+ while let Some(db) = self.peek() {
1064
+ if db.is_ascii_digit() || db == b'_' || (self.lang == Language::Cpp && db == b'\'' && self.peek_at(1).is_some_and(|n| n.is_ascii_digit())) {
1065
+ self.advance();
1066
+ } else if db == b'.' && self.peek_at(1).is_some_and(|n| n.is_ascii_digit()) {
1067
+ is_float = true;
1068
+ self.advance();
1069
+ } else if db == b'e' || db == b'E' {
1070
+ is_float = true;
1071
+ self.advance();
1072
+ if matches!(self.peek(), Some(b'+' | b'-')) {
1073
+ self.advance();
1074
+ }
1075
+ } else {
1076
+ break;
1077
+ }
1078
+ }
1079
+ let clean: String = self.src[start..self.pos]
1080
+ .chars()
1081
+ .filter(|&c| c != '_' && c != '\'')
1082
+ .collect();
1083
+ let suffix = consume_numeric_suffix(&mut self);
1084
+ if matches!(suffix.as_str(), "f" | "F" | "d" | "D" | "f32" | "f64") {
1085
+ is_float = true;
1086
+ }
1087
+ let span = self.make_span(start, self.pos, line, col);
1088
+ if is_float {
1089
+ let val: f64 = clean.parse().map_err(|_| {
1090
+ PolyError::spanned("E0104", "invalid float literal", span)
1091
+ })?;
1092
+ tokens.push(Tok {
1093
+ kind: TokKind::Float(val),
1094
+ span,
1095
+ });
1096
+ } else {
1097
+ let val: i64 = clean.parse().map_err(|_| {
1098
+ PolyError::spanned("E0104", "invalid integer literal", span)
1099
+ })?;
1100
+ tokens.push(Tok {
1101
+ kind: TokKind::Int(val),
1102
+ span,
1103
+ });
1104
+ }
1105
+ continue;
1106
+ }
1107
+
1108
+ if b.is_ascii_alphabetic() || b == b'_' || b == b'$' {
1109
+ while let Some(ib) = self.peek() {
1110
+ if ib.is_ascii_alphanumeric() || ib == b'_' || ib == b'$' {
1111
+ self.advance();
1112
+ } else {
1113
+ break;
1114
+ }
1115
+ }
1116
+ let ident = self.src[start..self.pos].to_string();
1117
+ tokens.push(Tok {
1118
+ kind: TokKind::Ident(ident),
1119
+ span: self.make_span(start, self.pos, line, col),
1120
+ });
1121
+ continue;
1122
+ }
1123
+
1124
+ let kind = match (b, self.peek_at(1), self.peek_at(2)) {
1125
+ (b'.', Some(b'.'), Some(b'=')) => {
1126
+ self.advance();
1127
+ self.advance();
1128
+ self.advance();
1129
+ TokKind::DotDotEq
1130
+ }
1131
+ (b'=', Some(b'='), Some(b'=')) => {
1132
+ self.advance();
1133
+ self.advance();
1134
+ self.advance();
1135
+ TokKind::EqEqEq
1136
+ }
1137
+ (b'!', Some(b'='), Some(b'=')) => {
1138
+ self.advance();
1139
+ self.advance();
1140
+ self.advance();
1141
+ TokKind::BangEqEq
1142
+ }
1143
+ (b':', Some(b':'), _) => {
1144
+ self.advance();
1145
+ self.advance();
1146
+ TokKind::ColonColon
1147
+ }
1148
+ (b':', Some(b'='), _) => {
1149
+ self.advance();
1150
+ self.advance();
1151
+ TokKind::ColonEq
1152
+ }
1153
+ (b'.', Some(b'.'), _) => {
1154
+ self.advance();
1155
+ self.advance();
1156
+ TokKind::DotDot
1157
+ }
1158
+ (b'-', Some(b'>'), _) => {
1159
+ self.advance();
1160
+ self.advance();
1161
+ TokKind::Arrow
1162
+ }
1163
+ (b'=', Some(b'>'), _) => {
1164
+ self.advance();
1165
+ self.advance();
1166
+ TokKind::FatArrow
1167
+ }
1168
+ (b'?', Some(b'.'), _) => {
1169
+ self.advance();
1170
+ self.advance();
1171
+ TokKind::QuestionDot
1172
+ }
1173
+ (b'?', Some(b'?'), _) => {
1174
+ self.advance();
1175
+ self.advance();
1176
+ TokKind::QuestionQuestion
1177
+ }
1178
+ (b'*', Some(b'*'), _) => {
1179
+ self.advance();
1180
+ self.advance();
1181
+ TokKind::StarStar
1182
+ }
1183
+ (b'/', Some(b'/'), _) => {
1184
+ self.advance();
1185
+ self.advance();
1186
+ TokKind::SlashSlash
1187
+ }
1188
+ (b'+', Some(b'+'), _) => {
1189
+ self.advance();
1190
+ self.advance();
1191
+ TokKind::PlusPlus
1192
+ }
1193
+ (b'-', Some(b'-'), _) => {
1194
+ self.advance();
1195
+ self.advance();
1196
+ TokKind::MinusMinus
1197
+ }
1198
+ (b'+', Some(b'='), _) => {
1199
+ self.advance();
1200
+ self.advance();
1201
+ TokKind::PlusEq
1202
+ }
1203
+ (b'-', Some(b'='), _) => {
1204
+ self.advance();
1205
+ self.advance();
1206
+ TokKind::MinusEq
1207
+ }
1208
+ (b'*', Some(b'='), _) => {
1209
+ self.advance();
1210
+ self.advance();
1211
+ TokKind::StarEq
1212
+ }
1213
+ (b'/', Some(b'='), _) => {
1214
+ self.advance();
1215
+ self.advance();
1216
+ TokKind::SlashEq
1217
+ }
1218
+ (b'%', Some(b'='), _) => {
1219
+ self.advance();
1220
+ self.advance();
1221
+ TokKind::PercentEq
1222
+ }
1223
+ (b'=', Some(b'='), _) => {
1224
+ self.advance();
1225
+ self.advance();
1226
+ TokKind::EqEq
1227
+ }
1228
+ (b'!', Some(b'='), _) => {
1229
+ self.advance();
1230
+ self.advance();
1231
+ TokKind::BangEq
1232
+ }
1233
+ (b'<', Some(b'='), _) => {
1234
+ self.advance();
1235
+ self.advance();
1236
+ TokKind::Le
1237
+ }
1238
+ (b'>', Some(b'='), _) => {
1239
+ self.advance();
1240
+ self.advance();
1241
+ TokKind::Ge
1242
+ }
1243
+ (b'<', Some(b'<'), _) => {
1244
+ self.advance();
1245
+ self.advance();
1246
+ TokKind::Shl
1247
+ }
1248
+ (b'>', Some(b'>'), _) => {
1249
+ self.advance();
1250
+ self.advance();
1251
+ TokKind::Shr
1252
+ }
1253
+ (b'&', Some(b'&'), _) => {
1254
+ self.advance();
1255
+ self.advance();
1256
+ TokKind::AmpAmp
1257
+ }
1258
+ (b'|', Some(b'|'), _) => {
1259
+ self.advance();
1260
+ self.advance();
1261
+ TokKind::PipePipe
1262
+ }
1263
+ (b'(', _, _) => {
1264
+ self.advance();
1265
+ paren_depth += 1;
1266
+ TokKind::LParen
1267
+ }
1268
+ (b')', _, _) => {
1269
+ self.advance();
1270
+ paren_depth = paren_depth.saturating_sub(1);
1271
+ TokKind::RParen
1272
+ }
1273
+ (b'[', _, _) => {
1274
+ self.advance();
1275
+ paren_depth += 1;
1276
+ TokKind::LBracket
1277
+ }
1278
+ (b']', _, _) => {
1279
+ self.advance();
1280
+ paren_depth = paren_depth.saturating_sub(1);
1281
+ TokKind::RBracket
1282
+ }
1283
+ (b'{', _, _) => {
1284
+ self.advance();
1285
+ if self.lang == Language::Python {
1286
+ paren_depth += 1;
1287
+ }
1288
+ TokKind::LBrace
1289
+ }
1290
+ (b'}', _, _) => {
1291
+ self.advance();
1292
+ if self.lang == Language::Python {
1293
+ paren_depth = paren_depth.saturating_sub(1);
1294
+ }
1295
+ TokKind::RBrace
1296
+ }
1297
+ (b',', _, _) => {
1298
+ self.advance();
1299
+ TokKind::Comma
1300
+ }
1301
+ (b':', _, _) => {
1302
+ self.advance();
1303
+ TokKind::Colon
1304
+ }
1305
+ (b';', _, _) => {
1306
+ self.advance();
1307
+ TokKind::Semi
1308
+ }
1309
+ (b'.', _, _) => {
1310
+ self.advance();
1311
+ TokKind::Dot
1312
+ }
1313
+ (b'?', _, _) => {
1314
+ self.advance();
1315
+ TokKind::Question
1316
+ }
1317
+ (b'+', _, _) => {
1318
+ self.advance();
1319
+ TokKind::Plus
1320
+ }
1321
+ (b'-', _, _) => {
1322
+ self.advance();
1323
+ TokKind::Minus
1324
+ }
1325
+ (b'*', _, _) => {
1326
+ self.advance();
1327
+ TokKind::Star
1328
+ }
1329
+ (b'/', _, _) => {
1330
+ self.advance();
1331
+ TokKind::Slash
1332
+ }
1333
+ (b'%', _, _) => {
1334
+ self.advance();
1335
+ TokKind::Percent
1336
+ }
1337
+ (b'=', _, _) => {
1338
+ self.advance();
1339
+ TokKind::Eq
1340
+ }
1341
+ (b'<', _, _) => {
1342
+ self.advance();
1343
+ TokKind::Lt
1344
+ }
1345
+ (b'>', _, _) => {
1346
+ self.advance();
1347
+ TokKind::Gt
1348
+ }
1349
+ (b'&', _, _) => {
1350
+ self.advance();
1351
+ TokKind::Amp
1352
+ }
1353
+ (b'|', _, _) => {
1354
+ self.advance();
1355
+ TokKind::Pipe
1356
+ }
1357
+ (b'^', _, _) => {
1358
+ self.advance();
1359
+ TokKind::Caret
1360
+ }
1361
+ (b'~', _, _) => {
1362
+ self.advance();
1363
+ TokKind::Tilde
1364
+ }
1365
+ (b'!', _, _) => {
1366
+ self.advance();
1367
+ TokKind::Bang
1368
+ }
1369
+ (b'@', _, _) => {
1370
+ self.advance();
1371
+ TokKind::At
1372
+ }
1373
+ other => {
1374
+ return Err(PolyError::spanned(
1375
+ "E0105",
1376
+ format!("unexpected character '{}'", other.0 as char),
1377
+ self.make_span(start, self.pos + 1, line, col),
1378
+ ));
1379
+ }
1380
+ };
1381
+
1382
+ tokens.push(Tok {
1383
+ kind,
1384
+ span: self.make_span(start, self.pos, line, col),
1385
+ });
1386
+ }
1387
+
1388
+ if self.lang == Language::Python {
1389
+ let eof_span = self.make_span(self.pos, self.pos, self.line, self.current_col());
1390
+ if tokens
1391
+ .last()
1392
+ .is_some_and(|t| !matches!(t.kind, TokKind::Newline | TokKind::Indent))
1393
+ {
1394
+ tokens.push(Tok {
1395
+ kind: TokKind::Newline,
1396
+ span: eof_span,
1397
+ });
1398
+ }
1399
+ while indent_stack.len() > 1 {
1400
+ indent_stack.pop();
1401
+ tokens.push(Tok {
1402
+ kind: TokKind::Dedent,
1403
+ span: eof_span,
1404
+ });
1405
+ }
1406
+ }
1407
+
1408
+ tokens.push(Tok {
1409
+ kind: TokKind::Eof,
1410
+ span: self.make_span(self.pos, self.pos, self.line, self.current_col()),
1411
+ });
1412
+
1413
+ Ok((tokens, self.directives))
1414
+ }
1415
+ }
1416
+
1417
+ fn consume_numeric_suffix(lex: &mut Lexer<'_>) -> String {
1418
+ let mut suf = String::new();
1419
+ while let Some(b) = lex.peek() {
1420
+ if b.is_ascii_alphanumeric() {
1421
+ suf.push(b as char);
1422
+ lex.advance();
1423
+ } else {
1424
+ break;
1425
+ }
1426
+ }
1427
+ suf
1428
+ }
1429
+
1430
+ fn split_interp_format(raw: &str) -> (String, Option<String>) {
1431
+ let mut depth_paren = 0usize;
1432
+ let mut depth_brack = 0usize;
1433
+ let mut in_quote: Option<u8> = None;
1434
+ let bytes = raw.as_bytes();
1435
+ let mut i = 0;
1436
+ while i < bytes.len() {
1437
+ let b = bytes[i];
1438
+ if let Some(q) = in_quote {
1439
+ if b == b'\\' {
1440
+ i += 2;
1441
+ continue;
1442
+ }
1443
+ if b == q {
1444
+ in_quote = None;
1445
+ }
1446
+ } else {
1447
+ match b {
1448
+ b'"' | b'\'' => in_quote = Some(b),
1449
+ b'(' => depth_paren += 1,
1450
+ b')' => depth_paren = depth_paren.saturating_sub(1),
1451
+ b'[' => depth_brack += 1,
1452
+ b']' => depth_brack = depth_brack.saturating_sub(1),
1453
+ b':' if depth_paren == 0 && depth_brack == 0 => {
1454
+ return (raw[..i].trim().to_string(), Some(raw[i + 1..].trim().to_string()));
1455
+ }
1456
+ _ => {}
1457
+ }
1458
+ }
1459
+ i += 1;
1460
+ }
1461
+ (raw.to_string(), None)
1462
+ }
1463
+
1464
+ fn unquote(s: &str) -> String {
1465
+ let s = s.trim();
1466
+ if s.len() >= 2
1467
+ && ((s.starts_with('"') && s.ends_with('"'))
1468
+ || (s.starts_with('\'') && s.ends_with('\'')))
1469
+ {
1470
+ s[1..s.len() - 1].to_string()
1471
+ } else {
1472
+ s.to_string()
1473
+ }
1474
+ }
1475
+
1476
+ fn default_alias_for_spec(spec: &str) -> String {
1477
+ let stripped = spec.trim_end_matches(&['/', '\\'][..]);
1478
+ let base = stripped.rsplit(&['/', '\\'][..]).next().unwrap_or(stripped);
1479
+ base.split('.').next().unwrap_or(base).to_string()
1480
+ }
1481
+
1482
+ fn parse_directive_item_list(raw: &str, span: Span) -> Vec<ImportItem> {
1483
+ let raw = raw.trim().trim_start_matches('{').trim_end_matches('}');
1484
+ let mut items = Vec::new();
1485
+ for part in raw.split(',') {
1486
+ let p = part.trim();
1487
+ if p.is_empty() {
1488
+ continue;
1489
+ }
1490
+ if let Some((orig, alias)) = p.split_once(" as ") {
1491
+ items.push(ImportItem {
1492
+ name: orig.trim().to_string(),
1493
+ alias: alias.trim().to_string(),
1494
+ span,
1495
+ });
1496
+ } else {
1497
+ items.push(ImportItem {
1498
+ name: p.to_string(),
1499
+ alias: p.to_string(),
1500
+ span,
1501
+ });
1502
+ }
1503
+ }
1504
+ items
1505
+ }
1506
+
1507
+ fn is_stdlib_go_package(pkg: &str) -> bool {
1508
+ matches!(
1509
+ pkg,
1510
+ "fmt" | "math" | "strings" | "regexp" | "strconv" | "time" | "os" | "errors" | "sort" | "io"
1511
+ )
1512
+ }
1513
+
1514
+ fn is_stdlib_csharp_namespace(ns: &str) -> bool {
1515
+ ns == "System" || ns.starts_with("System.") || ns.starts_with("Microsoft.")
1516
+ }
1517
+
1518
+ struct Parser {
1519
+ file_id: usize,
1520
+ lang: Language,
1521
+ tokens: Vec<Tok>,
1522
+ pos: usize,
1523
+ struct_names: Vec<String>,
1524
+ enum_names: Vec<String>,
1525
+ anon_counter: usize,
1526
+ extra_functions: Vec<FunctionDecl>,
1527
+ extra_enums: Vec<EnumDecl>,
1528
+ extra_structs: Vec<StructDecl>,
1529
+ using_namespaces: Vec<String>,
1530
+ }
1531
+
1532
+ impl Parser {
1533
+ fn new(file_id: usize, lang: Language, tokens: Vec<Tok>) -> Self {
1534
+ Self {
1535
+ file_id,
1536
+ lang,
1537
+ tokens,
1538
+ pos: 0,
1539
+ struct_names: Vec::new(),
1540
+ enum_names: Vec::new(),
1541
+ anon_counter: 0,
1542
+ extra_functions: Vec::new(),
1543
+ extra_enums: Vec::new(),
1544
+ extra_structs: Vec::new(),
1545
+ using_namespaces: Vec::new(),
1546
+ }
1547
+ }
1548
+
1549
+ fn peek(&self) -> &Tok {
1550
+ self.tokens
1551
+ .get(self.pos)
1552
+ .unwrap_or_else(|| self.tokens.last().unwrap())
1553
+ }
1554
+
1555
+ fn peek_n(&self, n: usize) -> &Tok {
1556
+ self.tokens
1557
+ .get(self.pos + n)
1558
+ .unwrap_or_else(|| self.tokens.last().unwrap())
1559
+ }
1560
+
1561
+ fn advance(&mut self) -> Tok {
1562
+ let t = self.peek().clone();
1563
+ if self.pos + 1 < self.tokens.len() {
1564
+ self.pos += 1;
1565
+ }
1566
+ t
1567
+ }
1568
+
1569
+ fn at(&self, kind: &TokKind) -> bool {
1570
+ &self.peek().kind == kind
1571
+ }
1572
+
1573
+ fn at_ident(&self, kw: &str) -> bool {
1574
+ matches!(&self.peek().kind, TokKind::Ident(s) if s == kw)
1575
+ }
1576
+
1577
+ fn eat(&mut self, kind: &TokKind) -> bool {
1578
+ if self.at(kind) {
1579
+ self.advance();
1580
+ true
1581
+ } else {
1582
+ false
1583
+ }
1584
+ }
1585
+
1586
+ fn eat_ident(&mut self, kw: &str) -> bool {
1587
+ if self.at_ident(kw) {
1588
+ self.advance();
1589
+ true
1590
+ } else {
1591
+ false
1592
+ }
1593
+ }
1594
+
1595
+ fn expect(&mut self, kind: &TokKind, desc: &str) -> Result<Tok, PolyError> {
1596
+ if self.at(kind) {
1597
+ Ok(self.advance())
1598
+ } else {
1599
+ let t = self.peek();
1600
+ Err(PolyError::spanned(
1601
+ "E0110",
1602
+ format!("expected {desc}, found {:?}", t.kind),
1603
+ t.span,
1604
+ ))
1605
+ }
1606
+ }
1607
+
1608
+ fn expect_ident(&mut self, desc: &str) -> Result<(String, Span), PolyError> {
1609
+ let t = self.peek().clone();
1610
+ match t.kind {
1611
+ TokKind::Ident(name) => {
1612
+ self.advance();
1613
+ Ok((name, t.span))
1614
+ }
1615
+ _ => Err(PolyError::spanned(
1616
+ "E0111",
1617
+ format!("expected {desc}, found {:?}", t.kind),
1618
+ t.span,
1619
+ )),
1620
+ }
1621
+ }
1622
+
1623
+ fn skip_newlines(&mut self) {
1624
+ while self.eat(&TokKind::Newline) {}
1625
+ }
1626
+
1627
+ fn eat_stmt_end(&mut self) {
1628
+ if self.lang == Language::Python {
1629
+ let _ = self.eat(&TokKind::Semi);
1630
+ while self.eat(&TokKind::Newline) {}
1631
+ } else {
1632
+ while self.eat(&TokKind::Semi) || self.eat(&TokKind::Newline) {}
1633
+ }
1634
+ }
1635
+
1636
+ fn parse_type_hint_str(s: &str) -> TypeHint {
1637
+ match s {
1638
+ "void" | "()" | "None" | "never" | "undefined" => TypeHint::Void,
1639
+ "bool" | "boolean" => TypeHint::Bool,
1640
+ "int" | "i8" | "i16" | "i32" | "i64" | "isize" | "u8" | "u16" | "u32" | "u64"
1641
+ | "usize" | "long" | "short" | "int64_t" | "int32_t" | "uint64_t" | "uint32_t"
1642
+ | "size_t" | "int64" | "int32" | "uint" | "uint64" | "bigint" | "byte" | "rune" => {
1643
+ TypeHint::Int
1644
+ }
1645
+ "float" | "double" | "f32" | "f64" | "float64" | "float32" | "number" | "decimal" => {
1646
+ TypeHint::Float
1647
+ }
1648
+ "str" | "String" | "string" | "char" => TypeHint::Str,
1649
+ "RegExp" | "Regex" | "Regexp" | "regex" => TypeHint::Regex,
1650
+ "Array" | "List" => TypeHint::Array,
1651
+ _ => TypeHint::Unknown,
1652
+ }
1653
+ }
1654
+
1655
+ fn is_c_cpp_cs_type_start(&self) -> bool {
1656
+ let TokKind::Ident(s) = &self.peek().kind else {
1657
+ return false;
1658
+ };
1659
+ if matches!(
1660
+ s.as_str(),
1661
+ "void"
1662
+ | "int"
1663
+ | "long"
1664
+ | "short"
1665
+ | "char"
1666
+ | "float"
1667
+ | "double"
1668
+ | "bool"
1669
+ | "unsigned"
1670
+ | "signed"
1671
+ | "size_t"
1672
+ | "int64_t"
1673
+ | "uint64_t"
1674
+ | "int32_t"
1675
+ | "const"
1676
+ | "struct"
1677
+ | "auto"
1678
+ | "var"
1679
+ | "string"
1680
+ | "decimal"
1681
+ | "byte"
1682
+ | "object"
1683
+ | "dynamic"
1684
+ ) || self.struct_names.contains(s)
1685
+ || self.enum_names.contains(s)
1686
+ {
1687
+ return true;
1688
+ }
1689
+ if s == "std" && self.peek_n(1).kind == TokKind::ColonColon {
1690
+ return true;
1691
+ }
1692
+ if self.lang == Language::CSharp
1693
+ && matches!(self.peek_n(1).kind, TokKind::Lt | TokKind::LBracket | TokKind::Ident(_))
1694
+ {
1695
+ if matches!(s.as_str(), "return" | "throw" | "if" | "else" | "while" | "for" | "foreach" | "switch" | "case" | "default" | "break" | "continue" | "try" | "catch" | "finally" | "using" | "namespace" | "class" | "struct" | "enum" | "new") {
1696
+ return false;
1697
+ }
1698
+ return true;
1699
+ }
1700
+ false
1701
+ }
1702
+
1703
+ fn try_skip_angle_generics(&mut self) -> bool {
1704
+ if !self.at(&TokKind::Lt) {
1705
+ return false;
1706
+ }
1707
+ let save = self.pos;
1708
+ self.advance();
1709
+ let mut depth = 1usize;
1710
+ while !self.at(&TokKind::Eof) && depth > 0 {
1711
+ match &self.peek().kind {
1712
+ TokKind::Lt => {
1713
+ depth += 1;
1714
+ self.advance();
1715
+ }
1716
+ TokKind::Gt => {
1717
+ depth -= 1;
1718
+ self.advance();
1719
+ }
1720
+ TokKind::Shr => {
1721
+ if depth >= 2 {
1722
+ depth -= 2;
1723
+ self.advance();
1724
+ } else {
1725
+ self.pos = save;
1726
+ return false;
1727
+ }
1728
+ }
1729
+ TokKind::Ident(_)
1730
+ | TokKind::Comma
1731
+ | TokKind::Colon
1732
+ | TokKind::ColonColon
1733
+ | TokKind::Dot
1734
+ | TokKind::Pipe
1735
+ | TokKind::Amp
1736
+ | TokKind::LBracket
1737
+ | TokKind::RBracket
1738
+ | TokKind::LParen
1739
+ | TokKind::RParen
1740
+ | TokKind::LBrace
1741
+ | TokKind::RBrace
1742
+ | TokKind::FatArrow
1743
+ | TokKind::Question
1744
+ | TokKind::Star
1745
+ | TokKind::Eq
1746
+ | TokKind::Str(_)
1747
+ | TokKind::Int(_) => {
1748
+ self.advance();
1749
+ }
1750
+ _ => {
1751
+ self.pos = save;
1752
+ return false;
1753
+ }
1754
+ }
1755
+ }
1756
+ if depth != 0 {
1757
+ self.pos = save;
1758
+ return false;
1759
+ }
1760
+ let valid_after = matches!(
1761
+ &self.peek().kind,
1762
+ TokKind::LParen
1763
+ | TokKind::LBrace
1764
+ | TokKind::Semi
1765
+ | TokKind::Eq
1766
+ | TokKind::Comma
1767
+ | TokKind::RParen
1768
+ | TokKind::Colon
1769
+ | TokKind::ColonColon
1770
+ | TokKind::Dot
1771
+ | TokKind::LBracket
1772
+ | TokKind::Gt
1773
+ | TokKind::Ident(_)
1774
+ );
1775
+ if !valid_after {
1776
+ self.pos = save;
1777
+ return false;
1778
+ }
1779
+ true
1780
+ }
1781
+
1782
+ fn parse_rich_type(&mut self) -> Result<TypeHint, PolyError> {
1783
+ if self.at(&TokKind::LParen) {
1784
+ self.advance();
1785
+ if self.eat(&TokKind::RParen) {
1786
+ return Ok(TypeHint::Void);
1787
+ }
1788
+ let mut count = 0usize;
1789
+ let mut first_ty = TypeHint::Unknown;
1790
+ while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
1791
+ let save = self.pos;
1792
+ if matches!(&self.peek().kind, TokKind::Ident(_)) && self.peek_n(1).kind == TokKind::Colon {
1793
+ self.advance();
1794
+ self.advance();
1795
+ }
1796
+ let t = self.parse_rich_type()?;
1797
+ if count == 0 {
1798
+ first_ty = t;
1799
+ }
1800
+ count += 1;
1801
+ if self.pos == save {
1802
+ self.advance();
1803
+ }
1804
+ if !self.eat(&TokKind::Comma) {
1805
+ break;
1806
+ }
1807
+ }
1808
+ self.expect(&TokKind::RParen, "')'")?;
1809
+ if self.eat(&TokKind::FatArrow) {
1810
+ let _ = self.parse_rich_type()?;
1811
+ return Ok(TypeHint::Unknown);
1812
+ }
1813
+ return Ok(if count == 1 { first_ty } else { TypeHint::Array });
1814
+ }
1815
+
1816
+ if self.eat(&TokKind::LBracket) {
1817
+ if self.eat(&TokKind::RBracket) {
1818
+ let _ = self.parse_rich_type()?;
1819
+ return Ok(TypeHint::Array);
1820
+ }
1821
+ while !self.at(&TokKind::RBracket) && !self.at(&TokKind::Eof) {
1822
+ let _ = self.parse_rich_type()?;
1823
+ if !self.eat(&TokKind::Comma) {
1824
+ break;
1825
+ }
1826
+ }
1827
+ self.expect(&TokKind::RBracket, "']'")?;
1828
+ return Ok(TypeHint::Array);
1829
+ }
1830
+
1831
+ if self.eat(&TokKind::LBrace) {
1832
+ let mut depth = 1usize;
1833
+ while !self.at(&TokKind::Eof) && depth > 0 {
1834
+ if self.eat(&TokKind::LBrace) {
1835
+ depth += 1;
1836
+ } else if self.eat(&TokKind::RBrace) {
1837
+ depth -= 1;
1838
+ } else {
1839
+ self.advance();
1840
+ }
1841
+ }
1842
+ return Ok(TypeHint::Object);
1843
+ }
1844
+
1845
+ let _ = self.eat(&TokKind::Amp);
1846
+ let _ = self.eat_ident("mut");
1847
+ let _ = self.eat_ident("const");
1848
+ let _ = self.eat_ident("readonly");
1849
+
1850
+ let mut base = match &self.peek().kind {
1851
+ TokKind::Ident(name) => {
1852
+ let mut full = name.clone();
1853
+ self.advance();
1854
+ while self.eat(&TokKind::Dot) || self.eat(&TokKind::ColonColon) {
1855
+ if let TokKind::Ident(seg) = &self.peek().kind {
1856
+ full = seg.clone();
1857
+ self.advance();
1858
+ } else {
1859
+ break;
1860
+ }
1861
+ }
1862
+ let _ = self.try_skip_angle_generics();
1863
+ Self::parse_type_hint_str(&full)
1864
+ }
1865
+ TokKind::Str(_) => {
1866
+ self.advance();
1867
+ TypeHint::Str
1868
+ }
1869
+ TokKind::Int(_) => {
1870
+ self.advance();
1871
+ TypeHint::Int
1872
+ }
1873
+ TokKind::Float(_) => {
1874
+ self.advance();
1875
+ TypeHint::Float
1876
+ }
1877
+ _ => {
1878
+ let t = self.peek();
1879
+ return Err(PolyError::spanned("E0112", "expected type annotation", t.span));
1880
+ }
1881
+ };
1882
+
1883
+ while self.at(&TokKind::LBracket) && self.peek_n(1).kind == TokKind::RBracket {
1884
+ self.advance();
1885
+ self.advance();
1886
+ base = TypeHint::Array;
1887
+ }
1888
+ while self.eat(&TokKind::Star) || self.eat(&TokKind::Amp) || self.eat(&TokKind::Question) {}
1889
+
1890
+ while self.eat(&TokKind::Pipe) || self.eat(&TokKind::Amp) {
1891
+ let other = self.parse_rich_type()?;
1892
+ if base != other {
1893
+ base = TypeHint::Unknown;
1894
+ }
1895
+ }
1896
+ Ok(base)
1897
+ }
1898
+
1899
+ fn parse_c_cpp_cs_type(&mut self) -> Result<TypeHint, PolyError> {
1900
+ let mut base = TypeHint::Unknown;
1901
+ let mut saw_any = false;
1902
+ while let TokKind::Ident(kw) = &self.peek().kind {
1903
+ let k = kw.clone();
1904
+ if matches!(
1905
+ k.as_str(),
1906
+ "const" | "unsigned" | "signed" | "struct" | "typename" | "virtual" | "inline" | "static"
1907
+ ) {
1908
+ self.advance();
1909
+ saw_any = true;
1910
+ if k == "unsigned" && !self.is_c_cpp_cs_type_start() {
1911
+ base = TypeHint::Int;
1912
+ }
1913
+ continue;
1914
+ }
1915
+ if k == "auto" || k == "var" || k == "dynamic" {
1916
+ self.advance();
1917
+ return Ok(TypeHint::Unknown);
1918
+ }
1919
+ if k == "std" && self.peek_n(1).kind == TokKind::ColonColon {
1920
+ self.advance();
1921
+ self.advance();
1922
+ let (inner, _) = self.expect_ident("std type")?;
1923
+ let _ = self.try_skip_angle_generics();
1924
+ base = if inner == "string" {
1925
+ TypeHint::Str
1926
+ } else if inner == "vector" {
1927
+ TypeHint::Array
1928
+ } else {
1929
+ Self::parse_type_hint_str(&inner)
1930
+ };
1931
+ saw_any = true;
1932
+ break;
1933
+ }
1934
+ let mapped = Self::parse_type_hint_str(&k);
1935
+ if mapped != TypeHint::Unknown
1936
+ || self.struct_names.contains(&k)
1937
+ || self.enum_names.contains(&k)
1938
+ || (self.lang == Language::CSharp && matches!(self.peek_n(1).kind, TokKind::Lt | TokKind::LBracket | TokKind::Ident(_)))
1939
+ {
1940
+ self.advance();
1941
+ saw_any = true;
1942
+ let _ = self.try_skip_angle_generics();
1943
+ if k == "char" && self.at(&TokKind::Star) {
1944
+ base = TypeHint::Str;
1945
+ } else {
1946
+ base = mapped;
1947
+ }
1948
+ break;
1949
+ } else {
1950
+ break;
1951
+ }
1952
+ }
1953
+ while self.at(&TokKind::LBracket) && self.peek_n(1).kind == TokKind::RBracket {
1954
+ self.advance();
1955
+ self.advance();
1956
+ base = TypeHint::Array;
1957
+ }
1958
+ while self.eat(&TokKind::Star) || self.eat(&TokKind::Amp) {
1959
+ if base == TypeHint::Unknown {
1960
+ base = TypeHint::Int;
1961
+ }
1962
+ }
1963
+ if !saw_any {
1964
+ let t = self.peek();
1965
+ return Err(PolyError::spanned("E0112", "expected type", t.span));
1966
+ }
1967
+ Ok(base)
1968
+ }
1969
+
1970
+ fn parse_module(&mut self, directives: Vec<ImportDecl>) -> Result<ModuleAst, PolyError> {
1971
+ let mut imports = directives;
1972
+ let mut structs = Vec::new();
1973
+ let mut enums = Vec::new();
1974
+ let mut functions = Vec::new();
1975
+ let mut top_level = Vec::new();
1976
+
1977
+ self.skip_newlines();
1978
+ while !self.at(&TokKind::Eof) {
1979
+ self.parse_top_level_item(&mut imports, &mut structs, &mut enums, &mut functions, &mut top_level)?;
1980
+ self.skip_newlines();
1981
+ }
1982
+
1983
+ functions.append(&mut self.extra_functions);
1984
+ enums.append(&mut self.extra_enums);
1985
+ structs.append(&mut self.extra_structs);
1986
+
1987
+ Ok(ModuleAst {
1988
+ language: self.lang,
1989
+ imports,
1990
+ using_namespaces: std::mem::take(&mut self.using_namespaces),
1991
+ enums,
1992
+ structs,
1993
+ functions,
1994
+ top_level,
1995
+ })
1996
+ }
1997
+
1998
+ fn parse_top_level_item(
1999
+ &mut self,
2000
+ imports: &mut Vec<ImportDecl>,
2001
+ structs: &mut Vec<StructDecl>,
2002
+ enums: &mut Vec<EnumDecl>,
2003
+ functions: &mut Vec<FunctionDecl>,
2004
+ top_level: &mut Vec<Stmt>,
2005
+ ) -> Result<(), PolyError> {
2006
+ self.skip_newlines();
2007
+ if self.at(&TokKind::Eof) {
2008
+ return Ok(());
2009
+ }
2010
+
2011
+ if self.lang == Language::Go && self.eat_ident("package") {
2012
+ let _ = self.expect_ident("package name")?;
2013
+ self.eat_stmt_end();
2014
+ return Ok(());
2015
+ }
2016
+
2017
+ if self.lang == Language::Cpp && self.eat_ident("template") {
2018
+ let _ = self.try_skip_angle_generics();
2019
+ self.skip_newlines();
2020
+ }
2021
+
2022
+ if (self.lang == Language::Cpp || self.lang == Language::CSharp) && self.at_ident("using") {
2023
+ let sp = self.peek().span;
2024
+ self.advance();
2025
+ if self.lang == Language::Cpp && self.eat_ident("namespace") {
2026
+ let (ns, _) = self.expect_ident("namespace")?;
2027
+ if ns != "std" {
2028
+ self.using_namespaces.push(ns);
2029
+ }
2030
+ self.eat_stmt_end();
2031
+ return Ok(());
2032
+ }
2033
+ let _ = self.eat_ident("static");
2034
+ if let TokKind::Str(spec) = &self.peek().kind {
2035
+ let spec = spec.clone();
2036
+ self.advance();
2037
+ imports.push(ImportDecl {
2038
+ module_specifier: spec,
2039
+ kind: ImportKind::Wildcard,
2040
+ span: sp,
2041
+ });
2042
+ self.eat_stmt_end();
2043
+ return Ok(());
2044
+ }
2045
+ let (first, _) = self.expect_ident("using identifier")?;
2046
+ if self.eat(&TokKind::Eq) {
2047
+ let (spec, _) = self.parse_module_specifier_tok()?;
2048
+ imports.push(ImportDecl {
2049
+ module_specifier: spec,
2050
+ kind: ImportKind::Namespace { alias: first },
2051
+ span: sp,
2052
+ });
2053
+ self.eat_stmt_end();
2054
+ return Ok(());
2055
+ }
2056
+ let mut full = first;
2057
+ while self.eat(&TokKind::Dot) || self.eat(&TokKind::ColonColon) {
2058
+ if let TokKind::Ident(seg) = &self.peek().kind {
2059
+ full.push('.');
2060
+ full.push_str(seg);
2061
+ self.advance();
2062
+ } else {
2063
+ break;
2064
+ }
2065
+ }
2066
+ if !is_stdlib_csharp_namespace(&full) && full != "std" {
2067
+ let spec = full.replace('.', "/");
2068
+ imports.push(ImportDecl {
2069
+ module_specifier: spec,
2070
+ kind: ImportKind::Wildcard,
2071
+ span: sp,
2072
+ });
2073
+ }
2074
+ self.eat_stmt_end();
2075
+ return Ok(());
2076
+ }
2077
+
2078
+ if (self.lang == Language::Cpp || self.lang == Language::CSharp) && self.eat_ident("namespace") {
2079
+ let (ns_name, _) = self.expect_ident("namespace name")?;
2080
+ while self.eat(&TokKind::Dot) || self.eat(&TokKind::ColonColon) {
2081
+ let _ = self.expect_ident("namespace segment")?;
2082
+ }
2083
+ if self.eat(&TokKind::Semi) {
2084
+ return Ok(());
2085
+ }
2086
+ self.expect(&TokKind::LBrace, "'{'")?;
2087
+ self.skip_newlines();
2088
+ let mut ns_funcs = Vec::new();
2089
+ while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
2090
+ self.parse_top_level_item(imports, structs, enums, &mut ns_funcs, top_level)?;
2091
+ self.skip_newlines();
2092
+ }
2093
+ self.expect(&TokKind::RBrace, "'}'")?;
2094
+ for mut f in ns_funcs {
2095
+ let orig = f.name.clone();
2096
+ f.name = format!("{ns_name}::{orig}");
2097
+ functions.push(f.clone());
2098
+ if self.lang == Language::CSharp {
2099
+ f.name = orig;
2100
+ functions.push(f);
2101
+ }
2102
+ }
2103
+ return Ok(());
2104
+ }
2105
+
2106
+ if self.at_ident("import") || self.at_ident("from") || self.at_ident("use") {
2107
+ let mut decls = self.parse_import_decl()?;
2108
+ imports.append(&mut decls);
2109
+ self.eat_stmt_end();
2110
+ return Ok(());
2111
+ }
2112
+
2113
+ if self.lang == Language::Rust && self.at_ident("mod") {
2114
+ let start = self.peek().span;
2115
+ self.advance();
2116
+ let (name, _) = self.expect_ident("module name")?;
2117
+ self.eat_stmt_end();
2118
+ imports.push(ImportDecl {
2119
+ module_specifier: name.clone(),
2120
+ kind: ImportKind::Namespace { alias: name },
2121
+ span: start,
2122
+ });
2123
+ return Ok(());
2124
+ }
2125
+
2126
+ if self.lang == Language::TypeScript && self.eat_ident("declare") {
2127
+ self.skip_statement_or_block();
2128
+ return Ok(());
2129
+ }
2130
+
2131
+ let mut exported = false;
2132
+ let mut is_const_enum = false;
2133
+ loop {
2134
+ if self.eat_ident("export") {
2135
+ let _ = self.eat_ident("default");
2136
+ exported = true;
2137
+ } else if self.eat_ident("pub") {
2138
+ exported = true;
2139
+ if self.eat(&TokKind::LParen) {
2140
+ while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
2141
+ self.advance();
2142
+ }
2143
+ let _ = self.eat(&TokKind::RParen);
2144
+ }
2145
+ } else if matches!(&self.peek().kind, TokKind::Ident(m) if matches!(m.as_str(), "public" | "private" | "protected" | "internal" | "static" | "virtual" | "override" | "sealed" | "abstract" | "async" | "extern")) {
2146
+ if self.at_ident("public") {
2147
+ exported = true;
2148
+ }
2149
+ self.advance();
2150
+ } else if self.lang == Language::TypeScript && self.at_ident("const") && self.peek_n(1).kind == TokKind::Ident("enum".into()) {
2151
+ self.advance();
2152
+ is_const_enum = true;
2153
+ } else {
2154
+ break;
2155
+ }
2156
+ }
2157
+ let _ = is_const_enum;
2158
+
2159
+ if self.at_ident("import") || self.at_ident("from") || self.at_ident("use") {
2160
+ let mut decls = self.parse_import_decl()?;
2161
+ imports.append(&mut decls);
2162
+ self.eat_stmt_end();
2163
+ return Ok(());
2164
+ }
2165
+
2166
+ if self.lang == Language::TypeScript && (self.at_ident("interface") || self.at_ident("type")) {
2167
+ if self.eat_ident("interface") {
2168
+ let (iname, _) = self.expect_ident("interface name")?;
2169
+ let _ = self.try_skip_angle_generics();
2170
+ self.struct_names.push(iname);
2171
+ while !self.at(&TokKind::LBrace) && !self.at(&TokKind::Eof) {
2172
+ self.advance();
2173
+ }
2174
+ let _ = self.skip_balanced_braces();
2175
+ return Ok(());
2176
+ }
2177
+ if self.eat_ident("type") && matches!(&self.peek().kind, TokKind::Ident(_)) {
2178
+ self.advance();
2179
+ let _ = self.try_skip_angle_generics();
2180
+ if self.eat(&TokKind::Eq) {
2181
+ self.skip_ts_type_rhs();
2182
+ }
2183
+ self.eat_stmt_end();
2184
+ return Ok(());
2185
+ }
2186
+ }
2187
+
2188
+ if self.lang == Language::Go && self.eat_ident("type") {
2189
+ let (name, span) = self.expect_ident("Go type name")?;
2190
+ if self.eat_ident("struct") {
2191
+ let s = self.parse_go_struct_body(name, span)?;
2192
+ self.struct_names.push(s.name.clone());
2193
+ structs.push(s);
2194
+ } else if self.eat_ident("interface") {
2195
+ let _ = self.skip_balanced_braces();
2196
+ } else {
2197
+ let _ = self.parse_rich_type()?;
2198
+ }
2199
+ self.eat_stmt_end();
2200
+ return Ok(());
2201
+ }
2202
+
2203
+ if self.at_ident("enum") {
2204
+ let e = self.parse_enum_decl()?;
2205
+ self.enum_names.push(e.name.clone());
2206
+ enums.push(e);
2207
+ return Ok(());
2208
+ }
2209
+
2210
+ if self.at_ident("fn")
2211
+ || self.at_ident("def")
2212
+ || self.at_ident("function")
2213
+ || (self.lang == Language::Go && self.at_ident("func"))
2214
+ {
2215
+ let f = self.parse_function(exported)?;
2216
+ functions.push(f);
2217
+ return Ok(());
2218
+ }
2219
+
2220
+ if self.at_ident("struct") || self.at_ident("class") {
2221
+ if matches!(self.lang, Language::C | Language::Cpp)
2222
+ && matches!(&self.peek_n(1).kind, TokKind::Ident(_))
2223
+ && !matches!(&self.peek_n(2).kind, TokKind::LBrace)
2224
+ && !self.peek_n(2).kind.eq(&TokKind::Colon)
2225
+ {
2226
+ if let Some(f) = self.try_parse_typed_top_level_fn()? {
2227
+ functions.push(f);
2228
+ return Ok(());
2229
+ }
2230
+ }
2231
+ let s = self.parse_struct_or_class()?;
2232
+ self.struct_names.push(s.name.clone());
2233
+ for m in &s.methods {
2234
+ functions.push(m.clone());
2235
+ }
2236
+ structs.push(s);
2237
+ return Ok(());
2238
+ }
2239
+
2240
+ if self.lang == Language::Rust && self.eat_ident("impl") {
2241
+ let _ = self.try_skip_angle_generics();
2242
+ let (struct_name, _) = self.expect_ident("struct name")?;
2243
+ let _ = self.try_skip_angle_generics();
2244
+ self.expect(&TokKind::LBrace, "'{'")?;
2245
+ while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
2246
+ let is_pub = self.eat_ident("pub");
2247
+ let mut m = self.parse_function(is_pub)?;
2248
+ m.name = format!("{struct_name}::{}", m.name);
2249
+ functions.push(m);
2250
+ }
2251
+ self.expect(&TokKind::RBrace, "'}'")?;
2252
+ return Ok(());
2253
+ }
2254
+
2255
+ if matches!(self.lang, Language::C | Language::Cpp | Language::CSharp)
2256
+ && self.is_c_cpp_cs_type_start()
2257
+ {
2258
+ if let Some(f) = self.try_parse_typed_top_level_fn()? {
2259
+ functions.push(f);
2260
+ return Ok(());
2261
+ }
2262
+ }
2263
+
2264
+ let stmt = self.parse_stmt()?;
2265
+ top_level.push(stmt);
2266
+ Ok(())
2267
+ }
2268
+
2269
+ fn skip_balanced_braces(&mut self) -> Result<(), PolyError> {
2270
+ self.expect(&TokKind::LBrace, "'{'")?;
2271
+ let mut depth = 1usize;
2272
+ while !self.at(&TokKind::Eof) && depth > 0 {
2273
+ if self.eat(&TokKind::LBrace) {
2274
+ depth += 1;
2275
+ } else if self.eat(&TokKind::RBrace) {
2276
+ depth -= 1;
2277
+ } else {
2278
+ self.advance();
2279
+ }
2280
+ }
2281
+ Ok(())
2282
+ }
2283
+
2284
+ fn skip_ts_type_rhs(&mut self) {
2285
+ let mut p = 0usize;
2286
+ let mut b = 0usize;
2287
+ let mut br = 0usize;
2288
+ while !self.at(&TokKind::Eof) {
2289
+ match &self.peek().kind {
2290
+ TokKind::Semi if p == 0 && b == 0 && br == 0 => break,
2291
+ TokKind::LParen => p += 1,
2292
+ TokKind::RParen => p = p.saturating_sub(1),
2293
+ TokKind::LBracket => b += 1,
2294
+ TokKind::RBracket => b = b.saturating_sub(1),
2295
+ TokKind::LBrace => br += 1,
2296
+ TokKind::RBrace => {
2297
+ if br == 0 {
2298
+ break;
2299
+ }
2300
+ br -= 1;
2301
+ }
2302
+ _ => {}
2303
+ }
2304
+ self.advance();
2305
+ }
2306
+ }
2307
+
2308
+ fn skip_statement_or_block(&mut self) {
2309
+ while !self.at(&TokKind::Eof) {
2310
+ if self.eat(&TokKind::Semi) {
2311
+ break;
2312
+ }
2313
+ if self.at(&TokKind::LBrace) {
2314
+ let _ = self.skip_balanced_braces();
2315
+ break;
2316
+ }
2317
+ self.advance();
2318
+ }
2319
+ }
2320
+
2321
+ fn parse_module_specifier_tok(&mut self) -> Result<(String, Span), PolyError> {
2322
+ let t = self.peek().clone();
2323
+ match t.kind {
2324
+ TokKind::Str(s) => {
2325
+ self.advance();
2326
+ Ok((s, t.span))
2327
+ }
2328
+ TokKind::Ident(first) => {
2329
+ self.advance();
2330
+ let mut spec = first;
2331
+ while self.eat(&TokKind::Dot) || self.eat(&TokKind::ColonColon) {
2332
+ if let TokKind::Ident(seg) = &self.peek().kind {
2333
+ spec.push('/');
2334
+ spec.push_str(seg);
2335
+ self.advance();
2336
+ } else {
2337
+ break;
2338
+ }
2339
+ }
2340
+ Ok((spec, t.span))
2341
+ }
2342
+ TokKind::Dot => {
2343
+ self.advance();
2344
+ let mut spec = String::from("./");
2345
+ while matches!(
2346
+ &self.peek().kind,
2347
+ TokKind::Ident(_) | TokKind::Dot | TokKind::Slash
2348
+ ) {
2349
+ match &self.peek().kind {
2350
+ TokKind::Ident(seg) => {
2351
+ spec.push_str(seg);
2352
+ self.advance();
2353
+ }
2354
+ TokKind::Dot => {
2355
+ spec.push('.');
2356
+ self.advance();
2357
+ }
2358
+ TokKind::Slash => {
2359
+ spec.push('/');
2360
+ self.advance();
2361
+ }
2362
+ _ => break,
2363
+ }
2364
+ }
2365
+ Ok((spec, t.span))
2366
+ }
2367
+ _ => Err(PolyError::spanned(
2368
+ "E0113",
2369
+ "expected module path or name",
2370
+ t.span,
2371
+ )),
2372
+ }
2373
+ }
2374
+
2375
+ fn parse_import_decl(&mut self) -> Result<Vec<ImportDecl>, PolyError> {
2376
+ let start = self.peek().span;
2377
+ if self.eat_ident("from") {
2378
+ let (mod_spec, _) = self.parse_module_specifier_tok()?;
2379
+ if !self.eat_ident("import") {
2380
+ return Err(PolyError::spanned(
2381
+ "E0114",
2382
+ "expected 'import' after module",
2383
+ self.peek().span,
2384
+ ));
2385
+ }
2386
+ if self.eat(&TokKind::Star) {
2387
+ return Ok(vec![ImportDecl {
2388
+ module_specifier: mod_spec,
2389
+ kind: ImportKind::Wildcard,
2390
+ span: start,
2391
+ }]);
2392
+ }
2393
+ let paren = self.eat(&TokKind::LParen);
2394
+ let mut items = Vec::new();
2395
+ loop {
2396
+ if paren && self.at(&TokKind::RParen) {
2397
+ break;
2398
+ }
2399
+ let (name, item_span) = self.expect_ident("imported symbol")?;
2400
+ let alias = if self.eat_ident("as") {
2401
+ self.expect_ident("import alias")?.0
2402
+ } else {
2403
+ name.clone()
2404
+ };
2405
+ items.push(ImportItem {
2406
+ name,
2407
+ alias,
2408
+ span: item_span,
2409
+ });
2410
+ if !self.eat(&TokKind::Comma) {
2411
+ break;
2412
+ }
2413
+ }
2414
+ if paren {
2415
+ self.expect(&TokKind::RParen, "')'")?;
2416
+ }
2417
+ return Ok(vec![ImportDecl {
2418
+ module_specifier: mod_spec,
2419
+ kind: ImportKind::Named { items },
2420
+ span: start,
2421
+ }]);
2422
+ }
2423
+
2424
+ if self.eat_ident("use") {
2425
+ let mut segments = Vec::new();
2426
+ let mut prefix = String::new();
2427
+ if self.eat(&TokKind::Dot) {
2428
+ let _ = self.eat(&TokKind::Slash);
2429
+ prefix = "./".to_string();
2430
+ }
2431
+ let (first, _) = self.expect_ident("module path")?;
2432
+ if first != "crate" && first != "self" {
2433
+ segments.push(first);
2434
+ }
2435
+ let mut named_items: Option<Vec<ImportItem>> = None;
2436
+ let mut wildcard = false;
2437
+ let mut single_alias: Option<String> = None;
2438
+
2439
+ while self.eat(&TokKind::ColonColon) {
2440
+ if self.eat(&TokKind::Star) {
2441
+ wildcard = true;
2442
+ break;
2443
+ }
2444
+ if self.eat(&TokKind::LBrace) {
2445
+ let mut items = Vec::new();
2446
+ while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
2447
+ let (name, ispan) = self.expect_ident("imported symbol")?;
2448
+ let alias = if self.eat_ident("as") {
2449
+ self.expect_ident("alias")?.0
2450
+ } else {
2451
+ name.clone()
2452
+ };
2453
+ items.push(ImportItem {
2454
+ name,
2455
+ alias,
2456
+ span: ispan,
2457
+ });
2458
+ if !self.eat(&TokKind::Comma) {
2459
+ break;
2460
+ }
2461
+ }
2462
+ self.expect(&TokKind::RBrace, "'}'")?;
2463
+ named_items = Some(items);
2464
+ break;
2465
+ }
2466
+ let (seg, _) = self.expect_ident("path segment")?;
2467
+ segments.push(seg);
2468
+ }
2469
+
2470
+ if named_items.is_none() && !wildcard && self.eat_ident("as") {
2471
+ single_alias = Some(self.expect_ident("alias")?.0);
2472
+ }
2473
+
2474
+ if let Some(items) = named_items {
2475
+ let mod_spec = format!("{prefix}{}", segments.join("/"));
2476
+ return Ok(vec![ImportDecl {
2477
+ module_specifier: mod_spec,
2478
+ kind: ImportKind::Named { items },
2479
+ span: start,
2480
+ }]);
2481
+ }
2482
+ if wildcard {
2483
+ let mod_spec = format!("{prefix}{}", segments.join("/"));
2484
+ return Ok(vec![ImportDecl {
2485
+ module_specifier: mod_spec,
2486
+ kind: ImportKind::Wildcard,
2487
+ span: start,
2488
+ }]);
2489
+ }
2490
+ if segments.len() >= 2 && single_alias.is_none() {
2491
+ let sym = segments.pop().unwrap();
2492
+ let mod_spec = format!("{prefix}{}", segments.join("/"));
2493
+ return Ok(vec![ImportDecl {
2494
+ module_specifier: mod_spec,
2495
+ kind: ImportKind::Named {
2496
+ items: vec![ImportItem {
2497
+ name: sym.clone(),
2498
+ alias: sym,
2499
+ span: start,
2500
+ }],
2501
+ },
2502
+ span: start,
2503
+ }]);
2504
+ }
2505
+ let mod_spec = format!("{prefix}{}", segments.join("/"));
2506
+ let alias = single_alias.unwrap_or_else(|| default_alias_for_spec(&mod_spec));
2507
+ return Ok(vec![ImportDecl {
2508
+ module_specifier: mod_spec,
2509
+ kind: ImportKind::Namespace { alias },
2510
+ span: start,
2511
+ }]);
2512
+ }
2513
+
2514
+ self.expect_ident("'import'")?;
2515
+
2516
+ if self.lang == Language::TypeScript && self.eat_ident("type") {
2517
+ while !self.at(&TokKind::Semi) && !self.at(&TokKind::Eof) {
2518
+ self.advance();
2519
+ }
2520
+ return Ok(Vec::new());
2521
+ }
2522
+
2523
+ if self.lang == Language::Go && self.eat(&TokKind::LParen) {
2524
+ let mut decls = Vec::new();
2525
+ self.skip_newlines();
2526
+ while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
2527
+ let sp = self.peek().span;
2528
+ let mut alias_opt = None;
2529
+ if let TokKind::Ident(a) = &self.peek().kind {
2530
+ alias_opt = Some(a.clone());
2531
+ self.advance();
2532
+ } else if self.eat(&TokKind::Dot) {
2533
+ alias_opt = Some(".".to_string());
2534
+ }
2535
+ let (spec, _) = self.parse_module_specifier_tok()?;
2536
+ if !is_stdlib_go_package(&spec) {
2537
+ let kind = if alias_opt.as_deref() == Some(".") {
2538
+ ImportKind::Wildcard
2539
+ } else {
2540
+ ImportKind::Namespace {
2541
+ alias: alias_opt.unwrap_or_else(|| default_alias_for_spec(&spec)),
2542
+ }
2543
+ };
2544
+ decls.push(ImportDecl {
2545
+ module_specifier: spec,
2546
+ kind,
2547
+ span: sp,
2548
+ });
2549
+ }
2550
+ self.eat_stmt_end();
2551
+ }
2552
+ self.expect(&TokKind::RParen, "')'")?;
2553
+ return Ok(decls);
2554
+ }
2555
+
2556
+ if let TokKind::Str(spec) = &self.peek().kind {
2557
+ let spec = spec.clone();
2558
+ self.advance();
2559
+ if self.lang == Language::Go && is_stdlib_go_package(&spec) {
2560
+ return Ok(Vec::new());
2561
+ }
2562
+ return Ok(vec![ImportDecl {
2563
+ module_specifier: spec,
2564
+ kind: ImportKind::Wildcard,
2565
+ span: start,
2566
+ }]);
2567
+ }
2568
+
2569
+ if self.eat(&TokKind::Star) {
2570
+ if !self.eat_ident("as") {
2571
+ return Err(PolyError::spanned(
2572
+ "E0115",
2573
+ "expected 'as' after 'import *'",
2574
+ self.peek().span,
2575
+ ));
2576
+ }
2577
+ let (alias, _) = self.expect_ident("namespace alias")?;
2578
+ if !self.eat_ident("from") {
2579
+ return Err(PolyError::spanned(
2580
+ "E0115",
2581
+ "expected 'from' in 'import * as ... from ...'",
2582
+ self.peek().span,
2583
+ ));
2584
+ }
2585
+ let (mod_spec, _) = self.parse_module_specifier_tok()?;
2586
+ return Ok(vec![ImportDecl {
2587
+ module_specifier: mod_spec,
2588
+ kind: ImportKind::Namespace { alias },
2589
+ span: start,
2590
+ }]);
2591
+ }
2592
+
2593
+ if self.eat(&TokKind::LBrace) {
2594
+ let items = self.parse_braced_import_items()?;
2595
+ if !self.eat_ident("from") {
2596
+ return Err(PolyError::spanned(
2597
+ "E0115",
2598
+ "expected 'from' after import list",
2599
+ self.peek().span,
2600
+ ));
2601
+ }
2602
+ let (mod_spec, _) = self.parse_module_specifier_tok()?;
2603
+ return Ok(vec![ImportDecl {
2604
+ module_specifier: mod_spec,
2605
+ kind: ImportKind::Named { items },
2606
+ span: start,
2607
+ }]);
2608
+ }
2609
+
2610
+ let mut first_entries: Vec<(String, Option<String>, Span)> = Vec::new();
2611
+ let mut braced_tail: Option<Vec<ImportItem>> = None;
2612
+
2613
+ if self.lang == Language::Go
2614
+ && matches!(&self.peek().kind, TokKind::Ident(_))
2615
+ && matches!(&self.peek_n(1).kind, TokKind::Str(_))
2616
+ {
2617
+ let (alias, sp) = self.expect_ident("import alias")?;
2618
+ let (spec, _) = self.parse_module_specifier_tok()?;
2619
+ if is_stdlib_go_package(&spec) {
2620
+ return Ok(Vec::new());
2621
+ }
2622
+ return Ok(vec![ImportDecl {
2623
+ module_specifier: spec,
2624
+ kind: ImportKind::Namespace { alias },
2625
+ span: sp,
2626
+ }]);
2627
+ }
2628
+
2629
+ loop {
2630
+ let (name, ispan) = self.expect_ident("module or symbol name")?;
2631
+ let alias = if self.eat_ident("as") {
2632
+ Some(self.expect_ident("alias")?.0)
2633
+ } else {
2634
+ None
2635
+ };
2636
+ first_entries.push((name, alias, ispan));
2637
+ if self.eat(&TokKind::Comma) {
2638
+ if self.eat(&TokKind::LBrace) {
2639
+ braced_tail = Some(self.parse_braced_import_items()?);
2640
+ break;
2641
+ }
2642
+ continue;
2643
+ }
2644
+ break;
2645
+ }
2646
+
2647
+ if self.eat_ident("from") {
2648
+ let (mod_spec, _) = self.parse_module_specifier_tok()?;
2649
+ let mut decls = Vec::new();
2650
+ if let Some(items) = braced_tail {
2651
+ if let Some((ns_name, ns_alias, _)) = first_entries.first() {
2652
+ decls.push(ImportDecl {
2653
+ module_specifier: mod_spec.clone(),
2654
+ kind: ImportKind::Namespace {
2655
+ alias: ns_alias.clone().unwrap_or_else(|| ns_name.clone()),
2656
+ },
2657
+ span: start,
2658
+ });
2659
+ }
2660
+ decls.push(ImportDecl {
2661
+ module_specifier: mod_spec,
2662
+ kind: ImportKind::Named { items },
2663
+ span: start,
2664
+ });
2665
+ return Ok(decls);
2666
+ }
2667
+ let items = first_entries
2668
+ .into_iter()
2669
+ .map(|(name, alias, ispan)| ImportItem {
2670
+ alias: alias.unwrap_or_else(|| name.clone()),
2671
+ name,
2672
+ span: ispan,
2673
+ })
2674
+ .collect();
2675
+ return Ok(vec![ImportDecl {
2676
+ module_specifier: mod_spec,
2677
+ kind: ImportKind::Named { items },
2678
+ span: start,
2679
+ }]);
2680
+ }
2681
+
2682
+ let decls = first_entries
2683
+ .into_iter()
2684
+ .map(|(mod_spec, alias, ispan)| ImportDecl {
2685
+ kind: ImportKind::Namespace {
2686
+ alias: alias.unwrap_or_else(|| default_alias_for_spec(&mod_spec)),
2687
+ },
2688
+ module_specifier: mod_spec,
2689
+ span: ispan,
2690
+ })
2691
+ .collect();
2692
+ Ok(decls)
2693
+ }
2694
+
2695
+ fn parse_braced_import_items(&mut self) -> Result<Vec<ImportItem>, PolyError> {
2696
+ let mut items = Vec::new();
2697
+ while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
2698
+ let _ = self.eat_ident("type");
2699
+ let (name, ispan) = self.expect_ident("imported symbol")?;
2700
+ let alias = if self.eat_ident("as") {
2701
+ self.expect_ident("alias")?.0
2702
+ } else {
2703
+ name.clone()
2704
+ };
2705
+ items.push(ImportItem {
2706
+ name,
2707
+ alias,
2708
+ span: ispan,
2709
+ });
2710
+ if !self.eat(&TokKind::Comma) {
2711
+ break;
2712
+ }
2713
+ }
2714
+ self.expect(&TokKind::RBrace, "'}'")?;
2715
+ Ok(items)
2716
+ }
2717
+
2718
+ fn try_parse_typed_top_level_fn(&mut self) -> Result<Option<FunctionDecl>, PolyError> {
2719
+ let save = self.pos;
2720
+ let ret_ty = self.parse_c_cpp_cs_type()?;
2721
+ if let TokKind::Ident(name) = &self.peek().kind {
2722
+ let fn_name = name.clone();
2723
+ let fn_span = self.peek().span;
2724
+ self.advance();
2725
+ let _ = self.try_skip_angle_generics();
2726
+ if self.eat(&TokKind::LParen) {
2727
+ let params = self.parse_c_cpp_cs_params()?;
2728
+ self.expect(&TokKind::RParen, "')'")?;
2729
+ let _ = self.eat_ident("const");
2730
+ let _ = self.eat_ident("override");
2731
+ if self.eat(&TokKind::Semi) {
2732
+ return Ok(None);
2733
+ }
2734
+ let body = if self.eat(&TokKind::FatArrow) {
2735
+ let expr = self.parse_expr()?;
2736
+ self.eat_stmt_end();
2737
+ vec![Stmt::Return(Some(expr), fn_span)]
2738
+ } else {
2739
+ self.parse_brace_block()?
2740
+ };
2741
+ return Ok(Some(FunctionDecl {
2742
+ name: fn_name,
2743
+ params,
2744
+ return_type: ret_ty,
2745
+ body,
2746
+ is_exported: true,
2747
+ span: fn_span,
2748
+ }));
2749
+ }
2750
+ }
2751
+ self.pos = save;
2752
+ Ok(None)
2753
+ }
2754
+
2755
+ fn parse_c_cpp_cs_params(&mut self) -> Result<Vec<Param>, PolyError> {
2756
+ let mut params = Vec::new();
2757
+ if self.at_ident("void") && self.peek_n(1).kind == TokKind::RParen {
2758
+ self.advance();
2759
+ return Ok(params);
2760
+ }
2761
+ while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
2762
+ let _ = self.eat_ident("ref") || self.eat_ident("out") || self.eat_ident("in") || self.eat_ident("params");
2763
+ let ty = if self.is_c_cpp_cs_type_start() {
2764
+ self.parse_c_cpp_cs_type()?
2765
+ } else {
2766
+ TypeHint::Unknown
2767
+ };
2768
+ let (name, span) = self.expect_ident("parameter name")?;
2769
+ if self.eat(&TokKind::LBracket) {
2770
+ let _ = self.eat(&TokKind::RBracket);
2771
+ }
2772
+ if self.eat(&TokKind::Eq) {
2773
+ let _ = self.parse_expr()?;
2774
+ }
2775
+ params.push(Param { name, ty, span });
2776
+ if !self.eat(&TokKind::Comma) {
2777
+ break;
2778
+ }
2779
+ }
2780
+ Ok(params)
2781
+ }
2782
+
2783
+ fn parse_go_params(&mut self) -> Result<Vec<Param>, PolyError> {
2784
+ let mut params = Vec::new();
2785
+ let mut untyped_group: Vec<(String, Span)> = Vec::new();
2786
+ while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
2787
+ let (pname, pspan) = self.expect_ident("Go parameter name")?;
2788
+ if self.at(&TokKind::Comma) {
2789
+ untyped_group.push((pname, pspan));
2790
+ self.advance();
2791
+ continue;
2792
+ }
2793
+ let ty = if !self.at(&TokKind::RParen) {
2794
+ self.parse_rich_type()?
2795
+ } else {
2796
+ TypeHint::Unknown
2797
+ };
2798
+ for (gn, gsp) in untyped_group.drain(..) {
2799
+ params.push(Param {
2800
+ name: gn,
2801
+ ty,
2802
+ span: gsp,
2803
+ });
2804
+ }
2805
+ params.push(Param {
2806
+ name: pname,
2807
+ ty,
2808
+ span: pspan,
2809
+ });
2810
+ if !self.eat(&TokKind::Comma) {
2811
+ break;
2812
+ }
2813
+ }
2814
+ for (gn, gsp) in untyped_group {
2815
+ params.push(Param {
2816
+ name: gn,
2817
+ ty: TypeHint::Unknown,
2818
+ span: gsp,
2819
+ });
2820
+ }
2821
+ Ok(params)
2822
+ }
2823
+
2824
+ fn parse_function(&mut self, _exported: bool) -> Result<FunctionDecl, PolyError> {
2825
+ let start_span = self.advance().span;
2826
+
2827
+ let mut go_receiver: Option<(Param, String)> = None;
2828
+ if self.lang == Language::Go && self.eat(&TokKind::LParen) {
2829
+ let (rname, rspan) = self.expect_ident("receiver name")?;
2830
+ let _ = self.eat(&TokKind::Star);
2831
+ let (rtype, _) = self.expect_ident("receiver struct type")?;
2832
+ self.expect(&TokKind::RParen, "')'")?;
2833
+ go_receiver = Some((
2834
+ Param {
2835
+ name: rname,
2836
+ ty: TypeHint::Object,
2837
+ span: rspan,
2838
+ },
2839
+ rtype,
2840
+ ));
2841
+ }
2842
+
2843
+ let (mut name, _) = self.expect_ident("function name")?;
2844
+ if let Some((_, ref rstruct)) = go_receiver {
2845
+ name = format!("{rstruct}::{name}");
2846
+ }
2847
+
2848
+ let _ = self.try_skip_angle_generics();
2849
+
2850
+ self.expect(&TokKind::LParen, "'('")?;
2851
+ let mut params = if let Some((recv, _)) = go_receiver {
2852
+ vec![recv]
2853
+ } else {
2854
+ Vec::new()
2855
+ };
2856
+
2857
+ if self.lang == Language::Go {
2858
+ params.extend(self.parse_go_params()?);
2859
+ } else {
2860
+ while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
2861
+ let _ = self.eat_ident("mut")
2862
+ || self.eat_ident("public")
2863
+ || self.eat_ident("private")
2864
+ || self.eat_ident("readonly");
2865
+ let (pname, pspan) = self.expect_ident("parameter name")?;
2866
+ let _ = self.eat(&TokKind::Question);
2867
+ let ty = if self.eat(&TokKind::Colon) {
2868
+ self.parse_rich_type()?
2869
+ } else {
2870
+ TypeHint::Unknown
2871
+ };
2872
+ if self.eat(&TokKind::Eq) {
2873
+ let _ = self.parse_expr()?;
2874
+ }
2875
+ params.push(Param {
2876
+ name: pname,
2877
+ ty,
2878
+ span: pspan,
2879
+ });
2880
+ if !self.eat(&TokKind::Comma) {
2881
+ break;
2882
+ }
2883
+ }
2884
+ }
2885
+ self.expect(&TokKind::RParen, "')'")?;
2886
+
2887
+ let mut return_type = TypeHint::Unknown;
2888
+ if self.eat(&TokKind::Arrow) {
2889
+ return_type = self.parse_rich_type()?;
2890
+ } else if self.lang != Language::Python && self.eat(&TokKind::Colon) {
2891
+ return_type = self.parse_rich_type()?;
2892
+ } else if self.lang == Language::Go && !self.at(&TokKind::LBrace) {
2893
+ return_type = self.parse_rich_type()?;
2894
+ }
2895
+
2896
+ let mut body = if self.lang == Language::Python {
2897
+ self.expect(&TokKind::Colon, "':'")?;
2898
+ self.parse_py_suite()?
2899
+ } else {
2900
+ self.parse_brace_block()?
2901
+ };
2902
+
2903
+ if self.lang == Language::Rust
2904
+ && return_type != TypeHint::Void
2905
+ && let Some(last) = body.pop()
2906
+ {
2907
+ match last {
2908
+ Stmt::ExprStmt(expr, sp) => {
2909
+ body.push(Stmt::Return(Some(expr), sp));
2910
+ }
2911
+ other => body.push(other),
2912
+ }
2913
+ }
2914
+
2915
+ Ok(FunctionDecl {
2916
+ name,
2917
+ params,
2918
+ return_type,
2919
+ body,
2920
+ is_exported: true,
2921
+ span: start_span,
2922
+ })
2923
+ }
2924
+
2925
+ fn parse_enum_decl(&mut self) -> Result<EnumDecl, PolyError> {
2926
+ let sp = self.advance().span;
2927
+ let (name, _) = self.expect_ident("enum name")?;
2928
+ self.expect(&TokKind::LBrace, "'{'")?;
2929
+ let mut variants = Vec::new();
2930
+ let mut next_int = 0i64;
2931
+ while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
2932
+ let (vname, vsp) = self.expect_ident("enum variant")?;
2933
+ let val = if self.eat(&TokKind::Eq) {
2934
+ let e = self.parse_expr()?;
2935
+ if let Expr::Int(i, _) = e {
2936
+ next_int = i + 1;
2937
+ }
2938
+ e
2939
+ } else {
2940
+ let e = Expr::Int(next_int, vsp);
2941
+ next_int += 1;
2942
+ e
2943
+ };
2944
+ variants.push((vname, val));
2945
+ if !self.eat(&TokKind::Comma) {
2946
+ break;
2947
+ }
2948
+ }
2949
+ self.expect(&TokKind::RBrace, "'}'")?;
2950
+ let _ = self.eat(&TokKind::Semi);
2951
+ Ok(EnumDecl {
2952
+ name,
2953
+ variants,
2954
+ span: sp,
2955
+ })
2956
+ }
2957
+
2958
+ fn parse_go_struct_body(&mut self, name: String, span: Span) -> Result<StructDecl, PolyError> {
2959
+ self.expect(&TokKind::LBrace, "'{'")?;
2960
+ let mut fields = Vec::new();
2961
+ self.skip_newlines();
2962
+ while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
2963
+ let (fname, _) = self.expect_ident("Go struct field")?;
2964
+ let fty = self.parse_rich_type()?;
2965
+ if matches!(&self.peek().kind, TokKind::Str(_)) {
2966
+ self.advance();
2967
+ }
2968
+ fields.push((fname, fty));
2969
+ self.eat_stmt_end();
2970
+ }
2971
+ self.expect(&TokKind::RBrace, "'}'")?;
2972
+ Ok(StructDecl {
2973
+ name,
2974
+ fields,
2975
+ methods: Vec::new(),
2976
+ span,
2977
+ })
2978
+ }
2979
+
2980
+ fn parse_struct_or_class(&mut self) -> Result<StructDecl, PolyError> {
2981
+ let start_span = self.advance().span;
2982
+ let (name, _) = self.expect_ident("struct/class name")?;
2983
+ let _ = self.try_skip_angle_generics();
2984
+ if self.eat_ident("extends") || self.eat_ident("implements") || self.eat(&TokKind::Colon) {
2985
+ while !self.at(&TokKind::LBrace) && !self.at(&TokKind::Eof) {
2986
+ self.advance();
2987
+ }
2988
+ }
2989
+
2990
+ let mut fields = Vec::new();
2991
+ let mut methods = Vec::new();
2992
+
2993
+ if self.lang == Language::Python {
2994
+ self.expect(&TokKind::Colon, "':'")?;
2995
+ self.skip_newlines();
2996
+ self.expect(&TokKind::Indent, "indented class body")?;
2997
+ while !self.at(&TokKind::Dedent) && !self.at(&TokKind::Eof) {
2998
+ self.skip_newlines();
2999
+ if self.at(&TokKind::Dedent) || self.at(&TokKind::Eof) {
3000
+ break;
3001
+ }
3002
+ if self.at_ident("def") {
3003
+ let mut m = self.parse_function(true)?;
3004
+ m.name = format!("{name}::{}", m.name);
3005
+ methods.push(m);
3006
+ } else if self.eat_ident("pass") {
3007
+ self.eat_stmt_end();
3008
+ } else {
3009
+ let _ = self.parse_stmt()?;
3010
+ }
3011
+ }
3012
+ let _ = self.eat(&TokKind::Dedent);
3013
+ } else {
3014
+ self.expect(&TokKind::LBrace, "'{'")?;
3015
+ self.skip_newlines();
3016
+ while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
3017
+ self.skip_newlines();
3018
+ if self.at(&TokKind::RBrace) || self.at(&TokKind::Eof) {
3019
+ break;
3020
+ }
3021
+ if self.lang == Language::Cpp
3022
+ && matches!(&self.peek().kind, TokKind::Ident(s) if matches!(s.as_str(), "public" | "private" | "protected"))
3023
+ && self.peek_n(1).kind == TokKind::Colon
3024
+ {
3025
+ self.advance();
3026
+ self.advance();
3027
+ continue;
3028
+ }
3029
+ while matches!(&self.peek().kind, TokKind::Ident(m) if matches!(m.as_str(), "pub" | "public" | "private" | "protected" | "internal" | "static" | "readonly" | "virtual" | "override" | "async")) {
3030
+ self.advance();
3031
+ }
3032
+
3033
+ if self.at_ident("fn") || self.at_ident("function") {
3034
+ let mut m = self.parse_function(true)?;
3035
+ m.name = format!("{name}::{}", m.name);
3036
+ methods.push(m);
3037
+ continue;
3038
+ }
3039
+
3040
+ if matches!(&self.peek().kind, TokKind::Ident(n) if n == &name)
3041
+ && self.peek_n(1).kind == TokKind::LParen
3042
+ {
3043
+ let cspan = self.advance().span;
3044
+ self.expect(&TokKind::LParen, "'('")?;
3045
+ let mut params = vec![Param {
3046
+ name: "this".to_string(),
3047
+ ty: TypeHint::Object,
3048
+ span: cspan,
3049
+ }];
3050
+ params.extend(self.parse_c_cpp_cs_params()?);
3051
+ self.expect(&TokKind::RParen, "')'")?;
3052
+ let body = self.parse_brace_block()?;
3053
+ methods.push(FunctionDecl {
3054
+ name: format!("{name}::__init"),
3055
+ params,
3056
+ return_type: TypeHint::Void,
3057
+ body,
3058
+ is_exported: true,
3059
+ span: cspan,
3060
+ });
3061
+ continue;
3062
+ }
3063
+
3064
+ if matches!(self.lang, Language::JavaScript | Language::TypeScript)
3065
+ && matches!(&self.peek().kind, TokKind::Ident(_))
3066
+ && (self.peek_n(1).kind == TokKind::LParen || self.peek_n(1).kind == TokKind::Lt)
3067
+ {
3068
+ let (raw_mname, mspan) = self.expect_ident("method name")?;
3069
+ let _ = self.try_skip_angle_generics();
3070
+ let mname = if raw_mname == "constructor" {
3071
+ "__init".to_string()
3072
+ } else {
3073
+ raw_mname
3074
+ };
3075
+ self.expect(&TokKind::LParen, "'('")?;
3076
+ let mut params = vec![Param {
3077
+ name: "this".to_string(),
3078
+ ty: TypeHint::Object,
3079
+ span: mspan,
3080
+ }];
3081
+ while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
3082
+ let _ = self.eat_ident("public") || self.eat_ident("private") || self.eat_ident("readonly");
3083
+ let (pn, ps) = self.expect_ident("param")?;
3084
+ let _ = self.eat(&TokKind::Question);
3085
+ let pty = if self.eat(&TokKind::Colon) {
3086
+ self.parse_rich_type()?
3087
+ } else {
3088
+ TypeHint::Unknown
3089
+ };
3090
+ if self.eat(&TokKind::Eq) {
3091
+ let _ = self.parse_expr()?;
3092
+ }
3093
+ params.push(Param {
3094
+ name: pn,
3095
+ ty: pty,
3096
+ span: ps,
3097
+ });
3098
+ if !self.eat(&TokKind::Comma) {
3099
+ break;
3100
+ }
3101
+ }
3102
+ self.expect(&TokKind::RParen, "')'")?;
3103
+ let rty = if self.eat(&TokKind::Colon) {
3104
+ self.parse_rich_type()?
3105
+ } else {
3106
+ TypeHint::Unknown
3107
+ };
3108
+ let body = self.parse_brace_block()?;
3109
+ methods.push(FunctionDecl {
3110
+ name: format!("{name}::{mname}"),
3111
+ params,
3112
+ return_type: rty,
3113
+ body,
3114
+ is_exported: true,
3115
+ span: mspan,
3116
+ });
3117
+ continue;
3118
+ }
3119
+
3120
+ if matches!(self.lang, Language::C | Language::Cpp | Language::CSharp)
3121
+ && self.is_c_cpp_cs_type_start()
3122
+ {
3123
+ let fty = self.parse_c_cpp_cs_type()?;
3124
+ let (fname, fspan) = self.expect_ident("member name")?;
3125
+ let _ = self.try_skip_angle_generics();
3126
+ if self.eat(&TokKind::LParen) {
3127
+ let mut params = vec![Param {
3128
+ name: "this".to_string(),
3129
+ ty: TypeHint::Object,
3130
+ span: fspan,
3131
+ }];
3132
+ params.extend(self.parse_c_cpp_cs_params()?);
3133
+ self.expect(&TokKind::RParen, "')'")?;
3134
+ let _ = self.eat_ident("const");
3135
+ let body = if self.eat(&TokKind::FatArrow) {
3136
+ let e = self.parse_expr()?;
3137
+ self.eat_stmt_end();
3138
+ vec![Stmt::Return(Some(e), fspan)]
3139
+ } else {
3140
+ self.parse_brace_block()?
3141
+ };
3142
+ methods.push(FunctionDecl {
3143
+ name: format!("{name}::{fname}"),
3144
+ params,
3145
+ return_type: fty,
3146
+ body,
3147
+ is_exported: true,
3148
+ span: fspan,
3149
+ });
3150
+ continue;
3151
+ }
3152
+ if self.lang == Language::CSharp && self.at(&TokKind::LBrace) {
3153
+ let _ = self.skip_balanced_braces();
3154
+ if self.eat(&TokKind::Eq) {
3155
+ let _ = self.parse_expr()?;
3156
+ }
3157
+ self.eat_stmt_end();
3158
+ fields.push((fname, fty));
3159
+ continue;
3160
+ }
3161
+ if self.eat(&TokKind::Eq) {
3162
+ let _ = self.parse_expr()?;
3163
+ }
3164
+ self.eat_stmt_end();
3165
+ fields.push((fname, fty));
3166
+ continue;
3167
+ }
3168
+
3169
+ let (fname, _) = self.expect_ident("field name")?;
3170
+ let _ = self.eat(&TokKind::Question);
3171
+ let fty = if self.eat(&TokKind::Colon) {
3172
+ self.parse_rich_type()?
3173
+ } else {
3174
+ TypeHint::Unknown
3175
+ };
3176
+ if self.eat(&TokKind::Eq) {
3177
+ let _ = self.parse_expr()?;
3178
+ }
3179
+ fields.push((fname, fty));
3180
+ let _ = self.eat(&TokKind::Comma) || self.eat(&TokKind::Semi);
3181
+ }
3182
+ self.expect(&TokKind::RBrace, "'}'")?;
3183
+ let _ = self.eat(&TokKind::Semi);
3184
+ }
3185
+
3186
+ Ok(StructDecl {
3187
+ name,
3188
+ fields,
3189
+ methods,
3190
+ span: start_span,
3191
+ })
3192
+ }
3193
+
3194
+ fn parse_py_suite(&mut self) -> Result<Vec<Stmt>, PolyError> {
3195
+ if self.eat(&TokKind::Newline) {
3196
+ self.skip_newlines();
3197
+ self.expect(&TokKind::Indent, "indented block")?;
3198
+ let mut stmts = Vec::new();
3199
+ while !self.at(&TokKind::Dedent) && !self.at(&TokKind::Eof) {
3200
+ self.skip_newlines();
3201
+ if self.at(&TokKind::Dedent) || self.at(&TokKind::Eof) {
3202
+ break;
3203
+ }
3204
+ stmts.push(self.parse_stmt()?);
3205
+ }
3206
+ let _ = self.eat(&TokKind::Dedent);
3207
+ Ok(stmts)
3208
+ } else {
3209
+ Ok(vec![self.parse_stmt()?])
3210
+ }
3211
+ }
3212
+
3213
+ fn parse_brace_block(&mut self) -> Result<Vec<Stmt>, PolyError> {
3214
+ self.expect(&TokKind::LBrace, "'{'")?;
3215
+ let mut stmts = Vec::new();
3216
+ self.skip_newlines();
3217
+ while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
3218
+ stmts.push(self.parse_stmt()?);
3219
+ self.skip_newlines();
3220
+ }
3221
+ self.expect(&TokKind::RBrace, "'}'")?;
3222
+ Ok(stmts)
3223
+ }
3224
+
3225
+ fn parse_stmt(&mut self) -> Result<Stmt, PolyError> {
3226
+ self.skip_newlines();
3227
+ let sp = self.peek().span;
3228
+
3229
+ if self.at(&TokKind::LBrace) {
3230
+ return Ok(Stmt::Block(self.parse_brace_block()?, sp));
3231
+ }
3232
+ if self.eat_ident("pass") {
3233
+ self.eat_stmt_end();
3234
+ return Ok(Stmt::Block(Vec::new(), sp));
3235
+ }
3236
+ if self.eat_ident("break") {
3237
+ self.eat_stmt_end();
3238
+ return Ok(Stmt::Break(sp));
3239
+ }
3240
+ if self.eat_ident("continue") {
3241
+ self.eat_stmt_end();
3242
+ return Ok(Stmt::Continue(sp));
3243
+ }
3244
+ if self.lang == Language::Go && self.eat_ident("defer") {
3245
+ let e = self.parse_expr()?;
3246
+ self.eat_stmt_end();
3247
+ return Ok(Stmt::Defer(e, sp));
3248
+ }
3249
+ if self.eat_ident("throw") || (self.lang == Language::Python && self.eat_ident("raise")) {
3250
+ let e = self.parse_expr()?;
3251
+ self.eat_stmt_end();
3252
+ return Ok(Stmt::Throw(e, sp));
3253
+ }
3254
+ if self.eat_ident("try") {
3255
+ return self.parse_try_catch(sp);
3256
+ }
3257
+ if self.eat_ident("switch") || (self.lang == Language::Rust && self.eat_ident("match")) {
3258
+ return self.parse_switch_or_match(sp);
3259
+ }
3260
+
3261
+ if self.eat_ident("return") {
3262
+ if self.at(&TokKind::Semi)
3263
+ || self.at(&TokKind::Newline)
3264
+ || self.at(&TokKind::RBrace)
3265
+ || self.at(&TokKind::Dedent)
3266
+ || self.at(&TokKind::Eof)
3267
+ {
3268
+ self.eat_stmt_end();
3269
+ return Ok(Stmt::Return(None, sp));
3270
+ }
3271
+ let first = self.parse_expr()?;
3272
+ let val = if self.eat(&TokKind::Comma) {
3273
+ let mut items = vec![first];
3274
+ loop {
3275
+ items.push(self.parse_expr()?);
3276
+ if !self.eat(&TokKind::Comma) {
3277
+ break;
3278
+ }
3279
+ }
3280
+ Expr::Tuple(items, sp)
3281
+ } else {
3282
+ first
3283
+ };
3284
+ self.eat_stmt_end();
3285
+ return Ok(Stmt::Return(Some(val), sp));
3286
+ }
3287
+
3288
+ if self.eat_ident("if") {
3289
+ return self.parse_if_stmt(sp);
3290
+ }
3291
+ if self.eat_ident("while") {
3292
+ let cond = self.parse_condition_expr()?;
3293
+ let body = if self.lang == Language::Python {
3294
+ self.expect(&TokKind::Colon, "':'")?;
3295
+ self.parse_py_suite()?
3296
+ } else {
3297
+ self.parse_brace_block()?
3298
+ };
3299
+ return Ok(Stmt::While {
3300
+ cond,
3301
+ body,
3302
+ span: sp,
3303
+ });
3304
+ }
3305
+ if self.eat_ident("loop") {
3306
+ let body = self.parse_brace_block()?;
3307
+ return Ok(Stmt::While {
3308
+ cond: Expr::Bool(true, sp),
3309
+ body,
3310
+ span: sp,
3311
+ });
3312
+ }
3313
+ if self.eat_ident("for") || self.eat_ident("foreach") {
3314
+ return self.parse_for_stmt(sp);
3315
+ }
3316
+
3317
+ if self.at_ident("let") || self.at_ident("const") || self.at_ident("var") {
3318
+ let kw = match &self.peek().kind {
3319
+ TokKind::Ident(s) => s.clone(),
3320
+ _ => unreachable!(),
3321
+ };
3322
+ let is_fn_scoped = kw == "var";
3323
+ self.advance();
3324
+ let _ = self.eat_ident("mut");
3325
+
3326
+ if self.eat(&TokKind::LBracket) || self.eat(&TokKind::LParen) {
3327
+ let close = if self.tokens[self.pos - 1].kind == TokKind::LBracket {
3328
+ TokKind::RBracket
3329
+ } else {
3330
+ TokKind::RParen
3331
+ };
3332
+ let mut names = Vec::new();
3333
+ while !self.at(&close) && !self.at(&TokKind::Eof) {
3334
+ let (n, _) = self.expect_ident("destructured variable")?;
3335
+ names.push(n);
3336
+ if !self.eat(&TokKind::Comma) {
3337
+ break;
3338
+ }
3339
+ }
3340
+ self.expect(&close, "closing bracket/paren")?;
3341
+ if self.eat(&TokKind::Colon) {
3342
+ let _ = self.parse_rich_type()?;
3343
+ }
3344
+ self.expect(&TokKind::Eq, "'='")?;
3345
+ let init = self.parse_expr()?;
3346
+ self.eat_stmt_end();
3347
+ return Ok(Stmt::MultiVarDecl {
3348
+ names,
3349
+ init,
3350
+ is_function_scoped: is_fn_scoped,
3351
+ span: sp,
3352
+ });
3353
+ }
3354
+
3355
+ let (name, _) = self.expect_ident("variable name")?;
3356
+ let ty = if self.eat(&TokKind::Colon) {
3357
+ self.parse_rich_type()?
3358
+ } else if self.lang == Language::Go && !self.at(&TokKind::Eq) {
3359
+ self.parse_rich_type()?
3360
+ } else {
3361
+ TypeHint::Unknown
3362
+ };
3363
+ let init = if self.eat(&TokKind::Eq) {
3364
+ Some(self.parse_expr()?)
3365
+ } else {
3366
+ None
3367
+ };
3368
+ self.eat_stmt_end();
3369
+ return Ok(Stmt::VarDecl {
3370
+ name,
3371
+ ty,
3372
+ init,
3373
+ is_function_scoped: is_fn_scoped,
3374
+ span: sp,
3375
+ });
3376
+ }
3377
+
3378
+ if matches!(self.lang, Language::C | Language::Cpp | Language::CSharp)
3379
+ && self.is_c_cpp_cs_type_start()
3380
+ {
3381
+ let save = self.pos;
3382
+ if let Ok(ty) = self.parse_c_cpp_cs_type()
3383
+ && let TokKind::Ident(_) = &self.peek().kind
3384
+ {
3385
+ let (name, _) = self.expect_ident("variable name")?;
3386
+ if self.eat(&TokKind::LBracket) {
3387
+ while !self.at(&TokKind::RBracket) && !self.at(&TokKind::Eof) {
3388
+ self.advance();
3389
+ }
3390
+ self.expect(&TokKind::RBracket, "']'")?;
3391
+ }
3392
+ let init = if self.lang == Language::Cpp && self.eat(&TokKind::LParen) {
3393
+ let mut args = Vec::new();
3394
+ while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
3395
+ args.push(self.parse_expr()?);
3396
+ if !self.eat(&TokKind::Comma) {
3397
+ break;
3398
+ }
3399
+ }
3400
+ self.expect(&TokKind::RParen, "')'")?;
3401
+ let fields = args
3402
+ .into_iter()
3403
+ .enumerate()
3404
+ .map(|(i, e)| (format!("_{i}"), e))
3405
+ .collect();
3406
+ Some(Expr::ObjectLit(None, fields, sp))
3407
+ } else if self.eat(&TokKind::Eq) {
3408
+ Some(self.parse_expr()?)
3409
+ } else {
3410
+ None
3411
+ };
3412
+ self.eat_stmt_end();
3413
+ return Ok(Stmt::VarDecl {
3414
+ name,
3415
+ ty,
3416
+ init,
3417
+ is_function_scoped: false,
3418
+ span: sp,
3419
+ });
3420
+ }
3421
+ self.pos = save;
3422
+ }
3423
+
3424
+ if self.lang == Language::Python
3425
+ && matches!(&self.peek().kind, TokKind::Ident(_))
3426
+ && self.peek_n(1).kind == TokKind::Colon
3427
+ {
3428
+ let (name, _) = self.expect_ident("variable name")?;
3429
+ self.advance();
3430
+ let ty = self.parse_rich_type()?;
3431
+ let init = if self.eat(&TokKind::Eq) {
3432
+ Some(self.parse_expr()?)
3433
+ } else {
3434
+ None
3435
+ };
3436
+ self.eat_stmt_end();
3437
+ return Ok(Stmt::VarDecl {
3438
+ name,
3439
+ ty,
3440
+ init,
3441
+ is_function_scoped: true,
3442
+ span: sp,
3443
+ });
3444
+ }
3445
+
3446
+ if (self.lang == Language::Go || self.lang == Language::Python)
3447
+ && matches!(&self.peek().kind, TokKind::Ident(_))
3448
+ && matches!(self.peek_n(1).kind, TokKind::Comma | TokKind::ColonEq)
3449
+ {
3450
+ let save = self.pos;
3451
+ let mut names = Vec::new();
3452
+ let mut ok_list = true;
3453
+ loop {
3454
+ if let TokKind::Ident(n) = &self.peek().kind {
3455
+ names.push(n.clone());
3456
+ self.advance();
3457
+ if self.eat(&TokKind::Comma) {
3458
+ continue;
3459
+ }
3460
+ break;
3461
+ } else {
3462
+ ok_list = false;
3463
+ break;
3464
+ }
3465
+ }
3466
+ if ok_list && self.eat(&TokKind::ColonEq) {
3467
+ let val = self.parse_expr()?;
3468
+ self.eat_stmt_end();
3469
+ if names.len() == 1 {
3470
+ return Ok(Stmt::VarDecl {
3471
+ name: names.remove(0),
3472
+ ty: TypeHint::Unknown,
3473
+ init: Some(val),
3474
+ is_function_scoped: false,
3475
+ span: sp,
3476
+ });
3477
+ }
3478
+ return Ok(Stmt::MultiVarDecl {
3479
+ names,
3480
+ init: val,
3481
+ is_function_scoped: false,
3482
+ span: sp,
3483
+ });
3484
+ }
3485
+ if ok_list && names.len() > 1 && self.eat(&TokKind::Eq) {
3486
+ let first = self.parse_expr()?;
3487
+ let rhs = if self.eat(&TokKind::Comma) {
3488
+ let mut items = vec![first];
3489
+ loop {
3490
+ items.push(self.parse_expr()?);
3491
+ if !self.eat(&TokKind::Comma) {
3492
+ break;
3493
+ }
3494
+ }
3495
+ Expr::Tuple(items, sp)
3496
+ } else {
3497
+ first
3498
+ };
3499
+ self.eat_stmt_end();
3500
+ if self.lang == Language::Python {
3501
+ return Ok(Stmt::MultiVarDecl {
3502
+ names,
3503
+ init: rhs,
3504
+ is_function_scoped: true,
3505
+ span: sp,
3506
+ });
3507
+ }
3508
+ return Ok(Stmt::Assign {
3509
+ target: AssignTarget::Tuple(names),
3510
+ op: None,
3511
+ value: rhs,
3512
+ span: sp,
3513
+ });
3514
+ }
3515
+ self.pos = save;
3516
+ }
3517
+
3518
+ if self.lang == Language::Cpp
3519
+ && ((self.at_ident("std")
3520
+ && self.peek_n(1).kind == TokKind::ColonColon
3521
+ && matches!(&self.peek_n(2).kind, TokKind::Ident(s) if s == "cout"))
3522
+ || (self.at_ident("cout") && self.peek_n(1).kind == TokKind::Shl))
3523
+ {
3524
+ if self.eat_ident("std") {
3525
+ self.advance();
3526
+ }
3527
+ self.advance();
3528
+ let mut args = Vec::new();
3529
+ let mut newline = false;
3530
+ while self.eat(&TokKind::Shl) {
3531
+ if (self.at_ident("std")
3532
+ && self.peek_n(1).kind == TokKind::ColonColon
3533
+ && matches!(&self.peek_n(2).kind, TokKind::Ident(s) if s == "endl"))
3534
+ || self.at_ident("endl")
3535
+ {
3536
+ if self.eat_ident("std") {
3537
+ self.advance();
3538
+ }
3539
+ self.advance();
3540
+ newline = true;
3541
+ } else {
3542
+ args.push(self.parse_expr_bp(18, true)?);
3543
+ }
3544
+ }
3545
+ self.eat_stmt_end();
3546
+ let callee_name = if newline { "println" } else { "print" };
3547
+ let joined = if args.is_empty() {
3548
+ vec![]
3549
+ } else if args.len() == 1 {
3550
+ args
3551
+ } else {
3552
+ let mut acc = args.remove(0);
3553
+ for a in args {
3554
+ let asp = acc.span().merge(a.span());
3555
+ acc = Expr::Binary(
3556
+ BinOp::Add,
3557
+ Box::new(Expr::Call {
3558
+ callee: Box::new(Expr::Var("str".into(), asp)),
3559
+ args: vec![acc],
3560
+ span: asp,
3561
+ }),
3562
+ Box::new(Expr::Call {
3563
+ callee: Box::new(Expr::Var("str".into(), asp)),
3564
+ args: vec![a],
3565
+ span: asp,
3566
+ }),
3567
+ asp,
3568
+ );
3569
+ }
3570
+ vec![acc]
3571
+ };
3572
+ return Ok(Stmt::ExprStmt(
3573
+ Expr::Call {
3574
+ callee: Box::new(Expr::Var(callee_name.to_string(), sp)),
3575
+ args: joined,
3576
+ span: sp,
3577
+ },
3578
+ sp,
3579
+ ));
3580
+ }
3581
+
3582
+ let lhs = self.parse_expr()?;
3583
+ let compound = if self.eat(&TokKind::Eq) {
3584
+ Some(None)
3585
+ } else if self.eat(&TokKind::PlusEq) {
3586
+ Some(Some(BinOp::Add))
3587
+ } else if self.eat(&TokKind::MinusEq) {
3588
+ Some(Some(BinOp::Sub))
3589
+ } else if self.eat(&TokKind::StarEq) {
3590
+ Some(Some(BinOp::Mul))
3591
+ } else if self.eat(&TokKind::SlashEq) {
3592
+ Some(Some(BinOp::Div))
3593
+ } else if self.eat(&TokKind::PercentEq) {
3594
+ Some(Some(BinOp::Mod))
3595
+ } else {
3596
+ None
3597
+ };
3598
+
3599
+ if let Some(op) = compound {
3600
+ let val = self.parse_expr()?;
3601
+ self.eat_stmt_end();
3602
+ let target = match lhs {
3603
+ Expr::Var(name, _) => {
3604
+ if self.lang == Language::Python && op.is_none() {
3605
+ return Ok(Stmt::VarDecl {
3606
+ name,
3607
+ ty: TypeHint::Unknown,
3608
+ init: Some(val),
3609
+ is_function_scoped: true,
3610
+ span: sp,
3611
+ });
3612
+ }
3613
+ AssignTarget::Var(name)
3614
+ }
3615
+ Expr::Member { object, field, .. } => AssignTarget::Field(object, field),
3616
+ Expr::Index { object, index, .. } => AssignTarget::Index(object, index),
3617
+ other => {
3618
+ return Err(PolyError::spanned(
3619
+ "E0116",
3620
+ "invalid assignment target",
3621
+ other.span(),
3622
+ ));
3623
+ }
3624
+ };
3625
+ return Ok(Stmt::Assign {
3626
+ target,
3627
+ op,
3628
+ value: val,
3629
+ span: sp,
3630
+ });
3631
+ }
3632
+
3633
+ self.eat_stmt_end();
3634
+ Ok(Stmt::ExprStmt(lhs, sp))
3635
+ }
3636
+
3637
+ fn parse_condition_expr(&mut self) -> Result<Expr, PolyError> {
3638
+ if self.lang == Language::Python || self.lang == Language::Go {
3639
+ self.parse_expr_no_struct()
3640
+ } else if self.at(&TokKind::LParen) {
3641
+ self.advance();
3642
+ let e = self.parse_expr()?;
3643
+ self.expect(&TokKind::RParen, "')'")?;
3644
+ Ok(e)
3645
+ } else {
3646
+ self.parse_expr_no_struct()
3647
+ }
3648
+ }
3649
+
3650
+ fn parse_if_stmt(&mut self, sp: Span) -> Result<Stmt, PolyError> {
3651
+ let mut init_stmt: Option<Box<Stmt>> = None;
3652
+ let cond = if self.lang == Language::Go {
3653
+ let save = self.pos;
3654
+ let first_stmt = self.parse_stmt_inline_or_expr()?;
3655
+ if self.eat(&TokKind::Semi) {
3656
+ init_stmt = Some(Box::new(first_stmt));
3657
+ self.parse_expr_no_struct()?
3658
+ } else {
3659
+ self.pos = save;
3660
+ self.parse_expr_no_struct()?
3661
+ }
3662
+ } else {
3663
+ self.parse_condition_expr()?
3664
+ };
3665
+
3666
+ let then_body = if self.lang == Language::Python {
3667
+ self.expect(&TokKind::Colon, "':'")?;
3668
+ self.parse_py_suite()?
3669
+ } else {
3670
+ self.parse_brace_block()?
3671
+ };
3672
+
3673
+ let mut else_body = Vec::new();
3674
+ if self.lang == Language::Python {
3675
+ self.skip_newlines();
3676
+ if self.eat_ident("elif") {
3677
+ let nested = self.parse_if_stmt(self.peek().span)?;
3678
+ else_body.push(nested);
3679
+ } else if self.eat_ident("else") {
3680
+ self.expect(&TokKind::Colon, "':'")?;
3681
+ else_body = self.parse_py_suite()?;
3682
+ }
3683
+ } else if self.eat_ident("else") {
3684
+ if self.eat_ident("if") {
3685
+ else_body.push(self.parse_if_stmt(self.peek().span)?);
3686
+ } else {
3687
+ else_body = self.parse_brace_block()?;
3688
+ }
3689
+ }
3690
+
3691
+ Ok(Stmt::If {
3692
+ init: init_stmt,
3693
+ cond,
3694
+ then_body,
3695
+ else_body,
3696
+ span: sp,
3697
+ })
3698
+ }
3699
+
3700
+ fn parse_try_catch(&mut self, sp: Span) -> Result<Stmt, PolyError> {
3701
+ let try_body = if self.lang == Language::Python {
3702
+ self.expect(&TokKind::Colon, "':'")?;
3703
+ self.parse_py_suite()?
3704
+ } else {
3705
+ self.parse_brace_block()?
3706
+ };
3707
+
3708
+ let mut catch_var = None;
3709
+ let mut catch_body = Vec::new();
3710
+ let mut finally_body = Vec::new();
3711
+
3712
+ if self.lang == Language::Python {
3713
+ self.skip_newlines();
3714
+ if self.eat_ident("except") {
3715
+ while !self.at(&TokKind::Colon) && !self.at(&TokKind::Eof) {
3716
+ if self.eat_ident("as") {
3717
+ catch_var = Some(self.expect_ident("except variable")?.0);
3718
+ } else {
3719
+ self.advance();
3720
+ }
3721
+ }
3722
+ self.expect(&TokKind::Colon, "':'")?;
3723
+ catch_body = self.parse_py_suite()?;
3724
+ }
3725
+ self.skip_newlines();
3726
+ if self.eat_ident("finally") {
3727
+ self.expect(&TokKind::Colon, "':'")?;
3728
+ finally_body = self.parse_py_suite()?;
3729
+ }
3730
+ } else {
3731
+ if self.eat_ident("catch") {
3732
+ if self.eat(&TokKind::LParen) {
3733
+ if !self.at(&TokKind::RParen) {
3734
+ if !self.eat(&TokKind::DotDot) {
3735
+ while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
3736
+ if let TokKind::Ident(n) = &self.peek().kind {
3737
+ catch_var = Some(n.clone());
3738
+ }
3739
+ self.advance();
3740
+ }
3741
+ } else {
3742
+ let _ = self.eat(&TokKind::Dot);
3743
+ }
3744
+ }
3745
+ self.expect(&TokKind::RParen, "')'")?;
3746
+ }
3747
+ catch_body = self.parse_brace_block()?;
3748
+ }
3749
+ if self.eat_ident("finally") {
3750
+ finally_body = self.parse_brace_block()?;
3751
+ }
3752
+ }
3753
+
3754
+ Ok(Stmt::TryCatch {
3755
+ try_body,
3756
+ catch_var,
3757
+ catch_body,
3758
+ finally_body,
3759
+ span: sp,
3760
+ })
3761
+ }
3762
+
3763
+ fn parse_switch_or_match(&mut self, sp: Span) -> Result<Stmt, PolyError> {
3764
+ let is_match = self.tokens[self.pos - 1].kind == TokKind::Ident("match".into());
3765
+ let expr = if is_match {
3766
+ Some(self.parse_expr_no_struct()?)
3767
+ } else if self.lang == Language::Go {
3768
+ if self.at(&TokKind::LBrace) {
3769
+ None
3770
+ } else {
3771
+ Some(self.parse_expr_no_struct()?)
3772
+ }
3773
+ } else {
3774
+ Some(self.parse_condition_expr()?)
3775
+ };
3776
+
3777
+ self.expect(&TokKind::LBrace, "'{'")?;
3778
+ let mut cases = Vec::new();
3779
+ let mut default = Vec::new();
3780
+ self.skip_newlines();
3781
+
3782
+ while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
3783
+ self.skip_newlines();
3784
+ if self.at(&TokKind::RBrace) {
3785
+ break;
3786
+ }
3787
+ if is_match {
3788
+ let is_wild = self.eat_ident("_");
3789
+ let mut pats = Vec::new();
3790
+ if !is_wild {
3791
+ loop {
3792
+ pats.push(self.parse_expr_no_struct()?);
3793
+ if !self.eat(&TokKind::Pipe) {
3794
+ break;
3795
+ }
3796
+ }
3797
+ }
3798
+ self.expect(&TokKind::FatArrow, "'=>'")?;
3799
+ let body = if self.at(&TokKind::LBrace) {
3800
+ self.parse_brace_block()?
3801
+ } else {
3802
+ let e = self.parse_expr()?;
3803
+ vec![Stmt::ExprStmt(e, sp)]
3804
+ };
3805
+ let _ = self.eat(&TokKind::Comma);
3806
+ if is_wild {
3807
+ default = body;
3808
+ } else {
3809
+ cases.push((pats, body));
3810
+ }
3811
+ } else if self.eat_ident("case") {
3812
+ let mut vals = Vec::new();
3813
+ loop {
3814
+ vals.push(self.parse_expr_no_struct()?);
3815
+ if !self.eat(&TokKind::Comma) {
3816
+ break;
3817
+ }
3818
+ }
3819
+ self.expect(&TokKind::Colon, "':'")?;
3820
+ self.skip_newlines();
3821
+ let mut body = Vec::new();
3822
+ while !self.at(&TokKind::RBrace)
3823
+ && !self.at_ident("case")
3824
+ && !self.at_ident("default")
3825
+ && !self.at(&TokKind::Eof)
3826
+ {
3827
+ let s = self.parse_stmt()?;
3828
+ if matches!(s, Stmt::Break(_)) {
3829
+ break;
3830
+ }
3831
+ body.push(s);
3832
+ self.skip_newlines();
3833
+ }
3834
+ cases.push((vals, body));
3835
+ } else if self.eat_ident("default") {
3836
+ self.expect(&TokKind::Colon, "':'")?;
3837
+ self.skip_newlines();
3838
+ while !self.at(&TokKind::RBrace)
3839
+ && !self.at_ident("case")
3840
+ && !self.at_ident("default")
3841
+ && !self.at(&TokKind::Eof)
3842
+ {
3843
+ let s = self.parse_stmt()?;
3844
+ if matches!(s, Stmt::Break(_)) {
3845
+ break;
3846
+ }
3847
+ default.push(s);
3848
+ self.skip_newlines();
3849
+ }
3850
+ } else {
3851
+ self.advance();
3852
+ }
3853
+ }
3854
+ self.expect(&TokKind::RBrace, "'}'")?;
3855
+ Ok(Stmt::Switch {
3856
+ expr,
3857
+ cases,
3858
+ default,
3859
+ span: sp,
3860
+ })
3861
+ }
3862
+
3863
+ fn parse_for_stmt(&mut self, sp: Span) -> Result<Stmt, PolyError> {
3864
+ if self.lang == Language::Python {
3865
+ let (var, _) = self.expect_ident("loop variable")?;
3866
+ if !self.eat_ident("in") {
3867
+ return Err(PolyError::spanned(
3868
+ "E0117",
3869
+ "expected 'in' in Python for-loop",
3870
+ self.peek().span,
3871
+ ));
3872
+ }
3873
+ if self.at_ident("range") && self.peek_n(1).kind == TokKind::LParen {
3874
+ self.advance();
3875
+ self.advance();
3876
+ let mut args = Vec::new();
3877
+ while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
3878
+ args.push(self.parse_expr()?);
3879
+ if !self.eat(&TokKind::Comma) {
3880
+ break;
3881
+ }
3882
+ }
3883
+ self.expect(&TokKind::RParen, "')'")?;
3884
+ self.expect(&TokKind::Colon, "':'")?;
3885
+ let body = self.parse_py_suite()?;
3886
+ let (start, end, step) = match args.len() {
3887
+ 1 => (Expr::Int(0, sp), args.remove(0), None),
3888
+ 2 => (args.remove(0), args.remove(0), None),
3889
+ 3 => (args.remove(0), args.remove(0), Some(args.remove(0))),
3890
+ _ => {
3891
+ return Err(PolyError::spanned(
3892
+ "E0118",
3893
+ "range() takes 1 to 3 arguments",
3894
+ sp,
3895
+ ));
3896
+ }
3897
+ };
3898
+ return Ok(Stmt::ForRange {
3899
+ var,
3900
+ start,
3901
+ end,
3902
+ inclusive: false,
3903
+ step,
3904
+ body,
3905
+ span: sp,
3906
+ });
3907
+ }
3908
+ let iter = self.parse_expr_no_struct()?;
3909
+ self.expect(&TokKind::Colon, "':'")?;
3910
+ let body = self.parse_py_suite()?;
3911
+ return Ok(Stmt::ForIn {
3912
+ index_var: None,
3913
+ var,
3914
+ iter,
3915
+ body,
3916
+ span: sp,
3917
+ });
3918
+ }
3919
+
3920
+ if self.lang == Language::Rust {
3921
+ let (var, _) = self.expect_ident("loop variable")?;
3922
+ if !self.eat_ident("in") {
3923
+ return Err(PolyError::spanned(
3924
+ "E0117",
3925
+ "expected 'in' in Rust for-loop",
3926
+ self.peek().span,
3927
+ ));
3928
+ }
3929
+ let start = self.parse_expr_no_struct()?;
3930
+ if self.eat(&TokKind::DotDotEq) {
3931
+ let end = self.parse_expr_no_struct()?;
3932
+ let body = self.parse_brace_block()?;
3933
+ return Ok(Stmt::ForRange {
3934
+ var,
3935
+ start,
3936
+ end,
3937
+ inclusive: true,
3938
+ step: None,
3939
+ body,
3940
+ span: sp,
3941
+ });
3942
+ } else if self.eat(&TokKind::DotDot) {
3943
+ let end = self.parse_expr_no_struct()?;
3944
+ let body = self.parse_brace_block()?;
3945
+ return Ok(Stmt::ForRange {
3946
+ var,
3947
+ start,
3948
+ end,
3949
+ inclusive: false,
3950
+ step: None,
3951
+ body,
3952
+ span: sp,
3953
+ });
3954
+ }
3955
+ let body = self.parse_brace_block()?;
3956
+ return Ok(Stmt::ForIn {
3957
+ index_var: None,
3958
+ var,
3959
+ iter: start,
3960
+ body,
3961
+ span: sp,
3962
+ });
3963
+ }
3964
+
3965
+ if self.lang == Language::Go {
3966
+ if self.at(&TokKind::LBrace) {
3967
+ let body = self.parse_brace_block()?;
3968
+ return Ok(Stmt::While {
3969
+ cond: Expr::Bool(true, sp),
3970
+ body,
3971
+ span: sp,
3972
+ });
3973
+ }
3974
+ let save = self.pos;
3975
+ if matches!(&self.peek().kind, TokKind::Ident(_)) {
3976
+ let (v1, _) = self.expect_ident("loop var")?;
3977
+ let v2 = if self.eat(&TokKind::Comma) {
3978
+ Some(self.expect_ident("second loop var")?.0)
3979
+ } else {
3980
+ None
3981
+ };
3982
+ if (self.eat(&TokKind::ColonEq) || self.eat(&TokKind::Eq)) && self.eat_ident("range") {
3983
+ let iter = self.parse_expr_no_struct()?;
3984
+ let body = self.parse_brace_block()?;
3985
+ return if let Some(val_var) = v2 {
3986
+ Ok(Stmt::ForIn {
3987
+ index_var: if v1 == "_" { None } else { Some(v1) },
3988
+ var: val_var,
3989
+ iter,
3990
+ body,
3991
+ span: sp,
3992
+ })
3993
+ } else {
3994
+ Ok(Stmt::ForRange {
3995
+ var: v1,
3996
+ start: Expr::Int(0, sp),
3997
+ end: iter,
3998
+ inclusive: false,
3999
+ step: None,
4000
+ body,
4001
+ span: sp,
4002
+ })
4003
+ };
4004
+ }
4005
+ self.pos = save;
4006
+ }
4007
+ let first = self.parse_stmt_inline_or_expr()?;
4008
+ if self.eat(&TokKind::Semi) {
4009
+ let cond = if !self.at(&TokKind::Semi) {
4010
+ self.parse_expr_no_struct()?
4011
+ } else {
4012
+ Expr::Bool(true, sp)
4013
+ };
4014
+ self.expect(&TokKind::Semi, "';'")?;
4015
+ let step = if !self.at(&TokKind::LBrace) {
4016
+ Some(self.parse_stmt_inline_or_expr()?)
4017
+ } else {
4018
+ None
4019
+ };
4020
+ let mut body = self.parse_brace_block()?;
4021
+ if let Some(st) = step {
4022
+ body.push(st);
4023
+ }
4024
+ return Ok(Stmt::Block(
4025
+ vec![
4026
+ first,
4027
+ Stmt::While {
4028
+ cond,
4029
+ body,
4030
+ span: sp,
4031
+ },
4032
+ ],
4033
+ sp,
4034
+ ));
4035
+ }
4036
+ let Stmt::ExprStmt(cond, _) = first else {
4037
+ return Err(PolyError::spanned("E0117", "invalid Go for-loop condition", sp));
4038
+ };
4039
+ let body = self.parse_brace_block()?;
4040
+ return Ok(Stmt::While {
4041
+ cond,
4042
+ body,
4043
+ span: sp,
4044
+ });
4045
+ }
4046
+
4047
+ self.expect(&TokKind::LParen, "'('")?;
4048
+ if self.at_ident("let")
4049
+ || self.at_ident("const")
4050
+ || self.at_ident("var")
4051
+ || (matches!(self.lang, Language::Cpp | Language::CSharp) && self.is_c_cpp_cs_type_start())
4052
+ {
4053
+ let save = self.pos;
4054
+ if self.eat_ident("let") || self.eat_ident("const") || self.eat_ident("var") {
4055
+ let _ = self.eat_ident("mut");
4056
+ } else {
4057
+ let _ = self.parse_c_cpp_cs_type()?;
4058
+ }
4059
+ if let Ok((var, _)) = self.expect_ident("loop var")
4060
+ && (self.eat_ident("of") || self.eat_ident("in") || self.eat(&TokKind::Colon))
4061
+ {
4062
+ let iter = self.parse_expr()?;
4063
+ self.expect(&TokKind::RParen, "')'")?;
4064
+ let body = self.parse_brace_block()?;
4065
+ return Ok(Stmt::ForIn {
4066
+ index_var: None,
4067
+ var,
4068
+ iter,
4069
+ body,
4070
+ span: sp,
4071
+ });
4072
+ }
4073
+ self.pos = save;
4074
+ }
4075
+
4076
+ let mut stmts = Vec::new();
4077
+ if !self.eat(&TokKind::Semi) {
4078
+ let init = self.parse_stmt()?;
4079
+ stmts.push(init);
4080
+ }
4081
+ let cond = if !self.at(&TokKind::Semi) {
4082
+ self.parse_expr()?
4083
+ } else {
4084
+ Expr::Bool(true, sp)
4085
+ };
4086
+ self.expect(&TokKind::Semi, "';'")?;
4087
+ let step_stmt = if !self.at(&TokKind::RParen) {
4088
+ Some(self.parse_stmt_inline_or_expr()?)
4089
+ } else {
4090
+ None
4091
+ };
4092
+ self.expect(&TokKind::RParen, "')'")?;
4093
+ let mut body = self.parse_brace_block()?;
4094
+ if let Some(step) = step_stmt {
4095
+ body.push(step);
4096
+ }
4097
+ stmts.push(Stmt::While {
4098
+ cond,
4099
+ body,
4100
+ span: sp,
4101
+ });
4102
+ Ok(Stmt::Block(stmts, sp))
4103
+ }
4104
+
4105
+ fn parse_stmt_inline_or_expr(&mut self) -> Result<Stmt, PolyError> {
4106
+ let sp = self.peek().span;
4107
+
4108
+ if (self.lang == Language::Go || self.lang == Language::Python)
4109
+ && matches!(&self.peek().kind, TokKind::Ident(_))
4110
+ && matches!(self.peek_n(1).kind, TokKind::Comma | TokKind::ColonEq)
4111
+ {
4112
+ let save = self.pos;
4113
+ let mut names = Vec::new();
4114
+ let mut ok_list = true;
4115
+ loop {
4116
+ if let TokKind::Ident(n) = &self.peek().kind {
4117
+ names.push(n.clone());
4118
+ self.advance();
4119
+ if self.eat(&TokKind::Comma) {
4120
+ continue;
4121
+ }
4122
+ break;
4123
+ } else {
4124
+ ok_list = false;
4125
+ break;
4126
+ }
4127
+ }
4128
+ if ok_list && self.eat(&TokKind::ColonEq) {
4129
+ let val = self.parse_expr_no_struct()?;
4130
+ if names.len() == 1 {
4131
+ return Ok(Stmt::VarDecl {
4132
+ name: names.remove(0),
4133
+ ty: TypeHint::Unknown,
4134
+ init: Some(val),
4135
+ is_function_scoped: false,
4136
+ span: sp,
4137
+ });
4138
+ }
4139
+ return Ok(Stmt::MultiVarDecl {
4140
+ names,
4141
+ init: val,
4142
+ is_function_scoped: false,
4143
+ span: sp,
4144
+ });
4145
+ }
4146
+ self.pos = save;
4147
+ }
4148
+
4149
+ if self.eat_ident("let") || self.eat_ident("const") || self.eat_ident("var") {
4150
+ let _ = self.eat_ident("mut");
4151
+ let (name, _) = self.expect_ident("variable name")?;
4152
+ let ty = if self.eat(&TokKind::Colon) {
4153
+ self.parse_rich_type()?
4154
+ } else {
4155
+ TypeHint::Unknown
4156
+ };
4157
+ let init = if self.eat(&TokKind::Eq) {
4158
+ Some(self.parse_expr_no_struct()?)
4159
+ } else {
4160
+ None
4161
+ };
4162
+ return Ok(Stmt::VarDecl {
4163
+ name,
4164
+ ty,
4165
+ init,
4166
+ is_function_scoped: false,
4167
+ span: sp,
4168
+ });
4169
+ }
4170
+
4171
+ if matches!(self.lang, Language::C | Language::Cpp | Language::CSharp)
4172
+ && self.is_c_cpp_cs_type_start()
4173
+ {
4174
+ let save = self.pos;
4175
+ if let Ok(ty) = self.parse_c_cpp_cs_type()
4176
+ && let TokKind::Ident(_) = &self.peek().kind
4177
+ {
4178
+ let (name, _) = self.expect_ident("variable name")?;
4179
+ let init = if self.eat(&TokKind::Eq) {
4180
+ Some(self.parse_expr_no_struct()?)
4181
+ } else {
4182
+ None
4183
+ };
4184
+ return Ok(Stmt::VarDecl {
4185
+ name,
4186
+ ty,
4187
+ init,
4188
+ is_function_scoped: false,
4189
+ span: sp,
4190
+ });
4191
+ }
4192
+ self.pos = save;
4193
+ }
4194
+
4195
+ let lhs = self.parse_expr_no_struct()?;
4196
+ let compound = if self.eat(&TokKind::Eq) {
4197
+ Some(None)
4198
+ } else if self.eat(&TokKind::PlusEq) {
4199
+ Some(Some(BinOp::Add))
4200
+ } else if self.eat(&TokKind::MinusEq) {
4201
+ Some(Some(BinOp::Sub))
4202
+ } else if self.eat(&TokKind::StarEq) {
4203
+ Some(Some(BinOp::Mul))
4204
+ } else if self.eat(&TokKind::SlashEq) {
4205
+ Some(Some(BinOp::Div))
4206
+ } else if self.eat(&TokKind::PercentEq) {
4207
+ Some(Some(BinOp::Mod))
4208
+ } else {
4209
+ None
4210
+ };
4211
+
4212
+ if let Some(op) = compound {
4213
+ let value = self.parse_expr_no_struct()?;
4214
+ let target = match lhs {
4215
+ Expr::Var(n, _) => AssignTarget::Var(n),
4216
+ Expr::Member { object, field, .. } => AssignTarget::Field(object, field),
4217
+ Expr::Index { object, index, .. } => AssignTarget::Index(object, index),
4218
+ other => {
4219
+ return Err(PolyError::spanned(
4220
+ "E0116",
4221
+ "invalid assignment target",
4222
+ other.span(),
4223
+ ));
4224
+ }
4225
+ };
4226
+ Ok(Stmt::Assign {
4227
+ target,
4228
+ op,
4229
+ value,
4230
+ span: sp,
4231
+ })
4232
+ } else {
4233
+ Ok(Stmt::ExprStmt(lhs, sp))
4234
+ }
4235
+ }
4236
+
4237
+ fn parse_expr(&mut self) -> Result<Expr, PolyError> {
4238
+ self.parse_expr_bp(0, true)
4239
+ }
4240
+
4241
+ fn parse_expr_no_struct(&mut self) -> Result<Expr, PolyError> {
4242
+ self.parse_expr_bp(0, false)
4243
+ }
4244
+
4245
+ fn parse_expr_bp(&mut self, min_bp: u8, allow_struct_lit: bool) -> Result<Expr, PolyError> {
4246
+ let mut lhs = self.parse_prefix(allow_struct_lit)?;
4247
+ lhs = self.parse_postfix(lhs, allow_struct_lit)?;
4248
+
4249
+ loop {
4250
+ if self.lang == Language::Python && min_bp <= 1 && self.eat_ident("if") {
4251
+ let cond = self.parse_expr_bp(0, allow_struct_lit)?;
4252
+ if !self.eat_ident("else") {
4253
+ return Err(PolyError::spanned(
4254
+ "E0119",
4255
+ "expected 'else' in Python conditional expression",
4256
+ self.peek().span,
4257
+ ));
4258
+ }
4259
+ let else_expr = self.parse_expr_bp(0, allow_struct_lit)?;
4260
+ let sp = lhs.span().merge(else_expr.span());
4261
+ lhs = Expr::Ternary {
4262
+ cond: Box::new(cond),
4263
+ then_expr: Box::new(lhs),
4264
+ else_expr: Box::new(else_expr),
4265
+ span: sp,
4266
+ };
4267
+ continue;
4268
+ }
4269
+
4270
+ if self.lang != Language::Python && min_bp <= 1 && self.eat(&TokKind::Question) {
4271
+ let then_expr = self.parse_expr()?;
4272
+ self.expect(&TokKind::Colon, "':'")?;
4273
+ let else_expr = self.parse_expr_bp(1, allow_struct_lit)?;
4274
+ let sp = lhs.span().merge(else_expr.span());
4275
+ lhs = Expr::Ternary {
4276
+ cond: Box::new(lhs),
4277
+ then_expr: Box::new(then_expr),
4278
+ else_expr: Box::new(else_expr),
4279
+ span: sp,
4280
+ };
4281
+ continue;
4282
+ }
4283
+
4284
+ if (self.lang == Language::Rust || self.lang == Language::TypeScript) && self.eat_ident("as") {
4285
+ let ty = self.parse_rich_type()?;
4286
+ let sp = lhs.span();
4287
+ lhs = Expr::Cast {
4288
+ ty,
4289
+ expr: Box::new(lhs),
4290
+ span: sp,
4291
+ };
4292
+ continue;
4293
+ }
4294
+
4295
+ let Some((op, l_bp, r_bp)) = self.infix_bp() else {
4296
+ break;
4297
+ };
4298
+ if l_bp < min_bp {
4299
+ break;
4300
+ }
4301
+ self.advance();
4302
+ let rhs = self.parse_expr_bp(r_bp, allow_struct_lit)?;
4303
+ let sp = lhs.span().merge(rhs.span());
4304
+ lhs = Expr::Binary(op, Box::new(lhs), Box::new(rhs), sp);
4305
+ }
4306
+
4307
+ Ok(lhs)
4308
+ }
4309
+
4310
+ fn infix_bp(&self) -> Option<(BinOp, u8, u8)> {
4311
+ match &self.peek().kind {
4312
+ TokKind::QuestionQuestion => Some((BinOp::NullCoal, 1, 2)),
4313
+ TokKind::PipePipe => Some((BinOp::Or, 2, 3)),
4314
+ TokKind::Ident(s) if s == "or" => Some((BinOp::Or, 2, 3)),
4315
+ TokKind::AmpAmp => Some((BinOp::And, 4, 5)),
4316
+ TokKind::Ident(s) if s == "and" => Some((BinOp::And, 4, 5)),
4317
+ TokKind::Pipe => Some((BinOp::BitOr, 6, 7)),
4318
+ TokKind::Caret => Some((BinOp::BitXor, 8, 9)),
4319
+ TokKind::Amp => Some((BinOp::BitAnd, 10, 11)),
4320
+ TokKind::EqEq | TokKind::EqEqEq => Some((BinOp::Eq, 12, 13)),
4321
+ TokKind::BangEq | TokKind::BangEqEq => Some((BinOp::Ne, 12, 13)),
4322
+ TokKind::Lt => Some((BinOp::Lt, 14, 15)),
4323
+ TokKind::Le => Some((BinOp::Le, 14, 15)),
4324
+ TokKind::Gt => Some((BinOp::Gt, 14, 15)),
4325
+ TokKind::Ge => Some((BinOp::Ge, 14, 15)),
4326
+ TokKind::Shl => Some((BinOp::Shl, 16, 17)),
4327
+ TokKind::Shr => Some((BinOp::Shr, 16, 17)),
4328
+ TokKind::Plus => Some((BinOp::Add, 18, 19)),
4329
+ TokKind::Minus => Some((BinOp::Sub, 18, 19)),
4330
+ TokKind::Star => Some((BinOp::Mul, 20, 21)),
4331
+ TokKind::Slash => Some((BinOp::Div, 20, 21)),
4332
+ TokKind::SlashSlash => Some((BinOp::FloorDiv, 20, 21)),
4333
+ TokKind::Percent => Some((BinOp::Mod, 20, 21)),
4334
+ TokKind::StarStar => Some((BinOp::Pow, 22, 21)),
4335
+ _ => None,
4336
+ }
4337
+ }
4338
+
4339
+ fn parse_prefix(&mut self, allow_struct_lit: bool) -> Result<Expr, PolyError> {
4340
+ let t = self.peek().clone();
4341
+ match t.kind {
4342
+ TokKind::Minus => {
4343
+ self.advance();
4344
+ let inner = self.parse_expr_bp(23, allow_struct_lit)?;
4345
+ let sp = t.span.merge(inner.span());
4346
+ Ok(Expr::Unary(UnaryOp::Neg, Box::new(inner), sp))
4347
+ }
4348
+ TokKind::Plus => {
4349
+ self.advance();
4350
+ self.parse_expr_bp(23, allow_struct_lit)
4351
+ }
4352
+ TokKind::Bang => {
4353
+ self.advance();
4354
+ let inner = self.parse_expr_bp(23, allow_struct_lit)?;
4355
+ let sp = t.span.merge(inner.span());
4356
+ Ok(Expr::Unary(UnaryOp::Not, Box::new(inner), sp))
4357
+ }
4358
+ TokKind::Tilde => {
4359
+ self.advance();
4360
+ let inner = self.parse_expr_bp(23, allow_struct_lit)?;
4361
+ let sp = t.span.merge(inner.span());
4362
+ Ok(Expr::Unary(UnaryOp::BitNot, Box::new(inner), sp))
4363
+ }
4364
+ TokKind::Ident(ref s) if s == "not" => {
4365
+ self.advance();
4366
+ let inner = self.parse_expr_bp(23, allow_struct_lit)?;
4367
+ let sp = t.span.merge(inner.span());
4368
+ Ok(Expr::Unary(UnaryOp::Not, Box::new(inner), sp))
4369
+ }
4370
+ TokKind::PlusPlus | TokKind::MinusMinus => {
4371
+ let inc = t.kind == TokKind::PlusPlus;
4372
+ self.advance();
4373
+ let (name, nspan) = self.expect_ident("variable")?;
4374
+ Ok(Expr::Update {
4375
+ name,
4376
+ inc,
4377
+ prefix: true,
4378
+ span: t.span.merge(nspan),
4379
+ })
4380
+ }
4381
+ TokKind::Int(v) => {
4382
+ self.advance();
4383
+ Ok(Expr::Int(v, t.span))
4384
+ }
4385
+ TokKind::Float(v) => {
4386
+ self.advance();
4387
+ Ok(Expr::Float(v, t.span))
4388
+ }
4389
+ TokKind::Str(s) => {
4390
+ self.advance();
4391
+ Ok(Expr::Str(s, t.span))
4392
+ }
4393
+ TokKind::Regex(pat, flags) => {
4394
+ self.advance();
4395
+ Ok(Expr::Regex {
4396
+ pattern: pat,
4397
+ flags,
4398
+ span: t.span,
4399
+ })
4400
+ }
4401
+ TokKind::InterpStr(parts) => {
4402
+ self.advance();
4403
+ let mut out_parts = Vec::with_capacity(parts.len());
4404
+ for (is_expr, text, fmt_opt, eline, ecol) in parts {
4405
+ if is_expr {
4406
+ let sub_tokens = Lexer::new(self.file_id, self.lang, &text)
4407
+ .tokenize()?
4408
+ .0;
4409
+ let mut sub_p = Parser::new(self.file_id, self.lang, sub_tokens);
4410
+ sub_p.struct_names = self.struct_names.clone();
4411
+ sub_p.enum_names = self.enum_names.clone();
4412
+ let expr = sub_p.parse_expr()?;
4413
+ out_parts.push(TemplatePart::Expr {
4414
+ expr,
4415
+ format_spec: fmt_opt,
4416
+ });
4417
+ } else {
4418
+ out_parts.push(TemplatePart::Literal(text));
4419
+ }
4420
+ let _ = (eline, ecol);
4421
+ }
4422
+ Ok(Expr::TemplateStr {
4423
+ parts: out_parts,
4424
+ span: t.span,
4425
+ })
4426
+ }
4427
+ TokKind::LParen => {
4428
+ self.advance();
4429
+
4430
+ if matches!(self.lang, Language::C | Language::Cpp | Language::CSharp)
4431
+ && self.is_c_cpp_cs_type_start()
4432
+ {
4433
+ let save = self.pos;
4434
+ if let Ok(cast_ty) = self.parse_c_cpp_cs_type()
4435
+ && self.eat(&TokKind::RParen)
4436
+ {
4437
+ let inner = self.parse_expr_bp(23, allow_struct_lit)?;
4438
+ let sp = t.span.merge(inner.span());
4439
+ return Ok(Expr::Cast {
4440
+ ty: cast_ty,
4441
+ expr: Box::new(inner),
4442
+ span: sp,
4443
+ });
4444
+ }
4445
+ self.pos = save;
4446
+ }
4447
+
4448
+ if self.eat(&TokKind::RParen) {
4449
+ return Ok(Expr::Nil(t.span));
4450
+ }
4451
+
4452
+ let first = self.parse_expr()?;
4453
+ if self.eat(&TokKind::Comma) {
4454
+ let mut items = vec![first];
4455
+ while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
4456
+ items.push(self.parse_expr()?);
4457
+ if !self.eat(&TokKind::Comma) {
4458
+ break;
4459
+ }
4460
+ }
4461
+ let end = self.expect(&TokKind::RParen, "')'")?;
4462
+ return Ok(Expr::Tuple(items, t.span.merge(end.span)));
4463
+ }
4464
+ self.expect(&TokKind::RParen, "')'")?;
4465
+ Ok(first)
4466
+ }
4467
+ TokKind::LBracket => {
4468
+ self.advance();
4469
+ let mut items = Vec::new();
4470
+ while !self.at(&TokKind::RBracket) && !self.at(&TokKind::Eof) {
4471
+ items.push(self.parse_expr()?);
4472
+ if !self.eat(&TokKind::Comma) {
4473
+ break;
4474
+ }
4475
+ }
4476
+ let end = self.expect(&TokKind::RBracket, "']'")?;
4477
+ Ok(Expr::Array(items, t.span.merge(end.span)))
4478
+ }
4479
+ TokKind::LBrace => {
4480
+ self.advance();
4481
+ let mut fields = Vec::new();
4482
+ while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
4483
+ let key = match &self.peek().kind {
4484
+ TokKind::Ident(k) | TokKind::Str(k) => {
4485
+ let k = k.clone();
4486
+ self.advance();
4487
+ k
4488
+ }
4489
+ _ => {
4490
+ return Err(PolyError::spanned(
4491
+ "E0120",
4492
+ "expected object literal field key",
4493
+ self.peek().span,
4494
+ ));
4495
+ }
4496
+ };
4497
+ self.expect(&TokKind::Colon, "':'")?;
4498
+ let val = self.parse_expr()?;
4499
+ fields.push((key, val));
4500
+ if !self.eat(&TokKind::Comma) {
4501
+ break;
4502
+ }
4503
+ }
4504
+ let end = self.expect(&TokKind::RBrace, "'}'")?;
4505
+ Ok(Expr::ObjectLit(None, fields, t.span.merge(end.span)))
4506
+ }
4507
+ TokKind::Ident(ref s) if matches!(s.as_str(), "None" | "null" | "nil" | "undefined") => {
4508
+ self.advance();
4509
+ Ok(Expr::Nil(t.span))
4510
+ }
4511
+ TokKind::Ident(ref s) if matches!(s.as_str(), "true" | "True") => {
4512
+ self.advance();
4513
+ Ok(Expr::Bool(true, t.span))
4514
+ }
4515
+ TokKind::Ident(ref s) if matches!(s.as_str(), "false" | "False") => {
4516
+ self.advance();
4517
+ Ok(Expr::Bool(false, t.span))
4518
+ }
4519
+ TokKind::Ident(ref s) if s == "new" => {
4520
+ self.advance();
4521
+ let (cls, _) = self.expect_ident("class name")?;
4522
+ let _ = self.try_skip_angle_generics();
4523
+ let mut args = Vec::new();
4524
+ if self.eat(&TokKind::LParen) {
4525
+ while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
4526
+ args.push(self.parse_expr()?);
4527
+ if !self.eat(&TokKind::Comma) {
4528
+ break;
4529
+ }
4530
+ }
4531
+ self.expect(&TokKind::RParen, "')'")?;
4532
+ } else if self.at(&TokKind::LBrace) {
4533
+ self.advance();
4534
+ let mut fields = Vec::new();
4535
+ while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
4536
+ let (k, _) = self.expect_ident("field name")?;
4537
+ self.expect(&TokKind::Colon, "':'")?;
4538
+ let v = self.parse_expr()?;
4539
+ fields.push((k, v));
4540
+ if !self.eat(&TokKind::Comma) {
4541
+ break;
4542
+ }
4543
+ }
4544
+ let end = self.expect(&TokKind::RBrace, "'}'")?;
4545
+ return Ok(Expr::ObjectLit(Some(cls), fields, t.span.merge(end.span)));
4546
+ }
4547
+ let fields = args
4548
+ .into_iter()
4549
+ .enumerate()
4550
+ .map(|(idx, a)| (format!("_{idx}"), a))
4551
+ .collect();
4552
+ Ok(Expr::ObjectLit(Some(cls), fields, t.span))
4553
+ }
4554
+ TokKind::Ident(ref s)
4555
+ if matches!(
4556
+ s.as_str(),
4557
+ "static_cast" | "reinterpret_cast" | "const_cast" | "dynamic_cast"
4558
+ ) =>
4559
+ {
4560
+ self.advance();
4561
+ self.expect(&TokKind::Lt, "'<'")?;
4562
+ let target_ty = self.parse_rich_type()?;
4563
+ self.expect(&TokKind::Gt, "'>'")?;
4564
+ self.expect(&TokKind::LParen, "'('")?;
4565
+ let inner = self.parse_expr()?;
4566
+ let end = self.expect(&TokKind::RParen, "')'")?;
4567
+ Ok(Expr::Cast {
4568
+ ty: target_ty,
4569
+ expr: Box::new(inner),
4570
+ span: t.span.merge(end.span),
4571
+ })
4572
+ }
4573
+ TokKind::Ident(ref s) if s == "lambda" && self.lang == Language::Python => {
4574
+ self.advance();
4575
+ let mut params = Vec::new();
4576
+ while !self.at(&TokKind::Colon) && !self.at(&TokKind::Eof) {
4577
+ let (pn, ps) = self.expect_ident("lambda param")?;
4578
+ params.push(Param {
4579
+ name: pn,
4580
+ ty: TypeHint::Unknown,
4581
+ span: ps,
4582
+ });
4583
+ if !self.eat(&TokKind::Comma) {
4584
+ break;
4585
+ }
4586
+ }
4587
+ self.expect(&TokKind::Colon, "':'")?;
4588
+ let body_expr = self.parse_expr()?;
4589
+ let sp = t.span.merge(body_expr.span());
4590
+ let name = self.fresh_anon_name();
4591
+ self.extra_functions.push(FunctionDecl {
4592
+ name: name.clone(),
4593
+ params,
4594
+ return_type: TypeHint::Unknown,
4595
+ body: vec![Stmt::Return(Some(body_expr), sp)],
4596
+ is_exported: false,
4597
+ span: sp,
4598
+ });
4599
+ Ok(Expr::Var(name, sp))
4600
+ }
4601
+ TokKind::Ident(name) => {
4602
+ self.advance();
4603
+ if allow_struct_lit
4604
+ && (self.lang == Language::Rust || self.lang == Language::Go)
4605
+ && (self.struct_names.contains(&name) || self.lang == Language::Go)
4606
+ && self.eat(&TokKind::LBrace)
4607
+ {
4608
+ let mut fields = Vec::new();
4609
+ let mut unkeyed = 0usize;
4610
+ while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
4611
+ if matches!(&self.peek().kind, TokKind::Ident(_)) && self.peek_n(1).kind == TokKind::Colon {
4612
+ let (k, _) = self.expect_ident("field name")?;
4613
+ self.advance();
4614
+ let v = self.parse_expr()?;
4615
+ fields.push((k, v));
4616
+ } else {
4617
+ let v = self.parse_expr()?;
4618
+ fields.push((format!("_{unkeyed}"), v));
4619
+ unkeyed += 1;
4620
+ }
4621
+ if !self.eat(&TokKind::Comma) {
4622
+ break;
4623
+ }
4624
+ }
4625
+ let end = self.expect(&TokKind::RBrace, "'}'")?;
4626
+ return Ok(Expr::ObjectLit(Some(name), fields, t.span.merge(end.span)));
4627
+ }
4628
+ Ok(Expr::Var(name, t.span))
4629
+ }
4630
+ other => Err(PolyError::spanned(
4631
+ "E0121",
4632
+ format!("unexpected token {:?} in expression", other),
4633
+ t.span,
4634
+ )),
4635
+ }
4636
+ }
4637
+
4638
+ fn fresh_anon_name(&mut self) -> String {
4639
+ let id = self.anon_counter;
4640
+ self.anon_counter += 1;
4641
+ format!("__lambda_{id}")
4642
+ }
4643
+
4644
+ fn parse_postfix(&mut self, mut expr: Expr, allow_struct_lit: bool) -> Result<Expr, PolyError> {
4645
+ loop {
4646
+ if self.eat(&TokKind::LParen) {
4647
+ let mut args = Vec::new();
4648
+ while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
4649
+ args.push(self.parse_expr()?);
4650
+ if !self.eat(&TokKind::Comma) {
4651
+ break;
4652
+ }
4653
+ }
4654
+ let end = self.expect(&TokKind::RParen, "')'")?;
4655
+ let sp = expr.span().merge(end.span);
4656
+ expr = Expr::Call {
4657
+ callee: Box::new(expr),
4658
+ args,
4659
+ span: sp,
4660
+ };
4661
+ } else if self.eat(&TokKind::Dot) || self.eat(&TokKind::ColonColon) {
4662
+ let (field, fspan) = self.expect_ident("member name")?;
4663
+ let sp = expr.span().merge(fspan);
4664
+ expr = Expr::Member {
4665
+ object: Box::new(expr),
4666
+ field,
4667
+ optional: false,
4668
+ span: sp,
4669
+ };
4670
+ } else if self.eat(&TokKind::QuestionDot) {
4671
+ let (field, fspan) = self.expect_ident("optional member name")?;
4672
+ let sp = expr.span().merge(fspan);
4673
+ expr = Expr::Member {
4674
+ object: Box::new(expr),
4675
+ field,
4676
+ optional: true,
4677
+ span: sp,
4678
+ };
4679
+ } else if self.eat(&TokKind::LBracket) {
4680
+ let idx = self.parse_expr()?;
4681
+ let end = self.expect(&TokKind::RBracket, "']'")?;
4682
+ let sp = expr.span().merge(end.span);
4683
+ expr = Expr::Index {
4684
+ object: Box::new(expr),
4685
+ index: Box::new(idx),
4686
+ span: sp,
4687
+ };
4688
+ } else if self.eat(&TokKind::PlusPlus) {
4689
+ let sp = expr.span();
4690
+ if let Expr::Var(name, _) = expr {
4691
+ expr = Expr::Update {
4692
+ name,
4693
+ inc: true,
4694
+ prefix: false,
4695
+ span: sp,
4696
+ };
4697
+ } else {
4698
+ return Err(PolyError::spanned("E0122", "'++' target must be variable", sp));
4699
+ }
4700
+ } else if self.eat(&TokKind::MinusMinus) {
4701
+ let sp = expr.span();
4702
+ if let Expr::Var(name, _) = expr {
4703
+ expr = Expr::Update {
4704
+ name,
4705
+ inc: false,
4706
+ prefix: false,
4707
+ span: sp,
4708
+ };
4709
+ } else {
4710
+ return Err(PolyError::spanned("E0122", "'--' target must be variable", sp));
4711
+ }
4712
+ } else if self.lang == Language::TypeScript && self.eat(&TokKind::Bang) && !matches!(self.peek().kind, TokKind::Eq | TokKind::EqEq) {
4713
+ // TypeScript post-fix non-null assertion `obj!`
4714
+ continue;
4715
+ } else if allow_struct_lit && self.lang == Language::TypeScript && self.eat(&TokKind::FatArrow) {
4716
+ // Concise arrow closure `x => x * 2`
4717
+ let body = self.parse_expr()?;
4718
+ let sp = expr.span().merge(body.span());
4719
+ let p_name = match expr {
4720
+ Expr::Var(n, _) => n,
4721
+ _ => "__p".to_string(),
4722
+ };
4723
+ let name = self.fresh_anon_name();
4724
+ self.extra_functions.push(FunctionDecl {
4725
+ name: name.clone(),
4726
+ params: vec![Param {
4727
+ name: p_name,
4728
+ ty: TypeHint::Unknown,
4729
+ span: sp,
4730
+ }],
4731
+ return_type: TypeHint::Unknown,
4732
+ body: vec![Stmt::Return(Some(body), sp)],
4733
+ is_exported: false,
4734
+ span: sp,
4735
+ });
4736
+ expr = Expr::Var(name, sp);
4737
+ } else {
4738
+ break;
4739
+ }
4740
+ }
4741
+ Ok(expr)
4742
+ }
4743
+ }
4744
+
4745
+ pub fn parse_module(file_id: usize, language: Language, source: &str) -> Result<ModuleAst, PolyError> {
4746
+ let lexer = Lexer::new(file_id, language, source);
4747
+ let (tokens, directives) = lexer.tokenize().map_err(|mut err| {
4748
+ if err.diagnostics.is_empty() {
4749
+ err.diagnostics.push(Diagnostic::error("E0100", "lexing error"));
4750
+ }
4751
+ err
4752
+ })?;
4753
+ let mut parser = Parser::new(file_id, language, tokens);
4754
+ parser.parse_module(directives)
4755
+ }