microcad_lang/lower/ir/
attribute.rs1use crate::lower::{Identifiable, SingleIdentifier, ir};
7
8use derive_more::{Deref, DerefMut};
9use microcad_lang_base::{Identifier, SrcRef, SrcReferrer};
10use microcad_lang_proc_macros::SrcReferrer;
11
12#[derive(Clone, Debug)]
14pub enum AttributeCommand {
15 Ident(Identifier),
17 Call(ir::Call),
19 Assignment {
21 src_ref: SrcRef,
23 name: Identifier,
25 value: ir::Expression,
27 },
28}
29
30impl Identifiable for AttributeCommand {
31 fn id_ref(&self) -> &Identifier {
33 match self {
34 AttributeCommand::Ident(name) => name,
35 AttributeCommand::Call(call) => call
36 .name
37 .single_identifier()
38 .expect("non-identifier attribute call"),
39 AttributeCommand::Assignment { name, .. } => name,
40 }
41 }
42}
43
44impl std::fmt::Display for AttributeCommand {
45 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46 match &self {
47 AttributeCommand::Ident(name) => write!(f, "{name}"),
48 AttributeCommand::Call(call) => write!(f, "{call}"),
49 AttributeCommand::Assignment { name, value, .. } => write!(f, "{name} = {value}"),
50 }
51 }
52}
53
54impl SrcReferrer for AttributeCommand {
55 fn src_ref(&self) -> SrcRef {
56 match &self {
57 AttributeCommand::Ident(name) => name.src_ref(),
58 AttributeCommand::Call(call) => call.src_ref(),
59 AttributeCommand::Assignment { src_ref, .. } => *src_ref,
60 }
61 }
62}
63
64#[derive(Clone, Debug, SrcReferrer)]
66pub struct Attribute {
67 pub commands: Vec<AttributeCommand>,
69 pub is_inner: bool,
71 pub src_ref: SrcRef,
73}
74
75impl Attribute {
76 pub fn single_command(&self) -> Option<&AttributeCommand> {
78 match self.commands.len() {
79 1 => self.commands.first(),
80 _ => None,
81 }
82 }
83}
84
85impl std::fmt::Display for Attribute {
86 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87 match self.is_inner {
88 true => write!(f, "#![")?,
89 false => write!(f, "#[")?,
90 }
91 write!(
92 f,
93 "{}",
94 self.commands
95 .iter()
96 .map(|command| command.to_string())
97 .collect::<Vec<_>>()
98 .join(", ")
99 )?;
100 writeln!(f, "]")
101 }
102}
103
104#[derive(Clone, Debug, Default, Deref, DerefMut)]
106pub struct AttributeList(Vec<Attribute>);
107
108impl From<Vec<Attribute>> for AttributeList {
109 fn from(value: Vec<Attribute>) -> Self {
110 AttributeList(value)
111 }
112}
113
114impl std::fmt::Display for AttributeList {
115 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116 self.0.iter().try_for_each(|attr| writeln!(f, "{attr}"))
117 }
118}
119
120impl SrcReferrer for AttributeList {
121 fn src_ref(&self) -> SrcRef {
122 if self.0.is_empty() {
123 SrcRef::none()
124 } else {
125 SrcRef::merge(
126 &self.0.first().expect("One element").src_ref(),
127 &self.0.last().expect("Second element").src_ref(),
128 )
129 }
130 }
131}