reek-rs 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/Cargo.lock +614 -0
- data/Cargo.toml +24 -0
- data/DIVERGENCES.md +15 -0
- data/LICENSE +22 -0
- data/README.md +125 -0
- data/THIRD_PARTY_NOTICES.md +57 -0
- data/crates/reek-cli/Cargo.toml +22 -0
- data/crates/reek-cli/src/main.rs +277 -0
- data/crates/reek-core/Cargo.toml +21 -0
- data/crates/reek-core/src/ast.rs +449 -0
- data/crates/reek-core/src/code_comment.rs +245 -0
- data/crates/reek-core/src/comments.rs +179 -0
- data/crates/reek-core/src/config.rs +803 -0
- data/crates/reek-core/src/context.rs +891 -0
- data/crates/reek-core/src/detectors/attribute.rs +13 -0
- data/crates/reek-core/src/detectors/boolean_parameter.rs +20 -0
- data/crates/reek-core/src/detectors/class_variable.rs +25 -0
- data/crates/reek-core/src/detectors/control_parameter.rs +110 -0
- data/crates/reek-core/src/detectors/data_clump.rs +114 -0
- data/crates/reek-core/src/detectors/duplicate_method_call.rs +63 -0
- data/crates/reek-core/src/detectors/feature_envy.rs +32 -0
- data/crates/reek-core/src/detectors/instance_variable_assumption.rs +39 -0
- data/crates/reek-core/src/detectors/irresponsible_module.rs +12 -0
- data/crates/reek-core/src/detectors/long_parameter_list.rs +16 -0
- data/crates/reek-core/src/detectors/long_yield_list.rs +20 -0
- data/crates/reek-core/src/detectors/manual_dispatch.rs +18 -0
- data/crates/reek-core/src/detectors/missing_safe_method.rs +34 -0
- data/crates/reek-core/src/detectors/mod.rs +479 -0
- data/crates/reek-core/src/detectors/module_initialize.rs +15 -0
- data/crates/reek-core/src/detectors/nested_iterators.rs +82 -0
- data/crates/reek-core/src/detectors/nil_check.rs +40 -0
- data/crates/reek-core/src/detectors/repeated_conditional.rs +51 -0
- data/crates/reek-core/src/detectors/subclassed_from_core_class.rs +22 -0
- data/crates/reek-core/src/detectors/too_many_constants.rs +18 -0
- data/crates/reek-core/src/detectors/too_many_instance_variables.rs +25 -0
- data/crates/reek-core/src/detectors/too_many_methods.rs +15 -0
- data/crates/reek-core/src/detectors/too_many_statements.rs +16 -0
- data/crates/reek-core/src/detectors/uncommunicative_method_name.rs +32 -0
- data/crates/reek-core/src/detectors/uncommunicative_module_name.rs +33 -0
- data/crates/reek-core/src/detectors/uncommunicative_parameter_name.rs +49 -0
- data/crates/reek-core/src/detectors/uncommunicative_variable_name.rs +138 -0
- data/crates/reek-core/src/detectors/unused_parameters.rs +21 -0
- data/crates/reek-core/src/detectors/unused_private_method.rs +59 -0
- data/crates/reek-core/src/detectors/utility_function.rs +27 -0
- data/crates/reek-core/src/encodings.rs +180 -0
- data/crates/reek-core/src/examiner.rs +165 -0
- data/crates/reek-core/src/lib.rs +21 -0
- data/crates/reek-core/src/node.rs +423 -0
- data/crates/reek-core/src/ruby_format.rs +60 -0
- data/crates/reek-core/src/ruby_inspect.rs +172 -0
- data/crates/reek-core/src/ruby_regexp.rs +243 -0
- data/crates/reek-core/src/single_byte_encodings.rs +6007 -0
- data/crates/reek-core/src/source.rs +280 -0
- data/crates/reek-core/src/translate.rs +3112 -0
- data/crates/reek-core/src/yaml.rs +520 -0
- data/ext/reek_rs/Cargo.toml +18 -0
- data/ext/reek_rs/extconf.rb +6 -0
- data/ext/reek_rs/src/lib.rs +155 -0
- data/lib/reek_rs/version.rb +8 -0
- data/lib/reek_rs.rb +390 -0
- metadata +123 -0
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
//! Reek's smell detectors (`Reek::SmellDetectors`), in the order
|
|
2
|
+
//! `DetectorRepository.smell_types` runs them: sorted by class name.
|
|
3
|
+
//!
|
|
4
|
+
//! [`DetectorClass`] holds what Reek's detector classes declare (smell
|
|
5
|
+
//! type, context types, default configuration) and the detector's `sniff`.
|
|
6
|
+
//! [`Detector`] is a detector instance examining one context, with
|
|
7
|
+
//! `BaseDetector`'s `run`, `value` and `smell_warning`.
|
|
8
|
+
|
|
9
|
+
mod attribute;
|
|
10
|
+
mod boolean_parameter;
|
|
11
|
+
mod class_variable;
|
|
12
|
+
mod control_parameter;
|
|
13
|
+
mod data_clump;
|
|
14
|
+
mod duplicate_method_call;
|
|
15
|
+
mod feature_envy;
|
|
16
|
+
mod instance_variable_assumption;
|
|
17
|
+
mod irresponsible_module;
|
|
18
|
+
mod long_parameter_list;
|
|
19
|
+
mod long_yield_list;
|
|
20
|
+
mod manual_dispatch;
|
|
21
|
+
mod missing_safe_method;
|
|
22
|
+
mod module_initialize;
|
|
23
|
+
mod nested_iterators;
|
|
24
|
+
mod nil_check;
|
|
25
|
+
mod repeated_conditional;
|
|
26
|
+
mod subclassed_from_core_class;
|
|
27
|
+
mod too_many_constants;
|
|
28
|
+
mod too_many_instance_variables;
|
|
29
|
+
mod too_many_methods;
|
|
30
|
+
mod too_many_statements;
|
|
31
|
+
mod uncommunicative_method_name;
|
|
32
|
+
mod uncommunicative_module_name;
|
|
33
|
+
mod uncommunicative_parameter_name;
|
|
34
|
+
mod uncommunicative_variable_name;
|
|
35
|
+
mod unused_parameters;
|
|
36
|
+
mod unused_private_method;
|
|
37
|
+
mod utility_function;
|
|
38
|
+
|
|
39
|
+
use indexmap::IndexMap;
|
|
40
|
+
|
|
41
|
+
use crate::ast::{NodeId, Tree};
|
|
42
|
+
use crate::code_comment::DetectorOptions;
|
|
43
|
+
use crate::context::{ContextError, ContextId, ContextTree};
|
|
44
|
+
use crate::ruby_regexp::RubyRegexp;
|
|
45
|
+
use crate::yaml::Value;
|
|
46
|
+
|
|
47
|
+
/// A detector's findings in one context, or why examining it failed.
|
|
48
|
+
pub type SniffResult = Result<Vec<SmellWarning>, ContextError>;
|
|
49
|
+
|
|
50
|
+
/// A detector class: its smell type, the context types it examines
|
|
51
|
+
/// (`contexts`) and its options beyond `enabled` and `exclude`.
|
|
52
|
+
pub struct DetectorClass {
|
|
53
|
+
pub smell_type: &'static str,
|
|
54
|
+
pub contexts: &'static [&'static str],
|
|
55
|
+
/// The `default_config` entries after `enabled` and `exclude`.
|
|
56
|
+
options: fn() -> Vec<(&'static str, Value)>,
|
|
57
|
+
/// `default_config['enabled']`.
|
|
58
|
+
enabled: bool,
|
|
59
|
+
/// `default_config['exclude']`.
|
|
60
|
+
exclude: &'static [&'static str],
|
|
61
|
+
/// `sniff`: the smells in the detector's context.
|
|
62
|
+
sniff: fn(&Detector) -> SniffResult,
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
impl DetectorClass {
|
|
66
|
+
/// `default_config`.
|
|
67
|
+
pub fn default_config(&self) -> IndexMap<String, Value> {
|
|
68
|
+
let mut config = IndexMap::new();
|
|
69
|
+
config.insert("enabled".to_string(), Value::Bool(self.enabled));
|
|
70
|
+
let exclude = self.exclude.iter().map(|name| Value::Str(name.to_string())).collect();
|
|
71
|
+
config.insert("exclude".to_string(), Value::Array(exclude));
|
|
72
|
+
for (key, value) in (self.options)() {
|
|
73
|
+
config.insert(key.to_string(), value);
|
|
74
|
+
}
|
|
75
|
+
config
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/// `configuration_keys`: the `default_config` keys.
|
|
79
|
+
pub fn configuration_keys(&self) -> Vec<String> {
|
|
80
|
+
self.default_config().into_keys().collect()
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const METHOD_CONTEXTS: &[&str] = &["def", "defs"];
|
|
85
|
+
|
|
86
|
+
fn no_options() -> Vec<(&'static str, Value)> {
|
|
87
|
+
Vec::new()
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
fn int(value: i64) -> Value {
|
|
91
|
+
Value::Int(value)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
fn strings(names: &[&str]) -> Value {
|
|
95
|
+
Value::Array(names.iter().map(|name| Value::Str(name.to_string())).collect())
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
fn regexps(sources: &[&str]) -> Value {
|
|
99
|
+
let compile = |source: &&str| Value::Regexp(RubyRegexp::new(source, "").expect("a default pattern compiles"));
|
|
100
|
+
Value::Array(sources.iter().map(compile).collect())
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const fn detector(
|
|
104
|
+
smell_type: &'static str,
|
|
105
|
+
contexts: &'static [&'static str],
|
|
106
|
+
options: fn() -> Vec<(&'static str, Value)>,
|
|
107
|
+
sniff: fn(&Detector) -> SniffResult,
|
|
108
|
+
) -> DetectorClass {
|
|
109
|
+
DetectorClass { smell_type, contexts, options, enabled: true, exclude: &[], sniff }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/// Every detector, sorted by name.
|
|
113
|
+
pub static DETECTORS: [DetectorClass; 29] = [
|
|
114
|
+
detector("Attribute", &["sym"], no_options, attribute::sniff),
|
|
115
|
+
detector("BooleanParameter", METHOD_CONTEXTS, no_options, boolean_parameter::sniff),
|
|
116
|
+
detector("ClassVariable", &["class", "module"], no_options, class_variable::sniff),
|
|
117
|
+
detector("ControlParameter", METHOD_CONTEXTS, no_options, control_parameter::sniff),
|
|
118
|
+
detector("DataClump", &["class", "module"], || vec![("max_copies", int(2)), ("min_clump_size", int(2))], data_clump::sniff),
|
|
119
|
+
detector("DuplicateMethodCall", METHOD_CONTEXTS, || vec![("max_calls", int(1)), ("allow_calls", strings(&[]))], duplicate_method_call::sniff),
|
|
120
|
+
detector("FeatureEnvy", METHOD_CONTEXTS, no_options, feature_envy::sniff),
|
|
121
|
+
detector("InstanceVariableAssumption", &["class"], no_options, instance_variable_assumption::sniff),
|
|
122
|
+
detector("IrresponsibleModule", &["casgn", "class", "module"], no_options, irresponsible_module::sniff),
|
|
123
|
+
detector("LongParameterList", METHOD_CONTEXTS, || {
|
|
124
|
+
let mut initialize = IndexMap::new();
|
|
125
|
+
initialize.insert("max_params".to_string(), int(5));
|
|
126
|
+
let mut overrides = IndexMap::new();
|
|
127
|
+
overrides.insert("initialize".to_string(), Value::Hash(initialize));
|
|
128
|
+
vec![("max_params", int(3)), ("overrides", Value::Hash(overrides))]
|
|
129
|
+
}, long_parameter_list::sniff),
|
|
130
|
+
detector("LongYieldList", METHOD_CONTEXTS, || vec![("max_params", int(3))], long_yield_list::sniff),
|
|
131
|
+
detector("ManualDispatch", METHOD_CONTEXTS, no_options, manual_dispatch::sniff),
|
|
132
|
+
detector("MissingSafeMethod", &["class"], no_options, missing_safe_method::sniff),
|
|
133
|
+
detector("ModuleInitialize", &["module"], no_options, module_initialize::sniff),
|
|
134
|
+
detector("NestedIterators", METHOD_CONTEXTS, || {
|
|
135
|
+
vec![("max_allowed_nesting", int(1)), ("ignore_iterators", strings(&["tap", "Tempfile.create"]))]
|
|
136
|
+
}, nested_iterators::sniff),
|
|
137
|
+
detector("NilCheck", METHOD_CONTEXTS, no_options, nil_check::sniff),
|
|
138
|
+
detector("RepeatedConditional", &["class"], || vec![("max_ifs", int(2))], repeated_conditional::sniff),
|
|
139
|
+
detector("SubclassedFromCoreClass", &["class", "casgn"], no_options, subclassed_from_core_class::sniff),
|
|
140
|
+
detector("TooManyConstants", &["class", "module"], || vec![("max_constants", int(5))], too_many_constants::sniff),
|
|
141
|
+
detector("TooManyInstanceVariables", &["class"], || vec![("max_instance_variables", int(4))], too_many_instance_variables::sniff),
|
|
142
|
+
detector("TooManyMethods", &["class"], || vec![("max_methods", int(15))], too_many_methods::sniff),
|
|
143
|
+
DetectorClass {
|
|
144
|
+
exclude: &["initialize"],
|
|
145
|
+
..detector("TooManyStatements", METHOD_CONTEXTS, || vec![("max_statements", int(5))], too_many_statements::sniff)
|
|
146
|
+
},
|
|
147
|
+
detector("UncommunicativeMethodName", METHOD_CONTEXTS, || {
|
|
148
|
+
vec![("reject", regexps(&["^[a-z]$", "[0-9]$", "[A-Z]"])), ("accept", strings(&[]))]
|
|
149
|
+
}, uncommunicative_method_name::sniff),
|
|
150
|
+
detector("UncommunicativeModuleName", &["module", "class"], || {
|
|
151
|
+
vec![("reject", regexps(&["^.$", "[0-9]$"])), ("accept", strings(&[]))]
|
|
152
|
+
}, uncommunicative_module_name::sniff),
|
|
153
|
+
detector("UncommunicativeParameterName", METHOD_CONTEXTS, || {
|
|
154
|
+
vec![("reject", regexps(&["^.$", "[0-9]$", "[A-Z]", "^_"])), ("accept", strings(&[]))]
|
|
155
|
+
}, uncommunicative_parameter_name::sniff),
|
|
156
|
+
detector("UncommunicativeVariableName", &["module", "class", "def", "defs"], || {
|
|
157
|
+
vec![("reject", regexps(&["^.$", "[0-9]$", "[A-Z]"])), ("accept", regexps(&["^_$"]))]
|
|
158
|
+
}, uncommunicative_variable_name::sniff),
|
|
159
|
+
detector("UnusedParameters", METHOD_CONTEXTS, no_options, unused_parameters::sniff),
|
|
160
|
+
DetectorClass { enabled: false, ..detector("UnusedPrivateMethod", &["class"], no_options, unused_private_method::sniff) },
|
|
161
|
+
detector("UtilityFunction", &["def"], || vec![("public_methods_only", Value::Bool(false))], utility_function::sniff),
|
|
162
|
+
];
|
|
163
|
+
|
|
164
|
+
/// `DetectorRepository#examine(context)`: runs each detector for the
|
|
165
|
+
/// context's type (among those in `filter_by_smells`, unless it is empty),
|
|
166
|
+
/// configured with its default configuration merged with `directive` (the
|
|
167
|
+
/// configuration file's settings for the file).
|
|
168
|
+
pub fn examine(
|
|
169
|
+
contexts: &ContextTree,
|
|
170
|
+
context: ContextId,
|
|
171
|
+
directive: &IndexMap<String, DetectorOptions>,
|
|
172
|
+
filter_by_smells: &[String],
|
|
173
|
+
) -> SniffResult {
|
|
174
|
+
let ty = contexts.ty(context);
|
|
175
|
+
let is_eligible =
|
|
176
|
+
|class: &&DetectorClass| filter_by_smells.is_empty() || filter_by_smells.iter().any(|name| name == class.smell_type);
|
|
177
|
+
let mut smells = Vec::new();
|
|
178
|
+
for class in DETECTORS.iter().filter(is_eligible).filter(|class| class.contexts.contains(&ty)) {
|
|
179
|
+
let mut config = class.default_config();
|
|
180
|
+
if let Some(options) = directive.get(class.smell_type) {
|
|
181
|
+
for (key, value) in options {
|
|
182
|
+
config.insert(key.clone(), value.clone());
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
let detector = Detector { class, config, contexts, context };
|
|
186
|
+
smells.extend(detector.run()?);
|
|
187
|
+
}
|
|
188
|
+
Ok(smells)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/// A detector examining one context.
|
|
192
|
+
pub struct Detector<'a, 'tree> {
|
|
193
|
+
class: &'static DetectorClass,
|
|
194
|
+
/// `config`: the default configuration merged with the directive's.
|
|
195
|
+
config: DetectorOptions,
|
|
196
|
+
pub contexts: &'a ContextTree<'tree>,
|
|
197
|
+
pub context: ContextId,
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
impl<'tree> Detector<'_, 'tree> {
|
|
201
|
+
/// `run`: the smells, unless the detector is disabled or the context
|
|
202
|
+
/// is excluded.
|
|
203
|
+
fn run(&self) -> SniffResult {
|
|
204
|
+
if !self.is_enabled()? {
|
|
205
|
+
return Ok(Vec::new());
|
|
206
|
+
}
|
|
207
|
+
if self.is_exception()? {
|
|
208
|
+
return Ok(Vec::new());
|
|
209
|
+
}
|
|
210
|
+
(self.class.sniff)(self)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/// `enabled?`: enabled by the configuration, and not disabled by a
|
|
214
|
+
/// comment directive (`enabled: false`).
|
|
215
|
+
fn is_enabled(&self) -> Result<bool, ContextError> {
|
|
216
|
+
if !self.config.get("enabled").is_some_and(Value::is_truthy) {
|
|
217
|
+
return Ok(false);
|
|
218
|
+
}
|
|
219
|
+
let disabled = matches!(self.config_for(self.context)?.get("enabled"), Some(Value::Bool(false)));
|
|
220
|
+
Ok(!disabled)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/// `exception?`: the context matches `exclude`.
|
|
224
|
+
fn is_exception(&self) -> Result<bool, ContextError> {
|
|
225
|
+
let exclude = self.value("exclude")?;
|
|
226
|
+
self.contexts.matches(self.context, &exclude)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
fn config_for(&self, context: ContextId) -> Result<DetectorOptions, ContextError> {
|
|
230
|
+
self.contexts.config_for(context, self.class.smell_type)
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/// `value(key, context)`: a truthy comment directive value, else the
|
|
234
|
+
/// first override for a context name matching the context, else the
|
|
235
|
+
/// configuration's.
|
|
236
|
+
pub fn value(&self, key: &str) -> Result<Value, ContextError> {
|
|
237
|
+
if let Some(value) = self.config_for(self.context)?.get(key).filter(|value| value.is_truthy()) {
|
|
238
|
+
return Ok(value.clone());
|
|
239
|
+
}
|
|
240
|
+
// `SmellConfiguration#value`
|
|
241
|
+
if let Some(overrides) = self.config.get("overrides") {
|
|
242
|
+
let Value::Hash(overrides) = overrides else {
|
|
243
|
+
return Err(no_method("keys", overrides));
|
|
244
|
+
};
|
|
245
|
+
let mut matching = Vec::new();
|
|
246
|
+
for (context_name, override_config) in overrides {
|
|
247
|
+
if self.contexts.matches(self.context, &Value::Array(vec![Value::Str(context_name.clone())]))? {
|
|
248
|
+
matching.push(override_config);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
for override_config in matching {
|
|
252
|
+
let Value::Hash(override_config) = override_config else {
|
|
253
|
+
return Err(no_method("key?", override_config));
|
|
254
|
+
};
|
|
255
|
+
if let Some(value) = override_config.get(key) {
|
|
256
|
+
return Ok(value.clone());
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
self.config.get(key).cloned().ok_or_else(|| ContextError::Unexpected(format!("key not found: {key:?}")))
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
pub fn tree(&self) -> &'tree Tree {
|
|
264
|
+
self.contexts.tree
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/// `expression`: the context's node.
|
|
268
|
+
pub fn expression(&self) -> NodeId {
|
|
269
|
+
self.contexts.context(self.context).exp
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/// `source_line`: the context's first line.
|
|
273
|
+
pub fn source_line(&self) -> Result<usize, ContextError> {
|
|
274
|
+
line(self.tree(), self.expression())
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/// `smell_warning(lines:, message:, parameters:)`.
|
|
278
|
+
pub fn smell_warning(
|
|
279
|
+
&self,
|
|
280
|
+
lines: Vec<usize>,
|
|
281
|
+
message: String,
|
|
282
|
+
parameters: Vec<(&'static str, Parameter)>,
|
|
283
|
+
) -> Result<SmellWarning, ContextError> {
|
|
284
|
+
Ok(SmellWarning {
|
|
285
|
+
smell_type: self.class.smell_type,
|
|
286
|
+
source: self.contexts.origin.to_string(),
|
|
287
|
+
context: self.contexts.full_name(self.context)?,
|
|
288
|
+
lines,
|
|
289
|
+
message,
|
|
290
|
+
parameters,
|
|
291
|
+
})
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/// `node.line`, which every node Reek reports a line for has.
|
|
296
|
+
pub fn line(tree: &Tree, node: NodeId) -> Result<usize, ContextError> {
|
|
297
|
+
tree.line(node).ok_or_else(|| ContextError::Unexpected(format!("a {} node without a location", tree.ty(node))))
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
fn no_method(method: &str, receiver: &Value) -> ContextError {
|
|
301
|
+
ContextError::Unexpected(format!("undefined method '{method}' for an instance of {}", receiver.class_name()))
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/// A smell (`Reek::SmellWarning`).
|
|
305
|
+
#[derive(Clone, Debug, PartialEq)]
|
|
306
|
+
pub struct SmellWarning {
|
|
307
|
+
pub smell_type: &'static str,
|
|
308
|
+
/// The file's origin.
|
|
309
|
+
pub source: String,
|
|
310
|
+
/// The full name of the context the smell is in.
|
|
311
|
+
pub context: String,
|
|
312
|
+
pub lines: Vec<usize>,
|
|
313
|
+
pub message: String,
|
|
314
|
+
/// Detector-specific details, in the order the detector gives them.
|
|
315
|
+
pub parameters: Vec<(&'static str, Parameter)>,
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
impl SmellWarning {
|
|
319
|
+
/// `identifying_values`, which `<=>`, `eql?` and `hash` compare.
|
|
320
|
+
pub fn identifying_values(&self) -> (&str, &str, &str, &[usize]) {
|
|
321
|
+
(self.smell_type, &self.context, &self.message, &self.lines)
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/// A value in [`SmellWarning::parameters`].
|
|
326
|
+
#[derive(Clone, Debug, PartialEq)]
|
|
327
|
+
pub enum Parameter {
|
|
328
|
+
String(String),
|
|
329
|
+
Integer(i64),
|
|
330
|
+
Strings(Vec<String>),
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/// `count > limit`, with Ruby's `Integer#>`: the limit may be an Integer
|
|
334
|
+
/// or a Float; anything else fails.
|
|
335
|
+
pub fn exceeds(count: i64, limit: &Value) -> Result<bool, ContextError> {
|
|
336
|
+
compare(count, limit).map(|ordering| ordering == Some(std::cmp::Ordering::Greater))
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/// `count >= limit`, with Ruby's `Integer#>=`.
|
|
340
|
+
pub fn at_least(count: i64, limit: &Value) -> Result<bool, ContextError> {
|
|
341
|
+
compare(count, limit).map(|ordering| matches!(ordering, Some(std::cmp::Ordering::Greater | std::cmp::Ordering::Equal)))
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/// `None` when the limit is NaN, which no comparison satisfies.
|
|
345
|
+
fn compare(count: i64, limit: &Value) -> Result<Option<std::cmp::Ordering>, ContextError> {
|
|
346
|
+
match limit {
|
|
347
|
+
Value::Int(limit) => Ok(Some(count.cmp(limit))),
|
|
348
|
+
Value::Float(limit) => Ok((count as f64).partial_cmp(limit)),
|
|
349
|
+
other => Err(ContextError::Unexpected(format!("comparison of Integer with {} failed", comparison_operand(other)))),
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
fn comparison_operand(value: &Value) -> String {
|
|
354
|
+
match value {
|
|
355
|
+
Value::Nil => "nil".to_string(),
|
|
356
|
+
Value::Bool(value) => value.to_string(),
|
|
357
|
+
other => other.class_name().to_string(),
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/// `String#match(pattern)` is truthy: a String pattern is compiled as a
|
|
362
|
+
/// regexp, a Regexp used as is.
|
|
363
|
+
pub fn string_match(text: &str, pattern: &Value) -> Result<bool, ContextError> {
|
|
364
|
+
let regexp = match pattern {
|
|
365
|
+
Value::Str(source) => RubyRegexp::new(source, "").map_err(ContextError::Unexpected)?,
|
|
366
|
+
Value::Regexp(regexp) => regexp.clone(),
|
|
367
|
+
other => {
|
|
368
|
+
return Err(ContextError::Unexpected(format!("wrong argument type {} (expected Regexp)", other.class_name())));
|
|
369
|
+
}
|
|
370
|
+
};
|
|
371
|
+
Ok(regexp.is_match(text.as_bytes()))
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/// `/#{pattern}/ =~ text` is truthy: the pattern's `to_s` is the source,
|
|
375
|
+
/// so a String is a pattern and a Regexp keeps its options.
|
|
376
|
+
pub fn interpolated_match(pattern: &Value, text: &[u8]) -> Result<bool, ContextError> {
|
|
377
|
+
let regexp = match pattern {
|
|
378
|
+
Value::Regexp(regexp) => regexp.clone(),
|
|
379
|
+
other => RubyRegexp::new(&other.to_s(), "").map_err(ContextError::Unexpected)?,
|
|
380
|
+
};
|
|
381
|
+
Ok(regexp.is_match(text))
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/// `Array(value)`.
|
|
385
|
+
pub fn ruby_array(value: Value) -> Vec<Value> {
|
|
386
|
+
match value {
|
|
387
|
+
Value::Nil => Vec::new(),
|
|
388
|
+
Value::Array(items) => items,
|
|
389
|
+
Value::Hash(hash) => hash.into_iter().map(|(key, value)| Value::Array(vec![Value::Str(key), value])).collect(),
|
|
390
|
+
other => vec![other],
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/// The items of a configuration value used as an array (`any?`,
|
|
395
|
+
/// `include?`): only Arrays have them here.
|
|
396
|
+
pub fn array_items(value: &Value, method: &str) -> Result<Vec<Value>, ContextError> {
|
|
397
|
+
match value {
|
|
398
|
+
Value::Array(items) => Ok(items.clone()),
|
|
399
|
+
other => Err(no_method(method, other)),
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/// A `Hash` keyed by node (`eql?` and `hash`), in insertion order.
|
|
404
|
+
pub struct NodeMap<V> {
|
|
405
|
+
entries: Vec<(NodeId, V)>,
|
|
406
|
+
buckets: std::collections::HashMap<u64, Vec<usize>>,
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
impl<V> Default for NodeMap<V> {
|
|
410
|
+
fn default() -> Self {
|
|
411
|
+
Self::new()
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
impl<V> NodeMap<V> {
|
|
416
|
+
pub fn new() -> Self {
|
|
417
|
+
NodeMap { entries: Vec::new(), buckets: std::collections::HashMap::new() }
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/// The value for `node`'s key, created with `default` when new.
|
|
421
|
+
pub fn entry(&mut self, tree: &Tree, node: NodeId, default: impl FnOnce() -> V) -> &mut V {
|
|
422
|
+
let bucket = self.buckets.entry(tree.node_hash(node)).or_default();
|
|
423
|
+
let index = match bucket.iter().find(|index| tree.eql(self.entries[**index].0, node)) {
|
|
424
|
+
Some(index) => *index,
|
|
425
|
+
None => {
|
|
426
|
+
self.entries.push((node, default()));
|
|
427
|
+
bucket.push(self.entries.len() - 1);
|
|
428
|
+
self.entries.len() - 1
|
|
429
|
+
}
|
|
430
|
+
};
|
|
431
|
+
&mut self.entries[index].1
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
pub fn into_entries(self) -> Vec<(NodeId, V)> {
|
|
435
|
+
self.entries
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/// `BaseDetector.to_detector(name).configuration_keys` for the names
|
|
440
|
+
/// `SmellDetectors.const_get` resolves to a detector class: the detectors
|
|
441
|
+
/// and `BaseDetector` itself.
|
|
442
|
+
pub fn configuration_keys_for(name: &str) -> Option<Vec<String>> {
|
|
443
|
+
if name == "BaseDetector" {
|
|
444
|
+
return Some(vec!["enabled".to_string(), "exclude".to_string()]);
|
|
445
|
+
}
|
|
446
|
+
find(name).map(DetectorClass::configuration_keys)
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/// The detector with this smell type.
|
|
450
|
+
pub fn find(smell_type: &str) -> Option<&'static DetectorClass> {
|
|
451
|
+
DETECTORS.iter().find(|detector| detector.smell_type == smell_type)
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
#[cfg(test)]
|
|
455
|
+
mod tests {
|
|
456
|
+
use super::*;
|
|
457
|
+
|
|
458
|
+
#[test]
|
|
459
|
+
fn detectors_are_sorted_by_name() {
|
|
460
|
+
let names: Vec<&str> = DETECTORS.iter().map(|detector| detector.smell_type).collect();
|
|
461
|
+
let mut sorted = names.clone();
|
|
462
|
+
sorted.sort();
|
|
463
|
+
assert_eq!(names, sorted);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
#[test]
|
|
467
|
+
fn default_configs_match_reek() {
|
|
468
|
+
let config = find("LongParameterList").unwrap().default_config();
|
|
469
|
+
assert_eq!(
|
|
470
|
+
Value::Hash(config).inspect(),
|
|
471
|
+
r#"{"enabled"=>true, "exclude"=>[], "max_params"=>3, "overrides"=>{"initialize"=>{"max_params"=>5}}}"#
|
|
472
|
+
);
|
|
473
|
+
let config = find("UncommunicativeVariableName").unwrap().default_config();
|
|
474
|
+
assert_eq!(
|
|
475
|
+
Value::Hash(config).inspect(),
|
|
476
|
+
r#"{"enabled"=>true, "exclude"=>[], "reject"=>[/^.$/, /[0-9]$/, /[A-Z]/], "accept"=>[/^_$/]}"#
|
|
477
|
+
);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
//! `ModuleInitialize`: a module defining `initialize`.
|
|
2
|
+
|
|
3
|
+
use super::{Detector, SniffResult};
|
|
4
|
+
|
|
5
|
+
pub fn sniff(detector: &Detector) -> SniffResult {
|
|
6
|
+
let contexts = detector.contexts;
|
|
7
|
+
let defines_initialize = contexts
|
|
8
|
+
.defined_instance_methods(detector.context, None)
|
|
9
|
+
.into_iter()
|
|
10
|
+
.any(|method| contexts.name(method).is_symbol("initialize"));
|
|
11
|
+
if !defines_initialize {
|
|
12
|
+
return Ok(Vec::new());
|
|
13
|
+
}
|
|
14
|
+
Ok(vec![detector.smell_warning(vec![detector.source_line()?], "has initialize method".to_string(), Vec::new())?])
|
|
15
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
//! `NestedIterators`: blocks nested more than `max_allowed_nesting` deep.
|
|
2
|
+
//! Blocks without arguments and calls matching `ignore_iterators` do not
|
|
3
|
+
//! add a level.
|
|
4
|
+
|
|
5
|
+
use std::cell::OnceCell;
|
|
6
|
+
|
|
7
|
+
use indexmap::IndexMap;
|
|
8
|
+
|
|
9
|
+
use super::{array_items, exceeds, interpolated_match, line, Detector, Parameter, SniffResult};
|
|
10
|
+
use crate::ast::NodeId;
|
|
11
|
+
use crate::context::ContextError;
|
|
12
|
+
use crate::yaml::Value;
|
|
13
|
+
|
|
14
|
+
pub fn sniff(detector: &Detector) -> SniffResult {
|
|
15
|
+
let tree = detector.tree();
|
|
16
|
+
let scout = Scout { detector, ignore_iterators: OnceCell::new() };
|
|
17
|
+
let candidates = scout.scout(Some(detector.expression()), 0)?;
|
|
18
|
+
// `find_violations`
|
|
19
|
+
let mut max_allowed_nesting = None;
|
|
20
|
+
let mut violations: IndexMap<i64, Vec<usize>> = IndexMap::new();
|
|
21
|
+
for (iterator, depth) in candidates {
|
|
22
|
+
if max_allowed_nesting.is_none() {
|
|
23
|
+
max_allowed_nesting = Some(detector.value("max_allowed_nesting")?);
|
|
24
|
+
}
|
|
25
|
+
if exceeds(depth, max_allowed_nesting.as_ref().expect("read above"))? {
|
|
26
|
+
violations.entry(depth).or_default().push(line(tree, iterator)?);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
let mut smells = Vec::new();
|
|
30
|
+
for (depth, lines) in violations {
|
|
31
|
+
smells.push(detector.smell_warning(
|
|
32
|
+
lines,
|
|
33
|
+
format!("contains iterators nested {depth} deep"),
|
|
34
|
+
vec![("depth", Parameter::Integer(depth))],
|
|
35
|
+
)?);
|
|
36
|
+
}
|
|
37
|
+
Ok(smells)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
struct Scout<'a, 'b, 'tree> {
|
|
41
|
+
detector: &'a Detector<'b, 'tree>,
|
|
42
|
+
/// `ignore_iterators`, read when the first block is found.
|
|
43
|
+
ignore_iterators: OnceCell<Vec<Value>>,
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
impl Scout<'_, '_, '_> {
|
|
47
|
+
/// `scout(exp:, depth:)`: the innermost blocks under the node with
|
|
48
|
+
/// their depths. A block's body is a level deeper; its call is not.
|
|
49
|
+
fn scout(&self, exp: Option<NodeId>, depth: i64) -> Result<Vec<(NodeId, i64)>, ContextError> {
|
|
50
|
+
let Some(exp) = exp else { return Ok(Vec::new()) };
|
|
51
|
+
let tree = self.detector.tree();
|
|
52
|
+
let mut out = Vec::new();
|
|
53
|
+
for iterator in tree.each_node(exp, &["block"], &["block"]) {
|
|
54
|
+
let new_depth = if self.is_ignored_iterator(iterator)? { depth } else { depth + 1 };
|
|
55
|
+
let mut nested_iterators = self.scout(tree.child_node(iterator, 2), new_depth)?;
|
|
56
|
+
nested_iterators.extend(self.scout(tree.child_node(iterator, 0), depth)?);
|
|
57
|
+
if nested_iterators.is_empty() {
|
|
58
|
+
out.push((iterator, new_depth));
|
|
59
|
+
} else {
|
|
60
|
+
out.extend(nested_iterators);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
Ok(out)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/// `ignored_iterator?`: the call matches an `ignore_iterators` pattern,
|
|
67
|
+
/// or the block takes no arguments.
|
|
68
|
+
fn is_ignored_iterator(&self, iterator: NodeId) -> Result<bool, ContextError> {
|
|
69
|
+
let tree = self.detector.tree();
|
|
70
|
+
if self.ignore_iterators.get().is_none() {
|
|
71
|
+
let value = self.detector.value("ignore_iterators")?;
|
|
72
|
+
let _ = self.ignore_iterators.set(array_items(&value, "any?")?);
|
|
73
|
+
}
|
|
74
|
+
let call = tree.format_to_ruby(tree.child_node(iterator, 0).expect("a block has a call"));
|
|
75
|
+
for pattern in self.ignore_iterators.get().expect("read above") {
|
|
76
|
+
if interpolated_match(pattern, &call)? {
|
|
77
|
+
return Ok(true);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
Ok(tree.is_block_without_arguments(iterator)?)
|
|
81
|
+
}
|
|
82
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
//! `NilCheck`: a method calling `nil?`, comparing with `nil` (`==`,
|
|
2
|
+
//! `===`), or with `when nil`.
|
|
3
|
+
|
|
4
|
+
use super::{line, Detector, SniffResult};
|
|
5
|
+
use crate::ast::{Child, NodeId, Tree};
|
|
6
|
+
|
|
7
|
+
pub fn sniff(detector: &Detector) -> SniffResult {
|
|
8
|
+
let tree = detector.tree();
|
|
9
|
+
let contexts = detector.contexts;
|
|
10
|
+
let calls = contexts.local_nodes(detector.context, &["send"], &[]).into_iter().filter(|call| is_nil_call(tree, *call));
|
|
11
|
+
let whens = contexts.local_nodes(detector.context, &["when"], &[]).into_iter().filter(|when| is_nil_when(tree, *when));
|
|
12
|
+
let lines: Vec<usize> = calls.chain(whens).map(|node| line(tree, node)).collect::<Result<_, _>>()?;
|
|
13
|
+
if lines.is_empty() {
|
|
14
|
+
return Ok(Vec::new());
|
|
15
|
+
}
|
|
16
|
+
Ok(vec![detector.smell_warning(lines, "performs a nil-check".to_string(), Vec::new())?])
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/// `NilCallNodeDetector.detect`: `nil?`, or `==`/`===` with a `nil`
|
|
20
|
+
/// receiver or argument.
|
|
21
|
+
fn is_nil_call(tree: &Tree, call: NodeId) -> bool {
|
|
22
|
+
let name = tree.name(call);
|
|
23
|
+
if name.is_symbol("nil?") {
|
|
24
|
+
return true;
|
|
25
|
+
}
|
|
26
|
+
let is_comparison = name.is_symbol("==") || name.is_symbol("===");
|
|
27
|
+
is_comparison && participants(tree, call).any(|participant| tree.ty(participant) == "nil")
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/// `participants`: the receiver and the arguments.
|
|
31
|
+
fn participants(tree: &Tree, call: NodeId) -> impl Iterator<Item = NodeId> + '_ {
|
|
32
|
+
tree.receiver(call).into_iter().chain(tree.send_args(call).iter().filter_map(Child::node))
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// `NilWhenNodeDetector.detect`: a `when` with a `nil` condition.
|
|
36
|
+
fn is_nil_when(tree: &Tree, when: NodeId) -> bool {
|
|
37
|
+
let children = tree.children(when);
|
|
38
|
+
let condition_list = &children[..children.len().saturating_sub(1)];
|
|
39
|
+
condition_list.iter().filter_map(Child::node).any(|condition| tree.ty(condition) == "nil")
|
|
40
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
//! `RepeatedConditional`: a class testing the same condition (in `if` or
|
|
2
|
+
//! `case`) more than `max_ifs` times.
|
|
3
|
+
|
|
4
|
+
use super::{exceeds, line, Detector, NodeMap, Parameter, SniffResult};
|
|
5
|
+
use crate::ast::{Child, NodeId, Tree};
|
|
6
|
+
|
|
7
|
+
pub fn sniff(detector: &Detector) -> SniffResult {
|
|
8
|
+
let tree = detector.tree();
|
|
9
|
+
let mut max_identical_ifs = None;
|
|
10
|
+
let mut smells = Vec::new();
|
|
11
|
+
for (condition, lines) in conditional_counts(detector)? {
|
|
12
|
+
if max_identical_ifs.is_none() {
|
|
13
|
+
max_identical_ifs = Some(detector.value("max_ifs")?);
|
|
14
|
+
}
|
|
15
|
+
let occurs = lines.len();
|
|
16
|
+
if !exceeds(occurs as i64, max_identical_ifs.as_ref().expect("read above"))? {
|
|
17
|
+
continue;
|
|
18
|
+
}
|
|
19
|
+
let expression = String::from_utf8_lossy(&tree.format_to_ruby(condition)).into_owned();
|
|
20
|
+
smells.push(detector.smell_warning(
|
|
21
|
+
lines,
|
|
22
|
+
format!("tests '{expression}' at least {occurs} times"),
|
|
23
|
+
vec![("name", Parameter::String(expression)), ("count", Parameter::Integer(occurs as i64))],
|
|
24
|
+
)?);
|
|
25
|
+
}
|
|
26
|
+
Ok(smells)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/// `conditional_counts`: the lines of each condition of the `if`s, then
|
|
30
|
+
/// of the `case`s; `block_given?` does not count.
|
|
31
|
+
fn conditional_counts(detector: &Detector) -> Result<Vec<(NodeId, Vec<usize>)>, crate::context::ContextError> {
|
|
32
|
+
let tree = detector.tree();
|
|
33
|
+
let mut result: NodeMap<Vec<usize>> = NodeMap::new();
|
|
34
|
+
for statement in ["if", "case"] {
|
|
35
|
+
for node in detector.contexts.local_nodes(detector.context, &[statement], &[]) {
|
|
36
|
+
let Some(condition) = tree.condition(node) else { continue };
|
|
37
|
+
if is_block_given_condition(tree, condition) {
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
let line = line(tree, condition)?;
|
|
41
|
+
result.entry(tree, condition, Vec::new).push(line);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
Ok(result.into_entries())
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/// `condition == BLOCK_GIVEN_CONDITION`: `(send nil :block_given?)`.
|
|
48
|
+
fn is_block_given_condition(tree: &Tree, condition: NodeId) -> bool {
|
|
49
|
+
tree.ty(condition) == "send"
|
|
50
|
+
&& matches!(tree.children(condition), [Child::Nil, Child::Sym(name)] if &**name == b"block_given?")
|
|
51
|
+
}
|