1pub mod cabi;
18pub mod class;
19pub mod closure;
20pub mod decl;
21pub mod expr;
22pub mod helpers;
23pub mod stmt;
24
25use std::collections::HashSet;
26
27use oxc_ast::ast::*;
28
29use crate::infer::TypeCheckResult;
30use crate::types::{ClosureManager, JSDocData, ZigType};
31use crate::zigir::builtins::BuiltinModule;
32use crate::zigir::ident::NameMangler;
33use crate::zigir::source_span::{DiagnosticLevel, IrDiagnostic};
34use crate::zigir::types::{IrDecl, IrImport, IrModule, IrTypedef, IrTypedefField};
35
36use helpers::FnContext;
37
38pub struct Lowerer {
49 pub(super) type_info: TypeCheckResult,
52 pub(super) jsdoc_data: JSDocData,
54 pub(super) async_host_fns: HashSet<String>,
56 pub(super) exported_functions: Option<HashSet<String>>,
58 pub(super) source: String,
60
61 pub(super) name_mangler: NameMangler,
63
64 pub(super) fn_ctx: Option<FnContext>,
66
67 pub(super) closure_mgr: ClosureManager,
69
70 pub(super) class_names: HashSet<String>,
73
74 pub(super) pending_expr_fns: Vec<IrDecl>,
78
79 pub(super) pending_arrow_structs: Vec<crate::zigir::types::IrClosureStruct>,
82
83 pub(super) pending_label: Option<String>,
86
87 pub(super) current_class: Option<String>,
89
90 pub(super) in_expr_stmt: bool,
93
94 pub(super) diagnostics: Vec<IrDiagnostic>,
96}
97
98impl Lowerer {
103 pub fn new(
105 type_info: TypeCheckResult,
106 jsdoc_data: JSDocData,
107 exported_functions: Option<HashSet<String>>,
108 async_host_fns: HashSet<String>,
109 source: String,
110 ) -> Self {
111 Self {
112 type_info,
113 jsdoc_data,
114 async_host_fns,
115 exported_functions,
116 source,
117 name_mangler: NameMangler::new(),
118 fn_ctx: None,
119 closure_mgr: ClosureManager::new(),
120 class_names: HashSet::new(),
121 pending_expr_fns: Vec::new(),
122 pending_arrow_structs: Vec::new(),
123 pending_label: None,
124 current_class: None,
125 in_expr_stmt: false,
126 diagnostics: Vec::new(),
127 }
128 }
129}
130
131impl Lowerer {
136 pub fn lower(&mut self, program: &Program) -> IrModule {
138 let module_name = String::from("main"); let imports = self.infer_imports();
142
143 let typedefs = self.lower_typedefs();
145
146 let mut declarations = Vec::new();
149 for stmt in &program.body {
150 let mut stmt_decls = self.lower_toplevel(stmt);
151 declarations.append(&mut stmt_decls);
152 }
153
154 let mut closure_structs = self.lower_closure_structs();
156 closure_structs.append(&mut self.pending_arrow_structs);
158
159 let cabi_exports = self.build_cabi_exports(&declarations);
161
162 IrModule {
163 name: module_name,
164 imports,
165 typedefs,
166 closure_structs,
167 declarations,
168 diagnostics: std::mem::take(&mut self.diagnostics),
169 cabi_exports,
170 }
171 }
172}
173
174impl Lowerer {
179 fn infer_imports(&self) -> Vec<IrImport> {
181 let mut imports = Vec::new();
182
183 let mut needs_std = false;
185 let mut needs_js_allocator = false;
186 let mut needs_js_runtime = false;
187 let mut needs_jsany = false;
188 let mut runtime_modules: std::collections::BTreeSet<BuiltinModule> =
189 std::collections::BTreeSet::new();
190
191 if !self.jsdoc_data.typedefs.is_empty() {
193 needs_std = true;
194 needs_js_allocator = true;
195 }
196
197 if !self.type_info.has_json_parse_types.is_empty() {
199 needs_std = true;
200 runtime_modules.insert(BuiltinModule::JsJson);
201 }
202
203 if !self.async_host_fns.is_empty() {
205 needs_js_allocator = true;
206 }
207
208 let mut all_types: Vec<&ZigType> = Vec::new();
210
211 for ty in self.type_info.var_types.values() {
212 all_types.push(ty);
213 }
214 for ty in self.type_info.fn_return_types.values() {
215 all_types.push(ty);
216 }
217 for params in self.type_info.fn_param_types.values() {
218 for (_name, ty) in params {
219 all_types.push(ty);
220 }
221 }
222 for fields in self.type_info.class_field_types.values() {
223 for ty in fields.values() {
224 all_types.push(ty);
225 }
226 }
227 for inner in self.type_info.array_element_types.values() {
228 all_types.push(inner);
229 }
230
231 for ty in &all_types {
232 self.zigtype_needs_imports(
233 ty,
234 &mut needs_std,
235 &mut needs_js_allocator,
236 &mut needs_js_runtime,
237 &mut needs_jsany,
238 &mut runtime_modules,
239 );
240 }
241
242 if needs_std {
246 let mut std_items: Vec<(String, String)> = Vec::new();
247
248 if self
249 .type_info
250 .var_types
251 .values()
252 .any(|t| matches!(t, ZigType::ArrayList(_)))
253 {
254 std_items.push(("ArrayList".to_string(), "ArrayList".to_string()));
255 }
256
257 imports.push(IrImport {
258 module_name: "std".to_string(),
259 items: std_items,
260 });
261 }
262
263 if needs_js_allocator {
265 imports.push(IrImport {
266 module_name: "js_runtime/js_allocator.zig".to_string(),
267 items: vec![("js_allocator".to_string(), "js_allocator".to_string())],
268 });
269 }
270
271 if needs_js_runtime {
273 imports.push(IrImport {
274 module_name: "js_runtime/js_runtime.zig".to_string(),
275 items: vec![("js_runtime".to_string(), "js_runtime".to_string())],
276 });
277 }
278
279 for module in &runtime_modules {
281 let module_path = module.module_path().to_string();
282
283 match module {
284 BuiltinModule::JsMath => {
285 }
287 BuiltinModule::JsConsole => {
288 imports.push(IrImport {
289 module_name: format!("js_runtime/{}.zig", module_path),
290 items: vec![(module_path.clone(), module_path.clone())],
291 });
292 }
293 BuiltinModule::JsSymbol => {
294 imports.push(IrImport {
295 module_name: format!("js_runtime/{}.zig", module_path),
296 items: vec![
297 (module_path.clone(), module_path.clone()),
298 ("JsSymbol".to_string(), "JsSymbol".to_string()),
299 ],
300 });
301 }
302 BuiltinModule::JsBigInt => {
303 imports.push(IrImport {
304 module_name: format!("js_runtime/{}.zig", module_path),
305 items: vec![(module_path.clone(), module_path.clone())],
306 });
307 }
308 BuiltinModule::JsTypedArray => {
309 imports.push(IrImport {
310 module_name: "js_runtime/js_runtime.zig".to_string(),
311 items: vec![("js_runtime".to_string(), "js_runtime".to_string())],
312 });
313 }
314 _ => {
315 imports.push(IrImport {
316 module_name: format!("js_runtime/{}.zig", module_path),
317 items: vec![(module_path.clone(), module_path.clone())],
318 });
319 }
320 }
321 }
322
323 if needs_jsany {
325 imports.push(IrImport {
326 module_name: "js_runtime/jsany.zig".to_string(),
327 items: vec![("JsAny".to_string(), "JsAny".to_string())],
328 });
329 }
330
331 imports = Self::deduplicate_imports(imports);
333
334 imports
335 }
336
337 fn deduplicate_imports(imports: Vec<IrImport>) -> Vec<IrImport> {
339 let mut map: std::collections::BTreeMap<String, Vec<(String, String)>> =
340 std::collections::BTreeMap::new();
341 for imp in imports {
342 let entry = map.entry(imp.module_name).or_default();
343 for item in imp.items {
344 if !entry.contains(&item) {
345 entry.push(item);
346 }
347 }
348 }
349 map.into_iter()
350 .map(|(module_name, items)| IrImport { module_name, items })
351 .collect()
352 }
353
354 fn zigtype_needs_imports(
356 &self,
357 ty: &ZigType,
358 needs_std: &mut bool,
359 needs_js_allocator: &mut bool,
360 needs_js_runtime: &mut bool,
361 needs_jsany: &mut bool,
362 runtime_modules: &mut std::collections::BTreeSet<BuiltinModule>,
363 ) {
364 match ty {
365 ZigType::ArrayList(_) => {
366 *needs_std = true;
367 }
368 ZigType::JsAny => {
369 *needs_jsany = true;
370 *needs_js_runtime = true;
371 }
372 ZigType::JsSymbol => {
373 runtime_modules.insert(BuiltinModule::JsSymbol);
374 }
375 ZigType::BigInt => {
376 runtime_modules.insert(BuiltinModule::JsBigInt);
377 *needs_js_allocator = true;
378 }
379 ZigType::JsError => {
380 runtime_modules.insert(BuiltinModule::JsError);
381 *needs_js_allocator = true;
382 }
383 ZigType::NamedStruct(name) => match name.as_str() {
384 "Map" | "Set" => {
385 runtime_modules.insert(BuiltinModule::JsCollections);
386 *needs_js_allocator = true;
387 }
388 "Date" | "JsDate" => {
389 runtime_modules.insert(BuiltinModule::JsDate);
390 *needs_js_allocator = true;
391 }
392 _ => {}
393 },
394 ZigType::Struct(fields) => {
395 for (_, field_ty) in fields {
396 self.zigtype_needs_imports(
397 field_ty,
398 needs_std,
399 needs_js_allocator,
400 needs_js_runtime,
401 needs_jsany,
402 runtime_modules,
403 );
404 }
405 }
406 ZigType::Void
407 | ZigType::I64
408 | ZigType::F64
409 | ZigType::Bool
410 | ZigType::Str
411 | ZigType::Anytype
412 | ZigType::AnytypeReturn => {}
413 }
414 }
415}
416
417impl Lowerer {
422 fn lower_typedefs(&self) -> Vec<IrTypedef> {
424 let mut typedefs = Vec::new();
425 for (name, td) in &self.jsdoc_data.typedefs {
426 let fields: Vec<IrTypedefField> = td
427 .fields
428 .iter()
429 .map(|f| {
430 let zig_type_str =
431 crate::jsdoc::jsdoc_type_to_zig(&f.ty, &self.jsdoc_data.typedefs);
432 IrTypedefField {
433 name: f.name.clone(),
434 zig_type: if f.optional {
435 format!("?{}", zig_type_str)
436 } else {
437 zig_type_str
438 },
439 optional: f.optional,
440 }
441 })
442 .collect();
443
444 let is_opaque = fields.is_empty();
445 typedefs.push(IrTypedef {
446 name: name.clone(),
447 fields,
448 is_opaque,
449 has_to_json: !is_opaque,
450 });
451 }
452 typedefs
453 }
454}
455
456impl Lowerer {
461 fn lower_toplevel(&mut self, stmt: &Statement) -> Vec<IrDecl> {
463 let mut decls = std::mem::take(&mut self.pending_expr_fns);
465
466 match stmt {
467 Statement::VariableDeclaration(vd) => {
468 for decl in &vd.declarations {
469 decls.push(self.lower_var_decl(decl, vd.kind.is_const()));
470 }
471 }
472 Statement::ClassDeclaration(cd) => {
473 if let Some(ir_class) = self.lower_class_decl(cd) {
474 self.class_names.insert(ir_class.name.js_name.clone());
475 decls.push(IrDecl::Class(ir_class));
476 }
477 }
478 Statement::FunctionDeclaration(fd) => {
479 let is_export = self.is_export_fn(fd.id.as_ref().map(|id| id.name.as_str()));
480 if let Some(ir_fn) = self.lower_fn_decl(fd, is_export) {
481 decls.push(IrDecl::Fn(ir_fn));
482 }
483 }
484 Statement::ExportNamedDeclaration(export_decl) => {
485 if let Some(decl) = &export_decl.declaration {
486 match decl {
487 Declaration::FunctionDeclaration(fd) => {
488 let is_export =
489 self.is_export_fn(fd.id.as_ref().map(|id| id.name.as_str()));
490 if let Some(ir_fn) = self.lower_fn_decl(fd, is_export) {
491 decls.push(IrDecl::Fn(ir_fn));
492 }
493 }
494 Declaration::VariableDeclaration(vd) => {
495 for decl in &vd.declarations {
496 decls.push(self.lower_var_decl(decl, vd.kind.is_const()));
497 }
498 }
499 _ => { }
500 }
501 }
502 }
503 Statement::WithStatement(ws) => {
504 let span = self.span_to_source_span(ws.span);
505 self.diagnostics.push(IrDiagnostic {
506 level: DiagnosticLevel::Error,
507 span: Some(span),
508 message: "with statement is not supported and deprecated in strict mode. Use explicit property access instead.".to_string(),
509 });
510 }
511 _ => { }
512 }
513
514 let pending = std::mem::take(&mut self.pending_expr_fns);
517 decls.extend(pending);
518
519 decls
520 }
521}
522
523#[cfg(test)]
528mod tests {
529 use super::*;
530 use crate::types::JSDocData;
531 use std::collections::HashMap;
532
533 fn empty_type_info() -> TypeCheckResult {
534 TypeCheckResult {
535 var_types: HashMap::new(),
536 array_element_types: HashMap::new(),
537 fn_return_types: HashMap::new(),
538 fn_param_types: HashMap::new(),
539 mutated_vars: HashSet::new(),
540 set_vars: HashSet::new(),
541 used_names: HashSet::new(),
542 has_json_parse_types: HashSet::new(),
543 errors: Vec::new(),
544 is_async: HashMap::new(),
545 class_field_types: HashMap::new(),
546 }
547 }
548
549 #[test]
550 fn test_lowerer_new() {
551 let type_info = empty_type_info();
552 let jsdoc_data = JSDocData {
553 typedefs: HashMap::new(),
554 type_annotations: HashMap::new(),
555 return_types: HashMap::new(),
556 param_types: HashMap::new(),
557 };
558 let lowerer = Lowerer::new(
559 type_info,
560 jsdoc_data,
561 None,
562 HashSet::new(),
563 "let x = 1;".to_string(),
564 );
565 assert!(lowerer.fn_ctx.is_none());
566 assert!(lowerer.class_names.is_empty());
567 assert!(lowerer.diagnostics.is_empty());
568 }
569
570 #[test]
571 fn test_lowerer_empty_program() {
572 let type_info = empty_type_info();
573 let jsdoc_data = JSDocData {
574 typedefs: HashMap::new(),
575 type_annotations: HashMap::new(),
576 return_types: HashMap::new(),
577 param_types: HashMap::new(),
578 };
579 let mut lowerer = Lowerer::new(type_info, jsdoc_data, None, HashSet::new(), String::new());
580
581 let js = "";
583 let allocator = oxc_allocator::Allocator::default();
584 let source_type = oxc_span::SourceType::default();
585 let parser = oxc_parser::Parser::new(&allocator, js, source_type);
586 let result = parser.parse();
587 let module = lowerer.lower(&result.program);
588
589 assert_eq!(module.name, "main");
590 assert!(module.declarations.is_empty());
591 assert!(module.closure_structs.is_empty());
592 assert!(module.diagnostics.is_empty());
593 }
594
595 #[test]
596 fn test_fn_context_enter_exit() {
597 let type_info = empty_type_info();
598 let jsdoc_data = JSDocData {
599 typedefs: HashMap::new(),
600 type_annotations: HashMap::new(),
601 return_types: HashMap::new(),
602 param_types: HashMap::new(),
603 };
604 let mut lowerer = Lowerer::new(type_info, jsdoc_data, None, HashSet::new(), String::new());
605
606 let saved = lowerer.enter_fn("foo", true, Some(ZigType::I64));
608 assert!(saved.is_none()); assert!(lowerer.fn_ctx.is_some());
610
611 let ctx = lowerer.fn_ctx().unwrap();
612 assert_eq!(ctx.name, "foo");
613 assert!(ctx.is_export);
614
615 let returned = lowerer.exit_fn(None);
617 assert_eq!(returned.name, "foo");
618 assert!(lowerer.fn_ctx.is_none());
619 }
620
621 #[test]
622 fn test_fn_context_nesting() {
623 let type_info = empty_type_info();
624 let jsdoc_data = JSDocData {
625 typedefs: HashMap::new(),
626 type_annotations: HashMap::new(),
627 return_types: HashMap::new(),
628 param_types: HashMap::new(),
629 };
630 let mut lowerer = Lowerer::new(type_info, jsdoc_data, None, HashSet::new(), String::new());
631
632 let saved_outer = lowerer.enter_fn("outer", true, Some(ZigType::Void));
634 assert!(saved_outer.is_none());
635
636 let saved_inner = lowerer.enter_fn("inner", false, Some(ZigType::I64));
638 assert!(saved_inner.is_some()); assert_eq!(saved_inner.as_ref().unwrap().name, "outer");
640
641 let inner_ctx = lowerer.exit_fn(saved_inner);
643 assert_eq!(inner_ctx.name, "inner");
644
645 assert!(lowerer.fn_ctx.is_some());
647 assert_eq!(lowerer.fn_ctx().unwrap().name, "outer");
648
649 let outer_ctx = lowerer.exit_fn(saved_outer);
651 assert_eq!(outer_ctx.name, "outer");
652 assert!(lowerer.fn_ctx.is_none());
653 }
654
655 #[test]
656 fn test_is_export_fn() {
657 let type_info = empty_type_info();
658 let jsdoc_data = JSDocData {
659 typedefs: HashMap::new(),
660 type_annotations: HashMap::new(),
661 return_types: HashMap::new(),
662 param_types: HashMap::new(),
663 };
664 let mut exported = HashSet::new();
665 exported.insert("greet".to_string());
666
667 let lowerer = Lowerer::new(
668 type_info,
669 jsdoc_data,
670 Some(exported),
671 HashSet::new(),
672 String::new(),
673 );
674
675 assert!(lowerer.is_export_fn(Some("greet")));
676 assert!(!lowerer.is_export_fn(Some("helper")));
677 assert!(!lowerer.is_export_fn(None));
678 }
679
680 fn make_jsdoc_data() -> JSDocData {
683 JSDocData {
684 typedefs: HashMap::new(),
685 type_annotations: HashMap::new(),
686 return_types: HashMap::new(),
687 param_types: HashMap::new(),
688 }
689 }
690
691 #[test]
692 fn test_infer_imports_empty() {
693 let lowerer = Lowerer::new(
694 empty_type_info(),
695 make_jsdoc_data(),
696 None,
697 HashSet::new(),
698 String::new(),
699 );
700 let imports = lowerer.infer_imports();
701 assert!(
702 imports.is_empty(),
703 "empty program should have no imports, got {:?}",
704 imports
705 );
706 }
707
708 #[test]
709 fn test_infer_imports_typedef() {
710 let mut td = HashMap::new();
711 td.insert(
712 "User".to_string(),
713 crate::jsdoc::TypedefDef {
714 name: "User".to_string(),
715 fields: vec![crate::jsdoc::TypedefField {
716 name: "name".to_string(),
717 ty: "string".to_string(),
718 optional: false,
719 }],
720 },
721 );
722 let jsdoc_data = JSDocData {
723 typedefs: td,
724 type_annotations: HashMap::new(),
725 return_types: HashMap::new(),
726 param_types: HashMap::new(),
727 };
728 let lowerer = Lowerer::new(
729 empty_type_info(),
730 jsdoc_data,
731 None,
732 HashSet::new(),
733 String::new(),
734 );
735 let imports = lowerer.infer_imports();
736 let module_names: Vec<&str> = imports.iter().map(|i| i.module_name.as_str()).collect();
737 assert!(
738 module_names.contains(&"std"),
739 "typedef should require std import, got {:?}",
740 module_names
741 );
742 assert!(
743 module_names.contains(&"js_runtime/js_allocator.zig"),
744 "typedef should require js_allocator, got {:?}",
745 module_names
746 );
747 }
748
749 #[test]
750 fn test_infer_imports_jsany() {
751 let mut var_types = HashMap::new();
752 var_types.insert("data".to_string(), ZigType::JsAny);
753 let type_info = TypeCheckResult {
754 var_types,
755 array_element_types: HashMap::new(),
756 fn_return_types: HashMap::new(),
757 fn_param_types: HashMap::new(),
758 mutated_vars: HashSet::new(),
759 set_vars: HashSet::new(),
760 used_names: HashSet::new(),
761 has_json_parse_types: HashSet::new(),
762 errors: Vec::new(),
763 is_async: HashMap::new(),
764 class_field_types: HashMap::new(),
765 };
766 let lowerer = Lowerer::new(
767 type_info,
768 make_jsdoc_data(),
769 None,
770 HashSet::new(),
771 String::new(),
772 );
773 let imports = lowerer.infer_imports();
774 let module_names: Vec<&str> = imports.iter().map(|i| i.module_name.as_str()).collect();
775 assert!(
776 module_names.contains(&"js_runtime/jsany.zig"),
777 "JsAny should require jsany.zig, got {:?}",
778 module_names
779 );
780 assert!(
781 module_names.contains(&"js_runtime/js_runtime.zig"),
782 "JsAny should require js_runtime, got {:?}",
783 module_names
784 );
785 }
786
787 #[test]
788 fn test_infer_imports_date_and_map() {
789 let mut var_types = HashMap::new();
790 var_types.insert("d".to_string(), ZigType::NamedStruct("Date".to_string()));
791 var_types.insert("m".to_string(), ZigType::NamedStruct("Map".to_string()));
792 let type_info = TypeCheckResult {
793 var_types,
794 array_element_types: HashMap::new(),
795 fn_return_types: HashMap::new(),
796 fn_param_types: HashMap::new(),
797 mutated_vars: HashSet::new(),
798 set_vars: HashSet::new(),
799 used_names: HashSet::new(),
800 has_json_parse_types: HashSet::new(),
801 errors: Vec::new(),
802 is_async: HashMap::new(),
803 class_field_types: HashMap::new(),
804 };
805 let lowerer = Lowerer::new(
806 type_info,
807 make_jsdoc_data(),
808 None,
809 HashSet::new(),
810 String::new(),
811 );
812 let imports = lowerer.infer_imports();
813 let module_names: Vec<&str> = imports.iter().map(|i| i.module_name.as_str()).collect();
814 assert!(
815 module_names.contains(&"js_runtime/js_date.zig"),
816 "Date should require js_date, got {:?}",
817 module_names
818 );
819 assert!(
820 module_names.contains(&"js_runtime/js_collections.zig"),
821 "Map should require js_collections, got {:?}",
822 module_names
823 );
824 assert!(
825 module_names.contains(&"js_runtime/js_allocator.zig"),
826 "Date/Map should require js_allocator, got {:?}",
827 module_names
828 );
829 }
830
831 #[test]
832 fn test_infer_imports_deduplication() {
833 let mut var_types = HashMap::new();
834 var_types.insert("a".to_string(), ZigType::JsAny);
835 var_types.insert("b".to_string(), ZigType::JsSymbol);
836 let type_info = TypeCheckResult {
837 var_types,
838 array_element_types: HashMap::new(),
839 fn_return_types: HashMap::new(),
840 fn_param_types: HashMap::new(),
841 mutated_vars: HashSet::new(),
842 set_vars: HashSet::new(),
843 used_names: HashSet::new(),
844 has_json_parse_types: HashSet::new(),
845 errors: Vec::new(),
846 is_async: HashMap::new(),
847 class_field_types: HashMap::new(),
848 };
849 let lowerer = Lowerer::new(
850 type_info,
851 make_jsdoc_data(),
852 None,
853 HashSet::new(),
854 String::new(),
855 );
856 let imports = lowerer.infer_imports();
857 let js_runtime_count = imports
858 .iter()
859 .filter(|i| i.module_name == "js_runtime/js_runtime.zig")
860 .count();
861 assert_eq!(
862 js_runtime_count, 1,
863 "js_runtime should appear exactly once, got {} times",
864 js_runtime_count
865 );
866 }
867}