1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
mod empty_do;
mod method_def;
mod rename_variables;
pub use empty_do::*;
pub use method_def::*;
pub use rename_variables::*;
use crate::nodes::Block;
use serde::{Serialize, Serializer, Deserialize, Deserializer};
use serde::ser::SerializeMap;
use serde::de::{self, MapAccess, Visitor};
use std::fmt;
use std::str::FromStr;
use std::collections::HashMap;
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RulePropertyValue {
String(String),
Usize(usize),
StringList(Vec<String>),
}
#[derive(Debug, Clone)]
pub enum RuleConfigurationError {
UnexpectedProperty(String),
StringExpected(String),
UsizeExpected(String),
StringListExpected(String),
}
impl fmt::Display for RuleConfigurationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnexpectedProperty(property) => write!(f, "unexpected field '{}'", property),
Self::StringExpected(property) => write!(f, "string value expected for field '{}'", property),
Self::UsizeExpected(property) => write!(f, "unsigned integer expected for field '{}'", property),
Self::StringListExpected(property) => write!(f, "list of string expected for field '{}'", property),
}
}
}
pub type RuleProperties = HashMap<String, RulePropertyValue>;
pub trait Rule {
fn process(&self, block: &mut Block);
fn configure(&mut self, properties: RuleProperties) -> Result<(), RuleConfigurationError>;
fn get_name(&self) -> &'static str;
fn serialize_to_properties(&self) -> RuleProperties;
}
pub fn get_default_rules() -> Vec<Box<dyn Rule>> {
vec![
Box::new(RemoveEmptyDo::default()),
Box::new(RemoveMethodDefinition::default()),
Box::new(RenameVariables::default()),
]
}
impl FromStr for Box<dyn Rule> {
type Err = String;
fn from_str(string: &str) -> Result<Self, Self::Err> {
let rule: Box<dyn Rule> = match string {
REMOVE_EMPTY_DO_RULE_NAME => Box::new(RemoveEmptyDo::default()),
REMOVE_METHOD_DEFINITION_RULE_NAME => Box::new(RemoveMethodDefinition::default()),
RENAME_VARIABLES_RULE_NAME => Box::new(RenameVariables::default()),
_ => return Err(format!("invalid rule name: {}", string)),
};
Ok(rule)
}
}
impl Serialize for Box<dyn Rule> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let properties = self.serialize_to_properties();
let property_count = properties.len();
let rule_name = self.get_name();
if property_count == 0 {
serializer.serialize_str(rule_name)
} else {
let mut map = serializer.serialize_map(Some(property_count + 1))?;
map.serialize_entry("rule", rule_name)?;
for (key, value) in properties {
map.serialize_entry(&key, &value)?;
}
map.end()
}
}
}
impl<'de> Deserialize<'de> for Box<dyn Rule> {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Box<dyn Rule>, D::Error> {
struct StringOrStruct;
impl<'de> Visitor<'de> for StringOrStruct {
type Value = Box<dyn Rule>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("rule name or rule object")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error {
FromStr::from_str(value).map_err(de::Error::custom)
}
fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error> where M: MapAccess<'de> {
let mut rule_name = None;
let mut properties = HashMap::new();
while let Some(key) = map.next_key::<String>()? {
match key.as_str() {
"rule" => if rule_name.is_none() {
rule_name.replace(map.next_value::<String>()?);
} else {
return Err(de::Error::duplicate_field("rule"))
}
property => {
let value = map.next_value::<RulePropertyValue>()?;
if properties.insert(property.to_owned(), value).is_some() {
return Err(de::Error::custom(format!("duplicate field {} in rule object", property)))
}
}
}
}
if let Some(rule_name) = rule_name {
let mut rule: Self::Value = FromStr::from_str(&rule_name)
.map_err(de::Error::custom)?;
rule.configure(properties).map_err(de::Error::custom)?;
Ok(rule)
} else {
Err(de::Error::missing_field("rule"))
}
}
}
deserializer.deserialize_any(StringOrStruct)
}
}
#[cfg(test)]
mod test {
use super::*;
use insta::assert_json_snapshot;
#[test]
fn snapshot_default_rules() {
let rules = get_default_rules();
assert_json_snapshot!("default_rules", rules);
}
}