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
//! Function declaration and generation for the code generator.
//!
//! This module handles:
//! - Function declaration with proper type signatures
//! - Function generation with parameter handling
//! - Module initialization functions
//! - Main function generation

use inkwell::AddressSpace;
use inkwell::types::BasicMetadataTypeEnum;
use inkwell::types::{BasicType, BasicTypeEnum};
use inkwell::values::FunctionValue;

use crate::ast::{AstNode, FunctionNode, PrimitiveType, StatementNode, TypeKind};
use crate::semantics::Type;

use super::CodeGenerator;

impl<'a> CodeGenerator<'a> {
    fn resolve_base_class_name_for_method(method_name: &str) -> &str {
        let class_name = method_name
            .split('.')
            .next()
            .or_else(|| method_name.split('$').next())
            .expect("class method name should contain '.' or '$'");
        class_name.split('$').next().unwrap_or(class_name)
    }

    fn resolve_self_type_for_method(&self, base_class_name: &str) -> Type {
        if let Some(ref context) = self.generic_context
            && let Some(class_symbol) = self.analyzer.symbol_table().lookup(base_class_name)
        {
            let type_args: Vec<Type> = class_symbol
                .type_params
                .iter()
                .filter_map(|(param_name, _bounds)| context.type_params.get(param_name).cloned())
                .collect();
            return Type::Named(base_class_name.to_string(), type_args);
        }

        Type::Named(base_class_name.to_string(), vec![])
    }

    fn setup_method_self_parameter(
        &mut self,
        func: &FunctionNode,
        function: FunctionValue<'a>,
        param_index: &mut u32,
    ) -> Result<(), String> {
        let base_class_name = Self::resolve_base_class_name_for_method(&func.name);
        let class_type = self
            .type_map
            .get(base_class_name)
            .expect("class type should be in type_map after type generation");
        let arg = function
            .get_nth_param(*param_index)
            .expect("self parameter should exist for class methods");
        *param_index += 1;

        let ptr_type = self.context.ptr_type(AddressSpace::default());
        let alloca = self
            .builder
            .build_alloca(ptr_type, "self")
            .map_err(|e| e.to_string())?;
        self.builder
            .build_store(alloca, arg)
            .map_err(|e| e.to_string())?;

        let self_type = self.resolve_self_type_for_method(base_class_name);
        self.variables
            .insert("self".to_string(), (alloca, *class_type, self_type.clone()));
        self.analyzer.current_self_type = Some(self_type);
        Ok(())
    }

    fn is_enum_type(&self, resolved_type: &Type) -> bool {
        matches!(resolved_type, Type::Named(type_name, _) if self
            .analyzer
            .symbol_table()
            .lookup(type_name)
            .map(|s| s.kind == crate::semantics::SymbolKind::Enum)
            .unwrap_or(false))
    }

    fn store_enum_parameter(
        &mut self,
        param_name: &str,
        arg: inkwell::values::BasicValueEnum<'a>,
        resolved_type: Type,
    ) -> Result<(), String> {
        let struct_type = arg.get_type();
        let alloca = self
            .builder
            .build_alloca(struct_type, param_name)
            .map_err(|e| e.to_string())?;
        self.builder
            .build_store(alloca, arg)
            .map_err(|e| e.to_string())?;
        self.variables
            .insert(param_name.to_string(), (alloca, struct_type, resolved_type));
        Ok(())
    }

    fn store_function_parameter(
        &mut self,
        param_name: &str,
        arg: inkwell::values::BasicValueEnum<'a>,
        resolved_type: Type,
    ) -> Result<(), String> {
        let func_ptr_type = self.context.ptr_type(AddressSpace::default());
        let alloca = self
            .builder
            .build_alloca(func_ptr_type, param_name)
            .map_err(|e| e.to_string())?;
        self.builder
            .build_store(alloca, arg)
            .map_err(|e| e.to_string())?;

        self.variables.insert(
            param_name.to_string(),
            (alloca, func_ptr_type.into(), resolved_type),
        );
        Ok(())
    }

    fn store_boxed_parameter(
        &mut self,
        param_name: &str,
        value_to_store: inkwell::values::PointerValue<'a>,
        resolved_type: Type,
    ) -> Result<(), String> {
        let ptr_type = self.context.ptr_type(AddressSpace::default());
        let alloca = self
            .builder
            .build_alloca(ptr_type, param_name)
            .map_err(|e| e.to_string())?;
        self.builder
            .build_store(alloca, value_to_store)
            .map_err(|e| e.to_string())?;

        self.variables.insert(
            param_name.to_string(),
            (alloca, BasicTypeEnum::PointerType(ptr_type), resolved_type),
        );
        Ok(())
    }

    fn store_function_parameter_value(
        &mut self,
        param_name: &str,
        arg: inkwell::values::BasicValueEnum<'a>,
        resolved_type: Type,
    ) -> Result<(), String> {
        if matches!(resolved_type, Type::Reference(_)) {
            return self.store_boxed_parameter(param_name, arg.into_pointer_value(), resolved_type);
        }

        if self.is_enum_type(&resolved_type) {
            return self.store_enum_parameter(param_name, arg, resolved_type);
        }

        if matches!(resolved_type, Type::Function { .. }) {
            return self.store_function_parameter(param_name, arg, resolved_type);
        }

        let boxed_value = self.box_value(arg);
        self.store_boxed_parameter(param_name, boxed_value, resolved_type)
    }

    fn setup_function_parameters(
        &mut self,
        func: &FunctionNode,
        function: FunctionValue<'a>,
        start_param_index: u32,
    ) -> Result<(), String> {
        for (i, param) in func.params.iter().enumerate() {
            let arg = function
                .get_nth_param((i as u32) + start_param_index)
                .expect("function parameter should exist at expected index");
            let resolved_type = self
                .analyzer
                .resolve_type(&param.type_)
                .map_err(|e| e.to_string())?;
            self.store_function_parameter_value(&param.name, arg, resolved_type)?;
        }

        Ok(())
    }

    fn resolve_decl_llvm_name(&self, func: &FunctionNode) -> String {
        if func.name.contains('$') {
            return func.name.clone();
        }

        if let Some(symbol) = self.analyzer.symbol_table().lookup(&func.name)
            && let Some(mangled_name) = &symbol.llvm_name
        {
            return mangled_name.clone();
        }

        for module_syms in self.analyzer.imported_symbols().values() {
            if let Some(func_symbol) = module_syms.get(&func.name)
                && let Some(mangled) = &func_symbol.llvm_name
            {
                return mangled.clone();
            }
        }

        func.name.clone()
    }

    pub(super) fn declare_function(&mut self, func: &FunctionNode) -> Result<(), String> {
        let mut param_types: Vec<BasicMetadataTypeEnum> = func
            .params
            .iter()
            .map(|p| self.llvm_type_from_mux_type(&p.type_).map(|t| t.into()))
            .collect::<Result<_, _>>()?;

        let is_class_method = func.name.contains('.');
        if is_class_method && !func.is_common {
            param_types.insert(0, self.context.ptr_type(AddressSpace::default()).into());
        }

        let is_specialized = func.name.contains('$');
        let is_static = func.is_common;
        if is_specialized && !is_static {
            let ptr_type = self.context.ptr_type(AddressSpace::default());
            param_types = param_types
                .into_iter()
                .enumerate()
                .map(|(i, param_type)| {
                    if i == 0 && is_class_method && !func.is_common {
                        param_type
                    } else {
                        ptr_type.into()
                    }
                })
                .collect();
        }

        let fn_type = if matches!(
            func.return_type.kind,
            TypeKind::Primitive(PrimitiveType::Void)
        ) {
            self.context.void_type().fn_type(&param_types, false)
        } else {
            let return_type = self.llvm_type_from_mux_type(&func.return_type)?;
            return_type.fn_type(&param_types, false)
        };
        let llvm_name = self.resolve_decl_llvm_name(func);

        let function = self.module.add_function(&llvm_name, fn_type, None);
        self.functions.insert(func.name.clone(), function);
        self.function_nodes.insert(func.name.clone(), func.clone());

        Ok(())
    }

    pub(super) fn declare_function_with_name(
        &mut self,
        func: &FunctionNode,
        llvm_name: &str,
    ) -> Result<(), String> {
        let mut param_types: Vec<BasicMetadataTypeEnum> = func
            .params
            .iter()
            .map(|p| self.llvm_type_from_mux_type(&p.type_).map(|t| t.into()))
            .collect::<Result<_, _>>()?;

        let is_class_method = func.name.contains('.');
        if is_class_method && !func.is_common {
            param_types.insert(0, self.context.ptr_type(AddressSpace::default()).into());
        }

        let is_specialized = func.name.contains('$');
        let is_static = func.is_common;
        if is_specialized && !is_static {
            let ptr_type = self.context.ptr_type(AddressSpace::default());
            param_types = param_types
                .into_iter()
                .enumerate()
                .map(|(i, param_type)| {
                    if i == 0 && is_class_method && !func.is_common {
                        param_type
                    } else {
                        ptr_type.into()
                    }
                })
                .collect();
        }

        let fn_type = if matches!(
            func.return_type.kind,
            TypeKind::Primitive(PrimitiveType::Void)
        ) {
            self.context.void_type().fn_type(&param_types, false)
        } else {
            let return_type = self.llvm_type_from_mux_type(&func.return_type)?;
            return_type.fn_type(&param_types, false)
        };

        let function = self.module.add_function(llvm_name, fn_type, None);
        self.functions.insert(llvm_name.to_string(), function);

        Ok(())
    }

    pub(super) fn generate_module_init(
        &mut self,
        top_level_statements: &[StatementNode],
        module_name: &str,
    ) -> Result<(), String> {
        // Use ! prefix to avoid conflicts with user-defined functions
        // (! is used for module-level generated code, $ is used for generic specializations)
        let init_name = format!("!{}!init", module_name.replace(['.', '/'], "_"));

        let init_type = self.context.void_type().fn_type(&[], false);
        let init_func = self.module.add_function(&init_name, init_type, None);
        let entry = self.context.append_basic_block(init_func, "entry");
        self.builder.position_at_end(entry);

        // copy global_variables to variables so statements can access/initialize them
        self.variables = self.global_variables.clone();

        // Execute top-level statements as module initialization
        for stmt in top_level_statements {
            self.generate_statement(stmt, Some(&init_func))?;
        }

        self.builder.build_return(None).map_err(|e| e.to_string())?;
        Ok(())
    }

    pub(super) fn generate_main_function(&mut self, module_name: &str) -> Result<(), String> {
        let main_type = self.context.i32_type().fn_type(&[], false);
        let main_func = self.module.add_function("main", main_type, None);
        let entry = self.context.append_basic_block(main_func, "entry");
        self.builder.position_at_end(entry);

        // Call imported module init functions in dependency order
        // This ensures modules are initialized before use
        for module_path in &self.analyzer.module_dependencies {
            let init_name = format!("!{}!init", Self::sanitize_module_path(module_path));
            if let Some(init_func) = self.module.get_function(&init_name) {
                self.builder
                    .build_call(
                        init_func,
                        &[],
                        &format!("{}_init_call", module_path.replace('.', "_")),
                    )
                    .map_err(|e| e.to_string())?;
            }
        }

        // Call main module init function
        let init_name = format!("!{}!init", Self::sanitize_module_path(module_name));
        if let Some(init_func) = self.module.get_function(&init_name) {
            self.builder
                .build_call(init_func, &[], "init_call")
                .map_err(|e| e.to_string())?;
        }

        // Call user-defined main function if it exists
        if let Some(user_main) = self.module.get_function("!user!main") {
            self.builder
                .build_call(user_main, &[], "user_main_call")
                .map_err(|e| e.to_string())?;
        }

        // return 0 from main
        self.builder
            .build_return(Some(&self.context.i32_type().const_int(0, false)))
            .map_err(|e| e.to_string())?;
        Ok(())
    }

    pub(super) fn get_module_name(&self, nodes: &[AstNode]) -> String {
        // Try to get module name from first class or function
        for node in nodes {
            match node {
                AstNode::Class { name, .. } => {
                    return name.split('.').next().unwrap_or("main").to_string();
                }
                AstNode::Function(func) => {
                    return func.name.split('.').next().unwrap_or("main").to_string();
                }
                _ => {}
            }
        }
        "main".to_string()
    }

    pub(super) fn generate_function(&mut self, func: &FunctionNode) -> Result<(), String> {
        // Save state that might be overwritten by nested function generation
        // (e.g., when generating specialized methods for generic classes used in this function)
        let saved_function_name = self.current_function_name.take();
        let saved_return_type = self.current_function_return_type.take();
        let saved_self_type = self.analyzer.current_self_type.take();

        // Save the RC scope stack from any parent function context.
        // Each function has its own isolated RC scope - nested function generation
        // (specialized methods, generic instantiation, etc.) should not see or clean up
        // variables from the calling function's scope.
        let saved_rc_scope_stack = std::mem::take(&mut self.rc_scope_stack);

        self.current_function_name = Some(func.name.clone());
        self.current_function_return_type = Some(
            self.analyzer
                .resolve_type(&func.return_type)
                .map_err(|e| e.to_string())?,
        );

        let function = *self
            .functions
            .get(&func.name)
            .ok_or("Function not declared")?;

        let entry = self.context.append_basic_block(function, "entry");
        self.builder.position_at_end(entry);

        // clear variables for new scope
        self.variables.clear();

        // Push RC scope for this function (on a fresh stack)
        self.push_rc_scope();

        // set up parameter variables
        let is_class_method = func.name.contains('.');
        let mut param_index = 0u32;
        if is_class_method && !func.is_common {
            self.setup_method_self_parameter(func, function, &mut param_index)?;
        }
        self.setup_function_parameters(func, function, param_index)?;

        // generate function body
        for stmt in &func.body {
            self.generate_statement(stmt, Some(&function))?;
        }

        // if void return, add return void if not already terminated
        if matches!(
            func.return_type.kind,
            TypeKind::Primitive(PrimitiveType::Void)
        ) && let Some(block) = self.builder.get_insert_block()
            && block.get_terminator().is_none()
        {
            // Generate cleanup for all RC variables before returning
            self.generate_all_scopes_cleanup()?;
            self.builder.build_return(None).map_err(|e| e.to_string())?;
        }

        // Pop the function's RC scope (no cleanup needed here since we already
        // cleaned up before returns, and non-void functions must have explicit returns)
        self.rc_scope_stack.pop();

        // Restore previous function context
        self.current_function_name = saved_function_name;
        self.current_function_return_type = saved_return_type;
        self.analyzer.current_self_type = saved_self_type;

        // Restore the parent function's RC scope stack
        self.rc_scope_stack = saved_rc_scope_stack;

        Ok(())
    }

    // Generate function with explicit LLVM name (for imported module functions)
    pub(super) fn generate_function_with_llvm_name(
        &mut self,
        func: &FunctionNode,
        llvm_name: &str,
    ) -> Result<(), String> {
        // Look up by LLVM name instead of source name
        let function = *self.functions.get(llvm_name).ok_or_else(|| {
            format!(
                "Function {} not declared (LLVM name: {})",
                func.name, llvm_name
            )
        })?;

        // Delegate to the regular implementation
        // but first we need to temporarily store it under the source name too
        self.functions.insert(func.name.clone(), function);
        let result = self.generate_function(func);
        // Remove the temporary entry
        self.functions.remove(&func.name);
        result
    }
}