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,165 @@
1
+ //! `Reek::Examiner`: a file's smells, sorted and without duplicates.
2
+
3
+ use indexmap::IndexMap;
4
+
5
+ use crate::ast::EMPTY;
6
+ use crate::code_comment::DetectorOptions;
7
+ use crate::config::{AppConfiguration, ConfigError};
8
+ use crate::context::{ContextError, ContextTree};
9
+ use crate::detectors::{self, SmellWarning};
10
+ use crate::source::{syntax_tree, SourceError};
11
+
12
+ /// A configuration directive for a file: options by detector name
13
+ /// (`AppConfiguration#directive_for(origin)`).
14
+ pub type Directive = IndexMap<String, DetectorOptions>;
15
+
16
+ /// Why a file could not be examined.
17
+ #[derive(Clone, Debug, PartialEq)]
18
+ pub enum ExamineError {
19
+ /// Reading or parsing the source failed.
20
+ Source(SourceError),
21
+ /// A `Reek::Errors::BaseError` subclass raised while examining (a bad
22
+ /// `:reek:` comment directive).
23
+ Reek { class: &'static str, message: String },
24
+ }
25
+
26
+ impl ExamineError {
27
+ /// The `Reek::Errors` class Reek raises.
28
+ pub fn reek_class(&self) -> &'static str {
29
+ match self {
30
+ ExamineError::Source(error) => error.reek_class(),
31
+ ExamineError::Reek { class, .. } => class,
32
+ }
33
+ }
34
+
35
+ /// The error's message for `origin`.
36
+ pub fn message(&self, origin: &str) -> String {
37
+ match self {
38
+ ExamineError::Source(error) => error.message(origin),
39
+ ExamineError::Reek { message, .. } => message.clone(),
40
+ }
41
+ }
42
+ }
43
+
44
+ /// `wrap_exceptions`: Reek's own errors pass through; any other error is
45
+ /// reported as `IncomprehensibleSourceError`.
46
+ impl From<ContextError> for ExamineError {
47
+ fn from(error: ContextError) -> Self {
48
+ match error {
49
+ ContextError::Reek { class, message } => ExamineError::Reek { class, message },
50
+ ContextError::Unexpected(cause) => ExamineError::Source(SourceError::Incomprehensible(cause)),
51
+ }
52
+ }
53
+ }
54
+
55
+ /// `Examiner.new(source, filter_by_smells:, configuration:).smells`: every
56
+ /// detector (or only those named in `filter_by_smells`, when given) run on
57
+ /// every context, sorted by smell type, context, message and lines, with
58
+ /// duplicates removed.
59
+ pub fn examine(
60
+ source: &[u8],
61
+ origin: &str,
62
+ directive: &Directive,
63
+ filter_by_smells: &[String],
64
+ ) -> Result<Vec<SmellWarning>, ExamineError> {
65
+ let mut tree = syntax_tree(source, origin).map_err(ExamineError::Source)?;
66
+ // A file without code is examined as an `(empty)` node.
67
+ let root = match tree.root {
68
+ Some(root) => root,
69
+ None => tree.add(EMPTY, Vec::new(), None),
70
+ };
71
+ let contexts = ContextTree::build(&tree, root, origin)?;
72
+ let mut smells = Vec::new();
73
+ for context in contexts.each() {
74
+ smells.extend(detectors::examine(&contexts, context, directive, filter_by_smells)?);
75
+ }
76
+ smells.sort_by(|a, b| a.identifying_values().cmp(&b.identifying_values()));
77
+ smells.dedup_by(|a, b| a.identifying_values() == b.identifying_values());
78
+ Ok(smells)
79
+ }
80
+
81
+ /// The error `Examiner.new(source, configuration:).smells` raises.
82
+ #[derive(Clone, Debug, PartialEq)]
83
+ pub struct ExaminerError {
84
+ /// The class Reek raises: a `Reek::Errors` class, or `RegexpError` for a
85
+ /// bad directory pattern in the configuration.
86
+ pub class: String,
87
+ pub message: String,
88
+ /// The message of the exception Reek wrapped (the error's `cause`), if
89
+ /// any.
90
+ pub cause: Option<String>,
91
+ }
92
+
93
+ impl ExaminerError {
94
+ /// `configuration.directive_for(origin)` raised (in `Examiner.new`).
95
+ pub fn from_config(error: ConfigError) -> Self {
96
+ ExaminerError { class: error.class.to_string(), message: error.message, cause: None }
97
+ }
98
+
99
+ /// Examining the source for `origin` raised.
100
+ pub fn from_examine(error: ExamineError, origin: &str) -> Self {
101
+ let cause = match &error {
102
+ ExamineError::Source(
103
+ SourceError::Syntax(cause) | SourceError::Incomprehensible(cause) | SourceError::UnsupportedEncoding(cause),
104
+ ) => Some(cause.clone()),
105
+ _ => None,
106
+ };
107
+ ExaminerError { class: error.reek_class().to_string(), message: error.message(origin), cause }
108
+ }
109
+ }
110
+
111
+ /// `Examiner.new(Pathname(path), configuration: configuration,
112
+ /// filter_by_smells: filter_by_smells).smells`: chooses the directive for
113
+ /// the file, reads it and examines it. As in Reek, a file that cannot be
114
+ /// read is an `IncomprehensibleSourceError`.
115
+ pub fn examine_file(
116
+ path: &str,
117
+ configuration: &AppConfiguration,
118
+ filter_by_smells: &[String],
119
+ ) -> Result<Vec<SmellWarning>, ExaminerError> {
120
+ let directive = configuration.directive_for(path).map_err(ExaminerError::from_config)?;
121
+ let source = std::fs::read(path).map_err(|error| {
122
+ ExaminerError::from_examine(ExamineError::Source(SourceError::Incomprehensible(error.to_string())), path)
123
+ })?;
124
+ examine(&source, path, &directive, filter_by_smells).map_err(|error| ExaminerError::from_examine(error, path))
125
+ }
126
+
127
+ #[cfg(test)]
128
+ mod examine_file_tests {
129
+ use super::*;
130
+
131
+ fn write(name: &str, source: &str) -> String {
132
+ let directory = std::env::temp_dir().join(format!("reek-core-examine-file-{}", std::process::id()));
133
+ std::fs::create_dir_all(&directory).unwrap();
134
+ let path = directory.join(name);
135
+ std::fs::write(&path, source).unwrap();
136
+ path.to_string_lossy().into_owned()
137
+ }
138
+
139
+ #[test]
140
+ fn smells_of_a_file() {
141
+ let path = write("module.rb", "class Greeter\nend\n");
142
+ let smells = examine_file(&path, &AppConfiguration::default(), &[]).unwrap();
143
+ assert_eq!(smells.iter().map(|smell| smell.smell_type).collect::<Vec<_>>(), ["IrresponsibleModule"]);
144
+ assert_eq!(smells[0].source, path);
145
+ }
146
+
147
+ #[test]
148
+ fn a_syntax_error_wraps_prisms_message() {
149
+ let path = write("syntax.rb", "def a(\n");
150
+ let error = examine_file(&path, &AppConfiguration::default(), &[]).unwrap_err();
151
+ assert_eq!(error.class, "Reek::Errors::SyntaxError");
152
+ assert_eq!(
153
+ error.message,
154
+ format!("Source '{path}' cannot be processed by Reek due to a syntax error in the source file.")
155
+ );
156
+ assert!(error.cause.is_some());
157
+ }
158
+
159
+ #[test]
160
+ fn an_unreadable_file_is_incomprehensible() {
161
+ let error = examine_file("/nonexistent/reek-core.rb", &AppConfiguration::default(), &[]).unwrap_err();
162
+ assert_eq!(error.class, "Reek::Errors::IncomprehensibleSourceError");
163
+ assert_eq!(error.message, "Source /nonexistent/reek-core.rb cannot be processed by Reek.");
164
+ }
165
+ }
@@ -0,0 +1,21 @@
1
+ //! Reek 6.5.0's code smells, computed from Prism's syntax tree.
2
+
3
+ pub mod ast;
4
+ pub mod code_comment;
5
+ mod comments;
6
+ pub mod config;
7
+ pub mod context;
8
+ pub mod detectors;
9
+ mod encodings;
10
+ pub mod examiner;
11
+ pub mod node;
12
+ pub mod ruby_format;
13
+ pub mod ruby_inspect;
14
+ pub mod ruby_regexp;
15
+ mod single_byte_encodings;
16
+ pub mod source;
17
+ mod translate;
18
+ pub mod yaml;
19
+
20
+ /// The Reek version whose smells this crate reproduces.
21
+ pub const REEK_COMPAT: &str = "6.5.0";
@@ -0,0 +1,423 @@
1
+ //! Reek's `AST::SexpExtensions`: the methods Reek adds to nodes by type
2
+ //! (`name`, `full_name`, `parameters`, `condition`, `body_nodes`, ...).
3
+ //!
4
+ //! Reek gives each node type a class that includes the extension module
5
+ //! named after it (`SendNode` for `send`, `Op_AsgnNode` and `CSendNode`
6
+ //! alias `SendNode`, and so on). A method called on a node whose type has no
7
+ //! extension defining it raises `NoMethodError`, which Reek reports as
8
+ //! `Reek::Errors::IncomprehensibleSourceError`; those calls return
9
+ //! [`NoMethodError`] here.
10
+
11
+ use crate::ast::{Child, NodeId, Tree};
12
+
13
+ /// A method Reek called on a node that does not define it.
14
+ #[derive(Clone, Debug, PartialEq, Eq)]
15
+ pub struct NoMethodError {
16
+ pub method: &'static str,
17
+ pub node_type: &'static str,
18
+ }
19
+
20
+ impl std::fmt::Display for NoMethodError {
21
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22
+ write!(formatter, "undefined method '{}' for a {} node", self.method, self.node_type)
23
+ }
24
+ }
25
+
26
+ /// What `#name` returns.
27
+ #[derive(Clone, Debug, PartialEq, Eq, Hash)]
28
+ pub enum Name {
29
+ /// A Symbol: method, argument and variable names.
30
+ Symbol(String),
31
+ /// A String: constant and module names, `'lambda'`, and the `to_s`
32
+ /// (s-expression) of nodes without a `name` of their own.
33
+ String(String),
34
+ Nil,
35
+ }
36
+
37
+ impl Name {
38
+ /// `to_s`.
39
+ pub fn to_s(&self) -> &str {
40
+ match self {
41
+ Name::Symbol(name) | Name::String(name) => name,
42
+ Name::Nil => "",
43
+ }
44
+ }
45
+
46
+ /// `== :symbol`.
47
+ pub fn is_symbol(&self, symbol: &str) -> bool {
48
+ matches!(self, Name::Symbol(name) if name == symbol)
49
+ }
50
+
51
+ fn symbol(bytes: &[u8]) -> Name {
52
+ Name::Symbol(String::from_utf8_lossy(bytes).into_owned())
53
+ }
54
+ }
55
+
56
+ /// Node types whose extension includes `ArgNodeBase`.
57
+ const ARGUMENT_TYPES: [&str; 11] = [
58
+ "arg", "kwarg", "optarg", "kwoptarg", "blockarg", "restarg", "kwrestarg", "shadowarg", "forward_args",
59
+ "forward_arg", "kwnilarg",
60
+ ];
61
+
62
+ /// Variable node types whose `name` is their first child
63
+ /// (`VariableBase` and its aliases).
64
+ const VARIABLE_TYPES: [&str; 8] = ["cvar", "ivar", "ivasgn", "lvar", "gvar", "lvasgn", "cvasgn", "cvdecl"];
65
+
66
+ impl Tree {
67
+ /// The symbol child at `index`, as text.
68
+ pub fn symbol_child(&self, id: NodeId, index: usize) -> Option<String> {
69
+ self.children(id).get(index).and_then(Child::sym).map(|name| String::from_utf8_lossy(name).into_owned())
70
+ }
71
+
72
+ /// `node.name`.
73
+ pub fn name(&self, id: NodeId) -> Name {
74
+ let ty = self.ty(id);
75
+ let first_symbol_or_nil = || match self.children(id).first() {
76
+ Some(Child::Sym(name)) => Name::symbol(name),
77
+ _ => Name::Nil,
78
+ };
79
+ match ty {
80
+ _ if ARGUMENT_TYPES.contains(&ty) || VARIABLE_TYPES.contains(&ty) || ty == "sym" => first_symbol_or_nil(),
81
+ "const" => Name::String(self.const_name(id)),
82
+ "lambda" => Name::String("lambda".to_string()),
83
+ "def" => first_symbol_or_nil(),
84
+ "defs" | "send" | "op_asgn" | "csend" => match self.children(id).get(1) {
85
+ Some(Child::Sym(name)) => Name::symbol(name),
86
+ _ => Name::Nil,
87
+ },
88
+ "module" | "class" => Name::String(self.module_name(id)),
89
+ "casgn" => Name::String(self.symbol_child(id, 1).unwrap_or_default()),
90
+ "self" => Name::Symbol("self".to_string()),
91
+ "super" | "zsuper" => Name::Symbol("super".to_string()),
92
+ _ => Name::String(self.to_sexp(id)),
93
+ }
94
+ }
95
+
96
+ /// `ConstNode#name`: `namespace::simple_name`, the namespace as written.
97
+ fn const_name(&self, id: NodeId) -> String {
98
+ let simple_name = self.symbol_child(id, 1).unwrap_or_default();
99
+ match self.child_node(id, 0) {
100
+ Some(namespace) => format!("{}::{simple_name}", String::from_utf8_lossy(&self.format_to_ruby(namespace))),
101
+ None => simple_name,
102
+ }
103
+ }
104
+
105
+ /// `ModuleNodeBase#name`: the constant as written.
106
+ fn module_name(&self, id: NodeId) -> String {
107
+ let constant = self.child_node(id, 0).expect("a module has a name");
108
+ String::from_utf8_lossy(&self.format_to_ruby(constant)).into_owned()
109
+ }
110
+
111
+ /// `ConstNode#simple_name`: the last child, a Symbol.
112
+ pub fn const_simple_name(&self, id: NodeId) -> Option<String> {
113
+ self.symbol_child(id, 1)
114
+ }
115
+
116
+ /// `ConstantDefiningNodeBase#simple_name`: the name after the last `::`.
117
+ pub fn module_simple_name(&self, id: NodeId) -> String {
118
+ let name = self.name(id);
119
+ name.to_s().rsplit("::").next().unwrap_or_default().to_string()
120
+ }
121
+
122
+ /// `node.full_name(outer)`.
123
+ pub fn full_name(&self, id: NodeId, outer: &str) -> Result<String, NoMethodError> {
124
+ let ty = self.ty(id);
125
+ match ty {
126
+ "def" => {
127
+ let name = self.name(id);
128
+ Ok([outer, name.to_s()].iter().filter(|part| !part.is_empty()).copied().collect::<Vec<_>>().join("#"))
129
+ }
130
+ "defs" => {
131
+ let prefix = if outer.is_empty() { String::new() } else { format!("{outer}#") };
132
+ let receiver = self.child_node(id, 0).expect("defs has a receiver");
133
+ Ok(format!("{prefix}{}.{}", self.name(receiver).to_s(), self.name(id).to_s()))
134
+ }
135
+ "module" | "class" | "casgn" => {
136
+ let name = self.name(id);
137
+ Ok([outer, name.to_s()].iter().filter(|part| !part.is_empty()).copied().collect::<Vec<_>>().join("::"))
138
+ }
139
+ "sym" => Ok(format!("{outer}#{}", self.name(id).to_s())),
140
+ _ => Err(NoMethodError { method: "full_name", node_type: ty }),
141
+ }
142
+ }
143
+
144
+ // ------------------------------------------------------------------
145
+ // Arguments
146
+
147
+ /// `components`: argument nodes, with `args` and `mlhs` flattened.
148
+ pub fn components(&self, id: NodeId) -> Result<Vec<NodeId>, NoMethodError> {
149
+ let ty = self.ty(id);
150
+ if ty == "args" || ty == "mlhs" {
151
+ let mut out = Vec::new();
152
+ for child in self.children(id) {
153
+ match child.node() {
154
+ Some(child) => out.extend(self.components(child)?),
155
+ None => return Err(NoMethodError { method: "components", node_type: "non-node child" }),
156
+ }
157
+ }
158
+ Ok(out)
159
+ } else if ARGUMENT_TYPES.contains(&ty) {
160
+ Ok(vec![id])
161
+ } else {
162
+ Err(NoMethodError { method: "components", node_type: ty })
163
+ }
164
+ }
165
+
166
+ /// `block?`: a `&block` parameter.
167
+ pub fn is_block_parameter(&self, id: NodeId) -> bool {
168
+ self.ty(id) == "blockarg"
169
+ }
170
+
171
+ /// `optional_argument?`.
172
+ pub fn is_optional_argument(&self, id: NodeId) -> bool {
173
+ matches!(self.ty(id), "optarg" | "kwoptarg")
174
+ }
175
+
176
+ /// `anonymous_splat?`.
177
+ pub fn is_anonymous_splat(&self, id: NodeId) -> bool {
178
+ match self.ty(id) {
179
+ "restarg" | "kwrestarg" => self.name(id) == Name::Nil,
180
+ "forward_args" | "forward_arg" | "kwnilarg" => true,
181
+ _ => false,
182
+ }
183
+ }
184
+
185
+ /// `marked_unused?`: the name starts with `_`.
186
+ pub fn is_marked_unused(&self, id: NodeId) -> bool {
187
+ self.name(id).to_s().starts_with('_')
188
+ }
189
+
190
+ /// The argument list of a `def` or `defs`.
191
+ pub fn argslist(&self, id: NodeId) -> NodeId {
192
+ let index = if self.ty(id) == "defs" { 2 } else { 1 };
193
+ self.child_node(id, index).expect("a method has an argument list")
194
+ }
195
+
196
+ /// The body of a `def` or `defs`.
197
+ pub fn method_body(&self, id: NodeId) -> Option<NodeId> {
198
+ let index = if self.ty(id) == "defs" { 3 } else { 2 };
199
+ self.child_node(id, index)
200
+ }
201
+
202
+ /// `MethodNodeBase#parameters`.
203
+ pub fn parameters(&self, id: NodeId) -> Result<Vec<NodeId>, NoMethodError> {
204
+ self.components(self.argslist(id))
205
+ }
206
+
207
+ /// `MethodNodeBase#arguments`: the parameters except a `&block`.
208
+ pub fn arguments(&self, id: NodeId) -> Result<Vec<NodeId>, NoMethodError> {
209
+ Ok(self.parameters(id)?.into_iter().filter(|parameter| !self.is_block_parameter(*parameter)).collect())
210
+ }
211
+
212
+ /// `MethodNodeBase#arg_names`.
213
+ pub fn arg_names(&self, id: NodeId) -> Result<Vec<Name>, NoMethodError> {
214
+ Ok(self.arguments(id)?.into_iter().map(|argument| self.name(argument)).collect())
215
+ }
216
+
217
+ /// `MethodNodeBase#parameter_names`.
218
+ pub fn parameter_names(&self, id: NodeId) -> Result<Vec<Name>, NoMethodError> {
219
+ Ok(self.parameters(id)?.into_iter().map(|parameter| self.name(parameter)).collect())
220
+ }
221
+
222
+ /// `BlockNode#without_block_arguments?`.
223
+ pub fn is_block_without_arguments(&self, id: NodeId) -> Result<bool, NoMethodError> {
224
+ let args = self.child_node(id, 1).expect("a block has arguments");
225
+ Ok(self.components(args)?.is_empty())
226
+ }
227
+
228
+ // ------------------------------------------------------------------
229
+ // Conditionals
230
+
231
+ /// `node.condition`: the first child of `if`, `case`, `and` and `or`;
232
+ /// `nil` for every other node.
233
+ pub fn condition(&self, id: NodeId) -> Option<NodeId> {
234
+ match self.ty(id) {
235
+ "if" | "case" | "and" | "or" => self.child_node(id, 0),
236
+ _ => None,
237
+ }
238
+ }
239
+
240
+ /// `node.body_nodes(types, ignoring)`.
241
+ pub fn body_nodes(&self, id: NodeId, types: &[&str], ignoring: &[&str]) -> Result<Vec<NodeId>, NoMethodError> {
242
+ let both: Vec<&str> = union(ignoring, types);
243
+ match self.ty(id) {
244
+ "if" => Ok(self
245
+ .children(id)
246
+ .iter()
247
+ .skip(1)
248
+ .filter_map(Child::node)
249
+ .filter(|child| !ignoring.contains(&self.ty(*child)))
250
+ .flat_map(|child| self.each_node(child, types, &both))
251
+ .collect()),
252
+ "case" => Ok(self
253
+ .children(id)
254
+ .iter()
255
+ .skip(1)
256
+ .filter_map(Child::node)
257
+ .flat_map(|child| self.each_node(child, types, &both))
258
+ .collect()),
259
+ "and" | "or" => {
260
+ let right = self.child_node(id, 1).expect("a logical operator has two operands");
261
+ Ok(self.each_node(right, types, &both))
262
+ }
263
+ "def" | "defs" => {
264
+ let Some(body) = self.method_body(id) else { return Ok(Vec::new()) };
265
+ if ignoring.contains(&self.ty(body)) {
266
+ return Ok(Vec::new());
267
+ }
268
+ Ok(self.each_node(body, types, &both))
269
+ }
270
+ ty => Err(NoMethodError { method: "body_nodes", node_type: ty }),
271
+ }
272
+ }
273
+
274
+ /// `node.statements`: a `begin`'s children, otherwise the node itself.
275
+ pub fn statements(&self, id: NodeId) -> Vec<NodeId> {
276
+ if self.ty(id) == "begin" {
277
+ self.child_nodes(id).collect()
278
+ } else {
279
+ vec![id]
280
+ }
281
+ }
282
+
283
+ // ------------------------------------------------------------------
284
+ // Sends
285
+
286
+ /// `SendNode#receiver`.
287
+ pub fn receiver(&self, id: NodeId) -> Option<NodeId> {
288
+ self.child_node(id, 0)
289
+ }
290
+
291
+ /// `SendNode#args`: the children after the method name.
292
+ pub fn send_args(&self, id: NodeId) -> &[Child] {
293
+ let children = self.children(id);
294
+ if children.len() > 2 { &children[2..] } else { &[] }
295
+ }
296
+
297
+ /// `SendNode#object_creation_call?`: a call to `new`.
298
+ pub fn is_object_creation_call(&self, id: NodeId) -> bool {
299
+ self.name(id).is_symbol("new")
300
+ }
301
+
302
+ /// `SendNode#module_creation_call?`: `Class.new`, `Struct.new` or
303
+ /// `Data.define`.
304
+ pub fn is_module_creation_call(&self, id: NodeId) -> bool {
305
+ let receiver_simple_name = self
306
+ .receiver(id)
307
+ .filter(|receiver| self.ty(*receiver) == "const")
308
+ .and_then(|receiver| self.const_simple_name(receiver));
309
+ let Some(receiver_simple_name) = receiver_simple_name else { return false };
310
+ let name = self.name(id);
311
+ (name.is_symbol("new") && matches!(receiver_simple_name.as_str(), "Class" | "Struct"))
312
+ || (name.is_symbol("define") && receiver_simple_name == "Data")
313
+ }
314
+
315
+ /// `SendNode#attribute_writer?`: `attr_writer`, `attr_accessor`, or
316
+ /// `attr` with a final `true` argument.
317
+ pub fn is_attribute_writer(&self, id: NodeId) -> bool {
318
+ let name = self.name(id);
319
+ if name.is_symbol("attr_writer") || name.is_symbol("attr_accessor") {
320
+ return true;
321
+ }
322
+ name.is_symbol("attr")
323
+ && self.send_args(id).last().and_then(Child::node).is_some_and(|last| self.ty(last) == "true")
324
+ }
325
+
326
+ // ------------------------------------------------------------------
327
+ // Modules
328
+
329
+ /// `CasgnNode#defines_module?`.
330
+ pub fn defines_module(&self, id: NodeId) -> bool {
331
+ self.constant_definition(id).is_some_and(|call| self.is_module_creation_call(call))
332
+ }
333
+
334
+ /// `CasgnNode#constant_definition`: the `send` the constant is
335
+ /// assigned, directly or as a block's call.
336
+ fn constant_definition(&self, id: NodeId) -> Option<NodeId> {
337
+ let value = self.child_node(id, 2)?;
338
+ match self.ty(value) {
339
+ "block" => self.child_node(value, 0).filter(|call| self.ty(*call) == "send"),
340
+ "send" => Some(value),
341
+ _ => None,
342
+ }
343
+ }
344
+
345
+ /// `superclass` of a `class`, or of a `casgn` defining a module with
346
+ /// `Class.new(superclass)`.
347
+ pub fn superclass(&self, id: NodeId) -> Option<NodeId> {
348
+ match self.ty(id) {
349
+ "class" => self.child_node(id, 1),
350
+ "casgn" => {
351
+ if !self.defines_module(id) {
352
+ return None;
353
+ }
354
+ let definition = self.constant_definition(id)?;
355
+ let receiver = self.receiver(definition)?;
356
+ if self.name(receiver) == Name::String("Class".to_string()) {
357
+ self.send_args(definition).first().and_then(Child::node)
358
+ } else {
359
+ None
360
+ }
361
+ }
362
+ _ => None,
363
+ }
364
+ }
365
+
366
+ /// `ModuleNodeBase#direct_children`: the statements of the body.
367
+ pub fn direct_children(&self, id: NodeId) -> Vec<NodeId> {
368
+ match self.children(id).last().and_then(Child::node) {
369
+ Some(contents) => self.statements(contents),
370
+ None => Vec::new(),
371
+ }
372
+ }
373
+
374
+ // ------------------------------------------------------------------
375
+ // Methods
376
+
377
+ /// `depends_on_instance?`: a `def` that refers to `self`, `super`, an
378
+ /// instance variable, or calls a method without a receiver; never a
379
+ /// `defs`.
380
+ pub fn depends_on_instance(&self, id: NodeId) -> bool {
381
+ if self.ty(id) == "defs" {
382
+ return false;
383
+ }
384
+ let explicit = self.each_node(id, &["self", "super", "zsuper", "ivar", "ivasgn"], &[]);
385
+ !explicit.is_empty() || self.each_node(id, &["send"], &[]).iter().any(|send| self.receiver(*send).is_none())
386
+ }
387
+
388
+ /// `full_comment`: the attached comments' text, one per line.
389
+ pub fn full_comment(&self, id: NodeId) -> String {
390
+ let texts: Vec<String> = self
391
+ .node(id)
392
+ .comments
393
+ .iter()
394
+ .map(|index| String::from_utf8_lossy(&self.comments[*index].text).into_owned())
395
+ .collect();
396
+ texts.join("\n")
397
+ }
398
+
399
+ /// `leading_comment`: the attached comments on lines before the node.
400
+ pub fn leading_comment(&self, id: NodeId) -> String {
401
+ let line = self.line(id).expect("a commented node has a location");
402
+ let texts: Vec<String> = self
403
+ .node(id)
404
+ .comments
405
+ .iter()
406
+ .map(|index| &self.comments[*index])
407
+ .filter(|comment| self.line_for(comment.range.start) < line)
408
+ .map(|comment| String::from_utf8_lossy(&comment.text).into_owned())
409
+ .collect();
410
+ texts.join("\n")
411
+ }
412
+ }
413
+
414
+ /// `a | b` for arrays of types.
415
+ pub fn union<'a>(a: &[&'a str], b: &[&'a str]) -> Vec<&'a str> {
416
+ let mut out: Vec<&str> = Vec::with_capacity(a.len() + b.len());
417
+ for ty in a.iter().chain(b) {
418
+ if !out.contains(ty) {
419
+ out.push(ty);
420
+ }
421
+ }
422
+ out
423
+ }
@@ -0,0 +1,60 @@
1
+ //! Text formatting that matches Ruby's `to_s`.
2
+
3
+ /// Formats a float exactly as Ruby's `Float#to_s` does.
4
+ ///
5
+ /// Ruby prints the shortest digit string that round-trips. It uses fixed
6
+ /// notation when `-4 < decpt <= 16` and the value has a fraction, or when
7
+ /// `0 < decpt <= 15` and the value is integral; otherwise `d.ddde+XX`.
8
+ pub fn float_to_s(value: f64) -> String {
9
+ if value.is_nan() {
10
+ return "NaN".to_string();
11
+ }
12
+ if value.is_infinite() {
13
+ return if value > 0.0 { "Infinity" } else { "-Infinity" }.to_string();
14
+ }
15
+ if value == 0.0 {
16
+ return if value.is_sign_negative() { "-0.0" } else { "0.0" }.to_string();
17
+ }
18
+
19
+ // Rust's `{:e}` gives the shortest round-trip digits, e.g. "1.2345e6".
20
+ let formatted = format!("{:e}", value.abs());
21
+ let (mantissa, exponent) = formatted.split_once('e').expect("exponent form");
22
+ let digits: String = mantissa.chars().filter(|c| *c != '.').collect();
23
+ let exponent: i32 = exponent.parse().expect("exponent digits");
24
+ let decpt = exponent + 1;
25
+ let digit_count = digits.len() as i32;
26
+
27
+ let mut out = String::new();
28
+ if value < 0.0 {
29
+ out.push('-');
30
+ }
31
+
32
+ let fixed_with_fraction = decpt > 0 && decpt < digit_count && decpt <= 16;
33
+ let fixed_integral = decpt > 0 && decpt >= digit_count && decpt <= 15;
34
+
35
+ if fixed_with_fraction || fixed_integral {
36
+ if decpt >= digit_count {
37
+ out.push_str(&digits);
38
+ out.extend(std::iter::repeat_n('0', (decpt - digit_count) as usize));
39
+ out.push_str(".0");
40
+ } else {
41
+ out.push_str(&digits[..decpt as usize]);
42
+ out.push('.');
43
+ out.push_str(&digits[decpt as usize..]);
44
+ }
45
+ } else if decpt <= 0 && decpt > -4 {
46
+ out.push_str("0.");
47
+ out.extend(std::iter::repeat_n('0', (-decpt) as usize));
48
+ out.push_str(&digits);
49
+ } else {
50
+ out.push_str(&digits[..1]);
51
+ out.push('.');
52
+ if digit_count > 1 {
53
+ out.push_str(&digits[1..]);
54
+ } else {
55
+ out.push('0');
56
+ }
57
+ out.push_str(&format!("e{:+03}", decpt - 1));
58
+ }
59
+ out
60
+ }