cas_compiler/expr/
literal.rs

1use cas_compute::{
2    numerical::value::Value,
3    primitive::{float_from_str, from_str_radix, int_from_str},
4};
5use cas_error::Error;
6use cas_parser::parser::ast::literal::Literal;
7use crate::{Compile, Compiler, InstructionKind};
8
9impl Compile for Literal {
10    fn compile(&self, compiler: &mut Compiler) -> Result<(), Error> {
11        match self {
12            Literal::Integer(int) => compiler.add_instr(InstructionKind::LoadConst(Value::Integer(int_from_str(&int.value)))),
13            Literal::Float(float) => compiler.add_instr(InstructionKind::LoadConst(Value::Float(float_from_str(&float.value)))),
14            Literal::Radix(radix) => compiler.add_instr(InstructionKind::LoadConst(Value::Integer(from_str_radix(radix.value.as_str(), radix.base)))),
15            Literal::Boolean(boolean) => compiler.add_instr(InstructionKind::LoadConst(Value::Boolean(boolean.value))),
16            Literal::Symbol(sym) => {
17                let symbol = compiler.resolve_symbol(sym)?;
18                compiler.add_instr_with_spans(
19                    InstructionKind::LoadVar(symbol),
20                    vec![sym.span.clone()],
21                );
22            },
23            Literal::Unit(_) => compiler.add_instr(InstructionKind::LoadConst(Value::Unit)),
24            Literal::List(list) => {
25                // compile the elements of the list
26                for element in list.values.iter() {
27                    element.compile(compiler)?;
28                }
29
30                // create a list with the number of elements on the stack
31                compiler.add_instr(InstructionKind::CreateList(list.values.len()));
32            },
33            Literal::ListRepeat(list_repeat) => {
34                // compile the element to repeat
35                list_repeat.value.compile(compiler)?;
36
37                // compile the number of times to repeat the element
38                list_repeat.count.compile(compiler)?;
39
40                // create a list with the number of elements on the stack
41                compiler.add_instr_with_spans(
42                    InstructionKind::CreateListRepeat,
43                    vec![list_repeat.count.span()],
44                );
45            },
46        };
47
48        Ok(())
49    }
50}