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,449 @@
|
|
|
1
|
+
//! The `parser` gem's syntax tree, as Reek 6.5.0 builds and dresses it.
|
|
2
|
+
//!
|
|
3
|
+
//! Nodes live in an arena ([`Tree`]) and are referred to by [`NodeId`]. Each
|
|
4
|
+
//! node has a type (`:send`, `:def`, ...), children (nodes or literal values)
|
|
5
|
+
//! and a source map reduced to what Reek reads: the expression range, the
|
|
6
|
+
//! `begin`/`end` ranges the builder inspects, and whether the map is a
|
|
7
|
+
//! `Source::Map::Heredoc`. Ranges are byte offsets into the CRLF-normalized
|
|
8
|
+
//! source; the `parser` gem counts characters, which orders and slices the
|
|
9
|
+
//! same way.
|
|
10
|
+
//!
|
|
11
|
+
//! Node equality is `AST::Node#eql?`: same type and `eql?` children, without
|
|
12
|
+
//! locations. Reek relies on it in three places: `Comment.associate` keys
|
|
13
|
+
//! comments by node, `DuplicateMethodCall` counts calls by node, and
|
|
14
|
+
//! `RepeatedConditional` counts conditions by node.
|
|
15
|
+
|
|
16
|
+
use std::hash::{Hash, Hasher};
|
|
17
|
+
|
|
18
|
+
/// A node in a [`Tree`].
|
|
19
|
+
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
|
20
|
+
pub struct NodeId(pub u32);
|
|
21
|
+
|
|
22
|
+
/// `Parser::Source::Range`: byte offsets `start..end`.
|
|
23
|
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
24
|
+
pub struct Range {
|
|
25
|
+
pub start: u32,
|
|
26
|
+
pub end: u32,
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
impl Range {
|
|
30
|
+
pub fn new(start: u32, end: u32) -> Self {
|
|
31
|
+
Range { start, end }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/// `Range#join`: from the smaller start to the larger end.
|
|
35
|
+
pub fn join(self, other: Range) -> Range {
|
|
36
|
+
Range { start: self.start.min(other.start), end: self.end.max(other.end) }
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/// The parts of a `Parser::Source::Map` that Reek or the builder read.
|
|
41
|
+
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
|
42
|
+
pub struct Loc {
|
|
43
|
+
pub expression: Option<Range>,
|
|
44
|
+
/// `loc.begin` of a collection map (opening token).
|
|
45
|
+
pub begin: Option<Range>,
|
|
46
|
+
/// `loc.end` of a collection map (closing token).
|
|
47
|
+
pub end: Option<Range>,
|
|
48
|
+
/// The map is a `Source::Map::Heredoc`.
|
|
49
|
+
pub heredoc: bool,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
impl Loc {
|
|
53
|
+
pub fn expr(expression: Option<Range>) -> Self {
|
|
54
|
+
Loc { expression, ..Loc::default() }
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/// A child of a node: another node or a literal value.
|
|
59
|
+
#[derive(Clone, Debug)]
|
|
60
|
+
pub enum Child {
|
|
61
|
+
Node(NodeId),
|
|
62
|
+
Nil,
|
|
63
|
+
/// A Symbol, as the bytes of its name.
|
|
64
|
+
Sym(Box<[u8]>),
|
|
65
|
+
/// A String's bytes.
|
|
66
|
+
Str(Box<[u8]>),
|
|
67
|
+
/// An Integer in decimal (`Integer#to_s`).
|
|
68
|
+
Int(Box<str>),
|
|
69
|
+
Float(f64),
|
|
70
|
+
/// A Rational, as `Rational#to_s`.
|
|
71
|
+
Rational(Box<str>),
|
|
72
|
+
/// A Complex, as `Complex#to_s`.
|
|
73
|
+
Complex(Box<str>),
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
impl Child {
|
|
77
|
+
pub fn node(&self) -> Option<NodeId> {
|
|
78
|
+
match self {
|
|
79
|
+
Child::Node(id) => Some(*id),
|
|
80
|
+
_ => None,
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
pub fn sym(&self) -> Option<&[u8]> {
|
|
85
|
+
match self {
|
|
86
|
+
Child::Sym(name) => Some(name),
|
|
87
|
+
_ => None,
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
pub fn is_nil(&self) -> bool {
|
|
92
|
+
matches!(self, Child::Nil)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
pub fn sym_name(name: &[u8]) -> Child {
|
|
96
|
+
Child::Sym(name.into())
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/// One node's data.
|
|
101
|
+
#[derive(Clone, Debug)]
|
|
102
|
+
pub struct NodeData {
|
|
103
|
+
pub ty: &'static str,
|
|
104
|
+
pub children: Vec<Child>,
|
|
105
|
+
/// `None` for nodes built without a source map (the inner
|
|
106
|
+
/// `(const nil :Encoding)` of `__ENCODING__`, Reek's `(empty)` root).
|
|
107
|
+
pub loc: Option<Loc>,
|
|
108
|
+
/// Indexes into [`Tree::comments`] of the comments Reek attached.
|
|
109
|
+
pub comments: Vec<usize>,
|
|
110
|
+
/// For a `str` in a `<<~` heredoc: its string before dedenting. The
|
|
111
|
+
/// parser gem dedents heredoc strings in place after their nodes have
|
|
112
|
+
/// computed their hashes, so `Hash` lookups (comment association) hash
|
|
113
|
+
/// this value while `eql?` compares the dedented one.
|
|
114
|
+
pub hashed_value: Option<Box<[u8]>>,
|
|
115
|
+
hash: u64,
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/// A source comment (`Parser::Source::Comment`).
|
|
119
|
+
#[derive(Clone, Debug)]
|
|
120
|
+
pub struct Comment {
|
|
121
|
+
pub range: Range,
|
|
122
|
+
/// The comment's source text, `#` included.
|
|
123
|
+
pub text: Vec<u8>,
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/// A parsed file: the source, its nodes, its comments and the root node.
|
|
127
|
+
#[derive(Debug, Default)]
|
|
128
|
+
pub struct Tree {
|
|
129
|
+
pub source: Vec<u8>,
|
|
130
|
+
pub nodes: Vec<NodeData>,
|
|
131
|
+
pub comments: Vec<Comment>,
|
|
132
|
+
/// `None` when the file has no code (Reek dresses it as `(empty)`).
|
|
133
|
+
pub root: Option<NodeId>,
|
|
134
|
+
/// The parser's buffer is `ASCII-8BIT`, so it counts positions in bytes
|
|
135
|
+
/// rather than characters.
|
|
136
|
+
pub binary: bool,
|
|
137
|
+
line_starts: Vec<u32>,
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/// The `type` of the `(empty)` node Reek uses for a file without code.
|
|
141
|
+
pub const EMPTY: &str = "empty";
|
|
142
|
+
|
|
143
|
+
impl Tree {
|
|
144
|
+
pub fn new(source: Vec<u8>) -> Self {
|
|
145
|
+
let mut line_starts = vec![0];
|
|
146
|
+
for (index, byte) in source.iter().enumerate() {
|
|
147
|
+
if *byte == b'\n' {
|
|
148
|
+
line_starts.push(index as u32 + 1);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
Tree { source, nodes: Vec::new(), comments: Vec::new(), root: None, binary: false, line_starts }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// ------------------------------------------------------------------
|
|
155
|
+
// Building
|
|
156
|
+
|
|
157
|
+
/// `AST::Node.new(type, children, location: loc)`.
|
|
158
|
+
pub fn add(&mut self, ty: &'static str, children: Vec<Child>, loc: Option<Loc>) -> NodeId {
|
|
159
|
+
let hash = self.structural_hash(ty, &children);
|
|
160
|
+
let id = NodeId(self.nodes.len() as u32);
|
|
161
|
+
self.nodes.push(NodeData { ty, children, loc, comments: Vec::new(), hashed_value: None, hash });
|
|
162
|
+
id
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
fn structural_hash(&self, ty: &str, children: &[Child]) -> u64 {
|
|
166
|
+
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
|
167
|
+
ty.hash(&mut hasher);
|
|
168
|
+
for child in children {
|
|
169
|
+
self.child_hash(child).hash(&mut hasher);
|
|
170
|
+
}
|
|
171
|
+
hasher.finish()
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/// One child's contribution to its node's structural hash.
|
|
175
|
+
pub fn child_hash(&self, child: &Child) -> u64 {
|
|
176
|
+
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
|
177
|
+
match child {
|
|
178
|
+
Child::Node(id) => {
|
|
179
|
+
0u8.hash(&mut hasher);
|
|
180
|
+
self.nodes[id.0 as usize].hash.hash(&mut hasher);
|
|
181
|
+
}
|
|
182
|
+
Child::Nil => 1u8.hash(&mut hasher),
|
|
183
|
+
Child::Sym(name) => {
|
|
184
|
+
2u8.hash(&mut hasher);
|
|
185
|
+
name.hash(&mut hasher);
|
|
186
|
+
}
|
|
187
|
+
Child::Str(bytes) => {
|
|
188
|
+
3u8.hash(&mut hasher);
|
|
189
|
+
bytes.hash(&mut hasher);
|
|
190
|
+
}
|
|
191
|
+
Child::Int(digits) => {
|
|
192
|
+
4u8.hash(&mut hasher);
|
|
193
|
+
digits.hash(&mut hasher);
|
|
194
|
+
}
|
|
195
|
+
// 0.0 and -0.0 are eql? in Ruby and hash alike.
|
|
196
|
+
Child::Float(value) => {
|
|
197
|
+
5u8.hash(&mut hasher);
|
|
198
|
+
let normalized = if *value == 0.0 { 0.0f64 } else { *value };
|
|
199
|
+
normalized.to_bits().hash(&mut hasher);
|
|
200
|
+
}
|
|
201
|
+
Child::Rational(text) => {
|
|
202
|
+
6u8.hash(&mut hasher);
|
|
203
|
+
text.hash(&mut hasher);
|
|
204
|
+
}
|
|
205
|
+
Child::Complex(text) => {
|
|
206
|
+
7u8.hash(&mut hasher);
|
|
207
|
+
text.hash(&mut hasher);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
hasher.finish()
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/// `node.updated(type, children, location: loc)`: a new node; `None`
|
|
214
|
+
/// keeps the old value.
|
|
215
|
+
pub fn updated(
|
|
216
|
+
&mut self,
|
|
217
|
+
id: NodeId,
|
|
218
|
+
ty: Option<&'static str>,
|
|
219
|
+
children: Option<Vec<Child>>,
|
|
220
|
+
loc: Option<Option<Loc>>,
|
|
221
|
+
) -> NodeId {
|
|
222
|
+
let node = &self.nodes[id.0 as usize];
|
|
223
|
+
let ty = ty.unwrap_or(node.ty);
|
|
224
|
+
let children = children.unwrap_or_else(|| node.children.clone());
|
|
225
|
+
let loc = loc.unwrap_or(node.loc);
|
|
226
|
+
self.add(ty, children, loc)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// ------------------------------------------------------------------
|
|
230
|
+
// Reading
|
|
231
|
+
|
|
232
|
+
pub fn node(&self, id: NodeId) -> &NodeData {
|
|
233
|
+
&self.nodes[id.0 as usize]
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
pub fn ty(&self, id: NodeId) -> &'static str {
|
|
237
|
+
self.nodes[id.0 as usize].ty
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
pub fn children(&self, id: NodeId) -> &[Child] {
|
|
241
|
+
&self.nodes[id.0 as usize].children
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/// `children[index]` when it is a node.
|
|
245
|
+
pub fn child_node(&self, id: NodeId, index: usize) -> Option<NodeId> {
|
|
246
|
+
self.children(id).get(index).and_then(Child::node)
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/// The node children, in order (`each_sexp`).
|
|
250
|
+
pub fn child_nodes(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ {
|
|
251
|
+
self.children(id).iter().filter_map(Child::node)
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
pub fn loc(&self, id: NodeId) -> Option<&Loc> {
|
|
255
|
+
self.nodes[id.0 as usize].loc.as_ref()
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
pub fn expression(&self, id: NodeId) -> Option<Range> {
|
|
259
|
+
self.loc(id).and_then(|loc| loc.expression)
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/// The 1-based line containing byte `offset` (`Buffer#line_for_position`).
|
|
263
|
+
pub fn line_for(&self, offset: u32) -> usize {
|
|
264
|
+
match self.line_starts.binary_search(&offset) {
|
|
265
|
+
Ok(index) => index + 1,
|
|
266
|
+
Err(index) => index,
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/// `Reek::AST::Node#line`: `loc && loc.line`.
|
|
271
|
+
pub fn line(&self, id: NodeId) -> Option<usize> {
|
|
272
|
+
self.expression(id).map(|range| self.line_for(range.start))
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/// `loc.last_line`.
|
|
276
|
+
pub fn last_line(&self, id: NodeId) -> Option<usize> {
|
|
277
|
+
self.expression(id).map(|range| self.line_for(range.end))
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
pub fn slice(&self, range: Range) -> &[u8] {
|
|
281
|
+
&self.source[range.start as usize..range.end as usize]
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/// `loc.expression.source`.
|
|
285
|
+
pub fn expression_source(&self, id: NodeId) -> Option<&[u8]> {
|
|
286
|
+
self.expression(id).map(|range| self.slice(range))
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/// `AST::Node#eql?`: same type and equal children, ignoring locations.
|
|
290
|
+
pub fn eql(&self, a: NodeId, b: NodeId) -> bool {
|
|
291
|
+
if a == b {
|
|
292
|
+
return true;
|
|
293
|
+
}
|
|
294
|
+
let (left, right) = (self.node(a), self.node(b));
|
|
295
|
+
if left.hash != right.hash || left.ty != right.ty || left.children.len() != right.children.len() {
|
|
296
|
+
return false;
|
|
297
|
+
}
|
|
298
|
+
left.children.iter().zip(&right.children).all(|pair| match pair {
|
|
299
|
+
(Child::Node(x), Child::Node(y)) => self.eql(*x, *y),
|
|
300
|
+
(Child::Nil, Child::Nil) => true,
|
|
301
|
+
(Child::Sym(x), Child::Sym(y)) => x == y,
|
|
302
|
+
(Child::Str(x), Child::Str(y)) => x == y,
|
|
303
|
+
(Child::Int(x), Child::Int(y)) => x == y,
|
|
304
|
+
(Child::Float(x), Child::Float(y)) => x == y,
|
|
305
|
+
(Child::Rational(x), Child::Rational(y)) => x == y,
|
|
306
|
+
(Child::Complex(x), Child::Complex(y)) => x == y,
|
|
307
|
+
_ => false,
|
|
308
|
+
})
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/// The structural hash used with [`Tree::eql`].
|
|
312
|
+
pub fn node_hash(&self, id: NodeId) -> u64 {
|
|
313
|
+
self.node(id).hash
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/// `Reek::AST::Node#each_node(target_types, ignoring)`: a depth-first
|
|
317
|
+
/// search yielding nodes of the target types, not descending into
|
|
318
|
+
/// ignored types (the root is descended into unless it is a yielded
|
|
319
|
+
/// ignored type).
|
|
320
|
+
pub fn each_node(&self, root: NodeId, targets: &[&str], ignoring: &[&str]) -> Vec<NodeId> {
|
|
321
|
+
let mut found = Vec::new();
|
|
322
|
+
let ty = self.ty(root);
|
|
323
|
+
if targets.contains(&ty) {
|
|
324
|
+
found.push(root);
|
|
325
|
+
if ignoring.contains(&ty) {
|
|
326
|
+
return found;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
for child in self.child_nodes(root) {
|
|
330
|
+
self.look_for_recurse(child, targets, ignoring, &mut found);
|
|
331
|
+
}
|
|
332
|
+
found
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
fn look_for_recurse(&self, id: NodeId, targets: &[&str], ignoring: &[&str], found: &mut Vec<NodeId>) {
|
|
336
|
+
let ty = self.ty(id);
|
|
337
|
+
if targets.contains(&ty) {
|
|
338
|
+
found.push(id);
|
|
339
|
+
}
|
|
340
|
+
if ignoring.contains(&ty) {
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
for child in self.child_nodes(id) {
|
|
344
|
+
self.look_for_recurse(child, targets, ignoring, found);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/// `Reek::AST::Node#format_to_ruby`: the expression's source, stripped
|
|
349
|
+
/// line by line; two lines joined with `; `, more shown as
|
|
350
|
+
/// `first ... last`.
|
|
351
|
+
pub fn format_to_ruby(&self, id: NodeId) -> Vec<u8> {
|
|
352
|
+
let Some(source) = self.expression_source(id) else {
|
|
353
|
+
return self.to_sexp(id).into_bytes();
|
|
354
|
+
};
|
|
355
|
+
// String#split("\n") drops trailing empty fields, then each is stripped.
|
|
356
|
+
let mut fields: Vec<&[u8]> = source.split(|byte| *byte == b'\n').collect();
|
|
357
|
+
while fields.last().is_some_and(|field| field.is_empty()) {
|
|
358
|
+
fields.pop();
|
|
359
|
+
}
|
|
360
|
+
let lines: Vec<&[u8]> = fields.into_iter().map(ruby_strip).collect();
|
|
361
|
+
match lines.len() {
|
|
362
|
+
// `[lines.first, lines.last].join(' ... ')` with no lines.
|
|
363
|
+
0 => b" ... ".to_vec(),
|
|
364
|
+
1 => lines[0].to_vec(),
|
|
365
|
+
2 => [lines[0], b"; ", lines[1]].concat(),
|
|
366
|
+
_ => [lines[0], b" ... ", lines[lines.len() - 1]].concat(),
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/// `Parser::AST::Node#to_s` (`to_sexp`): `(type child...)` with node
|
|
371
|
+
/// children on their own lines, indented two spaces per level, and other
|
|
372
|
+
/// children printed with `inspect`.
|
|
373
|
+
pub fn to_sexp(&self, id: NodeId) -> String {
|
|
374
|
+
self.to_sexp_indented(id, 0)
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
fn to_sexp_indented(&self, id: NodeId, indent: usize) -> String {
|
|
378
|
+
let node = self.node(id);
|
|
379
|
+
let mut out = format!("{}({}", " ".repeat(indent), node.ty.replace('_', "-"));
|
|
380
|
+
for child in &node.children {
|
|
381
|
+
match child {
|
|
382
|
+
Child::Node(child) => {
|
|
383
|
+
out.push('\n');
|
|
384
|
+
out.push_str(&self.to_sexp_indented(*child, indent + 1));
|
|
385
|
+
}
|
|
386
|
+
Child::Nil => out.push_str(" nil"),
|
|
387
|
+
Child::Sym(name) => {
|
|
388
|
+
out.push(' ');
|
|
389
|
+
out.push_str(&crate::ruby_inspect::symbol_inspect(name));
|
|
390
|
+
}
|
|
391
|
+
Child::Str(bytes) => {
|
|
392
|
+
out.push(' ');
|
|
393
|
+
out.push_str(&crate::ruby_inspect::string_inspect(bytes));
|
|
394
|
+
}
|
|
395
|
+
Child::Int(text) => {
|
|
396
|
+
out.push(' ');
|
|
397
|
+
out.push_str(text);
|
|
398
|
+
}
|
|
399
|
+
Child::Float(value) => {
|
|
400
|
+
out.push(' ');
|
|
401
|
+
out.push_str(&crate::ruby_format::float_to_s(*value));
|
|
402
|
+
}
|
|
403
|
+
Child::Rational(text) => {
|
|
404
|
+
out.push(' ');
|
|
405
|
+
out.push_str(&crate::ruby_inspect::rational_inspect(text));
|
|
406
|
+
}
|
|
407
|
+
Child::Complex(text) => {
|
|
408
|
+
out.push(' ');
|
|
409
|
+
out.push_str(&crate::ruby_inspect::complex_inspect(text));
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
out.push(')');
|
|
414
|
+
out
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/// `String#strip` (Ruby 3.3): removes leading and trailing whitespace and
|
|
419
|
+
/// NUL bytes (`\0`, `\t`, `\n`, `\v`, `\f`, `\r`, space).
|
|
420
|
+
pub fn ruby_strip(bytes: &[u8]) -> &[u8] {
|
|
421
|
+
let is_space = |byte: &u8| matches!(byte, 0 | b' ' | b'\t' | b'\n' | 0x0b | 0x0c | b'\r');
|
|
422
|
+
let start = bytes.iter().position(|byte| !is_space(byte)).unwrap_or(bytes.len());
|
|
423
|
+
let rest = &bytes[start..];
|
|
424
|
+
let end = rest.iter().rposition(|byte| !is_space(byte)).map_or(0, |index| index + 1);
|
|
425
|
+
&rest[..end]
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
#[cfg(test)]
|
|
429
|
+
mod tests {
|
|
430
|
+
use super::*;
|
|
431
|
+
|
|
432
|
+
#[test]
|
|
433
|
+
fn strip_matches_ruby() {
|
|
434
|
+
assert_eq!(ruby_strip(b" a b \t\r\n"), b"a b");
|
|
435
|
+
assert_eq!(ruby_strip(b"\0a\0"), b"a");
|
|
436
|
+
assert_eq!(ruby_strip(b" "), b"");
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
#[test]
|
|
440
|
+
fn line_for_offsets() {
|
|
441
|
+
let tree = Tree::new(b"a\nbc\n\nd".to_vec());
|
|
442
|
+
assert_eq!(tree.line_for(0), 1);
|
|
443
|
+
assert_eq!(tree.line_for(1), 1);
|
|
444
|
+
assert_eq!(tree.line_for(2), 2);
|
|
445
|
+
assert_eq!(tree.line_for(5), 3);
|
|
446
|
+
assert_eq!(tree.line_for(6), 4);
|
|
447
|
+
assert_eq!(tree.line_for(7), 4);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
//! `Reek::CodeComment`: `:reek:` directives in the comment before a module,
|
|
2
|
+
//! class or method (`# :reek:TooManyStatements { max_statements: 10 }`),
|
|
3
|
+
//! and whether a comment describes its module (`descriptive?`).
|
|
4
|
+
|
|
5
|
+
use std::sync::LazyLock;
|
|
6
|
+
|
|
7
|
+
use indexmap::IndexMap;
|
|
8
|
+
|
|
9
|
+
use crate::detectors;
|
|
10
|
+
use crate::ruby_regexp::RubyRegexp;
|
|
11
|
+
use crate::yaml::{self, Value};
|
|
12
|
+
|
|
13
|
+
/// `CONFIGURATION_REGEX`: the `:reek:` prefix, the detector name, the
|
|
14
|
+
/// separator, and options in hash style.
|
|
15
|
+
static CONFIGURATION_REGEX: LazyLock<RubyRegexp> =
|
|
16
|
+
LazyLock::new(|| RubyRegexp::new(r":reek:(\w+)(:?\s*)(\{.*?\})?", "").expect("CONFIGURATION_REGEX compiles"));
|
|
17
|
+
|
|
18
|
+
/// `SANITIZE_REGEX`: runs of `#`, newlines and whitespace.
|
|
19
|
+
static SANITIZE_REGEX: LazyLock<RubyRegexp> =
|
|
20
|
+
LazyLock::new(|| RubyRegexp::new(r"(#|\n|\s)+", "").expect("SANITIZE_REGEX compiles"));
|
|
21
|
+
|
|
22
|
+
/// `DISABLE_DETECTOR_CONFIGURATION`: the options of a directive without any.
|
|
23
|
+
const DISABLE_DETECTOR_CONFIGURATION: &str = "{ enabled: false }";
|
|
24
|
+
|
|
25
|
+
/// `MINIMUM_CONTENT_LENGTH`: the words a descriptive comment has.
|
|
26
|
+
const MINIMUM_CONTENT_LENGTH: usize = 2;
|
|
27
|
+
|
|
28
|
+
/// Options for one detector, keyed by option name.
|
|
29
|
+
pub type DetectorOptions = IndexMap<String, Value>;
|
|
30
|
+
|
|
31
|
+
/// Why a comment's directives could not be read.
|
|
32
|
+
#[derive(Clone, Debug, PartialEq)]
|
|
33
|
+
pub enum CodeCommentError {
|
|
34
|
+
/// A `Reek::Errors::BaseError` subclass, which the examiner raises as is.
|
|
35
|
+
Reek { class: &'static str, message: String },
|
|
36
|
+
/// Any other `StandardError` (a YAML class `safe_load` does not permit,
|
|
37
|
+
/// an alias, a key without `to_sym`), which the examiner reports as
|
|
38
|
+
/// `Reek::Errors::IncomprehensibleSourceError`.
|
|
39
|
+
Unexpected(String),
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/// Where a comment is, for error messages.
|
|
43
|
+
pub struct CommentLocation<'a> {
|
|
44
|
+
/// The expression's `source` (the file's origin).
|
|
45
|
+
pub source: &'a str,
|
|
46
|
+
/// The line the expression starts on.
|
|
47
|
+
pub line: usize,
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/// `CodeComment.new(comment:, line:, source:).config`: the options each
|
|
51
|
+
/// `:reek:` directive in the comment gives its detector, later directives
|
|
52
|
+
/// for the same detector replacing earlier ones.
|
|
53
|
+
pub fn config(comment: &str, location: &CommentLocation) -> Result<IndexMap<String, DetectorOptions>, CodeCommentError> {
|
|
54
|
+
let mut config = IndexMap::new();
|
|
55
|
+
for groups in CONFIGURATION_REGEX.scan(comment.as_bytes()) {
|
|
56
|
+
let group = |index: usize| groups[index].map(|(start, end)| &comment[start..end]);
|
|
57
|
+
let detector_name = group(1).expect("the detector name always matches");
|
|
58
|
+
let separator = group(2).expect("the separator always matches");
|
|
59
|
+
let options = group(3);
|
|
60
|
+
escalate_legacy_separator(separator, comment, location)?;
|
|
61
|
+
let parsed_options = parsed_options(detector_name, options, comment, location)?;
|
|
62
|
+
escalate_unknown_configuration_key(detector_name, &parsed_options, comment, location)?;
|
|
63
|
+
config.insert(detector_name.to_string(), parsed_options);
|
|
64
|
+
}
|
|
65
|
+
Ok(config)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
fn escalate_legacy_separator(separator: &str, comment: &str, location: &CommentLocation) -> Result<(), CodeCommentError> {
|
|
69
|
+
if !separator.starts_with(':') {
|
|
70
|
+
return Ok(());
|
|
71
|
+
}
|
|
72
|
+
let message = LEGACY_COMMENT_SEPARATOR_MESSAGE
|
|
73
|
+
.replace("%<source>s", location.source)
|
|
74
|
+
.replace("%<line>d", &location.line.to_string())
|
|
75
|
+
.replace("%<comment>s", comment);
|
|
76
|
+
Err(CodeCommentError::Reek { class: "Reek::Errors::LegacyCommentSeparatorError", message })
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/// `CodeCommentValidator#parsed_options`: the options loaded as YAML.
|
|
80
|
+
fn parsed_options(
|
|
81
|
+
detector_name: &str,
|
|
82
|
+
options: Option<&str>,
|
|
83
|
+
comment: &str,
|
|
84
|
+
location: &CommentLocation,
|
|
85
|
+
) -> Result<DetectorOptions, CodeCommentError> {
|
|
86
|
+
let text = options.unwrap_or(DISABLE_DETECTOR_CONFIGURATION);
|
|
87
|
+
match yaml::load(text, true) {
|
|
88
|
+
Ok(Some(Value::Hash(hash))) => Ok(hash),
|
|
89
|
+
Ok(other) => {
|
|
90
|
+
let class = other.as_ref().map_or("FalseClass", Value::class_name);
|
|
91
|
+
Err(CodeCommentError::Unexpected(format!("undefined method 'keys' for an instance of {class}")))
|
|
92
|
+
}
|
|
93
|
+
Err(yaml::YamlError::Syntax(_)) => Err(CodeCommentError::Reek {
|
|
94
|
+
class: "Reek::Errors::GarbageDetectorConfigurationInCommentError",
|
|
95
|
+
message: detector_message(GARBAGE_DETECTOR_CONFIGURATION_MESSAGE, detector_name, comment, location),
|
|
96
|
+
}),
|
|
97
|
+
Err(error) => Err(CodeCommentError::Unexpected(error.to_string())),
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/// `CodeCommentValidator#escalate_unknown_configuration_key`: every given
|
|
102
|
+
/// key must be one of the detector's `configuration_keys`. An unknown
|
|
103
|
+
/// detector raises first.
|
|
104
|
+
fn escalate_unknown_configuration_key(
|
|
105
|
+
detector_name: &str,
|
|
106
|
+
parsed_options: &DetectorOptions,
|
|
107
|
+
comment: &str,
|
|
108
|
+
location: &CommentLocation,
|
|
109
|
+
) -> Result<(), CodeCommentError> {
|
|
110
|
+
let Some(valid_detector_keys) = detectors::configuration_keys_for(detector_name) else {
|
|
111
|
+
return Err(CodeCommentError::Reek {
|
|
112
|
+
class: "Reek::Errors::BadDetectorInCommentError",
|
|
113
|
+
message: detector_message(BAD_DETECTOR_MESSAGE, detector_name, comment, location),
|
|
114
|
+
});
|
|
115
|
+
};
|
|
116
|
+
let offensive_keys: Vec<String> =
|
|
117
|
+
parsed_options.keys().filter(|key| !valid_detector_keys.contains(key)).map(|key| format!("'{key}'")).collect();
|
|
118
|
+
if offensive_keys.is_empty() {
|
|
119
|
+
return Ok(());
|
|
120
|
+
}
|
|
121
|
+
let message = detector_message(BAD_DETECTOR_CONFIGURATION_KEY_MESSAGE, detector_name, comment, location)
|
|
122
|
+
.replace("%<option>s", &offensive_keys.join(", "));
|
|
123
|
+
Err(CodeCommentError::Reek { class: "Reek::Errors::BadDetectorConfigurationKeyInCommentError", message })
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
fn detector_message(template: &str, detector_name: &str, comment: &str, location: &CommentLocation) -> String {
|
|
127
|
+
// The comment goes in last so that its own text is never substituted.
|
|
128
|
+
template
|
|
129
|
+
.replace("%<detector>s", detector_name)
|
|
130
|
+
.replace("%<source>s", location.source)
|
|
131
|
+
.replace("%<line>d", &location.line.to_string())
|
|
132
|
+
.replace("%<comment>s", comment)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/// `CodeComment#descriptive?`: without its directives, `#` signs and
|
|
136
|
+
/// extra whitespace, the comment has at least two words.
|
|
137
|
+
pub fn is_descriptive(comment: &str) -> bool {
|
|
138
|
+
let without_directives = CONFIGURATION_REGEX.replace_all(comment, "");
|
|
139
|
+
let sanitized = SANITIZE_REGEX.replace_all(&without_directives, " ");
|
|
140
|
+
let sanitized = String::from_utf8_lossy(crate::ast::ruby_strip(sanitized.as_bytes())).into_owned();
|
|
141
|
+
let words = if sanitized.is_empty() { 0 } else { sanitized.split(' ').count() };
|
|
142
|
+
words >= MINIMUM_CONTENT_LENGTH
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const BAD_DETECTOR_MESSAGE: &str = "
|
|
146
|
+
Error: You are trying to configure an unknown smell detector '%<detector>s' in one
|
|
147
|
+
of your source code comments.
|
|
148
|
+
The source is '%<source>s' and the comment belongs to the expression starting in line %<line>d.
|
|
149
|
+
Here's the original comment:
|
|
150
|
+
|
|
151
|
+
%<comment>s
|
|
152
|
+
|
|
153
|
+
Please see the Reek docs for:
|
|
154
|
+
* how to configure Reek via source code comments: https://github.com/troessner/reek/blob/v6.5.0/docs/Smell-Suppression.md
|
|
155
|
+
* what smell detectors are available: https://github.com/troessner/reek/blob/v6.5.0/docs/Code-Smells.md
|
|
156
|
+
Update the offensive comment (or remove it if no longer applicable) and re-run Reek.
|
|
157
|
+
|
|
158
|
+
";
|
|
159
|
+
|
|
160
|
+
const BAD_DETECTOR_CONFIGURATION_KEY_MESSAGE: &str = "
|
|
161
|
+
Error: You are trying to configure the smell detector '%<detector>s'
|
|
162
|
+
in one of your source code comments with the unknown option %<option>s.
|
|
163
|
+
The source is '%<source>s' and the comment belongs to the expression starting in line %<line>d.
|
|
164
|
+
Here's the original comment:
|
|
165
|
+
|
|
166
|
+
%<comment>s
|
|
167
|
+
|
|
168
|
+
Please see the Reek docs for:
|
|
169
|
+
* how to configure Reek via source code comments: https://github.com/troessner/reek/blob/v6.5.0/docs/Smell-Suppression.md
|
|
170
|
+
* what basic options are available: https://github.com/troessner/reek/blob/v6.5.0/docs/Basic-Smell-Options.md
|
|
171
|
+
* what custom options are available by checking the detector specific documentation in /docs
|
|
172
|
+
Update the offensive comment (or remove it if no longer applicable) and re-run Reek.
|
|
173
|
+
|
|
174
|
+
";
|
|
175
|
+
|
|
176
|
+
const GARBAGE_DETECTOR_CONFIGURATION_MESSAGE: &str = "
|
|
177
|
+
Error: You are trying to configure the smell detector '%<detector>s'.
|
|
178
|
+
Unfortunately we cannot parse the configuration you have given.
|
|
179
|
+
The source is '%<source>s' and the comment belongs to the expression starting in line %<line>d.
|
|
180
|
+
Here's the original comment:
|
|
181
|
+
|
|
182
|
+
%<comment>s
|
|
183
|
+
|
|
184
|
+
Please see the Reek docs for:
|
|
185
|
+
* how to configure Reek via source code comments: https://github.com/troessner/reek/blob/v6.5.0/docs/Smell-Suppression.md
|
|
186
|
+
* what smell detectors are available: https://github.com/troessner/reek/blob/v6.5.0/docs/Code-Smells.md
|
|
187
|
+
Update the offensive comment (or remove it if no longer applicable) and re-run Reek.
|
|
188
|
+
|
|
189
|
+
";
|
|
190
|
+
|
|
191
|
+
const LEGACY_COMMENT_SEPARATOR_MESSAGE: &str = " Error: You are using the legacy configuration format (including three
|
|
192
|
+
colons) to configure Reek in one your source code comments.
|
|
193
|
+
|
|
194
|
+
The source is '%<source>s' and the comment belongs to the expression
|
|
195
|
+
starting in line %<line>d.
|
|
196
|
+
|
|
197
|
+
Here's the original comment:
|
|
198
|
+
|
|
199
|
+
%<comment>s
|
|
200
|
+
|
|
201
|
+
Please see the Reek docs for information on how to configure Reek via
|
|
202
|
+
source code comments: https://github.com/troessner/reek/blob/v6.5.0/docs/Smell-Suppression.md
|
|
203
|
+
|
|
204
|
+
Update the offensive comment and re-run Reek.
|
|
205
|
+
|
|
206
|
+
";
|
|
207
|
+
|
|
208
|
+
#[cfg(test)]
|
|
209
|
+
mod tests {
|
|
210
|
+
use super::*;
|
|
211
|
+
|
|
212
|
+
const LOCATION: CommentLocation = CommentLocation { source: "a.rb", line: 3 };
|
|
213
|
+
|
|
214
|
+
#[test]
|
|
215
|
+
fn directives_give_detector_options() {
|
|
216
|
+
let config = config("# :reek:TooManyStatements { max_statements: 10 }\n# :reek:FeatureEnvy", &LOCATION).unwrap();
|
|
217
|
+
assert_eq!(Value::Hash(config["TooManyStatements"].clone()).inspect(), r#"{"max_statements"=>10}"#);
|
|
218
|
+
assert_eq!(Value::Hash(config["FeatureEnvy"].clone()).inspect(), r#"{"enabled"=>false}"#);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
#[test]
|
|
222
|
+
fn errors_match_reek() {
|
|
223
|
+
let error = |comment: &str| match config(comment, &LOCATION) {
|
|
224
|
+
Err(CodeCommentError::Reek { class, .. }) => class.to_string(),
|
|
225
|
+
Err(CodeCommentError::Unexpected(_)) => "Unexpected".to_string(),
|
|
226
|
+
Ok(_) => "ok".to_string(),
|
|
227
|
+
};
|
|
228
|
+
assert_eq!(error("# :reek:FeatureEnvy: { enabled: false }"), "Reek::Errors::LegacyCommentSeparatorError");
|
|
229
|
+
assert_eq!(error("# :reek::FeatureEnvy"), "ok");
|
|
230
|
+
assert_eq!(error("# :reek:Nope { a: [ }"), "Reek::Errors::GarbageDetectorConfigurationInCommentError");
|
|
231
|
+
assert_eq!(error("# :reek:Nope"), "Reek::Errors::BadDetectorInCommentError");
|
|
232
|
+
assert_eq!(error("# :reek:FeatureEnvy { max: 1 }"), "Reek::Errors::BadDetectorConfigurationKeyInCommentError");
|
|
233
|
+
assert_eq!(error("# :reek:FeatureEnvy { enabled: :no }"), "Reek::Errors::GarbageDetectorConfigurationInCommentError");
|
|
234
|
+
assert_eq!(error("# :reek:FeatureEnvy { enabled: 2020-01-01 }"), "Unexpected");
|
|
235
|
+
assert_eq!(error("# :reek:BaseDetector { exclude: [] }"), "ok");
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
#[test]
|
|
239
|
+
fn descriptive_comments_have_two_words() {
|
|
240
|
+
assert!(is_descriptive("# Does things\n"));
|
|
241
|
+
assert!(!is_descriptive("# Things :reek:FeatureEnvy"));
|
|
242
|
+
assert!(!is_descriptive("#\n# \n"));
|
|
243
|
+
assert!(!is_descriptive(""));
|
|
244
|
+
}
|
|
245
|
+
}
|