Skip to main content

yang_base/definition/
name.rs

1//! 构建期名称与受控引用。
2
3use super::BuildError;
4use std::fmt;
5
6#[derive(Clone, Copy)]
7enum NameRule {
8    Segment,
9    Qualified,
10    SqlIdentifier,
11}
12
13fn validate_name(kind: &'static str, value: &str, rule: NameRule) -> Result<(), BuildError> {
14    let valid_segment = |segment: &str| {
15        let mut chars = segment.chars();
16        matches!(chars.next(), Some(first) if first.is_ascii_lowercase())
17            && chars.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_')
18    };
19
20    let valid = match rule {
21        NameRule::Segment | NameRule::SqlIdentifier => valid_segment(value),
22        NameRule::Qualified => {
23            let mut segments = value.split('.');
24            let first = segments.next();
25            let second = segments.next();
26            first.is_some()
27                && second.is_some()
28                && first
29                    .into_iter()
30                    .chain(second)
31                    .chain(segments)
32                    .all(valid_segment)
33        }
34    };
35
36    if valid {
37        Ok(())
38    } else {
39        Err(BuildError::InvalidName {
40            kind,
41            name: value.to_string(),
42        })
43    }
44}
45
46macro_rules! define_name {
47    ($name:ident, $kind:literal, $rule:expr, $doc:literal) => {
48        #[doc = $doc]
49        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
50        pub struct $name(String);
51
52        impl $name {
53            /// 校验并创建名称。
54            pub fn new(value: impl Into<String>) -> Result<Self, BuildError> {
55                let value = value.into();
56                validate_name($kind, &value, $rule)?;
57                Ok(Self(value))
58            }
59
60            /// 返回规范名称字符串。
61            pub fn as_str(&self) -> &str {
62                &self.0
63            }
64        }
65
66        impl fmt::Display for $name {
67            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
68                formatter.write_str(&self.0)
69            }
70        }
71    };
72}
73
74define_name!(AddonName, "Addon", NameRule::Segment, "Addon 的受控名称。");
75define_name!(
76    ModuleName,
77    "Module",
78    NameRule::Qualified,
79    "包含 Addon 前缀的 Module 受控名称,例如 `org.user`。"
80);
81define_name!(
82    ActionName,
83    "Action",
84    NameRule::Segment,
85    "Action 的局部受控名称。"
86);
87define_name!(
88    TableName,
89    "Table",
90    NameRule::SqlIdentifier,
91    "数据库表的受控名称。"
92);
93define_name!(FieldName, "Field", NameRule::Segment, "字段的受控名称。");
94define_name!(ViewName, "View", NameRule::Segment, "View 的局部受控名称。");
95
96/// 指向已声明表字段的构建期引用。
97#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
98pub struct FieldRef {
99    table: TableName,
100    field: FieldName,
101}
102
103impl FieldRef {
104    /// 从受控表名和字段名创建引用。
105    pub fn new(table: TableName, field: FieldName) -> Self {
106        Self { table, field }
107    }
108
109    /// 返回目标表名。
110    pub fn table(&self) -> &TableName {
111        &self.table
112    }
113
114    /// 返回目标字段名。
115    pub fn field(&self) -> &FieldName {
116        &self.field
117    }
118}
119
120impl fmt::Display for FieldRef {
121    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
122        write!(formatter, "{}.{}", self.table, self.field)
123    }
124}
125
126impl FieldName {
127    /// 由已经通过宏内 const 校验的字段字面量创建。
128    #[doc(hidden)]
129    pub fn __from_validated_literal(value: &'static str) -> Self {
130        Self(value.to_string())
131    }
132}
133
134impl ActionName {
135    /// 由已经通过派生宏校验的 Action 名字面量创建。
136    #[doc(hidden)]
137    pub fn __from_validated_literal(value: &'static str) -> Self {
138        Self(value.to_string())
139    }
140}
141
142macro_rules! validated_name_literal {
143    ($name:ident) => {
144        impl $name {
145            #[doc(hidden)]
146            pub fn __from_validated_literal(value: &'static str) -> Self {
147                Self(value.to_string())
148            }
149        }
150    };
151}
152
153validated_name_literal!(AddonName);
154validated_name_literal!(ModuleName);
155validated_name_literal!(TableName);
156validated_name_literal!(ViewName);
157
158/// 编译期校验单段业务名称。
159#[doc(hidden)]
160pub const fn __validate_segment_literal(value: &str) {
161    __validate_field_literal(value);
162}
163
164/// 编译期校验点分隔的业务名称。
165#[doc(hidden)]
166pub const fn __validate_qualified_literal(value: &str) {
167    let bytes = value.as_bytes();
168    assert!(!bytes.is_empty(), "qualified name cannot be empty");
169    let mut start = 0;
170    let mut index = 0;
171    while index <= bytes.len() {
172        if index == bytes.len() || bytes[index] == b'.' {
173            assert!(index > start, "qualified name segment cannot be empty");
174            let mut part = start;
175            while part < index {
176                let byte = bytes[part];
177                if part == start {
178                    assert!(
179                        byte.is_ascii_lowercase(),
180                        "name segment must start lowercase"
181                    );
182                } else {
183                    assert!(
184                        byte == b'_' || byte.is_ascii_lowercase() || byte.is_ascii_digit(),
185                        "name segment must be snake_case ASCII"
186                    );
187                }
188                part += 1;
189            }
190            start = index + 1;
191        }
192        index += 1;
193    }
194}
195
196/// 编译期校验至少包含一个限定分隔符的引用。
197#[doc(hidden)]
198pub const fn __validate_ref_literal(value: &str) {
199    __validate_qualified_literal(value);
200    let bytes = value.as_bytes();
201    let mut index = 0;
202    let mut found = false;
203    while index < bytes.len() {
204        if bytes[index] == b'.' {
205            found = true;
206        }
207        index += 1;
208    }
209    assert!(found, "reference must contain a qualifier");
210}
211
212impl ActionRef {
213    #[doc(hidden)]
214    pub fn __from_validated_literal(value: &'static str) -> Self {
215        match value.rsplit_once('.') {
216            Some((module, action)) => Self {
217                module: ModuleName(module.to_string()),
218                action: ActionName(action.to_string()),
219            },
220            None => Self {
221                module: ModuleName(String::new()),
222                action: ActionName(String::new()),
223            },
224        }
225    }
226}
227
228impl FieldRef {
229    #[doc(hidden)]
230    pub fn __from_validated_literal(value: &'static str) -> Self {
231        match value.rsplit_once('.') {
232            Some((table, field)) => Self {
233                table: TableName(table.to_string()),
234                field: FieldName(field.to_string()),
235            },
236            None => Self {
237                table: TableName(String::new()),
238                field: FieldName(String::new()),
239            },
240        }
241    }
242}
243
244impl ViewRef {
245    #[doc(hidden)]
246    pub fn __from_validated_literal(value: &'static str) -> Self {
247        match value.rsplit_once('.') {
248            Some((module, view)) => Self {
249                module: ModuleName(module.to_string()),
250                view: ViewName(view.to_string()),
251            },
252            None => Self {
253                module: ModuleName(String::new()),
254                view: ViewName(String::new()),
255            },
256        }
257    }
258}
259
260/// 编译期校验 fields!/params! 中的 snake_case 字段名。
261#[doc(hidden)]
262pub const fn __validate_field_literal(value: &str) {
263    let bytes = value.as_bytes();
264    assert!(!bytes.is_empty(), "field name cannot be empty");
265    let first = bytes[0];
266    assert!(
267        first.is_ascii_lowercase(),
268        "field name must start with lowercase ASCII letter"
269    );
270    let mut index = 1;
271    while index < bytes.len() {
272        let byte = bytes[index];
273        assert!(
274            byte == b'_' || byte.is_ascii_lowercase() || byte.is_ascii_digit(),
275            "field name must be snake_case ASCII"
276        );
277        index += 1;
278    }
279}
280
281/// 指向已声明 Action 的构建期引用。
282#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
283pub struct ActionRef {
284    module: ModuleName,
285    action: ActionName,
286}
287
288impl ActionRef {
289    /// 从受控 Module 与 Action 名称创建引用。
290    pub fn new(module: ModuleName, action: ActionName) -> Self {
291        Self { module, action }
292    }
293
294    /// 返回目标 Module 名称。
295    pub fn module(&self) -> &ModuleName {
296        &self.module
297    }
298
299    /// 返回目标 Action 名称。
300    pub fn action(&self) -> &ActionName {
301        &self.action
302    }
303}
304
305impl fmt::Display for ActionRef {
306    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
307        write!(formatter, "{}.{}", self.module, self.action)
308    }
309}
310
311/// 指向已声明 View 的构建期引用。
312#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
313pub struct ViewRef {
314    module: ModuleName,
315    view: ViewName,
316}
317
318impl ViewRef {
319    /// 从受控 Module 与 View 名称创建引用。
320    pub fn new(module: ModuleName, view: ViewName) -> Self {
321        Self { module, view }
322    }
323
324    /// 返回目标 Module 名称。
325    pub fn module(&self) -> &ModuleName {
326        &self.module
327    }
328
329    /// 返回目标 View 名称。
330    pub fn view(&self) -> &ViewName {
331        &self.view
332    }
333}
334
335impl fmt::Display for ViewRef {
336    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
337        write!(formatter, "{}.{}", self.module, self.view)
338    }
339}