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/resolver.rs CHANGED
@@ -13,11 +13,8 @@ pub struct ImportedSymbol {
13
13
 
14
14
  #[derive(Debug, Clone, Default)]
15
15
  pub struct ImportBindings {
16
- /// alias -> target module specifier
17
16
  pub namespaces: FxHashMap<String, String>,
18
- /// local_name -> (target module specifier, original exported name)
19
17
  pub named: FxHashMap<String, ImportedSymbol>,
20
- /// Wildcard/require specifiers searched in order if symbol isn't locally defined
21
18
  pub wildcards: Vec<(String, Span)>,
22
19
  }
23
20
 
@@ -30,6 +27,7 @@ pub struct LoadedModule {
30
27
  pub bindings: ImportBindings,
31
28
  pub function_index: FxHashMap<String, usize>,
32
29
  pub struct_index: FxHashMap<String, usize>,
30
+ pub enum_index: FxHashMap<String, usize>,
33
31
  }
34
32
 
35
33
  #[derive(Debug, Clone, Default)]
@@ -38,12 +36,14 @@ pub struct ImportStats {
38
36
  pub parsed_paths: Vec<PathBuf>,
39
37
  pub cache_hits: usize,
40
38
  }
39
+
41
40
  #[derive(Debug, Clone)]
42
41
  pub struct StaticCheckReport {
43
42
  pub modules_parsed: usize,
44
43
  pub reachable_functions: usize,
45
44
  pub parsed_paths: Vec<PathBuf>,
46
45
  }
46
+
47
47
  #[derive(Debug)]
48
48
  pub struct ModuleResolver {
49
49
  pub sources: SourceMap,
@@ -64,7 +64,6 @@ impl ModuleResolver {
64
64
  }
65
65
  }
66
66
 
67
- /// Loads & parses ONLY the requested file (never eagerly parsing its imports).
68
67
  pub fn load_module(&mut self, raw_path: &Path) -> Result<usize, PolyError> {
69
68
  let canonical = canonicalize_soft(raw_path)?;
70
69
  if let Some(&id) = self.path_to_id.get(&canonical) {
@@ -76,7 +75,7 @@ impl ModuleResolver {
76
75
  PolyError::msg(
77
76
  "E0201",
78
77
  format!(
79
- "unsupported source extension for '{}'; expected .rs, .py, .js, .ts, .c, or .h",
78
+ "unsupported source extension for '{}'; expected .rs, .py, .js, .ts, .c, .cpp, .cs, or .go",
80
79
  canonical.display()
81
80
  ),
82
81
  )
@@ -92,42 +91,9 @@ impl ModuleResolver {
92
91
  let file_id = self.sources.add_file(canonical.clone(), source);
93
92
  let src_ref = &self.sources.get(file_id).unwrap().source;
94
93
  let ast = parse_module(file_id, lang, src_ref)?;
95
-
96
- let bindings = build_import_bindings(&ast.imports);
97
- let mut function_index = FxHashMap::default();
98
- for (i, f) in ast.functions.iter().enumerate() {
99
- function_index.insert(f.name.clone(), i);
100
- }
101
- let mut struct_index = FxHashMap::default();
102
- for (i, s) in ast.structs.iter().enumerate() {
103
- struct_index.insert(s.name.clone(), i);
104
- }
105
-
106
- let mod_id = self.modules.len();
107
- self.stats.modules_parsed += 1;
108
- self.stats.parsed_paths.push(canonical.clone());
109
- if self.trace_imports {
110
- eprintln!(
111
- "[polycomp:import] parsed module #{mod_id} ({}) <- {}",
112
- lang.name(),
113
- canonical.display()
114
- );
115
- }
116
-
117
- self.modules.push(LoadedModule {
118
- id: mod_id,
119
- path: canonical.clone(),
120
- language: lang,
121
- ast,
122
- bindings,
123
- function_index,
124
- struct_index,
125
- });
126
- self.path_to_id.insert(canonical, mod_id);
127
- Ok(mod_id)
94
+ Ok(self.register_parsed_module(canonical, lang, ast))
128
95
  }
129
- /// Loads source text directly from memory (stdin / JS raw source),
130
- /// resolving relative imports against `virtual_path`'s directory.
96
+
131
97
  pub fn load_source_in_memory(
132
98
  &mut self,
133
99
  virtual_path: &Path,
@@ -142,7 +108,15 @@ impl ModuleResolver {
142
108
  let file_id = self.sources.add_file(abs.clone(), source);
143
109
  let src_ref = &self.sources.get(file_id).unwrap().source;
144
110
  let ast = parse_module(file_id, lang, src_ref)?;
111
+ Ok(self.register_parsed_module(abs, lang, ast))
112
+ }
145
113
 
114
+ fn register_parsed_module(
115
+ &mut self,
116
+ canonical: PathBuf,
117
+ lang: Language,
118
+ ast: ModuleAst,
119
+ ) -> usize {
146
120
  let bindings = build_import_bindings(&ast.imports);
147
121
  let mut function_index = FxHashMap::default();
148
122
  for (i, f) in ast.functions.iter().enumerate() {
@@ -152,35 +126,40 @@ impl ModuleResolver {
152
126
  for (i, s) in ast.structs.iter().enumerate() {
153
127
  struct_index.insert(s.name.clone(), i);
154
128
  }
129
+ let mut enum_index = FxHashMap::default();
130
+ for (i, e) in ast.enums.iter().enumerate() {
131
+ enum_index.insert(e.name.clone(), i);
132
+ }
155
133
 
156
134
  let mod_id = self.modules.len();
157
135
  self.stats.modules_parsed += 1;
158
- self.stats.parsed_paths.push(abs.clone());
136
+ self.stats.parsed_paths.push(canonical.clone());
159
137
  if self.trace_imports {
160
138
  eprintln!(
161
- "[polycomp:import] parsed inline module #{mod_id} ({}) <- {}",
139
+ "[polycomp:import] parsed module #{mod_id} ({}) <- {}",
162
140
  lang.name(),
163
- abs.display()
141
+ canonical.display()
164
142
  );
165
143
  }
166
144
 
167
145
  self.modules.push(LoadedModule {
168
146
  id: mod_id,
169
- path: abs.clone(),
147
+ path: canonical.clone(),
170
148
  language: lang,
171
149
  ast,
172
150
  bindings,
173
151
  function_index,
174
152
  struct_index,
153
+ enum_index,
175
154
  });
176
- self.path_to_id.insert(abs, mod_id);
177
- Ok(mod_id)
155
+ self.path_to_id.insert(canonical, mod_id);
156
+ mod_id
178
157
  }
158
+
179
159
  pub fn get_module(&self, id: usize) -> &LoadedModule {
180
160
  &self.modules[id]
181
161
  }
182
162
 
183
- /// Resolves a module specifier relative to `from_module_id`, probing extensions if omitted.
184
163
  pub fn resolve_specifier_path(
185
164
  &self,
186
165
  from_module_id: usize,
@@ -198,13 +177,15 @@ impl ModuleResolver {
198
177
  }
199
178
 
200
179
  if candidate.extension().is_none() {
201
- for ext in ["rs", "py", "js", "c", "ts", "h"] {
180
+ for ext in [
181
+ "rs", "py", "ts", "mts", "js", "c", "cpp", "cc", "cs", "go", "hpp", "h",
182
+ ] {
202
183
  let with_ext = candidate.with_extension(ext);
203
184
  if with_ext.is_file() {
204
185
  return canonicalize_soft(&with_ext);
205
186
  }
206
187
  }
207
- for ext in ["rs", "py", "js", "c"] {
188
+ for ext in ["rs", "py", "ts", "js", "c", "cpp", "cs", "go"] {
208
189
  let index = candidate.join(format!("mod.{ext}"));
209
190
  if index.is_file() {
210
191
  return canonicalize_soft(&index);
@@ -226,18 +207,17 @@ impl ModuleResolver {
226
207
  ),
227
208
  )
228
209
  .with_span(span)
229
- .with_help("check the relative path or file extension (.rs, .py, .js, .c)"),
210
+ .with_help("check the relative path or file extension (.rs, .py, .ts, .js, .c, .cpp, .cs, .go)"),
230
211
  ))
231
212
  }
232
213
 
233
- /// Resolves a symbol lazily when actually invoked at runtime (or checked).
234
214
  pub fn resolve_symbol_lazy(
235
215
  &mut self,
236
216
  from_module_id: usize,
237
217
  symbol: &str,
238
218
  span: Span,
239
219
  ) -> Result<(usize, String), PolyError> {
240
- // 1. Local function inside the calling module
220
+ // 1. Direct local function
241
221
  if self.modules[from_module_id]
242
222
  .function_index
243
223
  .contains_key(symbol)
@@ -245,7 +225,19 @@ impl ModuleResolver {
245
225
  return Ok((from_module_id, symbol.to_string()));
246
226
  }
247
227
 
248
- // 2. Explicit named import (`from M import x, y as alias` / `import x, y from M`)
228
+ // 2. C++/C# `using namespace Foo;` local lookup (e.g. `apply_fee` -> `Foo::apply_fee`)
229
+ let namespaces = self.modules[from_module_id].ast.using_namespaces.clone();
230
+ for ns in namespaces {
231
+ let scoped = format!("{ns}::{symbol}");
232
+ if self.modules[from_module_id]
233
+ .function_index
234
+ .contains_key(&scoped)
235
+ {
236
+ return Ok((from_module_id, scoped));
237
+ }
238
+ }
239
+
240
+ // 3. Explicit named import
249
241
  if let Some(imp) = self.modules[from_module_id].bindings.named.get(symbol).cloned() {
250
242
  let target_path =
251
243
  self.resolve_specifier_path(from_module_id, &imp.source_specifier, imp.span)?;
@@ -253,7 +245,7 @@ impl ModuleResolver {
253
245
  return self.verify_exported_symbol(target_mod_id, &imp.original_name, span);
254
246
  }
255
247
 
256
- // 3. Wildcard / `polycomp require` fallback chain (lazy: loaded in declaration order until match)
248
+ // 4. Wildcard / `polycomp require` / `#include "..."` fallback chain
257
249
  let wildcards = self.modules[from_module_id].bindings.wildcards.clone();
258
250
  for (spec, wspan) in wildcards {
259
251
  let target_path = self.resolve_specifier_path(from_module_id, &spec, wspan)?;
@@ -265,7 +257,7 @@ impl ModuleResolver {
265
257
  Diagnostic::error(
266
258
  "E0204",
267
259
  format!(
268
- "function '{}' in '{}' is private; mark it `pub` or `export`",
260
+ "function '{}' in '{}' is private",
269
261
  symbol,
270
262
  self.modules[target_mod_id].path.display()
271
263
  ),
@@ -277,7 +269,6 @@ impl ModuleResolver {
277
269
  }
278
270
  }
279
271
 
280
- // Produce helpful suggestion from already-loaded local + named symbols
281
272
  let mut known: Vec<String> = self.modules[from_module_id]
282
273
  .function_index
283
274
  .keys()
@@ -290,11 +281,8 @@ impl ModuleResolver {
290
281
  .keys()
291
282
  .cloned(),
292
283
  );
293
- let mut diag = Diagnostic::error(
294
- "E0205",
295
- format!("undefined function '{symbol}'"),
296
- )
297
- .with_span(span);
284
+ let mut diag = Diagnostic::error("E0205", format!("undefined function '{symbol}'"))
285
+ .with_span(span);
298
286
  if let Some(sugg) = suggest_did_you_mean(symbol, known.iter().map(|s| s.as_str())) {
299
287
  diag = diag.with_help(format!("did you mean `{sugg}`?"));
300
288
  }
@@ -308,6 +296,15 @@ impl ModuleResolver {
308
296
  member_name: &str,
309
297
  span: Span,
310
298
  ) -> Result<(usize, String), PolyError> {
299
+ // Check local `Class::Method` or `namespace::func` first
300
+ let scoped = format!("{namespace_alias}::{member_name}");
301
+ if self.modules[from_module_id]
302
+ .function_index
303
+ .contains_key(&scoped)
304
+ {
305
+ return Ok((from_module_id, scoped));
306
+ }
307
+
311
308
  let Some(spec) = self.modules[from_module_id]
312
309
  .bindings
313
310
  .namespaces
@@ -316,7 +313,7 @@ impl ModuleResolver {
316
313
  else {
317
314
  return Err(PolyError::spanned(
318
315
  "E0206",
319
- format!("unknown module alias '{namespace_alias}'"),
316
+ format!("unknown module or class namespace '{namespace_alias}'"),
320
317
  span,
321
318
  ));
322
319
  };
@@ -325,6 +322,25 @@ impl ModuleResolver {
325
322
  self.verify_exported_symbol(target_mod_id, member_name, span)
326
323
  }
327
324
 
325
+ /// Resolves C# / Go / C++ entry points flexibly (`main`, `Main`, `Program::Main`, `Program::main`).
326
+ pub fn resolve_entry_fn_name(&self, mod_id: usize, requested: &str) -> Option<String> {
327
+ let m = &self.modules[mod_id];
328
+ if m.function_index.contains_key(requested) {
329
+ return Some(requested.to_string());
330
+ }
331
+ if requested == "main" {
332
+ if m.function_index.contains_key("Main") {
333
+ return Some("Main".to_string());
334
+ }
335
+ for k in m.function_index.keys() {
336
+ if k.ends_with("::Main") || k.ends_with("::main") {
337
+ return Some(k.clone());
338
+ }
339
+ }
340
+ }
341
+ None
342
+ }
343
+
328
344
  fn verify_exported_symbol(
329
345
  &self,
330
346
  target_mod_id: usize,
@@ -344,8 +360,7 @@ impl ModuleResolver {
344
360
  target.path.display()
345
361
  ),
346
362
  )
347
- .with_span(call_span)
348
- .with_help("add `pub` (Rust) or `export` (JS) to expose it"),
363
+ .with_span(call_span),
349
364
  ));
350
365
  }
351
366
  return Ok((target_mod_id, orig_name.to_string()));
@@ -368,14 +383,17 @@ impl ModuleResolver {
368
383
  Err(PolyError::single(diag))
369
384
  }
370
385
 
371
- /// Static reachability validation from entry function (still selective: never touches unused functions/imports).
372
386
  pub fn check_reachable_from_entry(
373
387
  &mut self,
374
388
  entry_mod: usize,
375
389
  entry_fn: &str,
376
390
  ) -> Result<Vec<(usize, String)>, PolyError> {
391
+ let actual_entry = self
392
+ .resolve_entry_fn_name(entry_mod, entry_fn)
393
+ .unwrap_or_else(|| entry_fn.to_string());
377
394
  let mut visited: FxHashSet<(usize, String)> = FxHashSet::default();
378
- let mut queue: Vec<(usize, String, Span)> = vec![(entry_mod, entry_fn.to_string(), Span::dummy())];
395
+ let mut queue: Vec<(usize, String, Span)> =
396
+ vec![(entry_mod, actual_entry, Span::dummy())];
379
397
  let mut order = Vec::new();
380
398
 
381
399
  while let Some((mod_id, fn_name, _sp)) = queue.pop() {
@@ -404,17 +422,39 @@ impl ModuleResolver {
404
422
  for (callee_kind, cspan) in calls {
405
423
  match callee_kind {
406
424
  StaticCall::Direct(name) => {
407
- if crate::ir::BuiltinId::from_name(&name).is_some() {
425
+ if crate::ir::BuiltinId::from_name(&name).is_some()
426
+ || matches!(
427
+ name.as_str(),
428
+ "static_cast" | "reinterpret_cast" | "const_cast" | "dynamic_cast"
429
+ )
430
+ {
408
431
  continue;
409
432
  }
410
433
  if is_local_param_or_var(&self.modules[mod_id].ast.functions[idx], &name) {
411
434
  continue;
412
435
  }
413
- let (t_mod, t_fn) = self.resolve_symbol_lazy(mod_id, &name, cspan)?;
414
- queue.push((t_mod, t_fn, cspan));
436
+ if let Some((t_mod, t_fn)) = self
437
+ .resolve_symbol_lazy(mod_id, &name, cspan)
438
+ .ok()
439
+ {
440
+ queue.push((t_mod, t_fn, cspan));
441
+ } else if !self.modules[mod_id].struct_index.contains_key(&name) {
442
+ let (t_mod, t_fn) = self.resolve_symbol_lazy(mod_id, &name, cspan)?;
443
+ queue.push((t_mod, t_fn, cspan));
444
+ }
415
445
  }
416
446
  StaticCall::Qualified(alias, member) => {
417
- if self.modules[mod_id].bindings.namespaces.contains_key(&alias) {
447
+ if matches!(
448
+ alias.as_str(),
449
+ "console" | "Console" | "Math" | "math" | "std" | "fmt" | "strings" | "re" | "regexp" | "Regex" | "String" | "Number" | "JSON"
450
+ ) {
451
+ continue;
452
+ }
453
+ if self.modules[mod_id].bindings.namespaces.contains_key(&alias)
454
+ || self.modules[mod_id]
455
+ .function_index
456
+ .contains_key(&format!("{alias}::{member}"))
457
+ {
418
458
  let (t_mod, t_fn) =
419
459
  self.resolve_member_function_lazy(mod_id, &alias, &member, cspan)?;
420
460
  queue.push((t_mod, t_fn, cspan));
@@ -481,12 +521,17 @@ fn is_local_param_or_var(f: &FunctionDecl, name: &str) -> bool {
481
521
  for s in stmts {
482
522
  match s {
483
523
  Stmt::VarDecl { name: n, .. } if n == name => return true,
524
+ Stmt::MultiVarDecl { names, .. } if names.iter().any(|n| n == name) => return true,
484
525
  Stmt::If {
526
+ init,
485
527
  then_body,
486
528
  else_body,
487
529
  ..
488
530
  } => {
489
- if has_var(then_body, name) || has_var(else_body, name) {
531
+ if init.as_ref().is_some_and(|i| has_var(&[(**i).clone()], name))
532
+ || has_var(then_body, name)
533
+ || has_var(else_body, name)
534
+ {
490
535
  return true;
491
536
  }
492
537
  }
@@ -498,6 +543,26 @@ fn is_local_param_or_var(f: &FunctionDecl, name: &str) -> bool {
498
543
  return true;
499
544
  }
500
545
  }
546
+ Stmt::Switch { cases, default, .. } => {
547
+ if cases.iter().any(|(_, b)| has_var(b, name)) || has_var(default, name) {
548
+ return true;
549
+ }
550
+ }
551
+ Stmt::TryCatch {
552
+ try_body,
553
+ catch_var,
554
+ catch_body,
555
+ finally_body,
556
+ ..
557
+ } => {
558
+ if catch_var.as_deref() == Some(name)
559
+ || has_var(try_body, name)
560
+ || has_var(catch_body, name)
561
+ || has_var(finally_body, name)
562
+ {
563
+ return true;
564
+ }
565
+ }
501
566
  _ => {}
502
567
  }
503
568
  }
@@ -509,7 +574,12 @@ fn is_local_param_or_var(f: &FunctionDecl, name: &str) -> bool {
509
574
  fn collect_static_calls_in_stmts(stmts: &[Stmt], out: &mut Vec<(StaticCall, Span)>) {
510
575
  for s in stmts {
511
576
  match s {
512
- Stmt::VarDecl { init: Some(e), .. } => collect_calls_in_expr(e, out),
577
+ Stmt::VarDecl { init: Some(e), .. }
578
+ | Stmt::MultiVarDecl { init: e, .. }
579
+ | Stmt::Throw(e, _)
580
+ | Stmt::Defer(e, _)
581
+ | Stmt::Return(Some(e), _)
582
+ | Stmt::ExprStmt(e, _) => collect_calls_in_expr(e, out),
513
583
  Stmt::Assign { target, value, .. } => {
514
584
  match target {
515
585
  AssignTarget::Field(obj, _) => collect_calls_in_expr(obj, out),
@@ -517,16 +587,20 @@ fn collect_static_calls_in_stmts(stmts: &[Stmt], out: &mut Vec<(StaticCall, Span
517
587
  collect_calls_in_expr(obj, out);
518
588
  collect_calls_in_expr(idx, out);
519
589
  }
520
- AssignTarget::Var(_) => {}
590
+ AssignTarget::Var(_) | AssignTarget::Tuple(_) => {}
521
591
  }
522
592
  collect_calls_in_expr(value, out);
523
593
  }
524
594
  Stmt::If {
595
+ init,
525
596
  cond,
526
597
  then_body,
527
598
  else_body,
528
599
  ..
529
600
  } => {
601
+ if let Some(i) = init {
602
+ collect_static_calls_in_stmts(&[(**i).clone()], out);
603
+ }
530
604
  collect_calls_in_expr(cond, out);
531
605
  collect_static_calls_in_stmts(then_body, out);
532
606
  collect_static_calls_in_stmts(else_body, out);
@@ -553,7 +627,33 @@ fn collect_static_calls_in_stmts(stmts: &[Stmt], out: &mut Vec<(StaticCall, Span
553
627
  collect_calls_in_expr(iter, out);
554
628
  collect_static_calls_in_stmts(body, out);
555
629
  }
556
- Stmt::Return(Some(e), _) | Stmt::ExprStmt(e, _) => collect_calls_in_expr(e, out),
630
+ Stmt::Switch {
631
+ expr,
632
+ cases,
633
+ default,
634
+ ..
635
+ } => {
636
+ if let Some(e) = expr {
637
+ collect_calls_in_expr(e, out);
638
+ }
639
+ for (vals, body) in cases {
640
+ for v in vals {
641
+ collect_calls_in_expr(v, out);
642
+ }
643
+ collect_static_calls_in_stmts(body, out);
644
+ }
645
+ collect_static_calls_in_stmts(default, out);
646
+ }
647
+ Stmt::TryCatch {
648
+ try_body,
649
+ catch_body,
650
+ finally_body,
651
+ ..
652
+ } => {
653
+ collect_static_calls_in_stmts(try_body, out);
654
+ collect_static_calls_in_stmts(catch_body, out);
655
+ collect_static_calls_in_stmts(finally_body, out);
656
+ }
557
657
  Stmt::Block(b, _) => collect_static_calls_in_stmts(b, out),
558
658
  _ => {}
559
659
  }
@@ -578,7 +678,14 @@ fn collect_calls_in_expr(expr: &Expr, out: &mut Vec<(StaticCall, Span)>) {
578
678
  collect_calls_in_expr(a, out);
579
679
  }
580
680
  }
581
- Expr::Array(items, _) => {
681
+ Expr::TemplateStr { parts, .. } => {
682
+ for p in parts {
683
+ if let TemplatePart::Expr { expr, .. } = p {
684
+ collect_calls_in_expr(expr, out);
685
+ }
686
+ }
687
+ }
688
+ Expr::Array(items, _) | Expr::Tuple(items, _) => {
582
689
  for i in items {
583
690
  collect_calls_in_expr(i, out);
584
691
  }
@@ -588,7 +695,9 @@ fn collect_calls_in_expr(expr: &Expr, out: &mut Vec<(StaticCall, Span)>) {
588
695
  collect_calls_in_expr(v, out);
589
696
  }
590
697
  }
591
- Expr::Unary(_, inner, _) => collect_calls_in_expr(inner, out),
698
+ Expr::Unary(_, inner, _) | Expr::Cast { expr: inner, .. } => {
699
+ collect_calls_in_expr(inner, out)
700
+ }
592
701
  Expr::Binary(_, l, r, _) => {
593
702
  collect_calls_in_expr(l, out);
594
703
  collect_calls_in_expr(r, out);