mux-lang 0.3.2

The Mux Programming Language Compiler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
//! LLVM IR code generation for the Mux compiler.
//!
//! This module generates LLVM IR from the AST and semantic analysis results.
//! It has been split into submodules for better organization:
//! - classes: Class, interface, and enum type generation
//! - constructors: Constructor generation for classes and enums
//! - expressions: Expression code generation
//! - functions: Function declaration and generation
//! - generics: Generic type instantiation
//! - memory: Memory management and RC tracking
//! - methods: Method call generation
//! - operators: Binary and logical operators
//! - runtime: Runtime function boxing/unboxing
//! - statements: Statement code generation
//! - types: Type conversion functions

use inkwell::AddressSpace;
use inkwell::builder::Builder;
use inkwell::context::Context;
use inkwell::module::Module;
use inkwell::types::BasicTypeEnum;
use inkwell::values::{FunctionValue, PointerValue};
use std::collections::HashMap;

use crate::ast::{
    AstNode, EnumVariantField, Field, FunctionNode, StatementKind, StatementNode, TraitBound,
    TypeNode,
};
use crate::semantics::{GenericContext, SemanticAnalyzer, Type, Type as ResolvedType};

type ClassTypeParamBounds = Vec<(String, Vec<(String, Vec<Type>)>)>;
type EnumVariantFieldMap = HashMap<String, HashMap<String, Vec<EnumVariantField>>>;

pub struct CodeGenerator<'a> {
    context: &'a Context,
    module: Module<'a>,
    runtime_signatures: Module<'a>,
    builder: Builder<'a>,
    analyzer: &'a mut SemanticAnalyzer,
    type_map: HashMap<String, BasicTypeEnum<'a>>,
    vtable_map: HashMap<String, PointerValue<'a>>,
    vtable_type_map: HashMap<String, inkwell::types::StructType<'a>>,
    class_copy_fns: HashMap<String, PointerValue<'a>>,
    class_destructor_fns: HashMap<String, PointerValue<'a>>,
    enum_variants: HashMap<String, Vec<String>>,
    enum_variant_fields: EnumVariantFieldMap,
    field_map: HashMap<String, HashMap<String, usize>>,
    field_types_map: HashMap<String, Vec<BasicTypeEnum<'a>>>,
    classes: HashMap<String, Vec<Field>>,
    constructors: HashMap<String, FunctionValue<'a>>,
    lambda_counter: usize,
    string_counter: usize,
    label_counter: usize,
    variables: HashMap<String, (PointerValue<'a>, BasicTypeEnum<'a>, ResolvedType)>,
    global_variables: HashMap<String, (PointerValue<'a>, BasicTypeEnum<'a>, ResolvedType)>,
    functions: HashMap<String, FunctionValue<'a>>,
    function_nodes: HashMap<String, FunctionNode>,
    current_function_name: Option<String>,
    current_function_return_type: Option<ResolvedType>,
    generic_context: Option<GenericContext>,
    context_stack: Vec<GenericContext>,
    generated_methods: HashMap<String, bool>,
    rc_scope_stack: Vec<Vec<(String, PointerValue<'a>)>>,
}

impl<'a> CodeGenerator<'a> {
    fn collect_imported_functions(&self) -> Vec<(String, FunctionNode)> {
        self.analyzer
            .all_module_asts()
            .iter()
            .flat_map(|(module_path, module_nodes)| {
                let module_name_for_mangling = Self::sanitize_module_path(module_path);
                module_nodes
                    .iter()
                    .filter_map(|node| {
                        if let AstNode::Function(func) = node {
                            Some((module_name_for_mangling.clone(), func.clone()))
                        } else {
                            None
                        }
                    })
                    .collect::<Vec<_>>()
            })
            .collect()
    }

    fn collect_non_generic_main_functions(&self, nodes: &[AstNode]) -> Vec<FunctionNode> {
        nodes
            .iter()
            .filter_map(|node| {
                if let AstNode::Function(func) = node
                    && func.type_params.is_empty()
                {
                    return Some(func.clone());
                }
                None
            })
            .collect()
    }

    fn collect_top_level_statements(&self, nodes: &[AstNode]) -> Vec<StatementNode> {
        nodes
            .iter()
            .filter_map(|node| {
                if let AstNode::Statement(stmt) = node {
                    Some(stmt.clone())
                } else {
                    None
                }
            })
            .collect()
    }

    fn collect_class_methods_to_declare(&self, nodes: &[AstNode]) -> Vec<FunctionNode> {
        let mut methods = Vec::new();
        for node in nodes {
            if let AstNode::Class {
                name,
                methods: class_methods,
                ..
            } = node
            {
                for method in class_methods {
                    let mut method_copy = method.clone();
                    method_copy.name = format!("{}.{}", name, method.name);
                    methods.push(method_copy);
                }
            }
        }
        methods
    }

    fn declare_imported_functions(
        &mut self,
        imported_functions: &[(String, FunctionNode)],
    ) -> Result<(), String> {
        for (module_name, func) in imported_functions {
            self.function_nodes.insert(func.name.clone(), func.clone());
            if func.type_params.is_empty() {
                let mangled_name = format!("{}!{}", module_name, func.name);
                self.declare_function_with_name(func, &mangled_name)?;
            }
        }
        Ok(())
    }

    fn declare_main_functions(&mut self, main_module_nodes: &[AstNode]) -> Result<(), String> {
        for node in main_module_nodes {
            if let AstNode::Function(func) = node {
                self.function_nodes.insert(func.name.clone(), func.clone());

                if func.type_params.is_empty() {
                    let llvm_name = if func.name == "main" {
                        "!user!main".to_string()
                    } else {
                        func.name.clone()
                    };
                    self.declare_function_with_name(func, &llvm_name)?;
                }
            }
        }
        Ok(())
    }

    fn declare_class_methods(&mut self, nodes: &[AstNode]) -> Result<(), String> {
        for method in self.collect_class_methods_to_declare(nodes) {
            self.declare_function(&method)?;
        }
        Ok(())
    }

    fn generate_vtables(&mut self, nodes: &[AstNode]) -> Result<(), String> {
        for node in nodes {
            if let AstNode::Class { name, .. } = node {
                let interfaces = self
                    .analyzer
                    .all_symbols()
                    .get(name)
                    .map(|sym| sym.interfaces.clone())
                    .unwrap_or_default();
                self.generate_class_vtables(name, &interfaces)?;
            }
        }
        Ok(())
    }

    fn generate_enum_and_class_constructors(&mut self, nodes: &[AstNode]) -> Result<(), String> {
        for node in nodes {
            match node {
                AstNode::Enum { name, variants, .. } => {
                    self.generate_enum_constructors(name, variants)?;
                }
                AstNode::Class { name, fields, .. } => {
                    let interfaces = self
                        .analyzer
                        .all_symbols()
                        .get(name)
                        .map(|sym| sym.interfaces.clone())
                        .unwrap_or_default();
                    // Generate the copy and destructor functions first so
                    // the constructor body can register them as runtime
                    // callbacks. The function definitions are emitted at
                    // module level, so the order only affects the lookup
                    // in `class_copy_fns` / `class_destructor_fns`.
                    self.generate_class_copy_and_destructor(name, fields)?;
                    self.generate_class_constructors(name, fields, &interfaces)?;
                }
                _ => {}
            }
        }
        Ok(())
    }

    fn declare_global_variable(
        &mut self,
        name: &str,
        llvm_type: BasicTypeEnum<'a>,
        resolved_type: ResolvedType,
    ) {
        let global = self.module.add_global(llvm_type, None, name);
        global.set_initializer(&llvm_type.const_zero());
        self.global_variables.insert(
            name.to_string(),
            (global.as_pointer_value(), llvm_type, resolved_type),
        );
    }

    fn llvm_global_type_for_resolved_type(
        &mut self,
        resolved_type: &ResolvedType,
    ) -> Result<BasicTypeEnum<'a>, String> {
        match resolved_type {
            Type::Primitive(_) => Ok(self.context.ptr_type(AddressSpace::default()).into()),
            _ => {
                let type_node = self.type_to_type_node(resolved_type);
                self.llvm_type_from_mux_type(&type_node)
            }
        }
    }

    fn declare_typed_or_const_global(
        &mut self,
        name: &str,
        type_node: &TypeNode,
    ) -> Result<(), String> {
        let resolved_type = self
            .analyzer
            .resolve_type(type_node)
            .map_err(|e| e.to_string())?;
        let llvm_type = self.llvm_global_type_for_resolved_type(&resolved_type)?;
        self.declare_global_variable(name, llvm_type, resolved_type);
        Ok(())
    }

    fn declare_auto_global(
        &mut self,
        name: &str,
        expr: &crate::ast::ExpressionNode,
    ) -> Result<(), String> {
        let resolved_type = self
            .resolve_expression_type_with_fallback(expr)
            .map_err(|e| format!("Failed to get type for {}: {}", name, e))?;
        let llvm_type = self.llvm_global_type_for_resolved_type(&resolved_type)?;
        self.declare_global_variable(name, llvm_type, resolved_type);
        Ok(())
    }

    fn declare_top_level_globals(
        &mut self,
        top_level_statements: &[StatementNode],
    ) -> Result<(), String> {
        for stmt in top_level_statements {
            match &stmt.kind {
                StatementKind::TypedDecl(name, type_, _)
                | StatementKind::ConstDecl(name, type_, _) => {
                    self.declare_typed_or_const_global(name, type_)?;
                }
                StatementKind::AutoDecl(name, _, expr) => {
                    self.declare_auto_global(name, expr)?;
                }
                _ => {}
            }
        }
        Ok(())
    }

    fn collect_module_init_data(&self) -> Vec<(String, Vec<StatementNode>)> {
        self.analyzer
            .all_module_asts()
            .iter()
            .map(|(module_path, module_nodes)| {
                let module_top_level_statements = module_nodes
                    .iter()
                    .filter_map(|node| {
                        if let AstNode::Statement(stmt) = node {
                            Some(stmt.clone())
                        } else {
                            None
                        }
                    })
                    .collect();
                (module_path.replace('/', "_"), module_top_level_statements)
            })
            .collect()
    }

    fn generate_imported_user_functions(
        &mut self,
        imported_functions: &[(String, FunctionNode)],
    ) -> Result<(), String> {
        for (module_name_mangled, func) in imported_functions {
            if func.type_params.is_empty() {
                let mangled_name = format!("{}!{}", module_name_mangled, func.name);
                self.generate_function_with_llvm_name(func, &mangled_name)?;
            }
        }
        Ok(())
    }

    fn generate_main_user_functions(
        &mut self,
        user_functions: &[FunctionNode],
    ) -> Result<(), String> {
        for func in user_functions {
            if func.name == "main" {
                self.generate_function_with_llvm_name(func, "!user!main")?;
            } else {
                self.generate_function(func)?;
            }
        }
        Ok(())
    }

    fn generate_class_methods_for_node(
        &mut self,
        name: &str,
        methods: &[FunctionNode],
        type_params: &[(String, Vec<TraitBound>)],
    ) -> Result<(), String> {
        if !type_params.is_empty() {
            let bounds: ClassTypeParamBounds = type_params
                .iter()
                .map(|(p, b)| {
                    (
                        p.clone(),
                        b.iter().map(|tb| (tb.name.clone(), Vec::new())).collect(),
                    )
                })
                .collect();
            self.analyzer.set_class_type_params(bounds);
        }

        for method in methods {
            let prefixed_name = format!("{}.{}", name, method.name);
            if type_params.is_empty() {
                let mut method_copy = method.clone();
                method_copy.name = prefixed_name;
                self.generate_function(&method_copy)?;
                continue;
            }

            let class_type_param_names: Vec<&str> =
                type_params.iter().map(|(p, _)| p.as_str()).collect();
            if method.is_common
                && method.type_params.is_empty()
                && !Self::method_uses_type_params(method, &class_type_param_names)
            {
                let mut method_copy = method.clone();
                method_copy.name = prefixed_name;
                self.generate_function(&method_copy)?;
            }
        }

        if !type_params.is_empty() {
            self.analyzer.clear_class_type_params();
        }

        Ok(())
    }

    fn generate_class_methods_for_all_nodes(&mut self, nodes: &[AstNode]) -> Result<(), String> {
        for node in nodes {
            if let AstNode::Class {
                name,
                methods,
                type_params,
                ..
            } = node
            {
                self.generate_class_methods_for_node(name, methods, type_params)?;
            }
        }
        Ok(())
    }

    // Helper function to sanitize module paths for use in LLVM identifiers
    fn sanitize_module_path(module_path: &str) -> String {
        module_path.replace(['.', '/'], "_")
    }

    // small helpers for runtime declarations were moved to runtime.rs

    pub fn new(context: &'a Context, analyzer: &'a mut SemanticAnalyzer) -> Self {
        let module = context.create_module("mux_module");
        let runtime_signatures = context.create_module("mux_runtime_signatures");
        let builder = context.create_builder();

        Self::declare_runtime_functions(&runtime_signatures, context);

        let mut type_map = HashMap::new();
        let mut enum_variants = HashMap::new();

        let i32_type = context.i32_type();
        let i8_ptr = context.ptr_type(AddressSpace::default());
        let struct_type = context.struct_type(&[i32_type.into(), i8_ptr.into()], false);
        type_map.insert("optional".to_string(), struct_type.into());
        type_map.insert("result".to_string(), struct_type.into());

        use std::collections::BTreeMap;
        let mut ordered_variants = BTreeMap::new();
        ordered_variants.insert(
            "optional".to_string(),
            vec!["some".to_string(), "none".to_string()],
        );
        ordered_variants.insert(
            "result".to_string(),
            vec!["ok".to_string(), "err".to_string()],
        );

        for (enum_name, variants) in ordered_variants {
            enum_variants.insert(enum_name, variants);
        }

        for (name, symbol) in analyzer.all_symbols() {
            if symbol.kind == crate::semantics::SymbolKind::Enum {
                let mut variants = vec![];
                for method_name in symbol.methods.keys() {
                    variants.push(method_name.clone());
                }
                enum_variants.insert(name.clone(), variants);
            }
        }

        Self {
            context,
            module,
            runtime_signatures,
            builder,
            analyzer,
            type_map,
            vtable_map: HashMap::new(),
            vtable_type_map: HashMap::new(),
            class_copy_fns: HashMap::new(),
            class_destructor_fns: HashMap::new(),
            enum_variants,
            enum_variant_fields: HashMap::new(),
            field_map: HashMap::new(),
            field_types_map: HashMap::new(),
            classes: HashMap::new(),
            constructors: HashMap::new(),
            lambda_counter: 0,
            string_counter: 0,
            label_counter: 0,
            variables: HashMap::new(),
            global_variables: HashMap::new(),
            functions: HashMap::new(),
            function_nodes: HashMap::new(),
            current_function_name: None,
            current_function_return_type: None,
            generic_context: None,
            context_stack: Vec::new(),
            generated_methods: HashMap::new(),
            rc_scope_stack: Vec::new(),
        }
    }

    // Runtime declarations are implemented in the `runtime` submodule to keep
    // the code generator file smaller and data-driven. The real implementation
    // is an associated function on `CodeGenerator` defined in
    // `codegen/runtime.rs`. Calling `Self::declare_runtime_functions` here will
    // resolve to that implementation after the file is compiled.
    //
    // Note: We intentionally leave this method as an empty wrapper by relying on
    // the method provided in the `runtime` module; keeping the call site in
    // `new` unchanged avoids changing call sites elsewhere.
    // runtime declarations moved to `codegen::runtime` impl for CodeGenerator
    /// Create an alloca instruction in the entry block of the current function.
    /// This ensures proper LLVM dominance - allocas must be in the entry block
    /// to be used throughout the function, including in match arms and loops.
    fn create_entry_block_alloca(
        &self,
        function: FunctionValue<'a>,
        ty: BasicTypeEnum<'a>,
        name: &str,
    ) -> Result<PointerValue<'a>, String> {
        let builder = self.context.create_builder();

        let entry = function
            .get_first_basic_block()
            .expect("function should have entry block after creation");
        match entry.get_first_instruction() {
            Some(first_instr) => builder.position_before(&first_instr),
            None => builder.position_at_end(entry),
        }

        let alloca = builder.build_alloca(ty, name).map_err(|e| e.to_string())?;

        // Pointer locals can be hoisted to the entry block even when their
        // declaration is inside conditional control flow. Initialize them to
        // null so cleanup paths never decrement uninitialized memory.
        if matches!(ty, BasicTypeEnum::PointerType(_)) {
            let null_ptr = self.context.ptr_type(AddressSpace::default()).const_null();
            builder
                .build_store(alloca, null_ptr)
                .map_err(|e| e.to_string())?;
        }

        Ok(alloca)
    }

    /// Create an alloca in the entry block of the current function (inferred from builder position).
    /// If not in a function context, creates alloca at current position.
    fn create_entry_alloca(
        &self,
        ty: BasicTypeEnum<'a>,
        name: &str,
    ) -> Result<PointerValue<'a>, String> {
        // try to get the current function from the builder's insert block
        if let Some(block) = self.builder.get_insert_block()
            && let Some(function) = block.get_parent()
        {
            return self.create_entry_block_alloca(function, ty, name);
        }

        // fallback: create alloca at current position (shouldn't happen in normal code)
        self.builder
            .build_alloca(ty, name)
            .map_err(|e| e.to_string())
    }

    pub fn generate(&mut self, nodes: &[AstNode]) -> Result<(), String> {
        let main_module_nodes = nodes;
        let mut all_nodes = Vec::new();
        for module_nodes in self.analyzer.all_module_asts().values() {
            all_nodes.extend(module_nodes.clone());
        }
        all_nodes.extend(nodes.to_vec());
        let nodes = &all_nodes;

        self.generate_user_defined_types(nodes)?;

        let imported_functions = self.collect_imported_functions();

        self.declare_imported_functions(&imported_functions)?;
        self.declare_main_functions(main_module_nodes)?;
        self.declare_class_methods(nodes)?;
        self.generate_vtables(nodes)?;
        self.generate_enum_and_class_constructors(nodes)?;

        let top_level_statements = self.collect_top_level_statements(nodes);
        let user_functions = self.collect_non_generic_main_functions(main_module_nodes);
        let main_top_level_statements = self.collect_top_level_statements(main_module_nodes);

        self.declare_top_level_globals(&top_level_statements)?;

        let modules_data = self.collect_module_init_data();

        for (module_name, module_top_level_statements) in modules_data {
            self.generate_module_init(&module_top_level_statements, &module_name)?;
        }

        let module_name = self.get_module_name(main_module_nodes);
        self.generate_module_init(&main_top_level_statements, &module_name)?;
        self.generate_main_function(&module_name)?;

        self.generate_imported_user_functions(&imported_functions)?;
        self.generate_main_user_functions(&user_functions)?;
        self.generate_class_methods_for_all_nodes(nodes)?;

        Ok(())
    }

    pub fn emit_ir_to_file(&self, filename: &str) -> Result<(), String> {
        self.module
            .verify()
            .map_err(|e| format!("LLVM module verification failed: {}", e.to_string()))?;
        self.module
            .print_to_file(filename)
            .map_err(|e| format!("Failed to write IR: {}", e))
    }
}

// Re-export all submodules
mod classes;
mod constructors;
mod expressions;
mod functions;
mod generics;
mod memory;
mod methods;
mod operators;
mod runtime;
mod statements;
mod types;