polycomp 0.2.0 → 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 CHANGED
@@ -7,6 +7,8 @@ enum TokKind {
7
7
  Int(i64),
8
8
  Float(f64),
9
9
  Str(String),
10
+ Regex(String, String),
11
+ InterpStr(Vec<(bool, String, Option<String>, u32, u32)>),
10
12
  Newline,
11
13
  Indent,
12
14
  Dedent,
@@ -19,6 +21,7 @@ enum TokKind {
19
21
  Comma,
20
22
  Colon,
21
23
  ColonColon,
24
+ ColonEq,
22
25
  Semi,
23
26
  Dot,
24
27
  DotDot,
@@ -26,9 +29,12 @@ enum TokKind {
26
29
  Arrow,
27
30
  FatArrow,
28
31
  Question,
32
+ QuestionDot,
33
+ QuestionQuestion,
29
34
  Plus,
30
35
  Minus,
31
36
  Star,
37
+ StarStar,
32
38
  Slash,
33
39
  SlashSlash,
34
40
  Percent,
@@ -57,6 +63,7 @@ enum TokKind {
57
63
  Bang,
58
64
  Shl,
59
65
  Shr,
66
+ At,
60
67
  Eof,
61
68
  }
62
69
 
@@ -66,6 +73,72 @@ struct Tok {
66
73
  span: Span,
67
74
  }
68
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
+
69
142
  struct Lexer<'a> {
70
143
  file_id: usize,
71
144
  lang: Language,
@@ -173,6 +246,294 @@ impl<'a> Lexer<'a> {
173
246
  }
174
247
  }
175
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
+
176
537
  fn tokenize(mut self) -> Result<(Vec<Tok>, Vec<ImportDecl>), PolyError> {
177
538
  let mut tokens = Vec::new();
178
539
  let mut indent_stack: Vec<usize> = vec![0];
@@ -269,7 +630,7 @@ impl<'a> Lexer<'a> {
269
630
  let line = self.line;
270
631
  let col = self.current_col();
271
632
  self.advance();
272
- if self.lang == Language::Python && paren_depth == 0 {
633
+ if (self.lang == Language::Python || self.lang == Language::Go) && paren_depth == 0 {
273
634
  let emit = tokens
274
635
  .last()
275
636
  .is_some_and(|t| !matches!(t.kind, TokKind::Newline | TokKind::Indent));
@@ -286,6 +647,33 @@ impl<'a> Lexer<'a> {
286
647
  at_line_start = false;
287
648
 
288
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
+
289
677
  let c_start = self.pos;
290
678
  let c_line = self.line;
291
679
  let c_col = self.current_col();
@@ -299,7 +687,7 @@ impl<'a> Lexer<'a> {
299
687
  }
300
688
  let raw_text = self.src[text_start..self.pos].trim();
301
689
  let span = self.make_span(c_start, self.pos, c_line, c_col);
302
- if self.lang == Language::C {
690
+ if matches!(self.lang, Language::C | Language::Cpp) {
303
691
  if let Some(inc) = raw_text.strip_prefix("include") {
304
692
  let inc = inc.trim();
305
693
  if inc.starts_with('"') && inc.ends_with('"') && inc.len() >= 2 {
@@ -367,118 +755,343 @@ impl<'a> Lexer<'a> {
367
755
  let line = self.line;
368
756
  let col = self.current_col();
369
757
 
370
- if b == b'"' || b == b'\'' || b == b'`' {
371
- let quote = b;
372
- self.advance();
373
- let mut s = String::new();
374
- let mut closed = false;
375
- while let Some(cb) = self.peek() {
376
- if cb == quote {
377
- self.advance();
378
- closed = true;
379
- break;
380
- }
381
- if cb == b'\\' {
382
- self.advance();
383
- match self.advance() {
384
- Some(b'n') => s.push('\n'),
385
- Some(b't') => s.push('\t'),
386
- Some(b'r') => s.push('\r'),
387
- Some(b'0') => s.push('\0'),
388
- Some(b'\\') => s.push('\\'),
389
- Some(b'"') => s.push('"'),
390
- Some(b'\'') => s.push('\''),
391
- Some(other) => s.push(other as char),
392
- None => break,
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;
393
797
  }
394
- } else {
395
798
  let ch = self.src[self.pos..].chars().next().unwrap();
396
799
  for _ in 0..ch.len_utf8() {
397
800
  self.advance();
398
801
  }
399
802
  s.push(ch);
400
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;
401
816
  }
402
- if !closed {
403
- return Err(PolyError::spanned(
404
- "E0103",
405
- "unterminated string literal",
406
- self.make_span(start, self.pos, line, col),
407
- ));
408
- }
409
- tokens.push(Tok {
410
- kind: TokKind::Str(s),
411
- span: self.make_span(start, self.pos, line, col),
412
- });
413
- continue;
414
817
  }
415
818
 
416
- if b.is_ascii_digit() {
417
- if b == b'0' && matches!(self.peek_at(1), Some(b'x' | b'X' | b'b' | b'B')) {
418
- let prefix = self.peek_at(1).unwrap();
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();
419
824
  self.advance();
420
825
  self.advance();
421
- let d_start = self.pos;
422
- while let Some(db) = self.peek() {
423
- if db.is_ascii_hexdigit() || db == b'_' {
424
- self.advance();
425
- } else {
426
- break;
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
+ ));
427
856
  }
857
+ tokens.push(Tok {
858
+ kind: TokKind::Str(s),
859
+ span: self.make_span(start, self.pos, line, col),
860
+ });
428
861
  }
429
- let clean: String = self.src[d_start..self.pos]
430
- .chars()
431
- .filter(|&c| c != '_')
432
- .collect();
433
- let radix = if prefix == b'x' || prefix == b'X' { 16 } else { 2 };
434
- let val = i64::from_str_radix(&clean, radix).map_err(|_| {
435
- PolyError::spanned(
436
- "E0104",
437
- "invalid integer literal",
438
- self.make_span(start, self.pos, line, col),
439
- )
440
- })?;
441
- tokens.push(Tok {
442
- kind: TokKind::Int(val),
443
- span: self.make_span(start, self.pos, line, col),
444
- });
445
862
  continue;
446
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
+ }
447
875
 
448
- let mut is_float = false;
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();
449
880
  while let Some(db) = self.peek() {
450
- if db.is_ascii_digit() || db == b'_' {
451
- self.advance();
452
- } else if db == b'.' && self.peek_at(1).is_some_and(|n| n.is_ascii_digit()) {
453
- is_float = true;
454
- self.advance();
455
- } else if (db == b'e' || db == b'E') && !is_float {
456
- is_float = true;
457
- self.advance();
458
- if matches!(self.peek(), Some(b'+' | b'-')) {
459
- self.advance();
460
- }
461
- } else if (db == b'e' || db == b'E') && is_float {
881
+ if db == b'(' {
462
882
  self.advance();
463
- if matches!(self.peek(), Some(b'+' | b'-')) {
464
- self.advance();
465
- }
466
- } else {
467
883
  break;
468
884
  }
885
+ delim.push(db as char);
886
+ self.advance();
469
887
  }
470
- let clean: String = self.src[start..self.pos]
471
- .chars()
472
- .filter(|&c| c != '_')
473
- .collect();
474
- let span = self.make_span(start, self.pos, line, col);
475
- if is_float {
476
- let val: f64 = clean.parse().map_err(|_| {
477
- PolyError::spanned("E0104", "invalid float literal", span)
478
- })?;
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
+ }
479
895
  tokens.push(Tok {
480
- kind: TokKind::Float(val),
481
- span,
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,
482
1095
  });
483
1096
  } else {
484
1097
  let val: i64 = clean.parse().map_err(|_| {
@@ -492,9 +1105,9 @@ impl<'a> Lexer<'a> {
492
1105
  continue;
493
1106
  }
494
1107
 
495
- if b.is_ascii_alphabetic() || b == b'_' {
1108
+ if b.is_ascii_alphabetic() || b == b'_' || b == b'$' {
496
1109
  while let Some(ib) = self.peek() {
497
- if ib.is_ascii_alphanumeric() || ib == b'_' {
1110
+ if ib.is_ascii_alphanumeric() || ib == b'_' || ib == b'$' {
498
1111
  self.advance();
499
1112
  } else {
500
1113
  break;
@@ -532,6 +1145,11 @@ impl<'a> Lexer<'a> {
532
1145
  self.advance();
533
1146
  TokKind::ColonColon
534
1147
  }
1148
+ (b':', Some(b'='), _) => {
1149
+ self.advance();
1150
+ self.advance();
1151
+ TokKind::ColonEq
1152
+ }
535
1153
  (b'.', Some(b'.'), _) => {
536
1154
  self.advance();
537
1155
  self.advance();
@@ -547,6 +1165,21 @@ impl<'a> Lexer<'a> {
547
1165
  self.advance();
548
1166
  TokKind::FatArrow
549
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
+ }
550
1183
  (b'/', Some(b'/'), _) => {
551
1184
  self.advance();
552
1185
  self.advance();
@@ -733,6 +1366,10 @@ impl<'a> Lexer<'a> {
733
1366
  self.advance();
734
1367
  TokKind::Bang
735
1368
  }
1369
+ (b'@', _, _) => {
1370
+ self.advance();
1371
+ TokKind::At
1372
+ }
736
1373
  other => {
737
1374
  return Err(PolyError::spanned(
738
1375
  "E0105",
@@ -752,7 +1389,7 @@ impl<'a> Lexer<'a> {
752
1389
  let eof_span = self.make_span(self.pos, self.pos, self.line, self.current_col());
753
1390
  if tokens
754
1391
  .last()
755
- .is_some_and(|t| !matches!(t.kind, TokKind::Newline | TokKind::Dedent))
1392
+ .is_some_and(|t| !matches!(t.kind, TokKind::Newline | TokKind::Indent))
756
1393
  {
757
1394
  tokens.push(Tok {
758
1395
  kind: TokKind::Newline,
@@ -777,6 +1414,53 @@ impl<'a> Lexer<'a> {
777
1414
  }
778
1415
  }
779
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
+
780
1464
  fn unquote(s: &str) -> String {
781
1465
  let s = s.trim();
782
1466
  if s.len() >= 2
@@ -820,24 +1504,45 @@ fn parse_directive_item_list(raw: &str, span: Span) -> Vec<ImportItem> {
820
1504
  items
821
1505
  }
822
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
+
823
1518
  struct Parser {
1519
+ file_id: usize,
824
1520
  lang: Language,
825
1521
  tokens: Vec<Tok>,
826
1522
  pos: usize,
827
1523
  struct_names: Vec<String>,
1524
+ enum_names: Vec<String>,
828
1525
  anon_counter: usize,
829
1526
  extra_functions: Vec<FunctionDecl>,
1527
+ extra_enums: Vec<EnumDecl>,
1528
+ extra_structs: Vec<StructDecl>,
1529
+ using_namespaces: Vec<String>,
830
1530
  }
831
1531
 
832
1532
  impl Parser {
833
- fn new(lang: Language, tokens: Vec<Tok>) -> Self {
1533
+ fn new(file_id: usize, lang: Language, tokens: Vec<Tok>) -> Self {
834
1534
  Self {
1535
+ file_id,
835
1536
  lang,
836
1537
  tokens,
837
1538
  pos: 0,
838
1539
  struct_names: Vec::new(),
1540
+ enum_names: Vec::new(),
839
1541
  anon_counter: 0,
840
1542
  extra_functions: Vec::new(),
1543
+ extra_enums: Vec::new(),
1544
+ extra_structs: Vec::new(),
1545
+ using_namespaces: Vec::new(),
841
1546
  }
842
1547
  }
843
1548
 
@@ -928,217 +1633,691 @@ impl Parser {
928
1633
  }
929
1634
  }
930
1635
 
931
- fn is_c_type_start(&self) -> bool {
932
- match &self.peek().kind {
933
- TokKind::Ident(s) => {
934
- matches!(
935
- s.as_str(),
936
- "void"
937
- | "int"
938
- | "long"
939
- | "short"
940
- | "char"
941
- | "float"
942
- | "double"
943
- | "bool"
944
- | "unsigned"
945
- | "signed"
946
- | "size_t"
947
- | "int64_t"
948
- | "uint64_t"
949
- | "int32_t"
950
- | "const"
951
- | "struct"
952
- ) || self.struct_names.contains(s)
953
- }
954
- _ => false,
955
- }
956
- }
957
-
958
1636
  fn parse_type_hint_str(s: &str) -> TypeHint {
959
1637
  match s {
960
- "void" | "()" | "None" => TypeHint::Void,
961
- "bool" => TypeHint::Bool,
1638
+ "void" | "()" | "None" | "never" | "undefined" => TypeHint::Void,
1639
+ "bool" | "boolean" => TypeHint::Bool,
962
1640
  "int" | "i8" | "i16" | "i32" | "i64" | "isize" | "u8" | "u16" | "u32" | "u64"
963
- | "usize" | "long" | "short" | "int64_t" | "int32_t" | "uint64_t" | "size_t" => {
1641
+ | "usize" | "long" | "short" | "int64_t" | "int32_t" | "uint64_t" | "uint32_t"
1642
+ | "size_t" | "int64" | "int32" | "uint" | "uint64" | "bigint" | "byte" | "rune" => {
964
1643
  TypeHint::Int
965
1644
  }
966
- "float" | "double" | "f32" | "f64" | "number" => TypeHint::Float,
1645
+ "float" | "double" | "f32" | "f64" | "float64" | "float32" | "number" | "decimal" => {
1646
+ TypeHint::Float
1647
+ }
967
1648
  "str" | "String" | "string" | "char" => TypeHint::Str,
1649
+ "RegExp" | "Regex" | "Regexp" | "regex" => TypeHint::Regex,
1650
+ "Array" | "List" => TypeHint::Array,
968
1651
  _ => TypeHint::Unknown,
969
1652
  }
970
1653
  }
971
1654
 
972
- fn parse_c_type(&mut self) -> Result<TypeHint, PolyError> {
973
- let mut base = TypeHint::Unknown;
974
- let mut saw_any = false;
975
- while let TokKind::Ident(kw) = &self.peek().kind {
976
- let k = kw.clone();
977
- if matches!(k.as_str(), "const" | "unsigned" | "signed" | "struct") {
978
- self.advance();
979
- saw_any = true;
980
- if k == "unsigned" && !self.is_c_type_start() {
981
- base = TypeHint::Int;
982
- }
983
- continue;
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;
984
1697
  }
985
- let mapped = Self::parse_type_hint_str(&k);
986
- if mapped != TypeHint::Unknown || self.struct_names.contains(&k) {
987
- self.advance();
988
- saw_any = true;
989
- if k == "char" && self.at(&TokKind::Star) {
990
- base = TypeHint::Str;
991
- } else {
992
- base = mapped;
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;
993
1753
  }
994
- break;
995
- } else {
996
- break;
997
1754
  }
998
1755
  }
999
- while self.eat(&TokKind::Star) {
1000
- if base == TypeHint::Unknown {
1001
- base = TypeHint::Int;
1002
- }
1756
+ if depth != 0 {
1757
+ self.pos = save;
1758
+ return false;
1003
1759
  }
1004
- if !saw_any {
1005
- let t = self.peek();
1006
- return Err(PolyError::spanned("E0112", "expected C type", t.span));
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;
1007
1778
  }
1008
- Ok(base)
1779
+ true
1009
1780
  }
1010
1781
 
1011
- fn parse_rust_or_py_type(&mut self) -> Result<TypeHint, PolyError> {
1012
- if self.eat(&TokKind::LParen) {
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
+ }
1013
1808
  self.expect(&TokKind::RParen, "')'")?;
1014
- return Ok(TypeHint::Void);
1015
- }
1016
- if self.eat(&TokKind::Amp) {
1017
- let _ = self.eat_ident("mut");
1018
- let (name, _) = self.expect_ident("type name")?;
1019
- return Ok(Self::parse_type_hint_str(&name));
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 });
1020
1814
  }
1021
- let (name, _) = self.expect_ident("type name")?;
1022
- Ok(Self::parse_type_hint_str(&name))
1023
- }
1024
-
1025
- fn parse_module(
1026
- &mut self,
1027
- directives: Vec<ImportDecl>,
1028
- ) -> Result<ModuleAst, PolyError> {
1029
- let mut imports = directives;
1030
- let mut structs = Vec::new();
1031
- let mut functions = Vec::new();
1032
- let mut top_level = Vec::new();
1033
1815
 
1034
- self.skip_newlines();
1035
- while !self.at(&TokKind::Eof) {
1036
- if self.at_ident("import") || self.at_ident("from") || self.at_ident("use") {
1037
- let mut decls = self.parse_import_decl()?;
1038
- imports.append(&mut decls);
1039
- self.eat_stmt_end();
1040
- continue;
1816
+ if self.eat(&TokKind::LBracket) {
1817
+ if self.eat(&TokKind::RBracket) {
1818
+ let _ = self.parse_rich_type()?;
1819
+ return Ok(TypeHint::Array);
1041
1820
  }
1042
-
1043
- if self.lang == Language::Rust && self.at_ident("mod") {
1044
- let start = self.peek().span;
1045
- self.advance();
1046
- let (name, _) = self.expect_ident("module name")?;
1047
- self.eat_stmt_end();
1048
- imports.push(ImportDecl {
1049
- module_specifier: name.clone(),
1050
- kind: ImportKind::Namespace { alias: name },
1051
- span: start,
1052
- });
1053
- continue;
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
+ }
1054
1826
  }
1827
+ self.expect(&TokKind::RBracket, "']'")?;
1828
+ return Ok(TypeHint::Array);
1829
+ }
1055
1830
 
1056
- let exported = if self.eat_ident("export") {
1057
- let _ = self.eat_ident("default");
1058
- true
1059
- } else {
1060
- self.eat_ident("pub")
1061
- };
1062
-
1063
- if self.at_ident("import") || self.at_ident("from") || self.at_ident("use") {
1064
- let mut decls = self.parse_import_decl()?;
1065
- imports.append(&mut decls);
1066
- self.eat_stmt_end();
1067
- continue;
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
+ }
1068
1841
  }
1842
+ return Ok(TypeHint::Object);
1843
+ }
1069
1844
 
1070
- if self.at_ident("fn")
1071
- || self.at_ident("def")
1072
- || self.at_ident("function")
1073
- {
1074
- let f = self.parse_function(exported)?;
1075
- functions.push(f);
1076
- self.skip_newlines();
1077
- continue;
1078
- }
1845
+ let _ = self.eat(&TokKind::Amp);
1846
+ let _ = self.eat_ident("mut");
1847
+ let _ = self.eat_ident("const");
1848
+ let _ = self.eat_ident("readonly");
1079
1849
 
1080
- if self.at_ident("struct") || self.at_ident("class") {
1081
- if self.lang == Language::C
1082
- && matches!(&self.peek_n(1).kind, TokKind::Ident(_))
1083
- && !matches!(&self.peek_n(2).kind, TokKind::LBrace)
1084
- {
1085
- if let Some(f) = self.try_parse_c_top_level()? {
1086
- functions.push(f);
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;
1087
1860
  }
1088
- self.skip_newlines();
1089
- continue;
1090
1861
  }
1091
- let s = self.parse_struct_or_class()?;
1092
- self.struct_names.push(s.name.clone());
1093
- structs.push(s);
1094
- self.skip_newlines();
1095
- continue;
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
1096
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) {}
1097
1889
 
1098
- if self.lang == Language::Rust && self.at_ident("impl") {
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
+ ) {
1099
1908
  self.advance();
1100
- let (struct_name, _) = self.expect_ident("struct name")?;
1101
- self.expect(&TokKind::LBrace, "'{'")?;
1102
- let mut methods = Vec::new();
1103
- while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
1104
- let is_pub = self.eat_ident("pub");
1105
- let mut m = self.parse_function(is_pub)?;
1106
- m.name = format!("{struct_name}::{}", m.name);
1107
- methods.push(m);
1909
+ saw_any = true;
1910
+ if k == "unsigned" && !self.is_c_cpp_cs_type_start() {
1911
+ base = TypeHint::Int;
1108
1912
  }
1109
- self.expect(&TokKind::RBrace, "'}'")?;
1110
- functions.extend(methods);
1111
1913
  continue;
1112
1914
  }
1113
-
1114
- if self.lang == Language::C && self.is_c_type_start() {
1115
- if let Some(f) = self.try_parse_c_top_level()? {
1116
- functions.push(f);
1117
- self.skip_newlines();
1118
- continue;
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;
1119
1947
  }
1120
- let s = self.parse_stmt()?;
1121
- top_level.push(s);
1122
- self.skip_newlines();
1123
- continue;
1948
+ break;
1949
+ } else {
1950
+ break;
1124
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();
1125
1976
 
1126
- let stmt = self.parse_stmt()?;
1127
- top_level.push(stmt);
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)?;
1128
1980
  self.skip_newlines();
1129
1981
  }
1130
1982
 
1131
1983
  functions.append(&mut self.extra_functions);
1984
+ enums.append(&mut self.extra_enums);
1985
+ structs.append(&mut self.extra_structs);
1132
1986
 
1133
1987
  Ok(ModuleAst {
1134
1988
  language: self.lang,
1135
1989
  imports,
1990
+ using_namespaces: std::mem::take(&mut self.using_namespaces),
1991
+ enums,
1136
1992
  structs,
1137
1993
  functions,
1138
1994
  top_level,
1139
1995
  })
1140
1996
  }
1141
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
+
1142
2321
  fn parse_module_specifier_tok(&mut self) -> Result<(String, Span), PolyError> {
1143
2322
  let t = self.peek().clone();
1144
2323
  match t.kind {
@@ -1200,7 +2379,7 @@ impl Parser {
1200
2379
  if !self.eat_ident("import") {
1201
2380
  return Err(PolyError::spanned(
1202
2381
  "E0114",
1203
- "expected 'import' after module in 'from ... import ...'",
2382
+ "expected 'import' after module",
1204
2383
  self.peek().span,
1205
2384
  ));
1206
2385
  }
@@ -1332,12 +2511,54 @@ impl Parser {
1332
2511
  }]);
1333
2512
  }
1334
2513
 
1335
- // `import ...`
1336
2514
  self.expect_ident("'import'")?;
1337
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
+
1338
2556
  if let TokKind::Str(spec) = &self.peek().kind {
1339
2557
  let spec = spec.clone();
1340
2558
  self.advance();
2559
+ if self.lang == Language::Go && is_stdlib_go_package(&spec) {
2560
+ return Ok(Vec::new());
2561
+ }
1341
2562
  return Ok(vec![ImportDecl {
1342
2563
  module_specifier: spec,
1343
2564
  kind: ImportKind::Wildcard,
@@ -1386,15 +2607,25 @@ impl Parser {
1386
2607
  }]);
1387
2608
  }
1388
2609
 
1389
- // Handles:
1390
- // import mod
1391
- // import mod as alias
1392
- // import a, b as c
1393
- // import x, y, z from module
1394
- // import mod, { x, y } from "module"
1395
2610
  let mut first_entries: Vec<(String, Option<String>, Span)> = Vec::new();
1396
2611
  let mut braced_tail: Option<Vec<ImportItem>> = None;
1397
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
+
1398
2629
  loop {
1399
2630
  let (name, ispan) = self.expect_ident("module or symbol name")?;
1400
2631
  let alias = if self.eat_ident("as") {
@@ -1433,23 +2664,6 @@ impl Parser {
1433
2664
  });
1434
2665
  return Ok(decls);
1435
2666
  }
1436
- if first_entries.len() == 1 && first_entries[0].1.is_none() && self.lang == Language::JavaScript {
1437
- // In JS, `import foo from "./mod.js"` can be default/namespace or named; treat single unbraced as Named OR Namespace fallback?
1438
- // Wait: in `import x,y,z from module` it's always Named items!
1439
- let (name, alias, ispan) = first_entries.remove(0);
1440
- let alias = alias.unwrap_or_else(|| name.clone());
1441
- return Ok(vec![ImportDecl {
1442
- module_specifier: mod_spec,
1443
- kind: ImportKind::Named {
1444
- items: vec![ImportItem {
1445
- name,
1446
- alias,
1447
- span: ispan,
1448
- }],
1449
- },
1450
- span: start,
1451
- }]);
1452
- }
1453
2667
  let items = first_entries
1454
2668
  .into_iter()
1455
2669
  .map(|(name, alias, ispan)| ImportItem {
@@ -1465,7 +2679,6 @@ impl Parser {
1465
2679
  }]);
1466
2680
  }
1467
2681
 
1468
- // Plain `import mod1, mod2 as m2`
1469
2682
  let decls = first_entries
1470
2683
  .into_iter()
1471
2684
  .map(|(mod_spec, alias, ispan)| ImportDecl {
@@ -1482,6 +2695,7 @@ impl Parser {
1482
2695
  fn parse_braced_import_items(&mut self) -> Result<Vec<ImportItem>, PolyError> {
1483
2696
  let mut items = Vec::new();
1484
2697
  while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
2698
+ let _ = self.eat_ident("type");
1485
2699
  let (name, ispan) = self.expect_ident("imported symbol")?;
1486
2700
  let alias = if self.eat_ident("as") {
1487
2701
  self.expect_ident("alias")?.0
@@ -1501,21 +2715,29 @@ impl Parser {
1501
2715
  Ok(items)
1502
2716
  }
1503
2717
 
1504
- fn try_parse_c_top_level(&mut self) -> Result<Option<FunctionDecl>, PolyError> {
2718
+ fn try_parse_typed_top_level_fn(&mut self) -> Result<Option<FunctionDecl>, PolyError> {
1505
2719
  let save = self.pos;
1506
- let ret_ty = self.parse_c_type()?;
2720
+ let ret_ty = self.parse_c_cpp_cs_type()?;
1507
2721
  if let TokKind::Ident(name) = &self.peek().kind {
1508
2722
  let fn_name = name.clone();
1509
2723
  let fn_span = self.peek().span;
1510
2724
  self.advance();
2725
+ let _ = self.try_skip_angle_generics();
1511
2726
  if self.eat(&TokKind::LParen) {
1512
- let params = self.parse_c_params()?;
2727
+ let params = self.parse_c_cpp_cs_params()?;
1513
2728
  self.expect(&TokKind::RParen, "')'")?;
2729
+ let _ = self.eat_ident("const");
2730
+ let _ = self.eat_ident("override");
1514
2731
  if self.eat(&TokKind::Semi) {
1515
- // Forward prototype; return a no-op or skip? Return None only if var decl; for prototype re-loop cleanly!
1516
2732
  return Ok(None);
1517
2733
  }
1518
- let body = self.parse_brace_block()?;
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
+ };
1519
2741
  return Ok(Some(FunctionDecl {
1520
2742
  name: fn_name,
1521
2743
  params,
@@ -1530,15 +2752,16 @@ impl Parser {
1530
2752
  Ok(None)
1531
2753
  }
1532
2754
 
1533
- fn parse_c_params(&mut self) -> Result<Vec<Param>, PolyError> {
2755
+ fn parse_c_cpp_cs_params(&mut self) -> Result<Vec<Param>, PolyError> {
1534
2756
  let mut params = Vec::new();
1535
2757
  if self.at_ident("void") && self.peek_n(1).kind == TokKind::RParen {
1536
2758
  self.advance();
1537
2759
  return Ok(params);
1538
2760
  }
1539
2761
  while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
1540
- let ty = if self.is_c_type_start() {
1541
- self.parse_c_type()?
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()?
1542
2765
  } else {
1543
2766
  TypeHint::Unknown
1544
2767
  };
@@ -1546,6 +2769,9 @@ impl Parser {
1546
2769
  if self.eat(&TokKind::LBracket) {
1547
2770
  let _ = self.eat(&TokKind::RBracket);
1548
2771
  }
2772
+ if self.eat(&TokKind::Eq) {
2773
+ let _ = self.parse_expr()?;
2774
+ }
1549
2775
  params.push(Param { name, ty, span });
1550
2776
  if !self.eat(&TokKind::Comma) {
1551
2777
  break;
@@ -1554,48 +2780,117 @@ impl Parser {
1554
2780
  Ok(params)
1555
2781
  }
1556
2782
 
1557
-
1558
- fn parse_function(&mut self, _exported: bool) -> Result<FunctionDecl, PolyError> {
1559
- let start_span = self.advance().span;
1560
- let (name, _) = self.expect_ident("function name")?;
1561
- self.expect(&TokKind::LParen, "'('")?;
2783
+ fn parse_go_params(&mut self) -> Result<Vec<Param>, PolyError> {
1562
2784
  let mut params = Vec::new();
2785
+ let mut untyped_group: Vec<(String, Span)> = Vec::new();
1563
2786
  while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
1564
- if self.eat_ident("mut") {}
1565
- let (pname, pspan) = self.expect_ident("parameter name")?;
1566
- let ty = if self.eat(&TokKind::Colon) {
1567
- self.parse_rust_or_py_type()?
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()?
1568
2795
  } else {
1569
2796
  TypeHint::Unknown
1570
2797
  };
1571
- if self.eat(&TokKind::Eq) {
1572
- // Skip optional default expr in signature
1573
- let _ = self.parse_expr()?;
1574
- }
1575
- if pname != "self" || !params.is_empty() {
2798
+ for (gn, gsp) in untyped_group.drain(..) {
1576
2799
  params.push(Param {
1577
- name: pname,
2800
+ name: gn,
1578
2801
  ty,
1579
- span: pspan,
2802
+ span: gsp,
1580
2803
  });
1581
- } else {
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
+ }
1582
2875
  params.push(Param {
1583
2876
  name: pname,
1584
2877
  ty,
1585
2878
  span: pspan,
1586
2879
  });
1587
- }
1588
- if !self.eat(&TokKind::Comma) {
1589
- break;
2880
+ if !self.eat(&TokKind::Comma) {
2881
+ break;
2882
+ }
1590
2883
  }
1591
2884
  }
1592
2885
  self.expect(&TokKind::RParen, "')'")?;
1593
2886
 
1594
2887
  let mut return_type = TypeHint::Unknown;
1595
2888
  if self.eat(&TokKind::Arrow) {
1596
- return_type = self.parse_rust_or_py_type()?;
2889
+ return_type = self.parse_rich_type()?;
1597
2890
  } else if self.lang != Language::Python && self.eat(&TokKind::Colon) {
1598
- return_type = self.parse_rust_or_py_type()?;
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()?;
1599
2894
  }
1600
2895
 
1601
2896
  let mut body = if self.lang == Language::Python {
@@ -1605,7 +2900,6 @@ impl Parser {
1605
2900
  self.parse_brace_block()?
1606
2901
  };
1607
2902
 
1608
- // Rust implicit tail expression return
1609
2903
  if self.lang == Language::Rust
1610
2904
  && return_type != TypeHint::Void
1611
2905
  && let Some(last) = body.pop()
@@ -1617,6 +2911,7 @@ impl Parser {
1617
2911
  other => body.push(other),
1618
2912
  }
1619
2913
  }
2914
+
1620
2915
  Ok(FunctionDecl {
1621
2916
  name,
1622
2917
  params,
@@ -1627,9 +2922,71 @@ impl Parser {
1627
2922
  })
1628
2923
  }
1629
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
+
1630
2980
  fn parse_struct_or_class(&mut self) -> Result<StructDecl, PolyError> {
1631
2981
  let start_span = self.advance().span;
1632
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
+
1633
2990
  let mut fields = Vec::new();
1634
2991
  let mut methods = Vec::new();
1635
2992
 
@@ -1644,8 +3001,7 @@ impl Parser {
1644
3001
  }
1645
3002
  if self.at_ident("def") {
1646
3003
  let mut m = self.parse_function(true)?;
1647
- let short = m.name.clone();
1648
- m.name = format!("{name}::{short}");
3004
+ m.name = format!("{name}::{}", m.name);
1649
3005
  methods.push(m);
1650
3006
  } else if self.eat_ident("pass") {
1651
3007
  self.eat_stmt_end();
@@ -1656,29 +3012,87 @@ impl Parser {
1656
3012
  let _ = self.eat(&TokKind::Dedent);
1657
3013
  } else {
1658
3014
  self.expect(&TokKind::LBrace, "'{'")?;
3015
+ self.skip_newlines();
1659
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
+
1660
3033
  if self.at_ident("fn") || self.at_ident("function") {
1661
3034
  let mut m = self.parse_function(true)?;
1662
3035
  m.name = format!("{name}::{}", m.name);
1663
3036
  methods.push(m);
1664
3037
  continue;
1665
3038
  }
1666
- if self.lang == Language::JavaScript
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)
1667
3065
  && matches!(&self.peek().kind, TokKind::Ident(_))
1668
- && self.peek_n(1).kind == TokKind::LParen
3066
+ && (self.peek_n(1).kind == TokKind::LParen || self.peek_n(1).kind == TokKind::Lt)
1669
3067
  {
1670
- let (mname, mspan) = self.expect_ident("method name")?;
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
+ };
1671
3075
  self.expect(&TokKind::LParen, "'('")?;
1672
3076
  let mut params = vec![Param {
1673
3077
  name: "this".to_string(),
1674
- ty: TypeHint::Unknown,
3078
+ ty: TypeHint::Object,
1675
3079
  span: mspan,
1676
3080
  }];
1677
3081
  while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
3082
+ let _ = self.eat_ident("public") || self.eat_ident("private") || self.eat_ident("readonly");
1678
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
+ }
1679
3093
  params.push(Param {
1680
3094
  name: pn,
1681
- ty: TypeHint::Unknown,
3095
+ ty: pty,
1682
3096
  span: ps,
1683
3097
  });
1684
3098
  if !self.eat(&TokKind::Comma) {
@@ -1686,31 +3100,82 @@ impl Parser {
1686
3100
  }
1687
3101
  }
1688
3102
  self.expect(&TokKind::RParen, "')'")?;
3103
+ let rty = if self.eat(&TokKind::Colon) {
3104
+ self.parse_rich_type()?
3105
+ } else {
3106
+ TypeHint::Unknown
3107
+ };
1689
3108
  let body = self.parse_brace_block()?;
1690
3109
  methods.push(FunctionDecl {
1691
3110
  name: format!("{name}::{mname}"),
1692
3111
  params,
1693
- return_type: TypeHint::Unknown,
3112
+ return_type: rty,
1694
3113
  body,
1695
3114
  is_exported: true,
1696
3115
  span: mspan,
1697
3116
  });
1698
3117
  continue;
1699
3118
  }
1700
- if self.lang == Language::C && self.is_c_type_start() {
1701
- let fty = self.parse_c_type()?;
1702
- let (fname, _) = self.expect_ident("field name")?;
1703
- self.eat(&TokKind::Semi);
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();
1704
3165
  fields.push((fname, fty));
1705
3166
  continue;
1706
3167
  }
1707
- let _ = self.eat_ident("pub");
3168
+
1708
3169
  let (fname, _) = self.expect_ident("field name")?;
3170
+ let _ = self.eat(&TokKind::Question);
1709
3171
  let fty = if self.eat(&TokKind::Colon) {
1710
- self.parse_rust_or_py_type()?
3172
+ self.parse_rich_type()?
1711
3173
  } else {
1712
3174
  TypeHint::Unknown
1713
3175
  };
3176
+ if self.eat(&TokKind::Eq) {
3177
+ let _ = self.parse_expr()?;
3178
+ }
1714
3179
  fields.push((fname, fty));
1715
3180
  let _ = self.eat(&TokKind::Comma) || self.eat(&TokKind::Semi);
1716
3181
  }
@@ -1741,9 +3206,7 @@ impl Parser {
1741
3206
  let _ = self.eat(&TokKind::Dedent);
1742
3207
  Ok(stmts)
1743
3208
  } else {
1744
- // Single-line suite: `if cond: return x`
1745
- let s = self.parse_stmt()?;
1746
- Ok(vec![s])
3209
+ Ok(vec![self.parse_stmt()?])
1747
3210
  }
1748
3211
  }
1749
3212
 
@@ -1764,55 +3227,69 @@ impl Parser {
1764
3227
  let sp = self.peek().span;
1765
3228
 
1766
3229
  if self.at(&TokKind::LBrace) {
1767
- let body = self.parse_brace_block()?;
1768
- return Ok(Stmt::Block(body, sp));
3230
+ return Ok(Stmt::Block(self.parse_brace_block()?, sp));
1769
3231
  }
1770
-
1771
3232
  if self.eat_ident("pass") {
1772
3233
  self.eat_stmt_end();
1773
3234
  return Ok(Stmt::Block(Vec::new(), sp));
1774
3235
  }
1775
-
1776
3236
  if self.eat_ident("break") {
1777
3237
  self.eat_stmt_end();
1778
3238
  return Ok(Stmt::Break(sp));
1779
3239
  }
1780
-
1781
3240
  if self.eat_ident("continue") {
1782
3241
  self.eat_stmt_end();
1783
3242
  return Ok(Stmt::Continue(sp));
1784
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
+ }
1785
3260
 
1786
3261
  if self.eat_ident("return") {
1787
- let val = if self.at(&TokKind::Semi)
3262
+ if self.at(&TokKind::Semi)
1788
3263
  || self.at(&TokKind::Newline)
1789
3264
  || self.at(&TokKind::RBrace)
1790
3265
  || self.at(&TokKind::Dedent)
1791
3266
  || self.at(&TokKind::Eof)
1792
3267
  {
1793
- None
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)
1794
3281
  } else {
1795
- Some(self.parse_expr()?)
3282
+ first
1796
3283
  };
1797
3284
  self.eat_stmt_end();
1798
- return Ok(Stmt::Return(val, sp));
3285
+ return Ok(Stmt::Return(Some(val), sp));
1799
3286
  }
1800
3287
 
1801
3288
  if self.eat_ident("if") {
1802
3289
  return self.parse_if_stmt(sp);
1803
3290
  }
1804
-
1805
3291
  if self.eat_ident("while") {
1806
- let cond = if self.lang == Language::Python {
1807
- self.parse_expr_no_struct()?
1808
- } else if self.at(&TokKind::LParen) {
1809
- self.advance();
1810
- let e = self.parse_expr()?;
1811
- self.expect(&TokKind::RParen, "')'")?;
1812
- e
1813
- } else {
1814
- self.parse_expr_no_struct()?
1815
- };
3292
+ let cond = self.parse_condition_expr()?;
1816
3293
  let body = if self.lang == Language::Python {
1817
3294
  self.expect(&TokKind::Colon, "':'")?;
1818
3295
  self.parse_py_suite()?
@@ -1825,7 +3302,6 @@ impl Parser {
1825
3302
  span: sp,
1826
3303
  });
1827
3304
  }
1828
-
1829
3305
  if self.eat_ident("loop") {
1830
3306
  let body = self.parse_brace_block()?;
1831
3307
  return Ok(Stmt::While {
@@ -1834,12 +3310,10 @@ impl Parser {
1834
3310
  span: sp,
1835
3311
  });
1836
3312
  }
1837
-
1838
- if self.eat_ident("for") {
3313
+ if self.eat_ident("for") || self.eat_ident("foreach") {
1839
3314
  return self.parse_for_stmt(sp);
1840
3315
  }
1841
3316
 
1842
- // `let [mut] x [: ty] = expr;` / `const x = expr;` / `var x = expr;`
1843
3317
  if self.at_ident("let") || self.at_ident("const") || self.at_ident("var") {
1844
3318
  let kw = match &self.peek().kind {
1845
3319
  TokKind::Ident(s) => s.clone(),
@@ -1848,9 +3322,41 @@ impl Parser {
1848
3322
  let is_fn_scoped = kw == "var";
1849
3323
  self.advance();
1850
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
+
1851
3355
  let (name, _) = self.expect_ident("variable name")?;
1852
3356
  let ty = if self.eat(&TokKind::Colon) {
1853
- self.parse_rust_or_py_type()?
3357
+ self.parse_rich_type()?
3358
+ } else if self.lang == Language::Go && !self.at(&TokKind::Eq) {
3359
+ self.parse_rich_type()?
1854
3360
  } else {
1855
3361
  TypeHint::Unknown
1856
3362
  };
@@ -1869,39 +3375,59 @@ impl Parser {
1869
3375
  });
1870
3376
  }
1871
3377
 
1872
- // C typed local declaration: `double final_cost = ...;`
1873
- if self.lang == Language::C && self.is_c_type_start() {
1874
- let ty = self.parse_c_type()?;
1875
- let (name, _) = self.expect_ident("variable name")?;
1876
- if self.eat(&TokKind::LBracket) {
1877
- while !self.at(&TokKind::RBracket) && !self.at(&TokKind::Eof) {
1878
- self.advance();
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, "']'")?;
1879
3391
  }
1880
- self.expect(&TokKind::RBracket, "']'")?;
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
+ });
1881
3420
  }
1882
- let init = if self.eat(&TokKind::Eq) {
1883
- Some(self.parse_expr()?)
1884
- } else {
1885
- None
1886
- };
1887
- self.eat_stmt_end();
1888
- return Ok(Stmt::VarDecl {
1889
- name,
1890
- ty,
1891
- init,
1892
- is_function_scoped: false,
1893
- span: sp,
1894
- });
3421
+ self.pos = save;
1895
3422
  }
1896
3423
 
1897
- // Python typed variable `x: int = 10`
1898
3424
  if self.lang == Language::Python
1899
3425
  && matches!(&self.peek().kind, TokKind::Ident(_))
1900
3426
  && self.peek_n(1).kind == TokKind::Colon
1901
3427
  {
1902
3428
  let (name, _) = self.expect_ident("variable name")?;
1903
- self.advance(); // ':'
1904
- let ty = self.parse_rust_or_py_type()?;
3429
+ self.advance();
3430
+ let ty = self.parse_rich_type()?;
1905
3431
  let init = if self.eat(&TokKind::Eq) {
1906
3432
  Some(self.parse_expr()?)
1907
3433
  } else {
@@ -1917,7 +3443,142 @@ impl Parser {
1917
3443
  });
1918
3444
  }
1919
3445
 
1920
- // Expression or assignment
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
+
1921
3582
  let lhs = self.parse_expr()?;
1922
3583
  let compound = if self.eat(&TokKind::Eq) {
1923
3584
  Some(None)
@@ -1969,52 +3630,232 @@ impl Parser {
1969
3630
  });
1970
3631
  }
1971
3632
 
1972
- // In Rust, a statement without `;` at the end of a block is an expression statement (handled by `parse_function` tail-return!).
1973
- self.eat_stmt_end();
1974
- Ok(Stmt::ExprStmt(lhs, sp))
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
+ })
1975
3761
  }
1976
3762
 
1977
- fn parse_if_stmt(&mut self, sp: Span) -> Result<Stmt, PolyError> {
1978
- let cond = if self.lang == Language::Python {
1979
- self.parse_expr_no_struct()?
1980
- } else if self.at(&TokKind::LParen) {
1981
- self.advance();
1982
- let e = self.parse_expr()?;
1983
- self.expect(&TokKind::RParen, "')'")?;
1984
- e
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
+ }
1985
3773
  } else {
1986
- self.parse_expr_no_struct()?
3774
+ Some(self.parse_condition_expr()?)
1987
3775
  };
1988
3776
 
1989
- let then_body = if self.lang == Language::Python {
1990
- self.expect(&TokKind::Colon, "':'")?;
1991
- self.parse_py_suite()?
1992
- } else {
1993
- self.parse_brace_block()?
1994
- };
3777
+ self.expect(&TokKind::LBrace, "'{'")?;
3778
+ let mut cases = Vec::new();
3779
+ let mut default = Vec::new();
3780
+ self.skip_newlines();
1995
3781
 
1996
- let mut else_body = Vec::new();
1997
- if self.lang == Language::Python {
3782
+ while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
1998
3783
  self.skip_newlines();
1999
- if self.eat_ident("elif") {
2000
- let nested = self.parse_if_stmt(self.peek().span)?;
2001
- else_body.push(nested);
2002
- } else if self.eat_ident("else") {
2003
- self.expect(&TokKind::Colon, "':'")?;
2004
- else_body = self.parse_py_suite()?;
3784
+ if self.at(&TokKind::RBrace) {
3785
+ break;
2005
3786
  }
2006
- } else if self.eat_ident("else") {
2007
- if self.eat_ident("if") {
2008
- else_body.push(self.parse_if_stmt(self.peek().span)?);
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
+ }
2009
3850
  } else {
2010
- else_body = self.parse_brace_block()?;
3851
+ self.advance();
2011
3852
  }
2012
3853
  }
2013
-
2014
- Ok(Stmt::If {
2015
- cond,
2016
- then_body,
2017
- else_body,
3854
+ self.expect(&TokKind::RBrace, "'}'")?;
3855
+ Ok(Stmt::Switch {
3856
+ expr,
3857
+ cases,
3858
+ default,
2018
3859
  span: sp,
2019
3860
  })
2020
3861
  }
@@ -2068,6 +3909,7 @@ impl Parser {
2068
3909
  self.expect(&TokKind::Colon, "':'")?;
2069
3910
  let body = self.parse_py_suite()?;
2070
3911
  return Ok(Stmt::ForIn {
3912
+ index_var: None,
2071
3913
  var,
2072
3914
  iter,
2073
3915
  body,
@@ -2112,6 +3954,7 @@ impl Parser {
2112
3954
  }
2113
3955
  let body = self.parse_brace_block()?;
2114
3956
  return Ok(Stmt::ForIn {
3957
+ index_var: None,
2115
3958
  var,
2116
3959
  iter: start,
2117
3960
  body,
@@ -2119,26 +3962,117 @@ impl Parser {
2119
3962
  });
2120
3963
  }
2121
3964
 
2122
- // C / JS `for (init; cond; step)` or `for (let x of arr)`
2123
- self.expect(&TokKind::LParen, "'('")?;
2124
- if (self.at_ident("let") || self.at_ident("const") || self.at_ident("var"))
2125
- && matches!(&self.peek_n(1).kind, TokKind::Ident(_))
2126
- && matches!(&self.peek_n(2).kind, TokKind::Ident(s) if s == "of")
2127
- {
2128
- self.advance();
2129
- let (var, _) = self.expect_ident("loop variable")?;
2130
- self.advance(); // 'of'
2131
- let iter = self.parse_expr()?;
2132
- self.expect(&TokKind::RParen, "')'")?;
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
+ };
2133
4039
  let body = self.parse_brace_block()?;
2134
- return Ok(Stmt::ForIn {
2135
- var,
2136
- iter,
4040
+ return Ok(Stmt::While {
4041
+ cond,
2137
4042
  body,
2138
4043
  span: sp,
2139
4044
  });
2140
4045
  }
2141
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
+
2142
4076
  let mut stmts = Vec::new();
2143
4077
  if !self.eat(&TokKind::Semi) {
2144
4078
  let init = self.parse_stmt()?;
@@ -2151,7 +4085,7 @@ impl Parser {
2151
4085
  };
2152
4086
  self.expect(&TokKind::Semi, "';'")?;
2153
4087
  let step_stmt = if !self.at(&TokKind::RParen) {
2154
- Some(self.parse_stmt_inline()?)
4088
+ Some(self.parse_stmt_inline_or_expr()?)
2155
4089
  } else {
2156
4090
  None
2157
4091
  };
@@ -2168,10 +4102,98 @@ impl Parser {
2168
4102
  Ok(Stmt::Block(stmts, sp))
2169
4103
  }
2170
4104
 
2171
- fn parse_stmt_inline(&mut self) -> Result<Stmt, PolyError> {
4105
+ fn parse_stmt_inline_or_expr(&mut self) -> Result<Stmt, PolyError> {
2172
4106
  let sp = self.peek().span;
2173
- let lhs = self.parse_expr()?;
2174
- let op = if self.eat(&TokKind::Eq) {
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) {
2175
4197
  Some(None)
2176
4198
  } else if self.eat(&TokKind::PlusEq) {
2177
4199
  Some(Some(BinOp::Add))
@@ -2181,11 +4203,14 @@ impl Parser {
2181
4203
  Some(Some(BinOp::Mul))
2182
4204
  } else if self.eat(&TokKind::SlashEq) {
2183
4205
  Some(Some(BinOp::Div))
4206
+ } else if self.eat(&TokKind::PercentEq) {
4207
+ Some(Some(BinOp::Mod))
2184
4208
  } else {
2185
4209
  None
2186
4210
  };
2187
- if let Some(op) = op {
2188
- let value = self.parse_expr()?;
4211
+
4212
+ if let Some(op) = compound {
4213
+ let value = self.parse_expr_no_struct()?;
2189
4214
  let target = match lhs {
2190
4215
  Expr::Var(n, _) => AssignTarget::Var(n),
2191
4216
  Expr::Member { object, field, .. } => AssignTarget::Field(object, field),
@@ -2222,13 +4247,12 @@ impl Parser {
2222
4247
  lhs = self.parse_postfix(lhs, allow_struct_lit)?;
2223
4248
 
2224
4249
  loop {
2225
- // Python ternary: `a if cond else b`
2226
4250
  if self.lang == Language::Python && min_bp <= 1 && self.eat_ident("if") {
2227
4251
  let cond = self.parse_expr_bp(0, allow_struct_lit)?;
2228
4252
  if !self.eat_ident("else") {
2229
4253
  return Err(PolyError::spanned(
2230
4254
  "E0119",
2231
- "expected 'else' in conditional expression",
4255
+ "expected 'else' in Python conditional expression",
2232
4256
  self.peek().span,
2233
4257
  ));
2234
4258
  }
@@ -2243,7 +4267,6 @@ impl Parser {
2243
4267
  continue;
2244
4268
  }
2245
4269
 
2246
- // C / JS ternary: `cond ? a : b`
2247
4270
  if self.lang != Language::Python && min_bp <= 1 && self.eat(&TokKind::Question) {
2248
4271
  let then_expr = self.parse_expr()?;
2249
4272
  self.expect(&TokKind::Colon, "':'")?;
@@ -2258,9 +4281,14 @@ impl Parser {
2258
4281
  continue;
2259
4282
  }
2260
4283
 
2261
- // Rust/C explicit cast `expr as f64`
2262
- if self.eat_ident("as") {
2263
- let _ = self.parse_rust_or_py_type()?;
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
+ };
2264
4292
  continue;
2265
4293
  }
2266
4294
 
@@ -2281,6 +4309,7 @@ impl Parser {
2281
4309
 
2282
4310
  fn infix_bp(&self) -> Option<(BinOp, u8, u8)> {
2283
4311
  match &self.peek().kind {
4312
+ TokKind::QuestionQuestion => Some((BinOp::NullCoal, 1, 2)),
2284
4313
  TokKind::PipePipe => Some((BinOp::Or, 2, 3)),
2285
4314
  TokKind::Ident(s) if s == "or" => Some((BinOp::Or, 2, 3)),
2286
4315
  TokKind::AmpAmp => Some((BinOp::And, 4, 5)),
@@ -2302,6 +4331,7 @@ impl Parser {
2302
4331
  TokKind::Slash => Some((BinOp::Div, 20, 21)),
2303
4332
  TokKind::SlashSlash => Some((BinOp::FloorDiv, 20, 21)),
2304
4333
  TokKind::Percent => Some((BinOp::Mod, 20, 21)),
4334
+ TokKind::StarStar => Some((BinOp::Pow, 22, 21)),
2305
4335
  _ => None,
2306
4336
  }
2307
4337
  }
@@ -2311,29 +4341,29 @@ impl Parser {
2311
4341
  match t.kind {
2312
4342
  TokKind::Minus => {
2313
4343
  self.advance();
2314
- let inner = self.parse_expr_bp(22, allow_struct_lit)?;
4344
+ let inner = self.parse_expr_bp(23, allow_struct_lit)?;
2315
4345
  let sp = t.span.merge(inner.span());
2316
4346
  Ok(Expr::Unary(UnaryOp::Neg, Box::new(inner), sp))
2317
4347
  }
2318
4348
  TokKind::Plus => {
2319
4349
  self.advance();
2320
- self.parse_expr_bp(22, allow_struct_lit)
4350
+ self.parse_expr_bp(23, allow_struct_lit)
2321
4351
  }
2322
4352
  TokKind::Bang => {
2323
4353
  self.advance();
2324
- let inner = self.parse_expr_bp(22, allow_struct_lit)?;
4354
+ let inner = self.parse_expr_bp(23, allow_struct_lit)?;
2325
4355
  let sp = t.span.merge(inner.span());
2326
4356
  Ok(Expr::Unary(UnaryOp::Not, Box::new(inner), sp))
2327
4357
  }
2328
4358
  TokKind::Tilde => {
2329
4359
  self.advance();
2330
- let inner = self.parse_expr_bp(22, allow_struct_lit)?;
4360
+ let inner = self.parse_expr_bp(23, allow_struct_lit)?;
2331
4361
  let sp = t.span.merge(inner.span());
2332
4362
  Ok(Expr::Unary(UnaryOp::BitNot, Box::new(inner), sp))
2333
4363
  }
2334
4364
  TokKind::Ident(ref s) if s == "not" => {
2335
4365
  self.advance();
2336
- let inner = self.parse_expr_bp(22, allow_struct_lit)?;
4366
+ let inner = self.parse_expr_bp(23, allow_struct_lit)?;
2337
4367
  let sp = t.span.merge(inner.span());
2338
4368
  Ok(Expr::Unary(UnaryOp::Not, Box::new(inner), sp))
2339
4369
  }
@@ -2360,19 +4390,79 @@ impl Parser {
2360
4390
  self.advance();
2361
4391
  Ok(Expr::Str(s, t.span))
2362
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
+ }
2363
4427
  TokKind::LParen => {
2364
4428
  self.advance();
2365
- if self.lang == Language::C
2366
- && self.is_c_type_start()
2367
- && self.peek_n(1).kind == TokKind::RParen
4429
+
4430
+ if matches!(self.lang, Language::C | Language::Cpp | Language::CSharp)
4431
+ && self.is_c_cpp_cs_type_start()
2368
4432
  {
2369
- let _ = self.parse_c_type()?;
2370
- self.expect(&TokKind::RParen, "')'")?;
2371
- return self.parse_expr_bp(22, allow_struct_lit);
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)));
2372
4463
  }
2373
- let e = self.parse_expr()?;
2374
4464
  self.expect(&TokKind::RParen, "')'")?;
2375
- Ok(e)
4465
+ Ok(first)
2376
4466
  }
2377
4467
  TokKind::LBracket => {
2378
4468
  self.advance();
@@ -2429,6 +4519,7 @@ impl Parser {
2429
4519
  TokKind::Ident(ref s) if s == "new" => {
2430
4520
  self.advance();
2431
4521
  let (cls, _) = self.expect_ident("class name")?;
4522
+ let _ = self.try_skip_angle_generics();
2432
4523
  let mut args = Vec::new();
2433
4524
  if self.eat(&TokKind::LParen) {
2434
4525
  while !self.at(&TokKind::RParen) && !self.at(&TokKind::Eof) {
@@ -2438,13 +4529,47 @@ impl Parser {
2438
4529
  }
2439
4530
  }
2440
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)));
2441
4546
  }
2442
- let mut fields = Vec::new();
2443
- for (idx, a) in args.into_iter().enumerate() {
2444
- fields.push((format!("_{idx}"), a));
2445
- }
4547
+ let fields = args
4548
+ .into_iter()
4549
+ .enumerate()
4550
+ .map(|(idx, a)| (format!("_{idx}"), a))
4551
+ .collect();
2446
4552
  Ok(Expr::ObjectLit(Some(cls), fields, t.span))
2447
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
+ }
2448
4573
  TokKind::Ident(ref s) if s == "lambda" && self.lang == Language::Python => {
2449
4574
  self.advance();
2450
4575
  let mut params = Vec::new();
@@ -2476,26 +4601,29 @@ impl Parser {
2476
4601
  TokKind::Ident(name) => {
2477
4602
  self.advance();
2478
4603
  if allow_struct_lit
2479
- && self.lang == Language::Rust
2480
- && self.struct_names.contains(&name)
4604
+ && (self.lang == Language::Rust || self.lang == Language::Go)
4605
+ && (self.struct_names.contains(&name) || self.lang == Language::Go)
2481
4606
  && self.eat(&TokKind::LBrace)
2482
4607
  {
2483
4608
  let mut fields = Vec::new();
4609
+ let mut unkeyed = 0usize;
2484
4610
  while !self.at(&TokKind::RBrace) && !self.at(&TokKind::Eof) {
2485
- let (k, _) = self.expect_ident("field name")?;
2486
- self.expect(&TokKind::Colon, "':'")?;
2487
- let v = self.parse_expr()?;
2488
- fields.push((k, v));
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
+ }
2489
4621
  if !self.eat(&TokKind::Comma) {
2490
4622
  break;
2491
4623
  }
2492
4624
  }
2493
4625
  let end = self.expect(&TokKind::RBrace, "'}'")?;
2494
- return Ok(Expr::ObjectLit(
2495
- Some(name),
2496
- fields,
2497
- t.span.merge(end.span),
2498
- ));
4626
+ return Ok(Expr::ObjectLit(Some(name), fields, t.span.merge(end.span)));
2499
4627
  }
2500
4628
  Ok(Expr::Var(name, t.span))
2501
4629
  }
@@ -2513,7 +4641,7 @@ impl Parser {
2513
4641
  format!("__lambda_{id}")
2514
4642
  }
2515
4643
 
2516
- fn parse_postfix(&mut self, mut expr: Expr, _allow_struct_lit: bool) -> Result<Expr, PolyError> {
4644
+ fn parse_postfix(&mut self, mut expr: Expr, allow_struct_lit: bool) -> Result<Expr, PolyError> {
2517
4645
  loop {
2518
4646
  if self.eat(&TokKind::LParen) {
2519
4647
  let mut args = Vec::new();
@@ -2536,6 +4664,16 @@ impl Parser {
2536
4664
  expr = Expr::Member {
2537
4665
  object: Box::new(expr),
2538
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,
2539
4677
  span: sp,
2540
4678
  };
2541
4679
  } else if self.eat(&TokKind::LBracket) {
@@ -2557,11 +4695,7 @@ impl Parser {
2557
4695
  span: sp,
2558
4696
  };
2559
4697
  } else {
2560
- return Err(PolyError::spanned(
2561
- "E0122",
2562
- "'++' target must be a variable",
2563
- sp,
2564
- ));
4698
+ return Err(PolyError::spanned("E0122", "'++' target must be variable", sp));
2565
4699
  }
2566
4700
  } else if self.eat(&TokKind::MinusMinus) {
2567
4701
  let sp = expr.span();
@@ -2573,12 +4707,33 @@ impl Parser {
2573
4707
  span: sp,
2574
4708
  };
2575
4709
  } else {
2576
- return Err(PolyError::spanned(
2577
- "E0122",
2578
- "'--' target must be a variable",
2579
- sp,
2580
- ));
4710
+ return Err(PolyError::spanned("E0122", "'--' target must be variable", sp));
2581
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);
2582
4737
  } else {
2583
4738
  break;
2584
4739
  }
@@ -2587,19 +4742,14 @@ impl Parser {
2587
4742
  }
2588
4743
  }
2589
4744
 
2590
- pub fn parse_module(
2591
- file_id: usize,
2592
- language: Language,
2593
- source: &str,
2594
- ) -> Result<ModuleAst, PolyError> {
4745
+ pub fn parse_module(file_id: usize, language: Language, source: &str) -> Result<ModuleAst, PolyError> {
2595
4746
  let lexer = Lexer::new(file_id, language, source);
2596
4747
  let (tokens, directives) = lexer.tokenize().map_err(|mut err| {
2597
4748
  if err.diagnostics.is_empty() {
2598
- err.diagnostics
2599
- .push(Diagnostic::error("E0100", "lexing error"));
4749
+ err.diagnostics.push(Diagnostic::error("E0100", "lexing error"));
2600
4750
  }
2601
4751
  err
2602
4752
  })?;
2603
- let mut parser = Parser::new(language, tokens);
4753
+ let mut parser = Parser::new(file_id, language, tokens);
2604
4754
  parser.parse_module(directives)
2605
- }
4755
+ }