Skip to main content

aranya_policy_module/
label.rs

1use core::fmt::{self, Display};
2
3use aranya_policy_ast::Identifier;
4use serde::{Deserialize, Serialize};
5
6/// Types of Labels
7#[derive(
8    Debug,
9    Clone,
10    PartialOrd,
11    Ord,
12    Eq,
13    PartialEq,
14    Serialize,
15    Deserialize,
16    rkyv::Archive,
17    rkyv::Deserialize,
18    rkyv::Serialize,
19)]
20#[rkyv(derive(Ord, PartialOrd, Eq, PartialEq))]
21pub enum LabelType {
22    /// This label represents the entry point of an action
23    Action,
24    /// This label represents the entry point of a command policy block
25    CommandPolicy,
26    /// This label represents the entry point of a command recall block
27    CommandRecall,
28    /// A command seal block
29    CommandSeal,
30    /// A command open block
31    CommandOpen,
32    /// This label is a temporary destination for implementing
33    /// branching constructs.
34    Temporary,
35    /// Function entry point
36    Function,
37}
38
39impl Display for LabelType {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        match self {
42            Self::Action => write!(f, "action"),
43            Self::CommandPolicy => write!(f, "policy"),
44            Self::CommandRecall => write!(f, "recall"),
45            Self::CommandSeal => write!(f, "seal"),
46            Self::CommandOpen => write!(f, "open"),
47            Self::Temporary => write!(f, "temp"),
48            Self::Function => write!(f, "fn"),
49        }
50    }
51}
52
53/// Labels are branch targets and execution entry points.
54#[derive(
55    Debug,
56    Clone,
57    PartialOrd,
58    Ord,
59    PartialEq,
60    Eq,
61    Serialize,
62    Deserialize,
63    rkyv::Archive,
64    rkyv::Deserialize,
65    rkyv::Serialize,
66)]
67// Ensures what is archived (zero-copy serialized representation) derives these traits. Necessarily derived in fields as well
68#[rkyv(derive(Ord, PartialOrd, Eq, PartialEq))]
69pub struct Label {
70    /// The address of the label
71    pub name: Identifier,
72    /// The type of the label
73    pub ltype: LabelType,
74}
75
76impl Label {
77    /// Creates a new named label of the given type.
78    pub fn new(name: Identifier, ltype: LabelType) -> Self {
79        Self { name, ltype }
80    }
81
82    /// Creates a new temporary label. Used by the compiler.
83    pub fn new_temp(name: Identifier) -> Self {
84        Self {
85            name,
86            ltype: LabelType::Temporary,
87        }
88    }
89}
90
91impl Display for Label {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        write!(f, "{}:{}", self.ltype, self.name)
94    }
95}