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.
Files changed (62) hide show
  1. checksums.yaml +7 -0
  2. data/Cargo.lock +614 -0
  3. data/Cargo.toml +24 -0
  4. data/DIVERGENCES.md +15 -0
  5. data/LICENSE +22 -0
  6. data/README.md +125 -0
  7. data/THIRD_PARTY_NOTICES.md +57 -0
  8. data/crates/reek-cli/Cargo.toml +22 -0
  9. data/crates/reek-cli/src/main.rs +277 -0
  10. data/crates/reek-core/Cargo.toml +21 -0
  11. data/crates/reek-core/src/ast.rs +449 -0
  12. data/crates/reek-core/src/code_comment.rs +245 -0
  13. data/crates/reek-core/src/comments.rs +179 -0
  14. data/crates/reek-core/src/config.rs +803 -0
  15. data/crates/reek-core/src/context.rs +891 -0
  16. data/crates/reek-core/src/detectors/attribute.rs +13 -0
  17. data/crates/reek-core/src/detectors/boolean_parameter.rs +20 -0
  18. data/crates/reek-core/src/detectors/class_variable.rs +25 -0
  19. data/crates/reek-core/src/detectors/control_parameter.rs +110 -0
  20. data/crates/reek-core/src/detectors/data_clump.rs +114 -0
  21. data/crates/reek-core/src/detectors/duplicate_method_call.rs +63 -0
  22. data/crates/reek-core/src/detectors/feature_envy.rs +32 -0
  23. data/crates/reek-core/src/detectors/instance_variable_assumption.rs +39 -0
  24. data/crates/reek-core/src/detectors/irresponsible_module.rs +12 -0
  25. data/crates/reek-core/src/detectors/long_parameter_list.rs +16 -0
  26. data/crates/reek-core/src/detectors/long_yield_list.rs +20 -0
  27. data/crates/reek-core/src/detectors/manual_dispatch.rs +18 -0
  28. data/crates/reek-core/src/detectors/missing_safe_method.rs +34 -0
  29. data/crates/reek-core/src/detectors/mod.rs +479 -0
  30. data/crates/reek-core/src/detectors/module_initialize.rs +15 -0
  31. data/crates/reek-core/src/detectors/nested_iterators.rs +82 -0
  32. data/crates/reek-core/src/detectors/nil_check.rs +40 -0
  33. data/crates/reek-core/src/detectors/repeated_conditional.rs +51 -0
  34. data/crates/reek-core/src/detectors/subclassed_from_core_class.rs +22 -0
  35. data/crates/reek-core/src/detectors/too_many_constants.rs +18 -0
  36. data/crates/reek-core/src/detectors/too_many_instance_variables.rs +25 -0
  37. data/crates/reek-core/src/detectors/too_many_methods.rs +15 -0
  38. data/crates/reek-core/src/detectors/too_many_statements.rs +16 -0
  39. data/crates/reek-core/src/detectors/uncommunicative_method_name.rs +32 -0
  40. data/crates/reek-core/src/detectors/uncommunicative_module_name.rs +33 -0
  41. data/crates/reek-core/src/detectors/uncommunicative_parameter_name.rs +49 -0
  42. data/crates/reek-core/src/detectors/uncommunicative_variable_name.rs +138 -0
  43. data/crates/reek-core/src/detectors/unused_parameters.rs +21 -0
  44. data/crates/reek-core/src/detectors/unused_private_method.rs +59 -0
  45. data/crates/reek-core/src/detectors/utility_function.rs +27 -0
  46. data/crates/reek-core/src/encodings.rs +180 -0
  47. data/crates/reek-core/src/examiner.rs +165 -0
  48. data/crates/reek-core/src/lib.rs +21 -0
  49. data/crates/reek-core/src/node.rs +423 -0
  50. data/crates/reek-core/src/ruby_format.rs +60 -0
  51. data/crates/reek-core/src/ruby_inspect.rs +172 -0
  52. data/crates/reek-core/src/ruby_regexp.rs +243 -0
  53. data/crates/reek-core/src/single_byte_encodings.rs +6007 -0
  54. data/crates/reek-core/src/source.rs +280 -0
  55. data/crates/reek-core/src/translate.rs +3112 -0
  56. data/crates/reek-core/src/yaml.rs +520 -0
  57. data/ext/reek_rs/Cargo.toml +18 -0
  58. data/ext/reek_rs/extconf.rb +6 -0
  59. data/ext/reek_rs/src/lib.rs +155 -0
  60. data/lib/reek_rs/version.rb +8 -0
  61. data/lib/reek_rs.rb +390 -0
  62. metadata +123 -0
@@ -0,0 +1,891 @@
1
+ //! Reek's code contexts (`Reek::Context::*`) and `ContextBuilder`.
2
+ //!
3
+ //! The builder walks the tree once and builds a tree of contexts: the root,
4
+ //! modules and classes, methods, attributes, and the calls made in methods.
5
+ //! Detectors examine each context (`context_tree.each`, parents before
6
+ //! children) whose type they list.
7
+ //!
8
+ //! Contexts live in an arena ([`ContextTree`]) and refer to each other by
9
+ //! [`ContextId`]. Reek's context classes become [`ContextKind`]; the methods
10
+ //! a class overrides become `match`es on the kind.
11
+
12
+ use std::cell::RefCell;
13
+
14
+ use indexmap::IndexMap;
15
+
16
+ use crate::ast::{Child, NodeId, Tree};
17
+ use crate::code_comment::{self, CodeCommentError, CommentLocation, DetectorOptions};
18
+ use crate::node::{Name, NoMethodError};
19
+ use crate::ruby_regexp::RubyRegexp;
20
+ use crate::yaml::Value;
21
+
22
+ /// A context in a [`ContextTree`].
23
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
24
+ pub struct ContextId(pub usize);
25
+
26
+ /// Reek's context classes.
27
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
28
+ pub enum ContextKind {
29
+ /// `RootContext`: the whole file.
30
+ Root,
31
+ /// `ModuleContext`: a `module`, a `class`, or a constant assigned
32
+ /// `Class.new`, `Struct.new` or `Data.define`.
33
+ Module,
34
+ /// `GhostContext`: `class << self`. It is not part of the tree; what is
35
+ /// defined in it is added to the enclosing context as well.
36
+ Ghost,
37
+ /// `RefinementContext`: a `refine` block.
38
+ Refinement,
39
+ /// `MethodContext`: a `def`.
40
+ Method,
41
+ /// `SingletonMethodContext`: a `defs`, or a `def` in `class << self`.
42
+ SingletonMethod,
43
+ /// `AttributeContext`: an argument of `attr_writer`, `attr_accessor` or
44
+ /// `attr ..., true`.
45
+ Attribute,
46
+ /// `SingletonAttributeContext`: an attribute in `class << self`.
47
+ SingletonAttribute,
48
+ /// `SendContext`: a call made in a method.
49
+ Send,
50
+ }
51
+
52
+ impl ContextKind {
53
+ /// `is_a?(Context::ModuleContext)`.
54
+ pub fn is_module_context(self) -> bool {
55
+ matches!(self, ContextKind::Module | ContextKind::Ghost | ContextKind::Refinement)
56
+ }
57
+
58
+ /// `is_a?(Context::MethodContext)`.
59
+ pub fn is_method_context(self) -> bool {
60
+ matches!(self, ContextKind::Method | ContextKind::SingletonMethod)
61
+ }
62
+
63
+ fn is_attribute_context(self) -> bool {
64
+ matches!(self, ContextKind::Attribute | ContextKind::SingletonAttribute)
65
+ }
66
+ }
67
+
68
+ /// A method's or attribute's visibility, as `VisibilityTracker` sets it.
69
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
70
+ pub enum Visibility {
71
+ Public,
72
+ Private,
73
+ Protected,
74
+ ModuleFunction,
75
+ }
76
+
77
+ impl Visibility {
78
+ /// `VISIBILITY_MODIFIERS`: the methods that change visibility.
79
+ fn from_modifier(name: &Name) -> Option<Visibility> {
80
+ match name {
81
+ Name::Symbol(name) => match name.as_str() {
82
+ "private" => Some(Visibility::Private),
83
+ "public" => Some(Visibility::Public),
84
+ "protected" => Some(Visibility::Protected),
85
+ "module_function" => Some(Visibility::ModuleFunction),
86
+ _ => None,
87
+ },
88
+ _ => None,
89
+ }
90
+ }
91
+
92
+ /// `VISIBILITY_MAP`: the class method modifiers.
93
+ fn from_class_method_modifier(name: &Name) -> Option<Visibility> {
94
+ match name {
95
+ Name::Symbol(name) => match name.as_str() {
96
+ "public_class_method" => Some(Visibility::Public),
97
+ "private_class_method" => Some(Visibility::Private),
98
+ _ => None,
99
+ },
100
+ _ => None,
101
+ }
102
+ }
103
+ }
104
+
105
+ /// `AST::ObjectRefs`: the lines each receiver is referred to on, by name
106
+ /// (`self` for calls without a receiver, `self`, `super` and instance
107
+ /// variables).
108
+ #[derive(Clone, Debug, Default)]
109
+ pub struct ObjectRefs {
110
+ refs: IndexMap<String, Vec<Option<usize>>>,
111
+ }
112
+
113
+ impl ObjectRefs {
114
+ fn record_reference(&mut self, name: &str, line: Option<usize>) {
115
+ self.refs.entry(name.to_string()).or_default().push(line);
116
+ }
117
+
118
+ /// `most_popular`: the names referred to most, in first-reference order.
119
+ pub fn most_popular(&self) -> IndexMap<&str, &[Option<usize>]> {
120
+ let max = self.refs.values().map(Vec::len).max();
121
+ self.refs
122
+ .iter()
123
+ .filter(|(_, lines)| Some(lines.len()) == max)
124
+ .map(|(name, lines)| (name.as_str(), lines.as_slice()))
125
+ .collect()
126
+ }
127
+
128
+ /// `references_to(name)`.
129
+ pub fn references_to(&self, name: &str) -> &[Option<usize>] {
130
+ self.refs.get(name).map_or(&[], Vec::as_slice)
131
+ }
132
+
133
+ /// `self_is_max?`.
134
+ pub fn self_is_max(&self) -> bool {
135
+ self.refs.is_empty() || self.most_popular().contains_key("self")
136
+ }
137
+ }
138
+
139
+ /// One context.
140
+ #[derive(Debug)]
141
+ pub struct Context {
142
+ pub kind: ContextKind,
143
+ pub exp: NodeId,
144
+ pub parent: Option<ContextId>,
145
+ pub children: Vec<ContextId>,
146
+ /// `StatementCounter#value`. A ghost context counts in its parent.
147
+ statement_count: i64,
148
+ pub refs: ObjectRefs,
149
+ /// Methods' and attributes' `visibility`.
150
+ pub visibility: Visibility,
151
+ /// `VisibilityTracker#tracked_visibility` of module contexts.
152
+ tracked_visibility: Visibility,
153
+ /// A method's `parent_exp`: the node containing the `def`.
154
+ parent_exp: Option<NodeId>,
155
+ /// An attribute's `send_expression`: the `attr_writer` call.
156
+ send_expression: Option<NodeId>,
157
+ /// `configuration_via_code_commment`, read when first needed.
158
+ comment_config: RefCell<Option<IndexMap<String, DetectorOptions>>>,
159
+ }
160
+
161
+ /// Why examining a context failed.
162
+ #[derive(Clone, Debug, PartialEq)]
163
+ pub enum ContextError {
164
+ /// A `Reek::Errors::BaseError` subclass, raised as is.
165
+ Reek { class: &'static str, message: String },
166
+ /// Any other `StandardError`, which the examiner reports as
167
+ /// `Reek::Errors::IncomprehensibleSourceError`.
168
+ Unexpected(String),
169
+ }
170
+
171
+ impl From<NoMethodError> for ContextError {
172
+ fn from(error: NoMethodError) -> Self {
173
+ ContextError::Unexpected(error.to_string())
174
+ }
175
+ }
176
+
177
+ impl From<CodeCommentError> for ContextError {
178
+ fn from(error: CodeCommentError) -> Self {
179
+ match error {
180
+ CodeCommentError::Reek { class, message } => ContextError::Reek { class, message },
181
+ CodeCommentError::Unexpected(cause) => ContextError::Unexpected(cause),
182
+ }
183
+ }
184
+ }
185
+
186
+ /// The contexts of a file (`ContextBuilder#context_tree`).
187
+ #[derive(Debug)]
188
+ pub struct ContextTree<'tree> {
189
+ pub tree: &'tree Tree,
190
+ /// The file's origin: the `source` of every node.
191
+ pub origin: &'tree str,
192
+ pub contexts: Vec<Context>,
193
+ }
194
+
195
+ /// The root context's id.
196
+ pub const ROOT: ContextId = ContextId(0);
197
+
198
+ impl<'tree> ContextTree<'tree> {
199
+ /// `ContextBuilder.new(syntax_tree).context_tree`.
200
+ pub fn build(tree: &'tree Tree, root: NodeId, origin: &'tree str) -> Result<Self, ContextError> {
201
+ let mut builder = ContextBuilder {
202
+ contexts: ContextTree { tree, origin, contexts: Vec::new() },
203
+ current_context: ROOT,
204
+ };
205
+ builder.contexts.new_context(ContextKind::Root, root);
206
+ builder.build(root, None)?;
207
+ Ok(builder.contexts)
208
+ }
209
+
210
+ pub fn context(&self, id: ContextId) -> &Context {
211
+ &self.contexts[id.0]
212
+ }
213
+
214
+ /// `each`: the root, then each child's contexts in turn.
215
+ pub fn each(&self) -> Vec<ContextId> {
216
+ let mut out = Vec::with_capacity(self.contexts.len());
217
+ self.collect_each(ROOT, &mut out);
218
+ out
219
+ }
220
+
221
+ fn collect_each(&self, id: ContextId, out: &mut Vec<ContextId>) {
222
+ out.push(id);
223
+ for child in &self.context(id).children {
224
+ self.collect_each(*child, out);
225
+ }
226
+ }
227
+
228
+ // ------------------------------------------------------------------
229
+ // Building
230
+
231
+ fn new_context(&mut self, kind: ContextKind, exp: NodeId) -> ContextId {
232
+ let id = ContextId(self.contexts.len());
233
+ self.contexts.push(Context {
234
+ kind,
235
+ exp,
236
+ parent: None,
237
+ children: Vec::new(),
238
+ statement_count: 0,
239
+ refs: ObjectRefs::default(),
240
+ visibility: Visibility::Public,
241
+ tracked_visibility: Visibility::Public,
242
+ parent_exp: None,
243
+ send_expression: None,
244
+ comment_config: RefCell::new(None),
245
+ });
246
+ id
247
+ }
248
+
249
+ /// `register_with_parent(parent)`: a ghost context only remembers its
250
+ /// parent; other contexts are appended to it.
251
+ fn register_with_parent(&mut self, child: ContextId, parent: ContextId) -> Result<(), ContextError> {
252
+ let parent = if self.context(child).kind == ContextKind::Ghost {
253
+ parent
254
+ } else {
255
+ self.append_child_context(parent, child)?
256
+ };
257
+ self.contexts[child.0].parent = Some(parent);
258
+ Ok(())
259
+ }
260
+
261
+ /// `append_child_context(child)`: adds the child and returns its parent.
262
+ /// A module context first applies its tracked visibility to the child;
263
+ /// a ghost context appends the child to its own parent first, and that
264
+ /// parent becomes the child's parent.
265
+ fn append_child_context(&mut self, context: ContextId, child: ContextId) -> Result<ContextId, ContextError> {
266
+ let kind = self.context(context).kind;
267
+ let real_parent = if kind == ContextKind::Ghost {
268
+ let parent = self.context(context).parent.expect("a ghost context has a parent");
269
+ Some(self.append_child_context(parent, child)?)
270
+ } else {
271
+ None
272
+ };
273
+ if kind.is_module_context() {
274
+ let tracked_visibility = self.context(context).tracked_visibility;
275
+ self.apply_current_visibility(child, tracked_visibility);
276
+ }
277
+ self.contexts[context.0].children.push(child);
278
+ Ok(real_parent.unwrap_or(context))
279
+ }
280
+
281
+ /// `apply_current_visibility`: methods and attributes take the tracked
282
+ /// visibility; singleton methods only when written as `def` (in
283
+ /// `class << self`).
284
+ fn apply_current_visibility(&mut self, context: ContextId, visibility: Visibility) {
285
+ let applies = match self.context(context).kind {
286
+ ContextKind::Method | ContextKind::Attribute | ContextKind::SingletonAttribute => true,
287
+ ContextKind::SingletonMethod => self.tree.ty(self.context(context).exp) == "def",
288
+ _ => false,
289
+ };
290
+ if applies {
291
+ self.contexts[context.0].visibility = visibility;
292
+ }
293
+ }
294
+
295
+ /// The context whose `statement_counter` a context uses: ghost contexts
296
+ /// use their parent's.
297
+ fn statement_counter_owner(&self, context: ContextId) -> ContextId {
298
+ let mut owner = context;
299
+ while self.context(owner).kind == ContextKind::Ghost {
300
+ owner = self.context(owner).parent.expect("a ghost context has a parent");
301
+ }
302
+ owner
303
+ }
304
+
305
+ /// `record_call_to(exp)`: a call on a local variable records the
306
+ /// variable (unless the call is `new`); a call on `self` or without a
307
+ /// receiver records `self`.
308
+ fn record_call_to(&mut self, context: ContextId, exp: NodeId) {
309
+ let tree = self.tree;
310
+ let line = tree.line(exp);
311
+ match tree.receiver(exp) {
312
+ Some(receiver) => match tree.ty(receiver) {
313
+ "lvar" | "lvasgn" => {
314
+ if !tree.is_object_creation_call(exp) {
315
+ let name = tree.name(receiver);
316
+ self.contexts[context.0].refs.record_reference(name.to_s(), line);
317
+ }
318
+ }
319
+ "self" => self.contexts[context.0].refs.record_reference("self", line),
320
+ _ => {}
321
+ },
322
+ None => self.contexts[context.0].refs.record_reference("self", line),
323
+ }
324
+ }
325
+
326
+ /// `record_use_of_self`: ghost contexts record in their parent.
327
+ fn record_use_of_self(&mut self, context: ContextId) {
328
+ let owner = self.statement_counter_owner(context);
329
+ self.contexts[owner.0].refs.record_reference("self", None);
330
+ }
331
+
332
+ /// `track_visibility(visibility, names)` of a module context.
333
+ fn track_visibility(&mut self, context: ContextId, visibility: &Name, names: &[Child]) -> Result<(), ContextError> {
334
+ if self.context(context).kind == ContextKind::Ghost {
335
+ let children = self.context(context).children.clone();
336
+ return self.track_visibility_of(context, &children, Visibility::from_modifier(visibility), names);
337
+ }
338
+ let instance_method_children = self.children_where(context, |kind| self.is_instance_method(kind));
339
+ self.track_visibility_of(context, &instance_method_children, Visibility::from_modifier(visibility), names)?;
340
+ // `track_singleton_visibility`
341
+ if names.is_empty() {
342
+ return Ok(());
343
+ }
344
+ let Some(visibility) = Visibility::from_class_method_modifier(visibility) else { return Ok(()) };
345
+ let singleton_method_children = self.children_where(context, |kind| kind == ContextKind::SingletonMethod);
346
+ self.track_visibility_of(context, &singleton_method_children, Some(visibility), names)
347
+ }
348
+
349
+ fn children_where(&self, context: ContextId, predicate: impl Fn(ContextKind) -> bool) -> Vec<ContextId> {
350
+ let children = &self.context(context).children;
351
+ children.iter().copied().filter(|child| predicate(self.context(*child).kind)).collect()
352
+ }
353
+
354
+ /// `instance_method?`.
355
+ fn is_instance_method(&self, kind: ContextKind) -> bool {
356
+ matches!(kind, ContextKind::Method | ContextKind::Attribute)
357
+ }
358
+
359
+ /// `VisibilityTracker#track_visibility`: with names, sets the visibility
360
+ /// of the named children; without, sets the visibility of what follows.
361
+ fn track_visibility_of(
362
+ &mut self,
363
+ context: ContextId,
364
+ children: &[ContextId],
365
+ visibility: Option<Visibility>,
366
+ names: &[Child],
367
+ ) -> Result<(), ContextError> {
368
+ let Some(visibility) = visibility else { return Ok(()) };
369
+ if !names.iter().any(|name| !name.is_nil()) {
370
+ self.contexts[context.0].tracked_visibility = visibility;
371
+ return Ok(());
372
+ }
373
+ for child in children {
374
+ let name = self.tree.name(self.context(*child).exp);
375
+ if !names.iter().any(|candidate| name_equals(&name, candidate)) {
376
+ continue;
377
+ }
378
+ let kind = self.context(*child).kind;
379
+ if !(kind.is_method_context() || kind.is_attribute_context()) {
380
+ return Err(ContextError::Unexpected(format!("undefined method 'visibility=' for a {kind:?} context")));
381
+ }
382
+ self.contexts[child.0].visibility = visibility;
383
+ }
384
+ Ok(())
385
+ }
386
+
387
+ // ------------------------------------------------------------------
388
+ // Reading
389
+
390
+ /// `type`: `:root` for the root context, otherwise the node's type.
391
+ pub fn ty(&self, context: ContextId) -> &'static str {
392
+ match self.context(context).kind {
393
+ ContextKind::Root => "root",
394
+ _ => self.tree.ty(self.context(context).exp),
395
+ }
396
+ }
397
+
398
+ /// `name`: the node's name.
399
+ pub fn name(&self, context: ContextId) -> Name {
400
+ self.tree.name(self.context(context).exp)
401
+ }
402
+
403
+ /// `number_of_statements`.
404
+ pub fn number_of_statements(&self, context: ContextId) -> i64 {
405
+ self.context(self.statement_counter_owner(context)).statement_count
406
+ }
407
+
408
+ /// `full_name`: the node's full name within its parent's; `''` for the
409
+ /// root, and a refinement's is the name of the refined class.
410
+ pub fn full_name(&self, context: ContextId) -> Result<String, ContextError> {
411
+ let data = self.context(context);
412
+ match data.kind {
413
+ ContextKind::Root => Ok(String::new()),
414
+ ContextKind::Refinement => {
415
+ let call = self.tree.child_node(data.exp, 0).expect("a block has a call");
416
+ match self.tree.send_args(call).first() {
417
+ Some(Child::Node(refined)) => Ok(self.tree.name(*refined).to_s().to_string()),
418
+ _ => Err(ContextError::Unexpected("undefined method 'name' for nil".to_string())),
419
+ }
420
+ }
421
+ _ => {
422
+ let outer = match data.parent {
423
+ Some(parent) => self.full_name(parent)?,
424
+ None => String::new(),
425
+ };
426
+ Ok(self.tree.full_name(data.exp, &outer)?)
427
+ }
428
+ }
429
+ }
430
+
431
+ /// `matches?(candidates)`: whether the full name matches any candidate,
432
+ /// strings literally and anything else as a pattern.
433
+ pub fn matches(&self, context: ContextId, candidates: &Value) -> Result<bool, ContextError> {
434
+ let Value::Array(candidates) = candidates else {
435
+ return Err(ContextError::Unexpected(format!("undefined method 'any?' for an instance of {}", candidates.class_name())));
436
+ };
437
+ let full_name = self.full_name(context)?;
438
+ for candidate in candidates {
439
+ let pattern = match candidate {
440
+ Value::Str(text) => RubyRegexp::quoted(text),
441
+ Value::Regexp(regexp) => regexp.clone(),
442
+ other => RubyRegexp::new(&other.to_s(), "").map_err(ContextError::Unexpected)?,
443
+ };
444
+ if pattern.is_match(full_name.as_bytes()) {
445
+ return Ok(true);
446
+ }
447
+ }
448
+ Ok(false)
449
+ }
450
+
451
+ /// `config_for(detector_class)`: the parent's configuration for the
452
+ /// detector merged with this context's comment directive for it.
453
+ pub fn config_for(&self, context: ContextId, smell_type: &str) -> Result<DetectorOptions, ContextError> {
454
+ let mut config = match self.context(context).parent {
455
+ Some(parent) => self.config_for(parent, smell_type)?,
456
+ None => DetectorOptions::new(),
457
+ };
458
+ self.load_comment_config(context)?;
459
+ let comment_config = self.context(context).comment_config.borrow();
460
+ if let Some(options) = comment_config.as_ref().and_then(|config| config.get(smell_type)) {
461
+ for (key, value) in options {
462
+ config.insert(key.clone(), value.clone());
463
+ }
464
+ }
465
+ Ok(config)
466
+ }
467
+
468
+ /// Reads `configuration_via_code_commment` the first time it is needed.
469
+ fn load_comment_config(&self, context: ContextId) -> Result<(), ContextError> {
470
+ let data = self.context(context);
471
+ if data.comment_config.borrow().is_some() {
472
+ return Ok(());
473
+ }
474
+ let comment = self.full_comment(context);
475
+ let config = if comment.is_empty() {
476
+ IndexMap::new()
477
+ } else {
478
+ let line = self.tree.line(data.exp).expect("a commented node has a location");
479
+ code_comment::config(&comment, &CommentLocation { source: self.origin, line })?
480
+ };
481
+ *data.comment_config.borrow_mut() = Some(config);
482
+ Ok(())
483
+ }
484
+
485
+ /// `full_comment`: the node's comments; a method without its own uses
486
+ /// those of the node containing it, and an attribute those of its
487
+ /// `attr_writer` call.
488
+ fn full_comment(&self, context: ContextId) -> String {
489
+ let data = self.context(context);
490
+ match data.kind {
491
+ ContextKind::Method | ContextKind::SingletonMethod => {
492
+ let own = self.tree.full_comment(data.exp);
493
+ match data.parent_exp {
494
+ Some(parent_exp) if own.is_empty() => self.tree.full_comment(parent_exp),
495
+ _ => own,
496
+ }
497
+ }
498
+ ContextKind::Attribute | ContextKind::SingletonAttribute => {
499
+ self.tree.full_comment(data.send_expression.expect("an attribute has a send expression"))
500
+ }
501
+ _ => self.tree.full_comment(data.exp),
502
+ }
503
+ }
504
+
505
+ /// `local_nodes(type, ignored)`: the nodes of the types under the
506
+ /// context's node, not descending into the ignored types, classes or
507
+ /// modules.
508
+ pub fn local_nodes(&self, context: ContextId, types: &[&str], ignored: &[&str]) -> Vec<NodeId> {
509
+ let ignored = crate::node::union(ignored, &["class", "module"]);
510
+ self.tree.each_node(self.context(context).exp, types, &ignored)
511
+ }
512
+
513
+ /// `singleton_method?`.
514
+ pub fn is_singleton_method(&self, context: ContextId) -> bool {
515
+ self.context(context).kind == ContextKind::SingletonMethod
516
+ }
517
+
518
+ /// `instance_method?`.
519
+ pub fn is_instance_method_context(&self, context: ContextId) -> bool {
520
+ self.is_instance_method(self.context(context).kind)
521
+ }
522
+
523
+ // ------------------------------------------------------------------
524
+ // MethodContext
525
+
526
+ /// `references_self?`.
527
+ pub fn references_self(&self, context: ContextId) -> bool {
528
+ self.tree.depends_on_instance(self.context(context).exp)
529
+ }
530
+
531
+ /// `uses_param?(param)`: a local variable read or assigned has the
532
+ /// parameter's name.
533
+ pub fn uses_param(&self, context: ContextId, param: NodeId) -> bool {
534
+ let name = self.tree.name(param);
535
+ self.local_nodes(context, &["lvar", "lvasgn"], &[]).into_iter().any(|node| self.tree.name(node) == name)
536
+ }
537
+
538
+ /// `unused_params`: the arguments (not `&block`) that are not anonymous
539
+ /// splats, not marked unused with `_`, and not used.
540
+ pub fn unused_params(&self, context: ContextId) -> Result<Vec<NodeId>, ContextError> {
541
+ let arguments = self.tree.arguments(self.context(context).exp)?;
542
+ Ok(arguments
543
+ .into_iter()
544
+ .filter(|param| {
545
+ !(self.tree.is_anonymous_splat(*param) || self.tree.is_marked_unused(*param) || self.uses_param(context, *param))
546
+ })
547
+ .collect())
548
+ }
549
+
550
+ /// `uses_super_with_implicit_arguments?`: the body calls `super`
551
+ /// without arguments.
552
+ pub fn uses_super_with_implicit_arguments(&self, context: ContextId) -> bool {
553
+ let body = self.tree.method_body(self.context(context).exp);
554
+ body.is_some_and(|body| !self.tree.each_node(body, &["zsuper"], &[]).is_empty())
555
+ }
556
+
557
+ /// `default_assignments`: each optional parameter's name and default.
558
+ pub fn default_assignments(&self, context: ContextId) -> Result<Vec<(Name, NodeId)>, ContextError> {
559
+ let parameters = self.tree.parameters(self.context(context).exp)?;
560
+ Ok(parameters
561
+ .into_iter()
562
+ .filter(|parameter| self.tree.is_optional_argument(*parameter))
563
+ .map(|parameter| {
564
+ let value = self.tree.child_node(parameter, 1).expect("an optional argument has a default");
565
+ (self.tree.name(parameter), value)
566
+ })
567
+ .collect())
568
+ }
569
+
570
+ /// `module_function?`: never for singleton methods.
571
+ pub fn is_module_function(&self, context: ContextId) -> bool {
572
+ let data = self.context(context);
573
+ data.kind == ContextKind::Method && data.visibility == Visibility::ModuleFunction
574
+ }
575
+
576
+ /// `non_public_visibility?`.
577
+ pub fn has_non_public_visibility(&self, context: ContextId) -> bool {
578
+ self.context(context).visibility != Visibility::Public
579
+ }
580
+
581
+ // ------------------------------------------------------------------
582
+ // ModuleContext
583
+
584
+ /// `node_instance_methods`: the `def` nodes in the module, outside
585
+ /// nested modules and classes.
586
+ pub fn node_instance_methods(&self, context: ContextId) -> Vec<NodeId> {
587
+ self.local_nodes(context, &["def"], &[])
588
+ }
589
+
590
+ /// `defined_instance_methods(visibility:)`: the instance method and
591
+ /// attribute children, of any visibility when `None`.
592
+ pub fn defined_instance_methods(&self, context: ContextId, visibility: Option<Visibility>) -> Vec<ContextId> {
593
+ let children = self.children_where(context, |kind| self.is_instance_method(kind));
594
+ match visibility {
595
+ None => children,
596
+ Some(visibility) => {
597
+ children.into_iter().filter(|child| self.context(*child).visibility == visibility).collect()
598
+ }
599
+ }
600
+ }
601
+
602
+ /// `instance_method_calls`: the calls made in instance methods.
603
+ pub fn instance_method_calls(&self, context: ContextId) -> Vec<ContextId> {
604
+ self.defined_instance_methods(context, None)
605
+ .into_iter()
606
+ .flat_map(|method| self.children_where(method, |kind| kind == ContextKind::Send))
607
+ .collect()
608
+ }
609
+
610
+ /// `instance_method_names_via_to_call`: the symbols in calls to
611
+ /// `method` (`method(:name)`).
612
+ pub fn instance_method_names_via_to_call(&self, context: ContextId) -> Vec<Name> {
613
+ self.instance_method_calls(context)
614
+ .into_iter()
615
+ .filter(|call| self.name(*call).is_symbol("method"))
616
+ .flat_map(|call| self.local_nodes(call, &["sym"], &[]))
617
+ .map(|sym| self.tree.name(sym))
618
+ .collect()
619
+ }
620
+
621
+ /// `descriptively_commented?`: the comment before the module has at
622
+ /// least two words. Reek reads its directives again, without a line,
623
+ /// so a bad directive fails formatting its error message.
624
+ pub fn is_descriptively_commented(&self, context: ContextId) -> Result<bool, ContextError> {
625
+ let comment = self.tree.leading_comment(self.context(context).exp);
626
+ if code_comment::config(&comment, &CommentLocation { source: "", line: 0 }).is_err() {
627
+ return Err(ContextError::Unexpected("can't convert nil into Integer".to_string()));
628
+ }
629
+ Ok(code_comment::is_descriptive(&comment))
630
+ }
631
+
632
+ /// `namespace_module?`: a module or class whose body only defines
633
+ /// constants, classes and modules; never a constant assignment.
634
+ pub fn is_namespace_module(&self, context: ContextId) -> bool {
635
+ let exp = self.context(context).exp;
636
+ if self.tree.ty(exp) == "casgn" {
637
+ return false;
638
+ }
639
+ let children = self.tree.direct_children(exp);
640
+ !children.is_empty() && children.iter().all(|child| matches!(self.tree.ty(*child), "casgn" | "class" | "module"))
641
+ }
642
+ }
643
+
644
+ /// `names.include?(child.name)`: a name equals a Symbol or String child
645
+ /// with the same text.
646
+ fn name_equals(name: &Name, candidate: &Child) -> bool {
647
+ match (name, candidate) {
648
+ (Name::Symbol(name), Child::Sym(bytes)) | (Name::String(name), Child::Str(bytes)) => name.as_bytes() == &**bytes,
649
+ (Name::Nil, Child::Nil) => true,
650
+ _ => false,
651
+ }
652
+ }
653
+
654
+ /// `ContextBuilder`.
655
+ struct ContextBuilder<'tree> {
656
+ contexts: ContextTree<'tree>,
657
+ current_context: ContextId,
658
+ }
659
+
660
+ impl ContextBuilder<'_> {
661
+ /// `build(exp, parent_exp)`: the node's `process_<type>`, or `process`.
662
+ fn build(&mut self, exp: NodeId, parent_exp: Option<NodeId>) -> Result<(), ContextError> {
663
+ match self.contexts.tree.ty(exp) {
664
+ "module" | "class" => self.process_module(exp),
665
+ "sclass" => self.process_sclass(exp),
666
+ "casgn" => self.process_casgn(exp),
667
+ "def" => self.process_def(exp, parent_exp),
668
+ "defs" => self.process_defs(exp, parent_exp),
669
+ "send" => self.process_send(exp),
670
+ "op_asgn" => self.process_op_asgn(exp),
671
+ "ivar" | "ivasgn" | "super" => self.process_ivar(exp),
672
+ "self" | "zsuper" => {
673
+ self.contexts.record_use_of_self(self.current_context);
674
+ Ok(())
675
+ }
676
+ "block" => self.process_block(exp),
677
+ "begin" | "kwbegin" => self.process_begin(exp),
678
+ "if" => self.process_if(exp),
679
+ "while" | "until" => self.process_while(exp),
680
+ "for" => self.process_for(exp),
681
+ "rescue" => self.process_rescue(exp),
682
+ "resbody" => self.process_resbody(exp),
683
+ "case" => self.process_case(exp),
684
+ "when" => self.process_when(exp),
685
+ _ => self.process(exp),
686
+ }
687
+ }
688
+
689
+ /// `process(exp)`: builds each node child.
690
+ fn process(&mut self, exp: NodeId) -> Result<(), ContextError> {
691
+ let tree = self.contexts.tree;
692
+ for child in tree.child_nodes(exp) {
693
+ self.build(child, Some(exp))?;
694
+ }
695
+ Ok(())
696
+ }
697
+
698
+ fn process_module(&mut self, exp: NodeId) -> Result<(), ContextError> {
699
+ self.inside_new_context(ContextKind::Module, exp, None, |builder| builder.process(exp))
700
+ }
701
+
702
+ fn process_sclass(&mut self, exp: NodeId) -> Result<(), ContextError> {
703
+ self.inside_new_context(ContextKind::Ghost, exp, None, |builder| builder.process(exp))
704
+ }
705
+
706
+ fn process_casgn(&mut self, exp: NodeId) -> Result<(), ContextError> {
707
+ if self.contexts.tree.defines_module(exp) {
708
+ self.process_module(exp)
709
+ } else {
710
+ self.process(exp)
711
+ }
712
+ }
713
+
714
+ /// A `def` is a singleton method in `class << self`, otherwise a method.
715
+ fn process_def(&mut self, exp: NodeId, parent_exp: Option<NodeId>) -> Result<(), ContextError> {
716
+ let kind = match self.contexts.context(self.current_context).kind {
717
+ ContextKind::Ghost | ContextKind::SingletonMethod => ContextKind::SingletonMethod,
718
+ _ => ContextKind::Method,
719
+ };
720
+ self.process_method(kind, exp, parent_exp)
721
+ }
722
+
723
+ fn process_defs(&mut self, exp: NodeId, parent_exp: Option<NodeId>) -> Result<(), ContextError> {
724
+ self.process_method(ContextKind::SingletonMethod, exp, parent_exp)
725
+ }
726
+
727
+ fn process_method(&mut self, kind: ContextKind, exp: NodeId, parent_exp: Option<NodeId>) -> Result<(), ContextError> {
728
+ self.inside_new_context(kind, exp, parent_exp, |builder| {
729
+ let body = builder.contexts.tree.method_body(exp);
730
+ builder.increase_statement_count_by(usize::from(body.is_some()));
731
+ builder.process(exp)
732
+ })
733
+ }
734
+
735
+ fn process_send(&mut self, exp: NodeId) -> Result<(), ContextError> {
736
+ self.process(exp)?;
737
+ let kind = self.contexts.context(self.current_context).kind;
738
+ if kind.is_module_context() {
739
+ self.handle_send_for_modules(exp)
740
+ } else if kind.is_method_context() {
741
+ self.handle_send_for_methods(exp)
742
+ } else {
743
+ Ok(())
744
+ }
745
+ }
746
+
747
+ fn process_op_asgn(&mut self, exp: NodeId) -> Result<(), ContextError> {
748
+ self.contexts.record_call_to(self.current_context, exp);
749
+ self.process(exp)
750
+ }
751
+
752
+ /// `process_ivar`, `process_ivasgn` and `process_super`.
753
+ fn process_ivar(&mut self, exp: NodeId) -> Result<(), ContextError> {
754
+ self.contexts.record_use_of_self(self.current_context);
755
+ self.process(exp)
756
+ }
757
+
758
+ fn process_block(&mut self, exp: NodeId) -> Result<(), ContextError> {
759
+ let tree = self.contexts.tree;
760
+ self.increase_statement_count_by(usize::from(tree.child_node(exp, 2).is_some()));
761
+ let call = tree.child_node(exp, 0).expect("a block has a call");
762
+ if tree.name(call).is_symbol("refine") {
763
+ self.inside_new_context(ContextKind::Refinement, exp, None, |builder| builder.process(exp))
764
+ } else {
765
+ self.process(exp)
766
+ }
767
+ }
768
+
769
+ /// `process_begin` and `process_kwbegin`: each statement counts, the
770
+ /// `begin` itself does not.
771
+ fn process_begin(&mut self, exp: NodeId) -> Result<(), ContextError> {
772
+ self.increase_statement_count_by(self.contexts.tree.children(exp).len());
773
+ self.decrease_statement_count();
774
+ self.process(exp)
775
+ }
776
+
777
+ fn process_if(&mut self, exp: NodeId) -> Result<(), ContextError> {
778
+ let tree = self.contexts.tree;
779
+ self.increase_statement_count_by(usize::from(tree.child_node(exp, 1).is_some()));
780
+ self.increase_statement_count_by(usize::from(tree.child_node(exp, 2).is_some()));
781
+ self.decrease_statement_count();
782
+ self.process(exp)
783
+ }
784
+
785
+ /// `process_while` and `process_until`.
786
+ fn process_while(&mut self, exp: NodeId) -> Result<(), ContextError> {
787
+ self.increase_statement_count_by(usize::from(self.contexts.tree.child_node(exp, 1).is_some()));
788
+ self.decrease_statement_count();
789
+ self.process(exp)
790
+ }
791
+
792
+ fn process_for(&mut self, exp: NodeId) -> Result<(), ContextError> {
793
+ self.increase_statement_count_by(usize::from(self.contexts.tree.child_node(exp, 2).is_some()));
794
+ self.decrease_statement_count();
795
+ self.process(exp)
796
+ }
797
+
798
+ fn process_rescue(&mut self, exp: NodeId) -> Result<(), ContextError> {
799
+ self.increase_statement_count_by(usize::from(self.contexts.tree.child_node(exp, 0).is_some()));
800
+ self.decrease_statement_count();
801
+ self.process(exp)
802
+ }
803
+
804
+ /// The exception variable and the body each count.
805
+ fn process_resbody(&mut self, exp: NodeId) -> Result<(), ContextError> {
806
+ let present = self.contexts.tree.children(exp).iter().skip(1).filter(|child| !child.is_nil()).count();
807
+ self.increase_statement_count_by(present);
808
+ self.process(exp)
809
+ }
810
+
811
+ fn process_case(&mut self, exp: NodeId) -> Result<(), ContextError> {
812
+ let else_body = self.contexts.tree.children(exp).last().and_then(Child::node);
813
+ self.increase_statement_count_by(usize::from(else_body.is_some()));
814
+ self.decrease_statement_count();
815
+ self.process(exp)
816
+ }
817
+
818
+ fn process_when(&mut self, exp: NodeId) -> Result<(), ContextError> {
819
+ let body = self.contexts.tree.children(exp).last().and_then(Child::node);
820
+ self.increase_statement_count_by(usize::from(body.is_some()));
821
+ self.process(exp)
822
+ }
823
+
824
+ fn increase_statement_count_by(&mut self, count: usize) {
825
+ let owner = self.contexts.statement_counter_owner(self.current_context);
826
+ self.contexts.contexts[owner.0].statement_count += count as i64;
827
+ }
828
+
829
+ fn decrease_statement_count(&mut self) {
830
+ let owner = self.contexts.statement_counter_owner(self.current_context);
831
+ self.contexts.contexts[owner.0].statement_count -= 1;
832
+ }
833
+
834
+ fn inside_new_context(
835
+ &mut self,
836
+ kind: ContextKind,
837
+ exp: NodeId,
838
+ parent_exp: Option<NodeId>,
839
+ body: impl FnOnce(&mut Self) -> Result<(), ContextError>,
840
+ ) -> Result<(), ContextError> {
841
+ let new_context = self.append_new_context(kind, exp)?;
842
+ self.contexts.contexts[new_context.0].parent_exp = parent_exp;
843
+ let original = std::mem::replace(&mut self.current_context, new_context);
844
+ body(self)?;
845
+ self.current_context = original;
846
+ Ok(())
847
+ }
848
+
849
+ fn append_new_context(&mut self, kind: ContextKind, exp: NodeId) -> Result<ContextId, ContextError> {
850
+ let new_context = self.contexts.new_context(kind, exp);
851
+ self.contexts.register_with_parent(new_context, self.current_context)?;
852
+ Ok(new_context)
853
+ }
854
+
855
+ fn handle_send_for_modules(&mut self, exp: NodeId) -> Result<(), ContextError> {
856
+ let tree = self.contexts.tree;
857
+ let arg_names: Vec<Child> = tree
858
+ .send_args(exp)
859
+ .iter()
860
+ .map(|arg| match arg.node().and_then(|arg| tree.children(arg).first()) {
861
+ Some(first) => first.clone(),
862
+ None => Child::Nil,
863
+ })
864
+ .collect();
865
+ self.contexts.track_visibility(self.current_context, &tree.name(exp), &arg_names)?;
866
+ self.register_attributes(exp)
867
+ }
868
+
869
+ fn handle_send_for_methods(&mut self, exp: NodeId) -> Result<(), ContextError> {
870
+ self.append_new_context(ContextKind::Send, exp)?;
871
+ self.contexts.record_call_to(self.current_context, exp);
872
+ Ok(())
873
+ }
874
+
875
+ /// One attribute context per argument of an attribute writer.
876
+ fn register_attributes(&mut self, exp: NodeId) -> Result<(), ContextError> {
877
+ let tree = self.contexts.tree;
878
+ if !tree.is_attribute_writer(exp) {
879
+ return Ok(());
880
+ }
881
+ let kind = match self.contexts.context(self.current_context).kind {
882
+ ContextKind::Ghost => ContextKind::SingletonAttribute,
883
+ _ => ContextKind::Attribute,
884
+ };
885
+ for arg in tree.send_args(exp).iter().filter_map(Child::node) {
886
+ let attribute = self.append_new_context(kind, arg)?;
887
+ self.contexts.contexts[attribute.0].send_expression = Some(exp);
888
+ }
889
+ Ok(())
890
+ }
891
+ }