Skip to main content

modelith_plugin_protocol/
rules.rs

1//! 検査ルールのファイル(マニフェストの `contributes.rules` が指す YAML、ADR-0018 §2)。
2//!
3//! 解釈は modelith-core だけが行う。ここでは形だけを定め、正規表現の妥当性や
4//! `min <= max` などの意味の検査は modelith-core が位置つきで報告する。
5//! 未知のキーは黙って捨てず、誤りとして返す(すべての構造体が `deny_unknown_fields`)。
6
7use std::fmt;
8
9use serde::{Deserialize, Serialize};
10
11use crate::DiagnosticSeverity;
12
13/// ルール ID の正規表現(英小文字・数字・`-`、英小文字か数字で始まる)。
14pub const RULE_ID_PATTERN: &str = r"^[a-z0-9][a-z0-9-]*$";
15
16/// 検査ルールのファイル。
17#[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/// 1 つの検査ルール。`match` に当たる要素ごとに `require` を確かめ、満たさなければ診断を出す。
26#[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    /// プラグインの中で一意な ID。診断の `code` になる。
31    pub id: RuleId,
32    pub severity: DiagnosticSeverity,
33    /// 診断のメッセージ。`{name}`(要素名)と `{kind}`(要素の種類)を差し込める。
34    pub message: String,
35    /// ルールを当てる要素。
36    #[serde(rename = "match")]
37    pub target: ElementMatch,
38    /// 当たった要素が満たすべき条件。
39    pub require: Requirement,
40}
41
42/// ルールを当てる要素の条件(すべてを満たす要素に当てる)。
43#[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    /// 要素の種類(例: `requirement def`)。並びはいずれかに当たればよい。
48    pub kind: OneOrMany,
49    /// 工程(`@Phase`)の名前(例: `SystemRequirements`)。
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    #[cfg_attr(feature = "codegen", ts(optional))]
52    pub phase: Option<String>,
53    /// 要素名の正規表現。
54    #[serde(default, skip_serializing_if = "Option::is_none")]
55    #[cfg_attr(feature = "codegen", ts(optional))]
56    pub name: Option<String>,
57}
58
59/// 当たった要素が満たすべき条件(書いたものすべて)。
60///
61/// 語彙は任意フィールドの追加で増やす(互換を保つ)。
62#[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    /// この種類の関係(例: `satisfy`)を 1 本以上受ける。並びはいずれかでよい。
67    #[serde(default, skip_serializing_if = "Option::is_none")]
68    #[cfg_attr(feature = "codegen", ts(optional))]
69    pub incoming: Option<OneOrMany>,
70    /// この種類の関係(例: `derivation`)を 1 本以上出す。並びはいずれかでよい。
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    #[cfg_attr(feature = "codegen", ts(optional))]
73    pub outgoing: Option<OneOrMany>,
74    /// 要素名がこの正規表現に当たる。
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    #[cfg_attr(feature = "codegen", ts(optional))]
77    pub name: Option<String>,
78    /// `true` なら工程(`@Phase`)を持つ、`false` なら持たない。
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    #[cfg_attr(feature = "codegen", ts(optional))]
81    pub phase: Option<bool>,
82    /// ポートの数。
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    #[cfg_attr(feature = "codegen", ts(optional))]
85    pub ports: Option<CountRange>,
86    /// 同じ形の条件の否定(満たさないこと)。
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    #[cfg_attr(feature = "codegen", ts(optional))]
89    pub not: Option<Box<Requirement>>,
90}
91
92/// 数の範囲(両端を含む)。省いた側は制限しない。
93#[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/// 文字列 1 つか、文字列の並び。
106#[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    /// 並びとして見る(1 つなら長さ 1)。
116    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/// ルール ID(例: `req-has-satisfier`)。
125#[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    // --- 正常系 ---
225
226    #[test]
227    fn parses_full_rule() {
228        // Arrange
229        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        // Act
237        let set = parse(json).unwrap();
238        // Assert
239        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        // Arrange(同値クラス: 文字列 1 つ/並び)
261        let inputs = [r#""a""#, r#"["a","b"]"#];
262        // Act
263        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
273        assert_eq!(slices, [vec!["a"], vec!["a", "b"]]);
274    }
275
276    #[test]
277    fn parses_every_require_field_and_nested_not() {
278        // Arrange
279        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        // Act
284        let require = parse(&json).unwrap().rules.remove(0).require;
285        // Assert
286        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        // Arrange(境界値: ルール 0 件)
311        let json = r#"{"rules":[]}"#;
312        // Act
313        let set = parse(json).unwrap();
314        // Assert
315        assert!(set.rules.is_empty());
316    }
317
318    #[test]
319    fn accepts_rule_ids_at_the_edges() {
320        // Arrange(境界値: 1 文字・数字始まり・末尾の `-`)
321        let ids = ["a", "0", "a-", "req-2"];
322        // Act
323        let results: Vec<bool> = ids.iter().map(|id| id.parse::<RuleId>().is_ok()).collect();
324        // Assert
325        assert_eq!(results, [true, true, true, true]);
326    }
327
328    // --- 異常系 ---
329
330    #[test]
331    fn rejects_malformed_rule_ids() {
332        // Arrange(空・`-` 始まり・大文字・使えない文字)
333        let ids = ["", "-a", "Req", "req_x", "req.x", "要求"];
334        // Act
335        let accepted: Vec<&str> = ids
336            .iter()
337            .copied()
338            .filter(|id| id.parse::<RuleId>().is_ok())
339            .collect();
340        // Assert
341        assert!(accepted.is_empty(), "accepted: {accepted:?}");
342    }
343
344    #[test]
345    fn rejects_unknown_keys_at_every_level() {
346        // Arrange(ルールセット・ルール・match・require・ports・not の各階層)
347        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        // Act
356        let accepted: Vec<&String> = cases.iter().filter(|c| parse(c).is_ok()).collect();
357        // Assert
358        assert!(accepted.is_empty(), "accepted: {accepted:?}");
359    }
360
361    #[test]
362    fn rejects_missing_match_kind() {
363        // Arrange(必須の `kind` が欠ける)
364        let json = r#"{"rules":[{"id":"r","severity":"hint","message":"m","match":{"phase":"P"},"require":{}}]}"#;
365        // Act
366        let result = parse(json);
367        // Assert
368        assert!(result.is_err());
369    }
370
371    #[test]
372    fn rejects_unknown_severity() {
373        // Arrange
374        let json = r#"{"rules":[{"id":"r","severity":"fatal","message":"m","match":{"kind":"x"},"require":{}}]}"#;
375        // Act
376        let result = parse(json);
377        // Assert
378        assert!(result.is_err());
379    }
380
381    #[test]
382    fn rejects_negative_port_count() {
383        // Arrange(境界値: min = -1)
384        let json = rule_with(r#"{"ports":{"min":-1}}"#);
385        // Act
386        let result = parse(&json);
387        // Assert
388        assert!(result.is_err());
389    }
390
391    #[test]
392    fn rejects_kind_that_is_neither_string_nor_list() {
393        // Arrange(異常系: 数値・文字列以外を含む並び)
394        let inputs = ["1", r#"["a",1]"#];
395        // Act
396        let accepted: Vec<&str> = inputs
397            .iter()
398            .copied()
399            .filter(|s| serde_json::from_str::<OneOrMany>(s).is_ok())
400            .collect();
401        // Assert
402        assert!(accepted.is_empty(), "accepted: {accepted:?}");
403    }
404}