Skip to main content

microcad_lang/lower/ir/
attribute.rs

1// Copyright © 2025-2026 The µcad authors <info@microcad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Attribute syntax entities.
5
6use 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/// *Command syntax* within an attribute.
13#[derive(Clone, Debug)]
14pub enum AttributeCommand {
15    /// A bare name
16    Ident(Identifier),
17    /// A command with optional arguments: `width(offset = 30mm)`.
18    Call(ir::Call),
19    /// An assignment: `color = "red"`.
20    Assignment {
21        /// Source code reference.
22        src_ref: SrcRef,
23        /// Name of the assignment.
24        name: Identifier,
25        /// Value name of the assignment.
26        value: ir::Expression,
27    },
28}
29
30impl Identifiable for AttributeCommand {
31    /// Id of the attribute command
32    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/// An attribute item.
65#[derive(Clone, Debug, SrcReferrer)]
66pub struct Attribute {
67    /// Attribute commands: `export = "test.stl", height(30mm)`.
68    pub commands: Vec<AttributeCommand>,
69    /// Tells if the attribute is an inner attribute: `#[...]` (outer) vs `#![...]` (inner).
70    pub is_inner: bool,
71    /// Source reference
72    pub src_ref: SrcRef,
73}
74
75impl Attribute {
76    /// Return some command it is the only one in the list.
77    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/// A list of attributes, e.g. `#foo #[bar, baz = 42]`
105#[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}