1use std::fmt;
8
9use serde::{Deserialize, Serialize};
10
11use crate::DiagnosticSeverity;
12
13pub const RULE_ID_PATTERN: &str = r"^[a-z0-9][a-z0-9-]*$";
15
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18#[cfg_attr(feature = "codegen", derive(schemars::JsonSchema, ts_rs::TS))]
19#[serde(rename_all = "camelCase", deny_unknown_fields)]
20#[cfg_attr(feature = "codegen", schemars(title = "Modelith rule set"))]
21pub struct RuleSet {
22 pub rules: Vec<Rule>,
23}
24
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27#[cfg_attr(feature = "codegen", derive(schemars::JsonSchema, ts_rs::TS))]
28#[serde(rename_all = "camelCase", deny_unknown_fields)]
29pub struct Rule {
30 pub id: RuleId,
32 pub severity: DiagnosticSeverity,
33 pub message: String,
35 #[serde(rename = "match")]
37 pub target: ElementMatch,
38 pub require: Requirement,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44#[cfg_attr(feature = "codegen", derive(schemars::JsonSchema, ts_rs::TS))]
45#[serde(rename_all = "camelCase", deny_unknown_fields)]
46pub struct ElementMatch {
47 pub kind: OneOrMany,
49 #[serde(default, skip_serializing_if = "Option::is_none")]
51 #[cfg_attr(feature = "codegen", ts(optional))]
52 pub phase: Option<String>,
53 #[serde(default, skip_serializing_if = "Option::is_none")]
55 #[cfg_attr(feature = "codegen", ts(optional))]
56 pub name: Option<String>,
57}
58
59#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
63#[cfg_attr(feature = "codegen", derive(schemars::JsonSchema, ts_rs::TS))]
64#[serde(rename_all = "camelCase", deny_unknown_fields)]
65pub struct Requirement {
66 #[serde(default, skip_serializing_if = "Option::is_none")]
68 #[cfg_attr(feature = "codegen", ts(optional))]
69 pub incoming: Option<OneOrMany>,
70 #[serde(default, skip_serializing_if = "Option::is_none")]
72 #[cfg_attr(feature = "codegen", ts(optional))]
73 pub outgoing: Option<OneOrMany>,
74 #[serde(default, skip_serializing_if = "Option::is_none")]
76 #[cfg_attr(feature = "codegen", ts(optional))]
77 pub name: Option<String>,
78 #[serde(default, skip_serializing_if = "Option::is_none")]
80 #[cfg_attr(feature = "codegen", ts(optional))]
81 pub phase: Option<bool>,
82 #[serde(default, skip_serializing_if = "Option::is_none")]
84 #[cfg_attr(feature = "codegen", ts(optional))]
85 pub ports: Option<CountRange>,
86 #[serde(default, skip_serializing_if = "Option::is_none")]
88 #[cfg_attr(feature = "codegen", ts(optional))]
89 pub not: Option<Box<Requirement>>,
90}
91
92#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
94#[cfg_attr(feature = "codegen", derive(schemars::JsonSchema, ts_rs::TS))]
95#[serde(rename_all = "camelCase", deny_unknown_fields)]
96pub struct CountRange {
97 #[serde(default, skip_serializing_if = "Option::is_none")]
98 #[cfg_attr(feature = "codegen", ts(optional))]
99 pub min: Option<u32>,
100 #[serde(default, skip_serializing_if = "Option::is_none")]
101 #[cfg_attr(feature = "codegen", ts(optional))]
102 pub max: Option<u32>,
103}
104
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
107#[cfg_attr(feature = "codegen", derive(schemars::JsonSchema, ts_rs::TS))]
108#[serde(untagged)]
109pub enum OneOrMany {
110 One(String),
111 Many(Vec<String>),
112}
113
114impl OneOrMany {
115 pub fn as_slice(&self) -> &[String] {
117 match self {
118 Self::One(s) => std::slice::from_ref(s),
119 Self::Many(v) => v,
120 }
121 }
122}
123
124#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
126#[cfg_attr(feature = "codegen", derive(ts_rs::TS))]
127#[cfg_attr(feature = "codegen", ts(type = "string"))]
128pub struct RuleId(String);
129
130impl<'de> Deserialize<'de> for RuleId {
131 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
132 String::deserialize(d)?
133 .try_into()
134 .map_err(serde::de::Error::custom)
135 }
136}
137
138#[derive(Debug, Clone, PartialEq, Eq)]
139pub struct RuleIdError(pub String);
140
141impl fmt::Display for RuleIdError {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 write!(
144 f,
145 "invalid rule id {:?}: expected lowercase letters, digits and '-' like \"req-has-satisfier\"",
146 self.0
147 )
148 }
149}
150
151impl std::error::Error for RuleIdError {}
152
153impl RuleId {
154 pub fn as_str(&self) -> &str {
155 &self.0
156 }
157
158 fn is_valid(s: &str) -> bool {
159 let is_word = |c: char| c.is_ascii_lowercase() || c.is_ascii_digit();
160 let mut chars = s.chars();
161 chars.next().is_some_and(is_word) && chars.all(|c| is_word(c) || c == '-')
162 }
163}
164
165impl TryFrom<String> for RuleId {
166 type Error = RuleIdError;
167 fn try_from(s: String) -> Result<Self, Self::Error> {
168 if Self::is_valid(&s) {
169 Ok(Self(s))
170 } else {
171 Err(RuleIdError(s))
172 }
173 }
174}
175
176impl std::str::FromStr for RuleId {
177 type Err = RuleIdError;
178 fn from_str(s: &str) -> Result<Self, Self::Err> {
179 s.to_owned().try_into()
180 }
181}
182
183impl From<RuleId> for String {
184 fn from(id: RuleId) -> Self {
185 id.0
186 }
187}
188
189impl fmt::Display for RuleId {
190 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191 f.write_str(&self.0)
192 }
193}
194
195#[cfg(feature = "codegen")]
196impl schemars::JsonSchema for RuleId {
197 fn schema_name() -> std::borrow::Cow<'static, str> {
198 "RuleId".into()
199 }
200
201 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
202 schemars::json_schema!({
203 "type": "string",
204 "pattern": RULE_ID_PATTERN,
205 "description": "Rule id unique within the plugin, e.g. \"req-has-satisfier\"."
206 })
207 }
208}
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213
214 fn rule_with(require: &str) -> String {
215 format!(
216 r#"{{"rules":[{{"id":"r","severity":"warning","message":"m","match":{{"kind":"part def"}},"require":{require}}}]}}"#
217 )
218 }
219
220 fn parse(json: &str) -> Result<RuleSet, serde_json::Error> {
221 serde_json::from_str(json)
222 }
223
224 #[test]
227 fn parses_full_rule() {
228 let json = r#"{"rules":[{
230 "id": "req-has-satisfier",
231 "severity": "warning",
232 "message": "要求「{name}」を満たす部品がありません",
233 "match": { "kind": "requirement def", "phase": "SystemRequirements", "name": "^[A-Z]" },
234 "require": { "incoming": "satisfy" }
235 }]}"#;
236 let set = parse(json).unwrap();
238 assert_eq!(
240 set.rules,
241 vec![Rule {
242 id: "req-has-satisfier".parse().unwrap(),
243 severity: DiagnosticSeverity::Warning,
244 message: "要求「{name}」を満たす部品がありません".to_owned(),
245 target: ElementMatch {
246 kind: OneOrMany::One("requirement def".to_owned()),
247 phase: Some("SystemRequirements".to_owned()),
248 name: Some("^[A-Z]".to_owned()),
249 },
250 require: Requirement {
251 incoming: Some(OneOrMany::One("satisfy".to_owned())),
252 ..Requirement::default()
253 },
254 }]
255 );
256 }
257
258 #[test]
259 fn one_or_many_accepts_string_and_list() {
260 let inputs = [r#""a""#, r#"["a","b"]"#];
262 let slices: Vec<Vec<String>> = inputs
264 .iter()
265 .map(|s| {
266 serde_json::from_str::<OneOrMany>(s)
267 .unwrap()
268 .as_slice()
269 .to_vec()
270 })
271 .collect();
272 assert_eq!(slices, [vec!["a"], vec!["a", "b"]]);
274 }
275
276 #[test]
277 fn parses_every_require_field_and_nested_not() {
278 let json = rule_with(
280 r#"{"outgoing":["derivation","flow"],"name":"^[A-Z]\\w*$","phase":true,
281 "ports":{"min":1,"max":8},"not":{"incoming":"satisfy"}}"#,
282 );
283 let require = parse(&json).unwrap().rules.remove(0).require;
285 assert_eq!(
287 require,
288 Requirement {
289 incoming: None,
290 outgoing: Some(OneOrMany::Many(vec![
291 "derivation".to_owned(),
292 "flow".to_owned()
293 ])),
294 name: Some(r"^[A-Z]\w*$".to_owned()),
295 phase: Some(true),
296 ports: Some(CountRange {
297 min: Some(1),
298 max: Some(8)
299 }),
300 not: Some(Box::new(Requirement {
301 incoming: Some(OneOrMany::One("satisfy".to_owned())),
302 ..Requirement::default()
303 })),
304 }
305 );
306 }
307
308 #[test]
309 fn accepts_empty_rule_list() {
310 let json = r#"{"rules":[]}"#;
312 let set = parse(json).unwrap();
314 assert!(set.rules.is_empty());
316 }
317
318 #[test]
319 fn accepts_rule_ids_at_the_edges() {
320 let ids = ["a", "0", "a-", "req-2"];
322 let results: Vec<bool> = ids.iter().map(|id| id.parse::<RuleId>().is_ok()).collect();
324 assert_eq!(results, [true, true, true, true]);
326 }
327
328 #[test]
331 fn rejects_malformed_rule_ids() {
332 let ids = ["", "-a", "Req", "req_x", "req.x", "要求"];
334 let accepted: Vec<&str> = ids
336 .iter()
337 .copied()
338 .filter(|id| id.parse::<RuleId>().is_ok())
339 .collect();
340 assert!(accepted.is_empty(), "accepted: {accepted:?}");
342 }
343
344 #[test]
345 fn rejects_unknown_keys_at_every_level() {
346 let cases = [
348 r#"{"rules":[],"extra":1}"#.to_owned(),
349 r#"{"rules":[{"id":"r","severity":"hint","message":"m","match":{"kind":"x"},"require":{},"extra":1}]}"#.to_owned(),
350 r#"{"rules":[{"id":"r","severity":"hint","message":"m","match":{"kind":"x","extra":1},"require":{}}]}"#.to_owned(),
351 rule_with(r#"{"extra":1}"#),
352 rule_with(r#"{"ports":{"min":1,"extra":1}}"#),
353 rule_with(r#"{"not":{"extra":1}}"#),
354 ];
355 let accepted: Vec<&String> = cases.iter().filter(|c| parse(c).is_ok()).collect();
357 assert!(accepted.is_empty(), "accepted: {accepted:?}");
359 }
360
361 #[test]
362 fn rejects_missing_match_kind() {
363 let json = r#"{"rules":[{"id":"r","severity":"hint","message":"m","match":{"phase":"P"},"require":{}}]}"#;
365 let result = parse(json);
367 assert!(result.is_err());
369 }
370
371 #[test]
372 fn rejects_unknown_severity() {
373 let json = r#"{"rules":[{"id":"r","severity":"fatal","message":"m","match":{"kind":"x"},"require":{}}]}"#;
375 let result = parse(json);
377 assert!(result.is_err());
379 }
380
381 #[test]
382 fn rejects_negative_port_count() {
383 let json = rule_with(r#"{"ports":{"min":-1}}"#);
385 let result = parse(&json);
387 assert!(result.is_err());
389 }
390
391 #[test]
392 fn rejects_kind_that_is_neither_string_nor_list() {
393 let inputs = ["1", r#"["a",1]"#];
395 let accepted: Vec<&str> = inputs
397 .iter()
398 .copied()
399 .filter(|s| serde_json::from_str::<OneOrMany>(s).is_ok())
400 .collect();
401 assert!(accepted.is_empty(), "accepted: {accepted:?}");
403 }
404}