Skip to main content

datex_core/core_compiler/
panic.rs

1//! Defines the `Panic` struct used for representing panic messages
2//! used by the core compiler.
3use crate::{
4    core_compiler::{
5        core_compilation_context::{CompileInput, CoreCompilationContext},
6        value_compiler::ApplyWithArgs,
7    },
8    instruction::regular_instruction::RegularInstruction,
9    libs::core::{core_lib_id::CoreLibId, value_id::CoreLibValueId},
10    prelude::*,
11    runtime::cache::shared_references_cache::SharedReferencesCache,
12    values::value_container::ValueContainer,
13};
14use core::fmt::Display;
15
16#[derive(Debug)]
17pub struct Panic {
18    message: String,
19}
20
21impl Panic {
22    pub fn new(message: impl Into<String>) -> Self {
23        Self {
24            message: message.into(),
25        }
26    }
27
28    pub fn message(&self) -> &str {
29        &self.message
30    }
31
32    /// Converts the panic message into a standalone
33    /// response block dxb
34    pub fn to_bytes(
35        self,
36        compile_input: CompileInput,
37        cache: &mut SharedReferencesCache,
38    ) -> Vec<u8> {
39        CoreCompilationContext::new(compile_input)
40            .compile_to_dxb_with_shared_values(
41                &ApplyWithArgs::new(
42                    RegularInstruction::get_core_lib_value(
43                        CoreLibId::Value(CoreLibValueId::Panic).into(),
44                    ),
45                    vec![ValueContainer::Local(self.message.into())],
46                ),
47                cache,
48            )
49            .dxb
50    }
51}
52
53impl Display for Panic {
54    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
55        write!(f, "Panic: {}", self.message)
56    }
57}