swamp_code_gen/
lib.rs

1/*
2 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/swamp/swamp
3 * Licensed under the MIT License. See LICENSE in the project root for license information.
4 */
5
6pub mod alloc;
7pub mod alloc_util;
8pub mod constants;
9pub mod ctx;
10mod location;
11mod vec;
12
13use crate::alloc::{ConstantMemoryRegion, FrameMemoryRegion, ScopeAllocator};
14use crate::alloc_util::{
15    is_map, is_vec, layout_struct, layout_tuple, layout_tuple_elements, reserve_space_for_type,
16    type_size_and_alignment,
17};
18use crate::constants::ConstantsManager;
19use crate::ctx::Context;
20use seq_map::SeqMap;
21use source_map_cache::{SourceMapLookup, SourceMapWrapper};
22use source_map_node::Node;
23use swamp_semantic::intr::IntrinsicFunction;
24use swamp_semantic::{
25    AnonymousStructLiteral, BinaryOperator, BinaryOperatorKind, BooleanExpression,
26    CompoundOperatorKind, ConstantId, ConstantRef, EnumLiteralData, Expression, ExpressionKind,
27    ForPattern, Function, Guard, InternalFunctionDefinitionRef, InternalFunctionId,
28    InternalMainExpression, Iterable, Literal, Match, MutRefOrImmutableExpression, NormalPattern,
29    Pattern, Postfix, PostfixKind, SingleLocationExpression, StructInstantiation,
30    TargetAssignmentLocation, UnaryOperator, UnaryOperatorKind, VariableRef, WhenBinding,
31};
32use swamp_types::{AnonymousStructType, EnumVariantType, Signature, StructTypeField, Type};
33use swamp_vm_disasm::{disasm_color, disasm_instructions_color};
34use swamp_vm_instr_build::{InstructionBuilder, PatchPosition};
35use swamp_vm_types::{
36    BOOL_SIZE, BinaryInstruction, CountU16, FrameMemoryAddress, FrameMemoryAddressIndirectPointer,
37    FrameMemorySize, HEAP_PTR_ALIGNMENT, HEAP_PTR_SIZE, HeapMemoryAddress, INT_SIZE,
38    InstructionPosition, MemoryAlignment, MemoryOffset, MemorySize, PTR_SIZE,
39    TempFrameMemoryAddress, VEC_ITERATOR_ALIGNMENT, VEC_ITERATOR_SIZE,
40};
41use tracing::{error, info, trace};
42
43pub struct GeneratedExpressionResult {
44    pub has_set_bool_z_flag: bool,
45}
46
47impl Default for GeneratedExpressionResult {
48    fn default() -> Self {
49        Self {
50            has_set_bool_z_flag: false,
51        }
52    }
53}
54
55#[derive(Debug)]
56pub enum ErrorKind {
57    IllegalCompoundAssignment,
58    VariableNotUnique,
59    IllegalCollection,
60    NotAnIterableCollection,
61}
62
63#[derive(Debug)]
64pub struct Error {
65    pub kind: ErrorKind,
66    pub node: Node,
67}
68
69pub struct SlicePairInfo {
70    pub addr: TempFrameMemoryAddress,
71    pub key_size: MemorySize,
72    pub value_size: MemorySize,
73    pub element_count: CountU16,
74    pub element_size: MemorySize,
75}
76
77pub struct FunctionInfo {
78    pub starts_at_ip: InstructionPosition,
79    pub internal_function_definition: InternalFunctionDefinitionRef,
80}
81
82pub struct FunctionFixup {
83    pub patch_position: PatchPosition,
84    pub fn_id: InternalFunctionId,
85    //pub internal_function_definition: InternalFunctionDefinitionRef,
86}
87
88pub struct ConstantInfo {
89    pub ip: InstructionPosition,
90    pub constant_ref: ConstantRef,
91    pub target_constant_memory: ConstantMemoryRegion,
92}
93
94pub struct CodeGenState {
95    builder: InstructionBuilder,
96    constants: ConstantsManager,
97    constant_offsets: SeqMap<ConstantId, ConstantMemoryRegion>,
98    constant_functions: SeqMap<ConstantId, ConstantInfo>,
99    function_infos: SeqMap<InternalFunctionId, FunctionInfo>,
100    function_fixups: Vec<FunctionFixup>,
101    //source_map_lookup: &'b SourceMapWrapper<'b>,
102    debug_last_ip: usize,
103}
104
105pub struct GenOptions {
106    pub is_halt_function: bool,
107}
108
109impl CodeGenState {
110    #[must_use]
111    pub fn new() -> Self {
112        Self {
113            builder: InstructionBuilder::default(),
114            constants: ConstantsManager::new(),
115            constant_offsets: SeqMap::default(),
116            function_infos: SeqMap::default(),
117            constant_functions: SeqMap::default(),
118            function_fixups: vec![],
119            debug_last_ip: 0,
120        }
121    }
122
123    #[must_use]
124    pub fn instructions(&self) -> &[BinaryInstruction] {
125        &self.builder.instructions
126    }
127    pub fn create_function_sections(&self) -> SeqMap<InstructionPosition, String> {
128        let mut lookups = SeqMap::new();
129        for (_func_id, function_info) in &self.function_infos {
130            let description = function_info
131                .internal_function_definition
132                .assigned_name
133                .clone();
134            lookups
135                .insert(function_info.starts_at_ip.clone(), description)
136                .unwrap();
137        }
138
139        for (_func_id, function_info) in &self.constant_functions {
140            let description = format!("constant {}", function_info.constant_ref.assigned_name);
141            lookups
142                .insert(function_info.ip.clone(), description)
143                .unwrap();
144        }
145
146        lookups
147    }
148    #[must_use]
149    pub fn builder(&self) -> &InstructionBuilder {
150        &self.builder
151    }
152    pub fn constant_functions(&self) -> &SeqMap<ConstantId, ConstantInfo> {
153        &self.constant_functions
154    }
155    pub(crate) fn add_call(&mut self, internal_fn: &InternalFunctionDefinitionRef, comment: &str) {
156        let call_comment = &format!("calling {} ({})", internal_fn.assigned_name, comment);
157
158        if let Some(found) = self.function_infos.get(&internal_fn.program_unique_id) {
159            self.builder.add_call(&found.starts_at_ip, call_comment);
160        } else {
161            let patch_position = self.builder.add_call_placeholder(call_comment);
162            self.function_fixups.push(FunctionFixup {
163                patch_position,
164                fn_id: internal_fn.program_unique_id,
165            });
166        }
167    }
168    #[must_use]
169    pub fn comments(&self) -> &[String] {
170        &self.builder.comments
171    }
172
173    pub fn finalize(&mut self) {
174        for function_fixup in &self.function_fixups {
175            let func = self.function_infos.get(&function_fixup.fn_id).unwrap();
176            self.builder.patch_call(
177                PatchPosition(InstructionPosition(function_fixup.patch_position.0.0)),
178                &func.starts_at_ip,
179            );
180        }
181    }
182
183    #[must_use]
184    pub fn take_instructions_and_constants(
185        self,
186    ) -> (
187        Vec<BinaryInstruction>,
188        Vec<u8>,
189        SeqMap<ConstantId, ConstantInfo>,
190    ) {
191        (
192            self.builder.instructions,
193            self.constants.take_data(),
194            self.constant_functions,
195        )
196    }
197
198    pub fn gen_function_def(
199        &mut self,
200        internal_fn_def: &InternalFunctionDefinitionRef,
201        options: &GenOptions,
202        source_map_wrapper: &SourceMapWrapper,
203    ) -> Result<(), Error> {
204        assert_ne!(internal_fn_def.program_unique_id, 0);
205        self.function_infos
206            .insert(
207                internal_fn_def.program_unique_id,
208                FunctionInfo {
209                    starts_at_ip: self.builder.position(),
210                    internal_function_definition: internal_fn_def.clone(),
211                },
212            )
213            .unwrap();
214
215        let mut function_generator = FunctionCodeGen::new(self, source_map_wrapper);
216
217        function_generator.layout_variables(
218            &internal_fn_def.function_scope_state,
219            &internal_fn_def.signature.signature.return_type,
220        )?;
221
222        let ExpressionKind::Block(block_expressions) = &internal_fn_def.body.kind else {
223            panic!("function body should be a block")
224        };
225
226        if let ExpressionKind::IntrinsicCallEx(found_intrinsic_fn, _non_instantiated_arguments) =
227            &block_expressions[0].kind
228        {
229            // Intentionally do nothing
230            todo!()
231        } else {
232            let (return_type_size, _return_alignment) =
233                type_size_and_alignment(&internal_fn_def.signature.signature.return_type);
234            let ctx = Context::new(FrameMemoryRegion::new(
235                FrameMemoryAddress(0),
236                return_type_size,
237            ));
238            function_generator.gen_expression(&internal_fn_def.body, &ctx)?;
239        }
240
241        self.finalize_function(options);
242
243        Ok(())
244    }
245
246    pub fn finalize_function(&mut self, options: &GenOptions) {
247        if options.is_halt_function {
248            self.builder.add_hlt("");
249        } else {
250            self.builder.add_ret("");
251        }
252    }
253
254    pub fn reserve_space_for_constants(&mut self, constants: &[ConstantRef]) -> Result<(), Error> {
255        for constant in constants {
256            let (size, alignment) = type_size_and_alignment(&constant.resolved_type);
257
258            let constant_memory_address = self.constants.reserve(size, alignment);
259
260            let constant_memory_region = ConstantMemoryRegion {
261                addr: constant_memory_address,
262                size,
263            };
264
265            self.constant_offsets
266                .insert(constant.id, constant_memory_region)
267                .unwrap();
268        }
269
270        Ok(())
271    }
272    pub fn gen_constants_expression_functions_in_order(
273        &mut self,
274        constants: &[ConstantRef],
275        source_map_wrapper: &SourceMapWrapper,
276    ) -> Result<(), Error> {
277        for constant in constants {
278            let target_region = *self.constant_offsets.get(&constant.id).unwrap();
279            let ip = self.builder.position();
280            {
281                let mut function_generator = FunctionCodeGen::new(self, source_map_wrapper);
282
283                let constant_target_ctx = Context::new(FrameMemoryRegion::new(
284                    FrameMemoryAddress(0),
285                    target_region.size,
286                ));
287                function_generator.gen_expression(&constant.expr, &constant_target_ctx)?;
288                self.finalize_function(&GenOptions {
289                    is_halt_function: true,
290                });
291            }
292
293            let constant_info = ConstantInfo {
294                ip,
295                target_constant_memory: target_region,
296                constant_ref: constant.clone(),
297            };
298
299            self.constant_functions
300                .insert(constant.id, constant_info)
301                .unwrap();
302        }
303
304        Ok(())
305    }
306
307    /// # Errors
308    ///
309    pub fn gen_main_function(
310        &mut self,
311        main: &InternalMainExpression,
312        options: &GenOptions,
313        source_map_lookup: &SourceMapWrapper,
314    ) -> Result<(), Error> {
315        let mut function_generator = FunctionCodeGen::new(self, source_map_lookup);
316
317        function_generator.layout_variables(&main.function_scope_state, &main.expression.ty)?;
318        let empty_ctx = Context::new(FrameMemoryRegion::default());
319        function_generator.gen_expression(&main.expression, &empty_ctx)?;
320        self.finalize_function(options);
321        Ok(())
322    }
323}
324
325pub struct FunctionCodeGen<'a> {
326    state: &'a mut CodeGenState,
327    variable_offsets: SeqMap<usize, FrameMemoryRegion>,
328    frame_size: FrameMemorySize,
329    //extra_frame_allocator: ScopeAllocator,
330    temp_allocator: ScopeAllocator,
331    argument_allocator: ScopeAllocator,
332    source_map_lookup: &'a SourceMapWrapper<'a>,
333}
334
335impl<'a> FunctionCodeGen<'a> {
336    #[must_use]
337    pub fn new(state: &'a mut CodeGenState, source_map_lookup: &'a SourceMapWrapper) -> Self {
338        Self {
339            state,
340            variable_offsets: SeqMap::default(),
341            frame_size: FrameMemorySize(0),
342            //  extra_frame_allocator: ScopeAllocator::new(FrameMemoryRegion::default()),
343            temp_allocator: ScopeAllocator::new(FrameMemoryRegion::default()),
344            argument_allocator: ScopeAllocator::new(FrameMemoryRegion::default()),
345            source_map_lookup,
346        }
347    }
348}
349
350impl FunctionCodeGen<'_> {
351    #[allow(clippy::too_many_lines)]
352    pub(crate) fn gen_single_intrinsic_call(
353        &mut self,
354        intrinsic_fn: &IntrinsicFunction,
355        self_addr: Option<FrameMemoryRegion>,
356        arguments: &[MutRefOrImmutableExpression],
357        ctx: &Context,
358    ) -> Result<(), Error> {
359        match intrinsic_fn {
360            // Fixed
361            IntrinsicFunction::FloatRound => todo!(),
362            IntrinsicFunction::FloatFloor => todo!(),
363            IntrinsicFunction::FloatSqrt => todo!(),
364            IntrinsicFunction::FloatSign => todo!(),
365            IntrinsicFunction::FloatAbs => todo!(),
366            IntrinsicFunction::FloatRnd => todo!(),
367            IntrinsicFunction::FloatCos => todo!(),
368            IntrinsicFunction::FloatSin => todo!(),
369            IntrinsicFunction::FloatAcos => todo!(),
370            IntrinsicFunction::FloatAsin => todo!(),
371            IntrinsicFunction::FloatAtan2 => todo!(),
372            IntrinsicFunction::FloatMin => todo!(),
373            IntrinsicFunction::FloatMax => todo!(),
374            IntrinsicFunction::FloatClamp => todo!(),
375            // Int
376            IntrinsicFunction::IntAbs => todo!(),
377            IntrinsicFunction::IntRnd => todo!(),
378            IntrinsicFunction::IntMax => todo!(),
379            IntrinsicFunction::IntMin => todo!(),
380            IntrinsicFunction::IntClamp => todo!(),
381            IntrinsicFunction::IntToFloat => todo!(),
382
383            // String
384            IntrinsicFunction::StringLen => {
385                self.state.builder.add_string_len(
386                    ctx.addr(),
387                    FrameMemoryAddressIndirectPointer(self_addr.unwrap().addr),
388                    "get the length",
389                );
390                Ok(())
391            }
392
393            // Vec
394            IntrinsicFunction::VecFromSlice => {
395                let slice_variable = &arguments[0];
396                let slice_region = self.gen_for_access_or_location_ex(slice_variable)?;
397                let (element_size, element_alignment) =
398                    type_size_and_alignment(&slice_variable.ty());
399                self.state.builder.add_vec_from_slice(
400                    ctx.addr(),
401                    slice_region.addr,
402                    element_size,
403                    CountU16(slice_region.size.0 / element_size.0),
404                    "create vec from slice",
405                );
406                Ok(())
407            }
408            IntrinsicFunction::VecPush => todo!(),
409            IntrinsicFunction::VecPop => todo!(),
410            IntrinsicFunction::VecRemoveIndex => todo!(),
411            IntrinsicFunction::VecRemoveIndexGetValue => todo!(),
412            IntrinsicFunction::VecClear => todo!(),
413            IntrinsicFunction::VecGet => todo!(),
414            IntrinsicFunction::VecCreate => todo!(),
415            IntrinsicFunction::VecSubscript => todo!(),
416            IntrinsicFunction::VecSubscriptMut => todo!(),
417            IntrinsicFunction::VecSubscriptRange => todo!(),
418            IntrinsicFunction::VecIter => todo!(),
419            IntrinsicFunction::VecIterMut => todo!(),
420            IntrinsicFunction::VecFor => todo!(),
421            IntrinsicFunction::VecWhile => todo!(),
422            IntrinsicFunction::VecFindMap => todo!(),
423            IntrinsicFunction::VecSelfPush => todo!(),
424            IntrinsicFunction::VecSelfExtend => todo!(),
425            IntrinsicFunction::VecLen => todo!(),
426            IntrinsicFunction::VecIsEmpty => todo!(),
427
428            // Map
429            IntrinsicFunction::MapCreate => todo!(),
430            IntrinsicFunction::MapFromSlicePair => {
431                let slice_pair_argument = &arguments[0];
432                let MutRefOrImmutableExpression::Expression(expr) = slice_pair_argument else {
433                    panic!();
434                };
435
436                let ExpressionKind::Literal(some_lit) = &expr.kind else {
437                    panic!();
438                };
439
440                let Literal::SlicePair(slice_type, expression_pairs) = some_lit else {
441                    panic!();
442                };
443
444                let slice_pair_info = self.gen_slice_pair_literal(slice_type, expression_pairs);
445                self.state.builder.add_map_new_from_slice(
446                    ctx.addr(),
447                    slice_pair_info.addr.to_addr(),
448                    slice_pair_info.key_size,
449                    slice_pair_info.value_size,
450                    slice_pair_info.element_count,
451                    "create map from temporary slice pair",
452                );
453
454                Ok(())
455            }
456            IntrinsicFunction::MapHas => todo!(),
457            IntrinsicFunction::MapRemove => {
458                let MutRefOrImmutableExpression::Expression(key_argument) = &arguments[0] else {
459                    panic!("must be expression for key");
460                };
461                self.gen_intrinsic_map_remove(self_addr.unwrap(), key_argument, ctx)
462            }
463            IntrinsicFunction::MapIter => todo!(),
464            IntrinsicFunction::MapIterMut => todo!(),
465            IntrinsicFunction::MapLen => todo!(),
466            IntrinsicFunction::MapIsEmpty => todo!(),
467            IntrinsicFunction::MapSubscript => todo!(),
468            IntrinsicFunction::MapSubscriptSet => todo!(),
469            IntrinsicFunction::MapSubscriptMut => todo!(),
470            IntrinsicFunction::MapSubscriptMutCreateIfNeeded => todo!(),
471
472            // Map2
473            IntrinsicFunction::Map2Remove => todo!(),
474            IntrinsicFunction::Map2Insert => todo!(),
475            IntrinsicFunction::Map2GetColumn => todo!(),
476            IntrinsicFunction::Map2GetRow => todo!(),
477            IntrinsicFunction::Map2Get => todo!(),
478            IntrinsicFunction::Map2Has => todo!(),
479            IntrinsicFunction::Map2Create => todo!(),
480
481            // Sparse
482            IntrinsicFunction::SparseCreate => todo!(),
483            IntrinsicFunction::SparseFromSlice => todo!(),
484            IntrinsicFunction::SparseIter => todo!(),
485            IntrinsicFunction::SparseIterMut => todo!(),
486            IntrinsicFunction::SparseSubscript => todo!(),
487            IntrinsicFunction::SparseSubscriptMut => todo!(),
488            IntrinsicFunction::SparseHas => todo!(),
489            IntrinsicFunction::SparseRemove => todo!(),
490
491            // Grid
492            IntrinsicFunction::GridCreate => todo!(),
493            IntrinsicFunction::GridFromSlice => todo!(),
494            IntrinsicFunction::GridSet => todo!(),
495            IntrinsicFunction::GridGet => todo!(),
496            IntrinsicFunction::GridGetColumn => todo!(),
497
498            IntrinsicFunction::Float2Magnitude => todo!(),
499
500            IntrinsicFunction::SparseAdd => todo!(),
501            IntrinsicFunction::SparseNew => todo!(),
502            IntrinsicFunction::VecAny => todo!(),
503            IntrinsicFunction::VecAll => todo!(),
504            IntrinsicFunction::VecMap => todo!(),
505            IntrinsicFunction::VecFilter => todo!(),
506            IntrinsicFunction::VecFilterMap => todo!(),
507            IntrinsicFunction::VecFind => todo!(),
508            IntrinsicFunction::VecSwap => todo!(),
509            IntrinsicFunction::VecInsert => todo!(),
510            IntrinsicFunction::VecFirst => todo!(),
511            IntrinsicFunction::VecLast => todo!(),
512            IntrinsicFunction::VecFold => todo!(),
513        }
514    }
515
516    fn gen_intrinsic_map_remove(
517        &mut self,
518        map_region: FrameMemoryRegion,
519        key_expr: &Expression,
520        ctx: &Context,
521    ) -> Result<(), Error> {
522        let key_region = self.gen_expression_for_access(key_expr)?;
523
524        self.state
525            .builder
526            .add_map_remove(map_region.addr, key_region.addr, "");
527
528        Ok(())
529    }
530
531    pub fn reserve(ty: &Type, allocator: &mut ScopeAllocator) -> FrameMemoryRegion {
532        let (size, alignment) = type_size_and_alignment(ty);
533        allocator.reserve(size, alignment)
534    }
535
536    /// # Errors
537    ///
538    pub fn layout_variables(
539        &mut self,
540        variables: &Vec<VariableRef>,
541        return_type: &Type,
542    ) -> Result<(), Error> {
543        let mut allocator = ScopeAllocator::new(FrameMemoryRegion::new(
544            FrameMemoryAddress(0),
545            MemorySize(1024),
546        ));
547        let _current_offset = Self::reserve(return_type, &mut allocator);
548
549        let mut enter_comment = "variables:\n".to_string();
550
551        for var_ref in variables {
552            let var_target = Self::reserve(&var_ref.resolved_type, &mut allocator);
553            trace!(?var_ref.assigned_name, ?var_target, "laying out");
554            enter_comment += &format!(
555                "  ${:04X}:{} {}\n",
556                var_target.addr.0, var_target.size.0, var_ref.assigned_name
557            );
558            self.variable_offsets
559                .insert(var_ref.unique_id_within_function, var_target)
560                .map_err(|_| self.create_err(ErrorKind::VariableNotUnique, &var_ref.name))?;
561        }
562
563        let extra_frame_size = MemorySize(80);
564        let extra_target = FrameMemoryRegion::new(allocator.addr(), extra_frame_size);
565        self.frame_size = allocator.addr().as_size().add(extra_frame_size);
566
567        self.state
568            .builder
569            .add_enter(self.frame_size, &enter_comment);
570
571        const ARGUMENT_MAX_SIZE: u16 = 256;
572        self.argument_allocator = ScopeAllocator::new(FrameMemoryRegion::new(
573            FrameMemoryAddress(self.frame_size.0),
574            MemorySize(ARGUMENT_MAX_SIZE),
575        ));
576
577        self.temp_allocator = ScopeAllocator::new(FrameMemoryRegion::new(
578            FrameMemoryAddress(self.frame_size.0 + ARGUMENT_MAX_SIZE),
579            MemorySize(1024),
580        ));
581
582        Ok(())
583    }
584
585    pub fn temp_memory_region_for_type(&mut self, ty: &Type, comment: &str) -> FrameMemoryRegion {
586        let new_target_info = reserve_space_for_type(ty, &mut self.temp_allocator);
587        new_target_info
588    }
589
590    pub fn temp_space_for_type(&mut self, ty: &Type, comment: &str) -> Context {
591        Context::new(self.temp_memory_region_for_type(ty, comment))
592    }
593
594    /// # Panics
595    ///
596    #[allow(clippy::single_match_else)]
597    pub fn gen_expression_for_access(
598        &mut self,
599        expr: &Expression,
600    ) -> Result<FrameMemoryRegion, Error> {
601        let (region, _gen_result) = self.gen_expression_for_access_internal(expr)?;
602
603        Ok(region)
604    }
605
606    /// # Panics
607    ///
608    #[allow(clippy::single_match_else)]
609    pub fn gen_expression_for_access_internal(
610        &mut self,
611        expr: &Expression,
612    ) -> Result<(FrameMemoryRegion, GeneratedExpressionResult), Error> {
613        match &expr.kind {
614            ExpressionKind::VariableAccess(var_ref) => {
615                let frame_address = self
616                    .variable_offsets
617                    .get(&var_ref.unique_id_within_function)
618                    .unwrap();
619
620                return Ok((*frame_address, GeneratedExpressionResult::default()));
621            }
622
623            ExpressionKind::Literal(lit) => match lit {
624                Literal::Slice(slice_type, expressions) => {
625                    return Ok((
626                        self.gen_slice_literal(slice_type, expressions)?,
627                        GeneratedExpressionResult::default(),
628                    ));
629                }
630                Literal::SlicePair(slice_pair_type, pairs) => {
631                    let info = self.gen_slice_pair_literal(slice_pair_type, pairs);
632                    return Ok((
633                        FrameMemoryRegion::new(
634                            info.addr.0,
635                            MemorySize(info.element_count.0 * info.element_size.0),
636                        ),
637                        GeneratedExpressionResult::default(),
638                    ));
639                }
640                _ => {}
641            },
642            _ => {}
643        };
644
645        let temp_ctx = self.temp_space_for_type(&expr.ty, "expression");
646
647        let expression_result = self.gen_expression(expr, &temp_ctx)?;
648
649        Ok((temp_ctx.target(), expression_result))
650    }
651
652    pub(crate) fn extra_frame_space_for_type(&mut self, ty: &Type) -> Context {
653        let target = Self::reserve(ty, &mut self.temp_allocator);
654        Context::new(target)
655    }
656
657    fn debug_node(&self, node: &Node) {
658        let line_info = self.source_map_lookup.get_line(&node.span);
659        let span_text = self.source_map_lookup.get_text_span(&node.span);
660        eprintln!(
661            "{}:{}:{}> {}",
662            line_info.relative_file_name, line_info.row, line_info.col, span_text,
663        );
664        //info!(?source_code_line, "generating");
665    }
666
667    fn debug_instructions(&mut self) {
668        let end_ip = self.state.builder.instructions.len() - 1;
669        let instructions_to_disasm =
670            &self.state.builder.instructions[self.state.debug_last_ip..=end_ip];
671        let mut descriptions = Vec::new();
672        for x in instructions_to_disasm {
673            descriptions.push(String::new());
674        }
675        let output = disasm_instructions_color(
676            instructions_to_disasm,
677            &InstructionPosition(self.state.debug_last_ip as u16),
678            &descriptions,
679            &SeqMap::default(),
680        );
681        eprintln!("{output}");
682        self.state.debug_last_ip = end_ip + 1;
683    }
684
685    pub fn gen_expression(
686        &mut self,
687        expr: &Expression,
688        ctx: &Context,
689    ) -> Result<GeneratedExpressionResult, Error> {
690        self.debug_node(&expr.node);
691        let result = match &expr.kind {
692            ExpressionKind::InterpolatedString(_) => todo!(),
693
694            ExpressionKind::ConstantAccess(constant_ref) => self
695                .gen_constant_access(constant_ref, ctx)
696                .map(|_| GeneratedExpressionResult::default()),
697            ExpressionKind::TupleDestructuring(variables, tuple_types, tuple_expression) => self
698                .gen_tuple_destructuring(variables, tuple_types, tuple_expression)
699                .map(|_| GeneratedExpressionResult::default()),
700
701            ExpressionKind::Assignment(target_mut_location_expr, source_expr) => self
702                .gen_assignment(target_mut_location_expr, source_expr)
703                .map(|_| GeneratedExpressionResult::default()),
704            ExpressionKind::VariableAccess(variable_ref) => self
705                .gen_variable_access(variable_ref, ctx)
706                .map(|_| GeneratedExpressionResult::default()),
707            ExpressionKind::InternalFunctionAccess(function) => self
708                .internal_function_access(function, ctx)
709                .map(|_| GeneratedExpressionResult::default()),
710            ExpressionKind::BinaryOp(operator) => self.gen_binary_operator(operator, ctx),
711            ExpressionKind::UnaryOp(operator) => self
712                .gen_unary_operator(operator, ctx)
713                .map(|_| GeneratedExpressionResult::default()),
714            ExpressionKind::PostfixChain(start, chain) => self
715                .gen_postfix_chain(start, chain, ctx)
716                .map(|_| GeneratedExpressionResult::default()),
717            ExpressionKind::VariableDefinition(variable, expression) => self
718                .gen_variable_definition(variable, expression, ctx)
719                .map(|_| GeneratedExpressionResult::default()),
720            ExpressionKind::VariableReassignment(variable, expression) => self
721                .gen_variable_reassignment(variable, expression, ctx)
722                .map(|_| GeneratedExpressionResult::default()),
723            ExpressionKind::StructInstantiation(struct_literal) => self
724                .gen_struct_literal(struct_literal, ctx)
725                .map(|()| GeneratedExpressionResult::default()),
726            ExpressionKind::AnonymousStructLiteral(anon_struct) => self
727                .gen_anonymous_struct_literal(anon_struct, ctx)
728                .map(|_| GeneratedExpressionResult::default()),
729            ExpressionKind::Literal(basic_literal) => self
730                .gen_literal(basic_literal, ctx)
731                .map(|_| GeneratedExpressionResult::default()),
732            ExpressionKind::Option(maybe_option) => self
733                .gen_option_expression(maybe_option.as_deref(), ctx)
734                .map(|_| GeneratedExpressionResult::default()),
735            ExpressionKind::ForLoop(a, b, c) => self
736                .gen_for_loop(a, b, c)
737                .map(|_| GeneratedExpressionResult::default()),
738            ExpressionKind::WhileLoop(condition, expression) => self
739                .gen_while_loop(condition, expression, ctx)
740                .map(|_| GeneratedExpressionResult::default()),
741            ExpressionKind::Block(expressions) => self
742                .gen_block(expressions, ctx)
743                .map(|_| GeneratedExpressionResult::default()),
744            ExpressionKind::Match(match_expr) => self
745                .gen_match(match_expr, ctx)
746                .map(|_| GeneratedExpressionResult::default()),
747            ExpressionKind::Guard(guards) => self
748                .gen_guard(guards, ctx)
749                .map(|_| GeneratedExpressionResult::default()),
750            ExpressionKind::If(conditional, true_expr, false_expr) => self
751                .gen_if(conditional, true_expr, false_expr.as_deref(), ctx)
752                .map(|_| GeneratedExpressionResult::default()),
753            ExpressionKind::When(bindings, true_expr, false_expr) => self
754                .gen_when(bindings, true_expr, false_expr.as_deref(), ctx)
755                .map(|_| GeneratedExpressionResult::default()),
756            ExpressionKind::CompoundAssignment(target_location, operator_kind, source_expr) => self
757                .compound_assignment(target_location, operator_kind, source_expr, ctx)
758                .map(|_| GeneratedExpressionResult::default()),
759            ExpressionKind::IntrinsicCallEx(intrinsic_fn, arguments) => self
760                .gen_intrinsic_call_ex(intrinsic_fn, arguments, ctx)
761                .map(|_| GeneratedExpressionResult::default()),
762
763            ExpressionKind::Lambda(vec, x) => {
764                todo!()
765            }
766            // --------- Not high prio
767            ExpressionKind::CoerceOptionToBool(_) => todo!(),
768            ExpressionKind::FunctionValueCall(_, _, _) => todo!(),
769
770            // --------- TO BE REMOVED
771            ExpressionKind::IntrinsicFunctionAccess(_) => todo!(), // TODO: IntrinsicFunctionAccess should be reduced away in analyzer
772            ExpressionKind::ExternalFunctionAccess(_) => todo!(), // TODO: ExternalFunctionAccess should be reduced away in analyzer
773            ExpressionKind::VariableBinding(_, _) => todo!(),
774        };
775
776        self.debug_instructions();
777
778        result
779    }
780
781    fn gen_unary_operator(
782        &mut self,
783        unary_operator: &UnaryOperator,
784        ctx: &Context,
785    ) -> Result<(), Error> {
786        match &unary_operator.kind {
787            UnaryOperatorKind::Not => todo!(),
788            UnaryOperatorKind::Negate => match (&unary_operator.left.ty) {
789                Type::Int => {
790                    let left_source = self.gen_expression_for_access(&unary_operator.left)?;
791                    self.state
792                        .builder
793                        .add_neg_i32(ctx.addr(), left_source.addr, "negate i32");
794                }
795
796                Type::Float => {
797                    let left_source = self.gen_expression_for_access(&unary_operator.left)?;
798                    self.state
799                        .builder
800                        .add_neg_f32(ctx.addr(), left_source.addr, "negate f32");
801                }
802                _ => todo!(),
803            },
804            UnaryOperatorKind::BorrowMutRef => todo!(),
805        }
806
807        Ok(())
808    }
809
810    fn gen_binary_operator(
811        &mut self,
812        binary_operator: &BinaryOperator,
813        ctx: &Context,
814    ) -> Result<GeneratedExpressionResult, Error> {
815        match (&binary_operator.left.ty, &binary_operator.right.ty) {
816            (Type::Int, Type::Int) => self.gen_binary_operator_i32(binary_operator, ctx),
817            (Type::Bool, Type::Bool) => self.gen_binary_operator_bool(binary_operator),
818            (Type::String, Type::String) => self.gen_binary_operator_string(binary_operator, ctx),
819            _ => todo!(),
820        }
821    }
822
823    fn gen_binary_operator_i32(
824        &mut self,
825        binary_operator: &BinaryOperator,
826        ctx: &Context,
827    ) -> Result<GeneratedExpressionResult, Error> {
828        let left_source = self.gen_expression_for_access(&binary_operator.left)?;
829        let right_source = self.gen_expression_for_access(&binary_operator.right)?;
830
831        match binary_operator.kind {
832            BinaryOperatorKind::Add => {
833                self.state.builder.add_add_i32(
834                    ctx.addr(),
835                    left_source.addr(),
836                    right_source.addr(),
837                    "i32 add",
838                );
839            }
840
841            BinaryOperatorKind::Subtract => todo!(),
842            BinaryOperatorKind::Multiply => {
843                self.state.builder.add_mul_i32(
844                    ctx.addr(),
845                    left_source.addr(),
846                    right_source.addr(),
847                    "i32 add",
848                );
849            }
850            BinaryOperatorKind::Divide => todo!(),
851            BinaryOperatorKind::Modulo => todo!(),
852            BinaryOperatorKind::LogicalOr => todo!(),
853            BinaryOperatorKind::LogicalAnd => todo!(),
854            BinaryOperatorKind::Equal => {
855                self.state
856                    .builder
857                    .add_eq_32(left_source.addr(), right_source.addr(), "i32 eq");
858            }
859            BinaryOperatorKind::NotEqual => todo!(),
860            BinaryOperatorKind::LessThan => {
861                self.state
862                    .builder
863                    .add_lt_i32(left_source.addr(), right_source.addr(), "i32 lt");
864            }
865            BinaryOperatorKind::LessEqual => todo!(),
866            BinaryOperatorKind::GreaterThan => {
867                self.state
868                    .builder
869                    .add_gt_i32(left_source.addr(), right_source.addr(), "i32 gt");
870            }
871            BinaryOperatorKind::GreaterEqual => todo!(),
872            BinaryOperatorKind::RangeExclusive => todo!(),
873        }
874
875        Ok(GeneratedExpressionResult {
876            has_set_bool_z_flag: true,
877        })
878    }
879
880    fn gen_binary_operator_string(
881        &mut self,
882        binary_operator: &BinaryOperator,
883        ctx: &Context,
884    ) -> Result<GeneratedExpressionResult, Error> {
885        let left_source = self.gen_expression_for_access(&binary_operator.left)?;
886        let right_source = self.gen_expression_for_access(&binary_operator.right)?;
887
888        match binary_operator.kind {
889            BinaryOperatorKind::Add => {
890                self.state.builder.add_string_append(
891                    ctx.addr(),
892                    left_source.addr(),
893                    right_source.addr(),
894                    "string add",
895                );
896            }
897
898            BinaryOperatorKind::Equal => todo!(),
899            BinaryOperatorKind::NotEqual => todo!(),
900            _ => panic!("illegal string operator"),
901        }
902
903        Ok(GeneratedExpressionResult {
904            has_set_bool_z_flag: false,
905        })
906    }
907
908    fn gen_binary_operator_bool(
909        &mut self,
910        binary_operator: &BinaryOperator,
911    ) -> Result<GeneratedExpressionResult, Error> {
912        match binary_operator.kind {
913            BinaryOperatorKind::LogicalOr => {
914                // this updates the z flag
915                self.gen_boolean_access_set_z_flag(&binary_operator.left);
916
917                let jump_after_patch = self
918                    .state
919                    .builder
920                    .add_jmp_if_equal_placeholder("skip rhs `or` expression");
921
922                // this updates the z flag
923                self.gen_boolean_access_set_z_flag(&binary_operator.right);
924
925                self.state.builder.patch_jump_here(jump_after_patch);
926            }
927            BinaryOperatorKind::LogicalAnd => {
928                // this updates the z flag
929                self.gen_boolean_access_set_z_flag(&binary_operator.left);
930
931                let jump_after_patch = self
932                    .state
933                    .builder
934                    .add_jmp_if_not_equal_placeholder("skip rhs `and` expression");
935
936                // this updates the z flag
937                self.gen_boolean_access_set_z_flag(&binary_operator.right);
938
939                self.state.builder.patch_jump_here(jump_after_patch);
940            }
941            _ => {
942                panic!("unknown operator")
943            }
944        }
945
946        Ok(GeneratedExpressionResult {
947            has_set_bool_z_flag: true,
948        })
949    }
950
951    fn gen_condition_context(
952        &mut self,
953        condition: &BooleanExpression,
954    ) -> Result<(Context, PatchPosition), Error> {
955        let condition_ctx = self.extra_frame_space_for_type(&Type::Bool);
956        self.gen_expression(&condition.expression, &condition_ctx)?;
957
958        let jump_on_false_condition = self
959            .state
960            .builder
961            .add_jmp_if_not_equal_placeholder("jump boolean condition false");
962
963        Ok((condition_ctx, jump_on_false_condition))
964    }
965
966    fn gen_boolean_access_set_z_flag(&mut self, condition: &Expression) -> Result<(), Error> {
967        let (frame_memory_region, gen_result) =
968            self.gen_expression_for_access_internal(condition)?;
969
970        if !gen_result.has_set_bool_z_flag {
971            self.state.builder.add_tst8(
972                frame_memory_region.addr,
973                "convert to boolean expression (update z flag)",
974            );
975        }
976
977        Ok(())
978    }
979
980    fn gen_boolean_expression(&mut self, condition: &BooleanExpression) -> Result<(), Error> {
981        self.gen_boolean_access_set_z_flag(&condition.expression)
982    }
983
984    fn gen_if(
985        &mut self,
986        condition: &BooleanExpression,
987        true_expr: &Expression,
988        maybe_false_expr: Option<&Expression>,
989        ctx: &Context,
990    ) -> Result<(), Error> {
991        let (_condition_ctx, jump_on_false_condition) = self.gen_condition_context(condition)?;
992
993        // True expression just takes over our target
994        self.gen_expression(true_expr, ctx)?;
995
996        if let Some(false_expr) = maybe_false_expr {
997            // we need to help the true expression to jump over false
998            let skip_false_if_true = self
999                .state
1000                .builder
1001                .add_jump_placeholder("condition is false skip");
1002
1003            // If the expression was false, it should continue here
1004            self.state.builder.patch_jump_here(jump_on_false_condition);
1005
1006            // Else expression also can just take over our if target
1007            self.gen_expression(false_expr, ctx)?;
1008
1009            self.state.builder.patch_jump_here(skip_false_if_true);
1010        } else {
1011            self.state.builder.patch_jump_here(jump_on_false_condition);
1012        }
1013
1014        Ok(())
1015    }
1016
1017    fn gen_while_loop(
1018        &mut self,
1019        condition: &BooleanExpression,
1020        expression: &Expression,
1021        ctx: &Context,
1022    ) -> Result<(), Error> {
1023        // `while` loops are only for side effects, make sure that the target size is zero (Unit)
1024        assert_eq!(ctx.target_size().0, 0);
1025
1026        let ip_for_condition = self.state.builder.position();
1027
1028        let (_condition_ctx, jump_on_false_condition) = self.gen_condition_context(condition)?;
1029
1030        // Expression is only for side effects
1031        let mut unit_ctx = self.temp_space_for_type(&Type::Unit, "while body expression");
1032        self.gen_expression(expression, &mut unit_ctx)?;
1033
1034        // Always jump to the condition again to see if it is true
1035        self.state
1036            .builder
1037            .add_jmp(ip_for_condition, "jmp to while condition");
1038
1039        self.state.builder.patch_jump_here(jump_on_false_condition);
1040
1041        Ok(())
1042    }
1043
1044    fn gen_location_argument(
1045        &mut self,
1046        argument: &SingleLocationExpression,
1047        ctx: &Context,
1048        comment: &str,
1049    ) -> Result<(), Error> {
1050        let region = self.gen_lvalue_address(argument)?;
1051
1052        self.state
1053            .builder
1054            .add_mov(ctx.addr(), region.addr, region.size, comment);
1055
1056        Ok(())
1057    }
1058
1059    fn gen_variable_assignment(
1060        &mut self,
1061        variable: &VariableRef,
1062        expression: &Expression,
1063        ctx: &Context,
1064    ) -> Result<(), Error> {
1065        let target_relative_frame_pointer = self
1066            .variable_offsets
1067            .get(&variable.unique_id_within_function)
1068            .unwrap_or_else(|| panic!("{}", variable.assigned_name));
1069
1070        let init_ctx =
1071            ctx.with_target(*target_relative_frame_pointer, "variable assignment target");
1072
1073        let _ = self.gen_expression(expression, &init_ctx)?;
1074
1075        Ok(())
1076    }
1077
1078    fn gen_variable_binding(
1079        &mut self,
1080        variable: &VariableRef,
1081        mut_or_immutable_expression: &MutRefOrImmutableExpression,
1082        ctx: &Context,
1083    ) -> Result<(), Error> {
1084        let target_relative_frame_pointer = self
1085            .variable_offsets
1086            .get(&variable.unique_id_within_function)
1087            .unwrap_or_else(|| panic!("{}", variable.assigned_name));
1088
1089        let init_ctx =
1090            ctx.with_target(*target_relative_frame_pointer, "variable assignment target");
1091
1092        self.gen_mut_or_immute(mut_or_immutable_expression, &init_ctx)
1093    }
1094
1095    fn gen_assignment(
1096        &mut self,
1097        lhs: &TargetAssignmentLocation,
1098        rhs: &Expression,
1099    ) -> Result<(), Error> {
1100        let lhs_addr = self.gen_lvalue_address(&lhs.0)?;
1101        let access = self.gen_expression_for_access(rhs)?;
1102
1103        self.state
1104            .builder
1105            .add_mov(lhs_addr.addr, access.addr, access.size, "assignment");
1106
1107        Ok(())
1108    }
1109
1110    fn gen_variable_definition(
1111        &mut self,
1112        variable: &VariableRef,
1113        expression: &Expression,
1114        ctx: &Context,
1115    ) -> Result<(), Error> {
1116        self.gen_variable_assignment(variable, expression, ctx)
1117    }
1118
1119    fn gen_variable_reassignment(
1120        &mut self,
1121        variable: &VariableRef,
1122        expression: &Expression,
1123        ctx: &Context,
1124    ) -> Result<(), Error> {
1125        self.gen_variable_assignment(variable, expression, ctx)
1126    }
1127
1128    fn copy_back_mutable_arguments(
1129        &mut self,
1130        signature: &Signature,
1131        maybe_self: Option<FrameMemoryRegion>,
1132        arguments: &Vec<MutRefOrImmutableExpression>,
1133    ) -> Result<(), Error> {
1134        let arguments_memory_region = self.infinite_above_frame_size();
1135        let mut arguments_allocator = ScopeAllocator::new(arguments_memory_region);
1136
1137        let _argument_addr = Self::reserve(&signature.return_type, &mut arguments_allocator);
1138
1139        let mut parameters = signature.parameters.clone();
1140        if let Some(found_self) = maybe_self {
1141            let source_region =
1142                Self::reserve(&parameters[0].resolved_type, &mut arguments_allocator);
1143            self.state.builder.add_mov(
1144                found_self.addr,
1145                source_region.addr,
1146                source_region.size,
1147                "copy back to <self>",
1148            );
1149            parameters.remove(0);
1150        }
1151        for (parameter, argument) in parameters.iter().zip(arguments) {
1152            let source_region = Self::reserve(&parameter.resolved_type, &mut arguments_allocator);
1153            if !parameter.is_mutable {
1154                continue;
1155            }
1156
1157            if let MutRefOrImmutableExpression::Location(found_location) = argument {
1158                let argument_target = self.gen_lvalue_address(found_location)?;
1159                self.state.builder.add_mov(
1160                    argument_target.addr,
1161                    source_region.addr,
1162                    source_region.size,
1163                    &format!(
1164                        "copy back mutable argument {}",
1165                        found_location.starting_variable.assigned_name
1166                    ),
1167                );
1168            } else {
1169                panic!("internal error. argument is mut but not a location")
1170            }
1171        }
1172        Ok(())
1173    }
1174    fn gen_arguments(
1175        &mut self,
1176        signature: &Signature,
1177        self_region: Option<FrameMemoryRegion>,
1178        arguments: &Vec<MutRefOrImmutableExpression>,
1179    ) -> Result<FrameMemoryRegion, Error> {
1180        self.argument_allocator.reset();
1181        // Layout return and arguments, must be continuous space
1182        let argument_addr = Self::reserve(&signature.return_type, &mut self.argument_allocator);
1183        assert_eq!(argument_addr.addr.0, self.frame_size.0);
1184
1185        let mut argument_targets = Vec::new();
1186        let mut argument_comments = Vec::new();
1187
1188        // Layout arguments, must be continuous space
1189        for (index, type_for_parameter) in signature.parameters.iter().enumerate() {
1190            let argument_target = Self::reserve(
1191                &type_for_parameter.resolved_type,
1192                &mut self.argument_allocator,
1193            );
1194            let arg_ctx = Context::new(argument_target);
1195            argument_targets.push(arg_ctx);
1196            argument_comments.push(format!("argument {}", type_for_parameter.name));
1197        }
1198
1199        if let Some(push_self) = self_region {
1200            self.state.builder.add_mov(
1201                argument_targets[0].addr(),
1202                push_self.addr,
1203                push_self.size,
1204                "<self>",
1205            );
1206            argument_targets.remove(0);
1207        }
1208
1209        for ((argument_target_ctx, argument_expr_or_loc), argument_comment) in argument_targets
1210            .iter()
1211            .zip(arguments)
1212            .zip(argument_comments)
1213        {
1214            let debug_addr = argument_target_ctx.target().addr();
1215            self.gen_argument(
1216                argument_expr_or_loc,
1217                &argument_target_ctx,
1218                &argument_comment,
1219            )?;
1220        }
1221
1222        let memory_size = argument_targets
1223            .last()
1224            .map_or(MemorySize(0), |last_target| {
1225                MemorySize(
1226                    last_target.addr().add(last_target.target_size()).0
1227                        - argument_targets[0].addr().0,
1228                )
1229            });
1230
1231        let start_addr = argument_targets
1232            .first()
1233            .map_or(FrameMemoryAddress(0), |first| first.addr());
1234
1235        Ok(FrameMemoryRegion {
1236            addr: start_addr,
1237            size: memory_size,
1238        })
1239    }
1240
1241    #[allow(clippy::too_many_lines)]
1242    fn gen_postfix_chain(
1243        &mut self,
1244        start_expression: &Expression,
1245        chain: &[Postfix],
1246        ctx: &Context,
1247    ) -> Result<(), Error> {
1248        if let ExpressionKind::InternalFunctionAccess(internal_fn) = &start_expression.kind {
1249            if chain.len() == 1 {
1250                if let PostfixKind::FunctionCall(args) = &chain[0].kind {
1251                    if let Some(intrinsic_fn) = single_intrinsic_fn(&internal_fn.body) {
1252                        self.gen_single_intrinsic_call(intrinsic_fn, None, args, ctx)?;
1253                    } else {
1254                        self.gen_arguments(&internal_fn.signature.signature, None, args)?;
1255                        self.state
1256                            .add_call(internal_fn, &format!("frame size: {}", self.frame_size)); // will be fixed up later
1257                        let (return_size, _alignment) =
1258                            type_size_and_alignment(&internal_fn.signature.signature.return_type);
1259                        if return_size.0 != 0 {
1260                            self.state.builder.add_mov(
1261                                ctx.addr(),
1262                                self.infinite_above_frame_size().addr,
1263                                return_size,
1264                                "copy the ret value to destination",
1265                            );
1266                        }
1267                        self.copy_back_mutable_arguments(
1268                            &internal_fn.signature.signature,
1269                            None,
1270                            args,
1271                        )?;
1272                    }
1273
1274                    return Ok(());
1275                }
1276            }
1277        }
1278
1279        if let ExpressionKind::ExternalFunctionAccess(external_fn) = &start_expression.kind {
1280            if chain.len() == 1 {
1281                if let PostfixKind::FunctionCall(args) = &chain[0].kind {
1282                    let total_region = self.gen_arguments(&external_fn.signature, None, args)?;
1283                    self.state.builder.add_host_call(
1284                        external_fn.id as u16,
1285                        total_region.size,
1286                        &format!("call external '{}'", external_fn.assigned_name),
1287                    );
1288                    let (return_size, _alignment) =
1289                        type_size_and_alignment(&external_fn.signature.return_type);
1290                    if return_size.0 != 0 {
1291                        self.state.builder.add_mov(
1292                            ctx.addr(),
1293                            self.infinite_above_frame_size().addr,
1294                            return_size,
1295                            "copy the ret value to destination",
1296                        );
1297                    }
1298
1299                    return Ok(());
1300                }
1301            }
1302        }
1303
1304        let mut start_source = self.gen_expression_for_access(start_expression)?;
1305
1306        for element in chain {
1307            match &element.kind {
1308                PostfixKind::StructField(anonymous_struct, field_index) => {
1309                    let (memory_offset, memory_size, _max_alignment) =
1310                        Self::get_struct_field_offset(
1311                            &anonymous_struct.field_name_sorted_fields,
1312                            *field_index,
1313                        );
1314                    start_source = FrameMemoryRegion::new(
1315                        start_source.addr.advance(memory_offset),
1316                        memory_size,
1317                    );
1318                }
1319                PostfixKind::MemberCall(function_to_call, arguments) => {
1320                    match &**function_to_call {
1321                        Function::Internal(internal_fn) => {
1322                            if let Some(intrinsic_fn) = single_intrinsic_fn(&internal_fn.body) {
1323                                self.gen_single_intrinsic_call(
1324                                    intrinsic_fn,
1325                                    Some(start_source),
1326                                    arguments,
1327                                    ctx,
1328                                )?;
1329                            } else {
1330                                self.gen_arguments(
1331                                    &internal_fn.signature.signature,
1332                                    Some(start_source),
1333                                    arguments,
1334                                )?;
1335                                self.state.add_call(
1336                                    internal_fn,
1337                                    &format!("frame size: {}", self.frame_size),
1338                                ); // will be fixed up later
1339
1340                                let (return_size, _alignment) = type_size_and_alignment(
1341                                    &internal_fn.signature.signature.return_type,
1342                                );
1343                                if return_size.0 != 0 {
1344                                    self.state.builder.add_mov(
1345                                        ctx.addr(),
1346                                        self.infinite_above_frame_size().addr,
1347                                        return_size,
1348                                        "copy the return value to destination",
1349                                    );
1350                                }
1351
1352                                self.copy_back_mutable_arguments(
1353                                    &internal_fn.signature.signature,
1354                                    Some(start_source),
1355                                    arguments,
1356                                )?;
1357                            }
1358                        }
1359                        Function::External(external_fn) => {
1360                            //self.state.builder.add_host_call(external_fn.id);
1361                        }
1362                    }
1363                }
1364                PostfixKind::FunctionCall(arguments) => {
1365                    //self.gen_arguments(arguments);
1366                    //self.state.add_call(start_expression)
1367                }
1368                PostfixKind::OptionalChainingOperator => todo!(),
1369                PostfixKind::NoneCoalescingOperator(_) => todo!(),
1370            }
1371        }
1372
1373        Ok(())
1374    }
1375
1376    fn gen_tuple(&mut self, expressions: &[Expression], ctx: &Context) -> Result<(), Error> {
1377        let mut scope = ScopeAllocator::new(ctx.target());
1378
1379        for expr in expressions {
1380            let (memory_size, alignment) = type_size_and_alignment(&expr.ty);
1381            let start_addr = scope.allocate(memory_size, alignment);
1382            let element_region = FrameMemoryRegion::new(start_addr, memory_size);
1383            let element_ctx = Context::new(element_region);
1384            self.gen_expression(expr, &element_ctx)?;
1385        }
1386
1387        Ok(())
1388    }
1389
1390    fn get_struct_field_offset(
1391        fields: &SeqMap<String, StructTypeField>,
1392        index_to_find: usize,
1393    ) -> (MemoryOffset, MemorySize, MemoryAlignment) {
1394        let mut offset = 0;
1395
1396        for (index, (_name, field)) in fields.iter().enumerate() {
1397            let (struct_field_size, struct_field_align) =
1398                type_size_and_alignment(&field.field_type);
1399            if index == index_to_find {
1400                return (MemoryOffset(offset), struct_field_size, struct_field_align);
1401            }
1402
1403            offset += struct_field_size.0;
1404        }
1405
1406        panic!("field not found");
1407    }
1408
1409    fn gen_anonymous_struct(
1410        &mut self,
1411        anon_struct_type: &AnonymousStructType,
1412        source_order_expressions: &Vec<(usize, Expression)>,
1413        base_context: &Context,
1414    ) -> Result<(), Error> {
1415        for (field_index, expression) in source_order_expressions {
1416            let (field_memory_offset, field_size, _field_alignment) = Self::get_struct_field_offset(
1417                &anon_struct_type.field_name_sorted_fields,
1418                *field_index,
1419            );
1420            let field_ctx = base_context.with_offset(field_memory_offset, field_size);
1421            self.gen_expression(expression, &field_ctx)?;
1422        }
1423
1424        Ok(())
1425    }
1426
1427    fn gen_literal(&mut self, literal: &Literal, ctx: &Context) -> Result<(), Error> {
1428        match literal {
1429            Literal::IntLiteral(int) => {
1430                self.state.builder.add_ld32(ctx.addr(), *int, "int literal");
1431            }
1432            Literal::FloatLiteral(fixed_point) => {
1433                self.state
1434                    .builder
1435                    .add_ld32(ctx.addr(), fixed_point.inner(), "float literal");
1436            }
1437            Literal::NoneLiteral => {
1438                self.state.builder.add_ld8(ctx.addr(), 0, "none literal");
1439            }
1440            Literal::BoolLiteral(truthy) => {
1441                self.state
1442                    .builder
1443                    .add_ld8(ctx.addr(), u8::from(*truthy), "bool literal");
1444            }
1445
1446            Literal::EnumVariantLiteral(enum_type, a, b) => {
1447                self.state.builder.add_ld8(
1448                    ctx.addr(),
1449                    a.common().container_index,
1450                    &format!("enum variant {} tag", a.common().assigned_name),
1451                );
1452
1453                let starting_offset = MemoryOffset(1);
1454
1455                let (data_size, data_alignment) = match a {
1456                    EnumVariantType::Struct(enum_variant_struct) => {
1457                        layout_struct(&enum_variant_struct.anon_struct)
1458                    }
1459                    EnumVariantType::Tuple(tuple_type) => layout_tuple(&tuple_type.fields_in_order),
1460                    EnumVariantType::Nothing(_) => (MemorySize(0), MemoryAlignment::U8),
1461                };
1462
1463                let skip_octets: usize = data_alignment.into();
1464                let skip = MemorySize(skip_octets as u16);
1465                let inner_addr = ctx.addr().add(skip);
1466                let region = FrameMemoryRegion::new(inner_addr, data_size);
1467                let inner_ctx = Context::new(region);
1468
1469                //layout_union(a)
1470                match b {
1471                    EnumLiteralData::Nothing => {}
1472                    EnumLiteralData::Tuple(expressions) => {
1473                        self.gen_tuple(expressions, &inner_ctx)?;
1474                    }
1475                    EnumLiteralData::Struct(sorted_expressions) => {
1476                        if let EnumVariantType::Struct(variant_struct_type) = a {
1477                            self.gen_anonymous_struct(
1478                                &variant_struct_type.anon_struct,
1479                                sorted_expressions,
1480                                &inner_ctx,
1481                            )?;
1482                        }
1483                    }
1484                }
1485            }
1486            Literal::TupleLiteral(_tuple_type, expressions) => self.gen_tuple(expressions, ctx)?,
1487            Literal::StringLiteral(str) => {
1488                self.gen_string_literal(str, ctx);
1489            }
1490            Literal::Slice(ty, expressions) => {
1491                //self.gen_slice_literal(ty, expressions, ctx)
1492                todo!()
1493            }
1494            Literal::SlicePair(ty, expression_pairs) => {
1495                todo!()
1496            }
1497        }
1498
1499        Ok(())
1500    }
1501
1502    fn gen_string_literal(&mut self, string: &str, ctx: &Context) {
1503        let string_bytes = string.as_bytes();
1504        let string_byte_count = string_bytes.len();
1505
1506        let data_ptr = self
1507            .state
1508            .constants
1509            .allocate(string_bytes, MemoryAlignment::U8);
1510
1511        let mem_size = MemorySize(string_byte_count as u16);
1512
1513        self.state.builder.add_string_from_constant_slice(
1514            ctx.addr(),
1515            data_ptr,
1516            mem_size,
1517            "create string",
1518        );
1519        // self.gen_vec_immediate(data_ptr, mem_size, mem_size, "string", ctx);
1520    }
1521
1522    /*
1523    fn gen_vec_immediate(
1524        &mut self,
1525        data_ptr: MemoryAddress,
1526        len: MemorySize,
1527        capacity: MemorySize,
1528        comment_prefix: &str,
1529        ctx: &Context,
1530    ) {
1531        self.state
1532            .builder
1533            .add_ld_u16(ctx.addr(), len.0, &format!("{} len", comment_prefix));
1534
1535        self.state.builder.add_ld_u16(
1536            ctx.addr().add(MemorySize(2)),
1537            capacity.0,
1538            &format!("{} capacity", comment_prefix),
1539        );
1540
1541        self.state.builder.add_ld_u16(
1542            ctx.addr().add(MemorySize(4)),
1543            data_ptr.0,
1544            &format!("{} ptr", comment_prefix),
1545        );
1546    }
1547
1548
1549     */
1550    fn gen_option_expression(
1551        &mut self,
1552        maybe_option: Option<&Expression>,
1553        ctx: &Context,
1554    ) -> Result<(), Error> {
1555        if let Some(found_value) = maybe_option {
1556            self.state.builder.add_ld8(ctx.addr(), 1, "option Some tag"); // 1 signals `Some`
1557            let (inner_size, inner_alignment) = type_size_and_alignment(&found_value.ty);
1558            let one_offset_ctx = ctx.with_offset(inner_alignment.into(), inner_size);
1559
1560            self.gen_expression(found_value, &one_offset_ctx)?; // Fills in more of the union
1561        } else {
1562            self.state.builder.add_ld8(ctx.addr(), 0, "option None tag"); // 0 signals `None`
1563            // No real need to clear the rest of the memory
1564        }
1565
1566        Ok(())
1567    }
1568
1569    fn gen_for_loop_vec(
1570        &mut self,
1571        for_pattern: &ForPattern,
1572        collection_expr: &MutRefOrImmutableExpression,
1573    ) -> Result<(InstructionPosition, PatchPosition), Error> {
1574        let collection_region = self.gen_for_access_or_location(collection_expr)?;
1575
1576        let temp_iterator_region = self
1577            .temp_allocator
1578            .allocate(MemorySize(VEC_ITERATOR_SIZE), VEC_ITERATOR_ALIGNMENT);
1579        self.state.builder.add_vec_iter_init(
1580            temp_iterator_region,
1581            FrameMemoryAddressIndirectPointer(collection_region.addr),
1582            "initialize vec iterator",
1583        );
1584
1585        let loop_ip = self.state.builder.position();
1586
1587        let placeholder_position = match for_pattern {
1588            ForPattern::Single(variable) => {
1589                let target_variable = self
1590                    .variable_offsets
1591                    .get(&variable.unique_id_within_function)
1592                    .unwrap();
1593                self.state.builder.add_vec_iter_next_placeholder(
1594                    temp_iterator_region,
1595                    target_variable.addr,
1596                    "move to next or jump over",
1597                )
1598            }
1599            ForPattern::Pair(variable_a, variable_b) => {
1600                let target_variable_a = self
1601                    .variable_offsets
1602                    .get(&variable_a.unique_id_within_function)
1603                    .unwrap();
1604                let target_variable_b = self
1605                    .variable_offsets
1606                    .get(&variable_b.unique_id_within_function)
1607                    .unwrap();
1608                self.state.builder.add_vec_iter_next_pair_placeholder(
1609                    temp_iterator_region,
1610                    target_variable_a.addr,
1611                    target_variable_b.addr,
1612                    "move to next or jump over",
1613                )
1614            }
1615        };
1616
1617        Ok((loop_ip, placeholder_position))
1618    }
1619
1620    fn gen_for_loop_map(
1621        &mut self,
1622        for_pattern: &ForPattern,
1623    ) -> Result<(InstructionPosition, PatchPosition), Error> {
1624        self.state.builder.add_map_iter_init(
1625            FrameMemoryAddress(0x80),
1626            FrameMemoryAddressIndirectPointer(FrameMemoryAddress(0xffff)),
1627            "initialize map iterator",
1628        );
1629
1630        let jump_ip = self.state.builder.position();
1631
1632        match for_pattern {
1633            ForPattern::Single(_) => {
1634                self.state.builder.add_map_iter_next(
1635                    FrameMemoryAddress(0x80),
1636                    FrameMemoryAddress(0x16),
1637                    InstructionPosition(256),
1638                    "move to next or jump over",
1639                );
1640            }
1641            ForPattern::Pair(_, _) => {
1642                self.state.builder.add_map_iter_next_pair(
1643                    FrameMemoryAddress(0x80),
1644                    FrameMemoryAddress(0x16),
1645                    FrameMemoryAddress(0x16),
1646                    InstructionPosition(256),
1647                    "move to next or jump over",
1648                );
1649            }
1650        }
1651
1652        Ok((jump_ip, PatchPosition(InstructionPosition(0))))
1653    }
1654
1655    fn gen_for_loop(
1656        &mut self,
1657        for_pattern: &ForPattern,
1658        iterable: &Iterable,
1659        closure: &Box<Expression>,
1660    ) -> Result<(), Error> {
1661        // Add check if the collection is empty, to skip everything
1662
1663        // get some kind of iteration pointer
1664
1665        // check if it has reached its end
1666
1667        let collection_type = &iterable.resolved_expression.ty();
1668        let (jump_ip, placeholder_position) = match collection_type {
1669            Type::String => {
1670                todo!();
1671            }
1672            Type::NamedStruct(_vec) => {
1673                if let Some(found_info) = is_vec(collection_type) {
1674                    self.gen_for_loop_vec(for_pattern, &iterable.resolved_expression)?
1675                } else if let Some(found_info) = is_map(collection_type) {
1676                    self.gen_for_loop_map(for_pattern)?
1677                } else {
1678                    return Err(self.create_err(
1679                        ErrorKind::NotAnIterableCollection,
1680                        iterable.resolved_expression.node(),
1681                    ));
1682                }
1683            }
1684            _ => {
1685                return Err(self.create_err(
1686                    ErrorKind::IllegalCollection,
1687                    iterable.resolved_expression.node(),
1688                ));
1689            }
1690        };
1691
1692        match for_pattern {
1693            ForPattern::Single(value_variable) => {}
1694            ForPattern::Pair(key_variable, value_variable) => {}
1695        }
1696
1697        let unit_expr = self.temp_space_for_type(&Type::Unit, "for loop body");
1698        self.gen_expression(closure, &unit_expr)?;
1699
1700        self.state
1701            .builder
1702            .add_jmp(jump_ip, "jump to next iteration");
1703        // advance iterator pointer
1704        // jump to check if iterator pointer has reached its end
1705        self.state.builder.patch_jump_here(placeholder_position);
1706
1707        Ok(())
1708    }
1709
1710    fn gen_for_loop_for_vec(
1711        &mut self,
1712        element_type: &Type,
1713        vector_expr: Expression,
1714        ctx: &mut Context,
1715    ) -> Result<GeneratedExpressionResult, Error> {
1716        // get the vector that is referenced
1717        let vector_ctx = self.temp_space_for_type(&vector_expr.ty, "vector space");
1718        self.gen_expression(&vector_expr, &vector_ctx)
1719
1720        /*
1721        let value_var_addr = match for_pattern {
1722            ForPattern::Single(value_variable) => self
1723                .variable_offsets
1724                .get(&value_variable.unique_id_within_function)
1725                .expect("Variable not found"),
1726            ForPattern::Pair(_, _) => {
1727                panic!("Cannot use key-value pattern with vectors");
1728            }
1729        };
1730
1731         */
1732
1733        /*
1734        let element_size = type_size(element_type);
1735               // Temporary for the counter
1736               let counter_addr = ctx.allocate_temp(MemorySize(2)); // u16 counter
1737               self.state
1738                   .builder
1739                   .add_ld_u16(counter_addr, 0, "temporary counter");
1740
1741               let loop_start_pos = self.state.builder.position();
1742
1743               // vector length
1744               let length_addr = ctx.allocate_temp(MemorySize(2));
1745               self.state.builder.add_mov(
1746                   length_addr,
1747                   vector_ctx.addr().add(MemorySize(VECTOR_LENGTH_OFFSET)),
1748                   MemorySize(2),
1749                   "vector length",
1750               );
1751
1752               // Compare counter < length
1753               let compare_result_addr = ctx.allocate_temp(MemorySize(1)); // boolean result
1754               self.state.builder.add_lt_u16(
1755                   compare_result_addr,
1756                   counter_addr,
1757                   length_addr,
1758                   "counter < length",
1759               );
1760
1761               // Exit loop if counter >= length
1762               let exit_jump = self
1763                   .state
1764                   .builder
1765                   .add_conditional_jump_placeholder(compare_result_addr, "counter >= length exit");
1766
1767               let data_ptr_addr = ctx.allocate_temp(MemorySize(2));
1768               self.state.builder.add_mov(
1769                   data_ptr_addr,
1770                   vector_ctx.addr().add(MemorySize(VECTOR_DATA_PTR_OFFSET)),
1771                   MemorySize(PTR_SIZE),
1772                   "copy vector data ptr",
1773               );
1774
1775
1776        */
1777        /*
1778        let offset_addr = ctx.allocate_temp(2);
1779        self.state.builder.add_mul_u16(
1780            offset_addr,
1781            counter_addr,
1782            element_size
1783        );
1784
1785        self.state.builder.add_ld_indirect(
1786            *value_var_addr,     // Destination: loop variable
1787            data_ptr_addr,       // Base: vector's data pointer
1788            offset_addr,         // Offset: counter * element_size
1789            element_size         // Size to copy
1790        );
1791
1792        let mut body_ctx = ctx.temp_space_for_type(&Type::Unit);
1793        self.gen_expression(body, &mut body_ctx);
1794
1795        self.state.builder.add_inc_u16(counter_addr);
1796
1797        self.state.builder.add_jmp_to_position(loop_start_pos);
1798
1799        let end_pos = self.state.builder.current_position();
1800        self.state.builder.patch_jump(exit_jump, end_pos);
1801
1802         */
1803    }
1804
1805    fn gen_block(&mut self, expressions: &[Expression], ctx: &Context) -> Result<(), Error> {
1806        if let Some((last, others)) = expressions.split_last() {
1807            for expr in others {
1808                let temp_context = self.temp_space_for_type(&Type::Unit, "block target");
1809                self.gen_expression(expr, &temp_context)?;
1810            }
1811            self.gen_expression(last, ctx)?;
1812        }
1813
1814        Ok(())
1815    }
1816
1817    fn get_variable_region(&self, variable: &VariableRef) -> (FrameMemoryRegion, MemoryAlignment) {
1818        let frame_address = self
1819            .variable_offsets
1820            .get(&variable.unique_id_within_function)
1821            .unwrap();
1822        let (_size, align) = type_size_and_alignment(&variable.resolved_type);
1823
1824        (*frame_address, align)
1825    }
1826
1827    fn gen_variable_access(&mut self, variable: &VariableRef, ctx: &Context) -> Result<(), Error> {
1828        let (region, alignment) = self.get_variable_region(variable);
1829        self.state.builder.add_mov(
1830            ctx.addr(),
1831            region.addr,
1832            region.size,
1833            &format!(
1834                "variable access '{}' ({})",
1835                variable.assigned_name,
1836                ctx.comment()
1837            ),
1838        );
1839
1840        Ok(())
1841    }
1842
1843    fn referenced_or_not_type(ty: &Type) -> Type {
1844        if let Type::MutableReference(inner_type) = ty {
1845            *inner_type.clone()
1846        } else {
1847            ty.clone()
1848        }
1849    }
1850
1851    fn compound_assignment(
1852        &mut self,
1853        target_location: &TargetAssignmentLocation,
1854        op: &CompoundOperatorKind,
1855        source: &Expression,
1856        ctx: &Context,
1857    ) -> Result<(), Error> {
1858        let target_location = self.gen_lvalue_address(&target_location.0)?;
1859
1860        let source_info = self.gen_expression_for_access(source)?;
1861
1862        let type_to_consider = Self::referenced_or_not_type(&source.ty);
1863
1864        match &type_to_consider {
1865            Type::Int => {
1866                self.gen_compound_assignment_i32(&target_location, op, &source_info);
1867            }
1868            Type::Float => {
1869                self.gen_compound_assignment_f32(&target_location, op, &source_info);
1870            }
1871            Type::String => todo!(),
1872            _ => return Err(self.create_err(ErrorKind::IllegalCompoundAssignment, &source.node)),
1873        }
1874
1875        Ok(())
1876    }
1877
1878    fn gen_compound_assignment_i32(
1879        &mut self,
1880        target: &FrameMemoryRegion,
1881        op: &CompoundOperatorKind,
1882        source_ctx: &FrameMemoryRegion,
1883    ) {
1884        match op {
1885            CompoundOperatorKind::Add => {
1886                self.state.builder.add_add_i32(
1887                    target.addr(),
1888                    target.addr(),
1889                    source_ctx.addr(),
1890                    "+=  (i32)",
1891                );
1892            }
1893            CompoundOperatorKind::Sub => todo!(),
1894            CompoundOperatorKind::Mul => todo!(),
1895            CompoundOperatorKind::Div => todo!(),
1896            CompoundOperatorKind::Modulo => todo!(),
1897        }
1898    }
1899
1900    fn gen_compound_assignment_f32(
1901        &mut self,
1902        target: &FrameMemoryRegion,
1903        op: &CompoundOperatorKind,
1904        source_ctx: &FrameMemoryRegion,
1905    ) {
1906        match op {
1907            CompoundOperatorKind::Add => {
1908                self.state.builder.add_add_f32(
1909                    target.addr(),
1910                    target.addr(),
1911                    source_ctx.addr(),
1912                    "+=  (f32)",
1913                );
1914            }
1915            CompoundOperatorKind::Sub => todo!(),
1916            CompoundOperatorKind::Mul => todo!(),
1917            CompoundOperatorKind::Div => todo!(),
1918            CompoundOperatorKind::Modulo => todo!(),
1919        }
1920    }
1921
1922    fn internal_function_access(
1923        &mut self,
1924        internal: &InternalFunctionDefinitionRef,
1925        ctx: &Context,
1926    ) -> Result<(), Error> {
1927        self.state.builder.add_ld_u16(
1928            ctx.addr(),
1929            internal.program_unique_id,
1930            &format!("function access '{}'", internal.assigned_name),
1931        );
1932        Ok(())
1933    }
1934
1935    fn infinite_above_frame_size(&self) -> FrameMemoryRegion {
1936        FrameMemoryRegion::new(FrameMemoryAddress(self.frame_size.0), MemorySize(1024))
1937    }
1938
1939    fn gen_struct_literal(
1940        &mut self,
1941        struct_literal: &StructInstantiation,
1942        ctx: &Context,
1943    ) -> Result<(), Error> {
1944        self.gen_struct_literal_helper(
1945            &struct_literal.struct_type_ref.anon_struct_type,
1946            &struct_literal.source_order_expressions,
1947            ctx,
1948        )
1949    }
1950
1951    fn gen_anonymous_struct_literal(
1952        &mut self,
1953        anon_struct_literal: &AnonymousStructLiteral,
1954        ctx: &Context,
1955    ) -> Result<(), Error> {
1956        self.gen_struct_literal_helper(
1957            &anon_struct_literal.anonymous_struct_type,
1958            &anon_struct_literal.source_order_expressions,
1959            ctx,
1960        )
1961    }
1962
1963    fn gen_struct_literal_helper(
1964        &mut self,
1965        struct_type_ref: &AnonymousStructType,
1966        source_order_expressions: &Vec<(usize, Expression)>,
1967        ctx: &Context,
1968    ) -> Result<(), Error> {
1969        let struct_type = Type::AnonymousStruct(struct_type_ref.clone());
1970        let (whole_struct_size, whole_struct_alignment) = type_size_and_alignment(&struct_type);
1971        if ctx.target_size().0 != whole_struct_size.0 {
1972            info!("problem");
1973        }
1974        assert_eq!(ctx.target_size().0, whole_struct_size.0);
1975
1976        for (field_index, expression) in source_order_expressions {
1977            let (field_offset, field_size, field_alignment) =
1978                struct_field_offset(*field_index, struct_type_ref);
1979            //info!(?field_offset, ?field_index, "field offset");
1980            let new_address = ctx.addr().advance(field_offset);
1981            let field_ctx = Context::new(FrameMemoryRegion::new(new_address, field_size));
1982            self.gen_expression(expression, &field_ctx)?;
1983        }
1984
1985        Ok(())
1986    }
1987
1988    fn gen_slice_literal(
1989        &mut self,
1990        ty: &Type,
1991        expressions: &Vec<Expression>,
1992    ) -> Result<FrameMemoryRegion, Error> {
1993        let (element_size, element_alignment) = type_size_and_alignment(ty);
1994        let element_count = expressions.len() as u16;
1995        let total_slice_size = MemorySize(element_size.0 * element_count);
1996
1997        let start_frame_address_to_transfer = self
1998            .temp_allocator
1999            .allocate(total_slice_size, element_alignment);
2000        for (index, expr) in expressions.iter().enumerate() {
2001            let memory_offset = MemoryOffset((index as u16) * element_size.0);
2002            let region = FrameMemoryRegion::new(
2003                start_frame_address_to_transfer.advance(memory_offset),
2004                element_size,
2005            );
2006            let element_ctx = Context::new(region);
2007            self.gen_expression(expr, &element_ctx)?;
2008        }
2009
2010        Ok(FrameMemoryRegion::new(
2011            start_frame_address_to_transfer,
2012            total_slice_size,
2013        ))
2014    }
2015
2016    fn gen_slice_pair_literal(
2017        &mut self,
2018        slice_type: &Type,
2019        expressions: &[(Expression, Expression)],
2020    ) -> SlicePairInfo {
2021        let Type::SlicePair(key_type, value_type) = slice_type else {
2022            panic!("should have been slice pair type")
2023        };
2024
2025        let constructed_tuple = Type::Tuple(vec![*key_type.clone(), *value_type.clone()]);
2026
2027        let (key_size, key_alignment) = type_size_and_alignment(key_type);
2028        let (value_size, value_alignment) = type_size_and_alignment(value_type);
2029        let (element_size, tuple_alignment) = type_size_and_alignment(&constructed_tuple);
2030        let element_count = expressions.len() as u16;
2031        let total_slice_size = MemorySize(element_size.0 * element_count);
2032
2033        let start_frame_address_to_transfer = self
2034            .temp_allocator
2035            .allocate(total_slice_size, tuple_alignment);
2036
2037        for (index, (key_expr, value_expr)) in expressions.iter().enumerate() {
2038            let memory_offset = MemoryOffset((index as u16) * element_size.0);
2039            let key_region = FrameMemoryRegion::new(
2040                start_frame_address_to_transfer.advance(memory_offset),
2041                element_size,
2042            );
2043            let key_ctx = Context::new(key_region);
2044            self.gen_expression(key_expr, &key_ctx);
2045
2046            let value_region = FrameMemoryRegion::new(
2047                start_frame_address_to_transfer.advance(memory_offset.add(key_size, key_alignment)),
2048                value_size,
2049            );
2050            let value_ctx = Context::new(value_region);
2051            self.gen_expression(value_expr, &value_ctx);
2052        }
2053
2054        SlicePairInfo {
2055            addr: TempFrameMemoryAddress(start_frame_address_to_transfer),
2056            key_size,
2057            value_size,
2058            element_count: CountU16(element_count),
2059            element_size,
2060        }
2061    }
2062
2063    fn gen_slice_helper(
2064        &mut self,
2065        start_temp_frame_address_to_transfer: FrameMemoryAddress,
2066        element_count: u16,
2067        element_size: MemorySize,
2068        ctx: &Context,
2069    ) {
2070        let total_slice_size = MemorySize(element_size.0 * element_count);
2071        let vec_len_addr = ctx.addr().advance(MemoryOffset(0));
2072        self.state
2073            .builder
2074            .add_ld_u16(vec_len_addr, element_count, "slice len");
2075
2076        let vec_capacity_addr = ctx.addr().advance(MemoryOffset(2));
2077        self.state
2078            .builder
2079            .add_ld_u16(vec_capacity_addr, element_count, "slice capacity");
2080
2081        let vec_element_size_addr = ctx.addr().advance(MemoryOffset(4));
2082        self.state
2083            .builder
2084            .add_ld_u16(vec_element_size_addr, element_size.0, "slice element size");
2085
2086        /*
2087        let allocated_vec_address = ctx.addr().advance(MemoryOffset(6));
2088        self.state
2089        .builder
2090        add_alloc(allocated_vec_address, total_slice_size, "slice literal");
2091
2092        self.state.builder.add_stx(
2093            allocated_vec_address,
2094            MemoryOffset(0),
2095            start_temp_frame_address_to_transfer,
2096            total_slice_size,
2097            "copy from slice continuous temporary frame memory to allocated vec ptr heap area",
2098        );
2099
2100         */
2101    }
2102
2103    fn gen_intrinsic_call_ex(
2104        &mut self,
2105        intrinsic_fn: &IntrinsicFunction,
2106        arguments: &Vec<MutRefOrImmutableExpression>,
2107        ctx: &Context,
2108    ) -> Result<(), Error> {
2109        //        info!(?intrinsic_fn, "generating intrinsic call");
2110
2111        match intrinsic_fn {
2112            // Fixed
2113            IntrinsicFunction::FloatRound => todo!(),
2114            IntrinsicFunction::FloatFloor => todo!(),
2115            IntrinsicFunction::FloatSqrt => todo!(),
2116            IntrinsicFunction::FloatSign => todo!(),
2117            IntrinsicFunction::FloatAbs => todo!(),
2118            IntrinsicFunction::FloatRnd => todo!(),
2119            IntrinsicFunction::FloatCos => todo!(),
2120            IntrinsicFunction::FloatSin => todo!(),
2121            IntrinsicFunction::FloatAcos => todo!(),
2122            IntrinsicFunction::FloatAsin => todo!(),
2123            IntrinsicFunction::FloatAtan2 => todo!(),
2124            IntrinsicFunction::FloatMin => todo!(),
2125            IntrinsicFunction::FloatMax => todo!(),
2126            IntrinsicFunction::FloatClamp => todo!(),
2127
2128            // i32
2129            IntrinsicFunction::IntAbs => todo!(),
2130            IntrinsicFunction::IntRnd => todo!(),
2131            IntrinsicFunction::IntMax => todo!(),
2132            IntrinsicFunction::IntMin => todo!(),
2133            IntrinsicFunction::IntClamp => todo!(),
2134            IntrinsicFunction::IntToFloat => todo!(),
2135
2136            // String
2137            IntrinsicFunction::StringLen => todo!(),
2138
2139            // Vector
2140            IntrinsicFunction::VecFromSlice => self.gen_intrinsic_vec_from_slice(arguments, ctx),
2141            IntrinsicFunction::VecPush => todo!(),
2142            IntrinsicFunction::VecPop => todo!(),
2143            IntrinsicFunction::VecFor => todo!(),
2144            IntrinsicFunction::VecWhile => todo!(),
2145            IntrinsicFunction::VecFindMap => todo!(),
2146            IntrinsicFunction::VecRemoveIndex => todo!(),
2147            IntrinsicFunction::VecRemoveIndexGetValue => todo!(),
2148            IntrinsicFunction::VecClear => todo!(),
2149            IntrinsicFunction::VecCreate => {
2150                self.gen_intrinsic_vec_create(arguments);
2151                Ok(())
2152            }
2153            IntrinsicFunction::VecSubscript => todo!(),
2154            IntrinsicFunction::VecSubscriptMut => todo!(),
2155            IntrinsicFunction::VecSubscriptRange => todo!(),
2156            IntrinsicFunction::VecIter => todo!(), // intentionally disregard, since it is never called
2157            IntrinsicFunction::VecIterMut => todo!(), // intentionally disregard, since it is never called
2158            IntrinsicFunction::VecLen => todo!(),
2159            IntrinsicFunction::VecIsEmpty => todo!(),
2160            IntrinsicFunction::VecSelfPush => todo!(),
2161            IntrinsicFunction::VecSelfExtend => todo!(),
2162            IntrinsicFunction::VecFold => todo!(),
2163            IntrinsicFunction::VecGet => todo!(),
2164
2165            // Map
2166            IntrinsicFunction::MapCreate => todo!(),
2167            IntrinsicFunction::MapFromSlicePair => todo!(),
2168            IntrinsicFunction::MapHas => todo!(),
2169            IntrinsicFunction::MapRemove => todo!(),
2170            IntrinsicFunction::MapIter => todo!(),
2171            IntrinsicFunction::MapIterMut => todo!(),
2172            IntrinsicFunction::MapLen => todo!(),
2173            IntrinsicFunction::MapIsEmpty => todo!(),
2174            IntrinsicFunction::MapSubscript => todo!(),
2175            IntrinsicFunction::MapSubscriptSet => todo!(),
2176            IntrinsicFunction::MapSubscriptMut => todo!(),
2177            IntrinsicFunction::MapSubscriptMutCreateIfNeeded => todo!(),
2178
2179            IntrinsicFunction::Map2GetColumn => todo!(),
2180            IntrinsicFunction::Map2GetRow => todo!(),
2181            IntrinsicFunction::Map2Remove => todo!(),
2182            IntrinsicFunction::Map2Has => todo!(),
2183            IntrinsicFunction::Map2Get => todo!(),
2184            IntrinsicFunction::Map2Insert => todo!(),
2185            IntrinsicFunction::Map2Create => todo!(),
2186
2187            // Sparse
2188            IntrinsicFunction::SparseAdd => todo!(),
2189            IntrinsicFunction::SparseNew => todo!(),
2190            IntrinsicFunction::SparseCreate => todo!(),
2191            IntrinsicFunction::SparseFromSlice => todo!(),
2192            IntrinsicFunction::SparseIter => todo!(),
2193            IntrinsicFunction::SparseIterMut => todo!(),
2194            IntrinsicFunction::SparseSubscript => todo!(),
2195            IntrinsicFunction::SparseSubscriptMut => todo!(),
2196            IntrinsicFunction::SparseHas => todo!(),
2197            IntrinsicFunction::SparseRemove => todo!(),
2198
2199            // Grid
2200            IntrinsicFunction::GridCreate => todo!(),
2201            IntrinsicFunction::GridFromSlice => todo!(),
2202            IntrinsicFunction::GridSet => todo!(),
2203            IntrinsicFunction::GridGet => todo!(),
2204            IntrinsicFunction::GridGetColumn => todo!(),
2205
2206            // Other
2207            IntrinsicFunction::Float2Magnitude => todo!(),
2208            IntrinsicFunction::VecAny => todo!(),
2209            IntrinsicFunction::VecAll => todo!(),
2210            IntrinsicFunction::VecMap => todo!(),
2211            IntrinsicFunction::VecFilter => todo!(),
2212            IntrinsicFunction::VecFilterMap => todo!(),
2213            IntrinsicFunction::VecFind => todo!(),
2214            IntrinsicFunction::VecSwap => todo!(),
2215            IntrinsicFunction::VecInsert => todo!(),
2216            IntrinsicFunction::VecFirst => todo!(),
2217            IntrinsicFunction::VecLast => todo!(),
2218        };
2219
2220        Ok(())
2221    }
2222
2223    fn gen_intrinsic_vec_create(&self, arguments: &Vec<MutRefOrImmutableExpression>) {
2224        for arg in arguments {
2225            info!(?arg, "argument");
2226        }
2227    }
2228
2229    fn gen_intrinsic_vec_from_slice(
2230        &mut self,
2231        arguments: &[MutRefOrImmutableExpression],
2232        ctx: &Context,
2233    ) -> Result<(), Error> {
2234        if let MutRefOrImmutableExpression::Expression(found_expr) = &arguments[0] {
2235            let memory = self.gen_expression_for_access(found_expr)?;
2236            self.state.builder.add_vec_from_slice(
2237                ctx.addr(),
2238                memory.addr,
2239                MemorySize(0),
2240                CountU16(0),
2241                "create vec",
2242            );
2243        } else {
2244            panic!("vec_from_slice");
2245        }
2246
2247        Ok(())
2248    }
2249
2250    fn gen_match(&mut self, match_expr: &Match, ctx: &Context) -> Result<(), Error> {
2251        let region_to_match = self.gen_for_access_or_location(&match_expr.expression)?;
2252
2253        let mut jump_to_exit_placeholders = Vec::new();
2254
2255        let arm_len_to_consider = if match_expr.contains_wildcard() {
2256            match_expr.arms.len()
2257        } else {
2258            match_expr.arms.len()
2259        };
2260        for (index, arm) in match_expr.arms.iter().enumerate() {
2261            let is_last = index == arm_len_to_consider - 1;
2262
2263            //  Each arm must set the CPU zero flag
2264            let maybe_guard = match &arm.pattern {
2265                Pattern::Normal(normal_pattern, maybe_guard) => match normal_pattern {
2266                    NormalPattern::PatternList(_) => None,
2267                    NormalPattern::EnumPattern(enum_variant, maybe_patterns) => {
2268                        self.state.builder.add_eq_u8_immediate(
2269                            region_to_match.addr,
2270                            enum_variant.common().container_index,
2271                            "check for enum variant",
2272                        );
2273                        maybe_guard.as_ref()
2274                    }
2275                    NormalPattern::Literal(_) => {
2276                        todo!()
2277                    }
2278                },
2279                Pattern::Wildcard(_) => {
2280                    // Wildcard is always true, so no comparison code is needed here at all
2281                    None
2282                }
2283            };
2284
2285            let did_add_comparison = !matches!(arm.pattern, Pattern::Wildcard(_));
2286
2287            let maybe_skip_added = if did_add_comparison {
2288                Some(
2289                    self.state
2290                        .builder
2291                        .add_jmp_if_not_equal_placeholder("placeholder for enum match"),
2292                )
2293            } else {
2294                None
2295            };
2296
2297            let maybe_guard_skip = if let Some(guard) = maybe_guard {
2298                self.gen_boolean_expression(guard)?;
2299                // z flag should have been updated now
2300
2301                Some(
2302                    self.state
2303                        .builder
2304                        .add_jmp_if_not_equal_placeholder("placeholder for skip guard"),
2305                )
2306            } else {
2307                None
2308            };
2309
2310            self.gen_expression(&arm.expression, ctx)?;
2311
2312            if !is_last {
2313                let jump_to_exit_placeholder =
2314                    self.state.builder.add_jump_placeholder("jump to exit");
2315                jump_to_exit_placeholders.push(jump_to_exit_placeholder);
2316            }
2317
2318            if let Some(skip) = maybe_skip_added {
2319                self.state.builder.patch_jump_here(skip);
2320            }
2321            if let Some(guard_skip) = maybe_guard_skip {
2322                self.state.builder.patch_jump_here(guard_skip);
2323            }
2324        }
2325
2326        for placeholder in jump_to_exit_placeholders {
2327            self.state.builder.patch_jump_here(placeholder);
2328        }
2329
2330        Ok(())
2331    }
2332
2333    fn gen_guard(&mut self, guards: &Vec<Guard>, ctx: &Context) -> Result<(), Error> {
2334        let mut jump_to_exit_placeholders = Vec::new();
2335        for guard in guards {
2336            if let Some(condition) = &guard.condition {
2337                self.gen_boolean_expression(condition); // update z flag
2338                let skip_expression_patch = self
2339                    .state
2340                    .builder
2341                    .add_jmp_if_not_equal_placeholder("guard condition");
2342                self.gen_expression(&guard.result, ctx)?;
2343                let jump_to_exit_placeholder =
2344                    self.state.builder.add_jump_placeholder("jump to exit");
2345                jump_to_exit_placeholders.push(jump_to_exit_placeholder);
2346                self.state.builder.patch_jump_here(skip_expression_patch);
2347            } else {
2348                // _ -> wildcard
2349                self.gen_expression(&guard.result, ctx)?;
2350            }
2351        }
2352
2353        for placeholder in jump_to_exit_placeholders {
2354            self.state.builder.patch_jump_here(placeholder);
2355        }
2356
2357        Ok(())
2358    }
2359
2360    fn gen_when(
2361        &mut self,
2362        bindings: &Vec<WhenBinding>,
2363        true_expr: &Expression,
2364        maybe_false_expr: Option<&Expression>,
2365        ctx: &Context,
2366    ) -> Result<(), Error> {
2367        let mut all_false_jumps = Vec::new();
2368
2369        for binding in bindings {
2370            let (variable_region, _alignment) = self.get_variable_region(&binding.variable);
2371
2372            let old_variable_region = self.gen_for_access_or_location(&binding.expr)?;
2373
2374            self.state
2375                .builder
2376                .add_tst8(old_variable_region.addr, "check binding");
2377            let patch = self
2378                .state
2379                .builder
2380                .add_jmp_if_not_equal_placeholder("jump if none");
2381            all_false_jumps.push(patch);
2382        }
2383
2384        // if we are here all bindings are `Some`
2385        for binding in bindings {
2386            let (variable_region, alignment) = self.get_variable_region(&binding.variable);
2387
2388            if binding.has_expression() {
2389                let var_ctx = Context::new(variable_region);
2390                self.gen_mut_or_immute(&binding.expr, &var_ctx)?;
2391            } else {
2392                let MutRefOrImmutableExpression::Expression(variable_access_expression) =
2393                    &binding.expr
2394                else {
2395                    panic!("must be expression");
2396                };
2397                let old_variable_region =
2398                    self.gen_expression_for_access(variable_access_expression)?;
2399                let alignment_offset: MemoryOffset = alignment.into();
2400                let some_value_region = FrameMemoryRegion::new(
2401                    old_variable_region.addr.advance(alignment_offset),
2402                    MemorySize(variable_region.size.0),
2403                );
2404                self.state.builder.add_movlp(
2405                    variable_region.addr,
2406                    some_value_region.addr,
2407                    some_value_region.size,
2408                    "move from Some to value",
2409                );
2410            }
2411        }
2412
2413        self.gen_expression(true_expr, ctx)?;
2414        let maybe_jump_over_false = if let Some(_else_expr) = maybe_false_expr {
2415            Some(
2416                self.state
2417                    .builder
2418                    .add_jump_placeholder("jump over false section"),
2419            )
2420        } else {
2421            None
2422        };
2423
2424        for false_jump_patch in all_false_jumps {
2425            self.state.builder.patch_jump_here(false_jump_patch);
2426        }
2427
2428        if let Some(else_expr) = maybe_false_expr {
2429            self.gen_expression(else_expr, ctx);
2430            self.state
2431                .builder
2432                .patch_jump_here(maybe_jump_over_false.unwrap());
2433        }
2434
2435        Ok(())
2436    }
2437
2438    fn create_err(&mut self, kind: ErrorKind, node: &Node) -> Error {
2439        error!(?kind, "encountered error");
2440        Error {
2441            kind,
2442            node: node.clone(),
2443        }
2444    }
2445
2446    fn gen_tuple_destructuring(
2447        &mut self,
2448        target_variables: &Vec<VariableRef>,
2449        tuple_type: &Vec<Type>,
2450        source_tuple_expression: &Expression,
2451    ) -> Result<(), Error> {
2452        let source_region = self.gen_expression_for_access(source_tuple_expression)?;
2453
2454        let (total_size, _max_alignment, element_offsets) = layout_tuple_elements(tuple_type);
2455        assert_eq!(total_size.0, source_region.size.0);
2456
2457        for (target_variable, (element_offset, element_size)) in
2458            target_variables.iter().zip(element_offsets)
2459        {
2460            if target_variable.is_unused {
2461            } else {
2462                let (target_region, _variable_alignment) =
2463                    self.get_variable_region(target_variable);
2464                assert_eq!(target_region.size.0, element_size.0);
2465
2466                let source_element_region = FrameMemoryRegion::new(
2467                    source_region.addr.advance(element_offset),
2468                    element_size,
2469                );
2470                self.state.builder.add_mov(
2471                    target_region.addr,
2472                    source_element_region.addr,
2473                    source_element_region.size,
2474                    &format!(
2475                        "destructuring to variable {}",
2476                        target_variable.assigned_name
2477                    ),
2478                );
2479            }
2480        }
2481
2482        Ok(())
2483    }
2484
2485    fn gen_constant_access(
2486        &mut self,
2487        constant_reference: &ConstantRef,
2488        ctx: &Context,
2489    ) -> Result<(), Error> {
2490        let constant_region = self
2491            .state
2492            .constant_offsets
2493            .get(&constant_reference.id)
2494            .unwrap();
2495        assert_eq!(constant_region.size.0, ctx.target_size().0);
2496
2497        self.state.builder.add_ld_constant(
2498            ctx.addr(),
2499            constant_region.addr,
2500            constant_region.size,
2501            &format!("load constant '{}'", constant_reference.assigned_name),
2502        );
2503
2504        Ok(())
2505    }
2506}
2507
2508fn single_intrinsic_fn(body: &Expression) -> Option<&IntrinsicFunction> {
2509    let ExpressionKind::Block(block_expressions) = &body.kind else {
2510        panic!("function body should be a block")
2511    };
2512
2513    if let ExpressionKind::IntrinsicCallEx(found_intrinsic_fn, _non_instantiated_arguments) =
2514        &block_expressions[0].kind
2515    {
2516        Some(found_intrinsic_fn)
2517    } else {
2518        None
2519    }
2520}
2521
2522fn struct_field_offset(
2523    index_to_look_for: usize,
2524    anon_struct_type: &AnonymousStructType,
2525) -> (MemoryOffset, MemorySize, MemoryAlignment) {
2526    let mut offset = MemoryOffset(0);
2527    for (field_index, (_name, field)) in
2528        anon_struct_type.field_name_sorted_fields.iter().enumerate()
2529    {
2530        let (field_size, field_alignment) = type_size_and_alignment(&field.field_type);
2531        let field_start_offset = offset.space(field_size, field_alignment);
2532        if field_index == index_to_look_for {
2533            return (field_start_offset, field_size, field_alignment);
2534        }
2535    }
2536
2537    panic!("field index is wrong")
2538}