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,280 @@
1
+ //! `Reek::Source::SourceCode#syntax_tree`: decoding, parsing, comment
2
+ //! association and dressing.
3
+ //!
4
+ //! Reek forces the file's bytes to UTF-8, then `Parser::Source::Buffer`
5
+ //! re-encodes them per the magic comment (`reencode_string`), rejects invalid
6
+ //! bytes, and replaces `"\r\n"` with `"\n"` before the parser lexes anything.
7
+ //! Reek's `Examiner#wrap_exceptions` turns failures into
8
+ //! `Reek::Errors::EncodingError`, `Reek::Errors::SyntaxError` and
9
+ //! `Reek::Errors::IncomprehensibleSourceError`.
10
+
11
+ use crate::ast::{Child, Comment, NodeId, Range, Tree};
12
+ use crate::comments::{self, ENCODING_RE};
13
+ use crate::encodings::ENCODINGS;
14
+ use crate::ruby_regexp::RubyRegexp;
15
+ use crate::single_byte_encodings::SINGLE_BYTE_ENCODINGS;
16
+ use crate::translate::translate;
17
+
18
+ /// Why Reek could not examine a file.
19
+ #[derive(Clone, Debug, PartialEq, Eq)]
20
+ pub enum SourceError {
21
+ /// `Reek::Errors::EncodingError`: Ruby raised `EncodingError` (invalid
22
+ /// bytes for the file's encoding, or bytes with no UTF-8 equivalent).
23
+ Encoding,
24
+ /// `Reek::Errors::SyntaxError`: the parser raised `Parser::SyntaxError`.
25
+ /// Holds Prism's first error message.
26
+ Syntax(String),
27
+ /// `Reek::Errors::IncomprehensibleSourceError`: any other error, such as
28
+ /// `Parser::UnknownEncodingInMagicComment`.
29
+ Incomprehensible(String),
30
+ /// The magic comment names an encoding this port does not transcode
31
+ /// (see DIVERGENCES.md). Reek would transcode the file to UTF-8.
32
+ UnsupportedEncoding(String),
33
+ }
34
+
35
+ impl SourceError {
36
+ /// The `Reek::Errors` class Reek raises.
37
+ pub fn reek_class(&self) -> &'static str {
38
+ match self {
39
+ SourceError::Encoding => "Reek::Errors::EncodingError",
40
+ SourceError::Syntax(_) => "Reek::Errors::SyntaxError",
41
+ SourceError::Incomprehensible(_) | SourceError::UnsupportedEncoding(_) => {
42
+ "Reek::Errors::IncomprehensibleSourceError"
43
+ }
44
+ }
45
+ }
46
+
47
+ /// The error's message, as Reek formats it for `origin`.
48
+ pub fn message(&self, origin: &str) -> String {
49
+ match self {
50
+ SourceError::Encoding => format!(
51
+ "Source '{origin}' cannot be processed by Reek due to an encoding error in the source file."
52
+ ),
53
+ SourceError::Syntax(_) => {
54
+ format!("Source '{origin}' cannot be processed by Reek due to a syntax error in the source file.")
55
+ }
56
+ SourceError::Incomprehensible(_) | SourceError::UnsupportedEncoding(_) => {
57
+ format!("Source {origin} cannot be processed by Reek.")
58
+ }
59
+ }
60
+ }
61
+ }
62
+
63
+ /// A file's decoded source, as `Parser::Source::Buffer#source` holds it.
64
+ pub struct DecodedSource {
65
+ /// UTF-8 bytes, or the file's own bytes when it is `ASCII-8BIT`.
66
+ pub bytes: Vec<u8>,
67
+ /// The buffer is `ASCII-8BIT`: the parser counts positions in bytes,
68
+ /// not characters.
69
+ pub binary: bool,
70
+ /// The bytes were transcoded to UTF-8 from the encoding the magic
71
+ /// comment names, so the comment no longer describes them.
72
+ pub transcoded: bool,
73
+ }
74
+
75
+ /// Parses `source` as `SourceCode#syntax_tree` does. `origin` is the file
76
+ /// name the parser sees (`__FILE__`).
77
+ pub fn syntax_tree(source: &[u8], origin: &str) -> Result<Tree, SourceError> {
78
+ let decoded = decode(source)?;
79
+ let mut tree = Tree::new(decoded.bytes);
80
+ tree.binary = decoded.binary;
81
+
82
+ let mut options = ruby_prism::Options::default()
83
+ .filepath(origin)
84
+ .partial_script(true)
85
+ .version(ruby_prism::Version::CRuby3_3);
86
+ if decoded.transcoded {
87
+ options = options.encoding("UTF-8").encoding_locked(true);
88
+ }
89
+ let options = options.build();
90
+ let source = tree.source.clone();
91
+ let parse_result = ruby_prism::parse_with_options(&source, &options);
92
+ if let Some(error) = parse_result.errors().next() {
93
+ return Err(SourceError::Syntax(String::from_utf8_lossy(error.message()).into_owned()));
94
+ }
95
+
96
+ tree.comments = parse_result
97
+ .comments()
98
+ .map(|comment| {
99
+ let location = comment.location();
100
+ let range = Range::new(location.start(), location.end());
101
+ Comment { range, text: location.as_slice().to_vec() }
102
+ })
103
+ .collect();
104
+ tree.root = translate(&mut tree, &parse_result.node(), origin.as_bytes());
105
+ check_static_regexps(&tree)?;
106
+ comments::associate(&mut tree);
107
+ Ok(tree)
108
+ }
109
+
110
+ /// The encoding checks of the parser gem's `static_regexp`, which
111
+ /// `regexp_compose` runs on every regexp whose parts are all strings: the
112
+ /// source is encoded as the `n` option asks, then compiled. Encoding invalid
113
+ /// bytes raises `EncodingError`; an unencodable character
114
+ /// (`Encoding::UndefinedConversionError`) or an invalid multibyte character
115
+ /// (`RegexpError`) is reported as a syntax error. Other `RegexpError`s are
116
+ /// left to Prism's own regexp checks.
117
+ fn check_static_regexps(tree: &Tree) -> Result<(), SourceError> {
118
+ if tree.binary {
119
+ return Ok(());
120
+ }
121
+ let mut regexps: Vec<NodeId> = (0..tree.nodes.len() as u32).map(NodeId).filter(|id| tree.ty(*id) == "regexp").collect();
122
+ regexps.sort_by_key(|id| tree.expression(*id).map(|range| range.start));
123
+ for regexp in regexps {
124
+ let children = tree.children(regexp);
125
+ let (options, parts) = children.split_last().expect("a regexp has options");
126
+ let options = tree.children(options.node().expect("regopt node"));
127
+ let string_values: Option<Vec<&[u8]>> = parts
128
+ .iter()
129
+ .map(|part| match tree.children(part.node()?) {
130
+ [Child::Str(value)] if tree.ty(part.node()?) == "str" => Some(&**value),
131
+ _ => None,
132
+ })
133
+ .collect();
134
+ let Some(string_values) = string_values else { continue };
135
+ let source = string_values.concat();
136
+ let has_option = |letter: &[u8]| options.iter().any(|option| option.sym() == Some(letter));
137
+ let valid_utf8 = std::str::from_utf8(&source).is_ok();
138
+ if has_option(b"u") || !(has_option(b"e") || has_option(b"s") || has_option(b"n")) {
139
+ if !valid_utf8 {
140
+ return Err(SourceError::Syntax("invalid multibyte character".to_string()));
141
+ }
142
+ } else if has_option(b"n") && !has_option(b"e") && !has_option(b"s") {
143
+ if !valid_utf8 {
144
+ return Err(SourceError::Encoding);
145
+ }
146
+ if !source.is_ascii() {
147
+ return Err(SourceError::Syntax("unencodable character in a /n regexp".to_string()));
148
+ }
149
+ }
150
+ }
151
+ Ok(())
152
+ }
153
+
154
+ /// `Buffer#source=`: `reencode_string`, the `valid_encoding?` check and the
155
+ /// `"\r\n"` replacement.
156
+ pub fn decode(source: &[u8]) -> Result<DecodedSource, SourceError> {
157
+ let decoded = match recognize_encoding(source)? {
158
+ None | Some("UTF-8") => DecodedSource { bytes: validate_utf8(source)?, binary: false, transcoded: false },
159
+ Some("ASCII-8BIT") => DecodedSource { bytes: source.to_vec(), binary: true, transcoded: false },
160
+ Some(_) if source.is_ascii() => DecodedSource { bytes: source.to_vec(), binary: false, transcoded: false },
161
+ Some("US-ASCII") => return Err(SourceError::Encoding),
162
+ Some(name) => DecodedSource { bytes: transcode_to_utf8(source, name)?, binary: false, transcoded: true },
163
+ };
164
+ Ok(DecodedSource { bytes: replace_crlf(&decoded.bytes), ..decoded })
165
+ }
166
+
167
+ /// `force_encoding(encoding).encode(Encoding::UTF_8)`. Bytes that are
168
+ /// invalid in the encoding, or have no UTF-8 equivalent, raise an
169
+ /// `EncodingError`. Single-byte encodings use Ruby's own tables; the
170
+ /// multibyte ones use the WHATWG Encoding Standard's (see DIVERGENCES.md).
171
+ fn transcode_to_utf8(source: &[u8], ruby_name: &str) -> Result<Vec<u8>, SourceError> {
172
+ if let Some((_, characters)) = SINGLE_BYTE_ENCODINGS.iter().find(|(name, _)| *name == ruby_name) {
173
+ return transcode_single_byte(source, characters);
174
+ }
175
+ let encoding = match ruby_name {
176
+ "Shift_JIS" | "Windows-31J" => encoding_rs::SHIFT_JIS,
177
+ "EUC-JP" => encoding_rs::EUC_JP,
178
+ "GBK" => encoding_rs::GBK,
179
+ "GB18030" => encoding_rs::GB18030,
180
+ "Big5" => encoding_rs::BIG5,
181
+ "EUC-KR" => encoding_rs::EUC_KR,
182
+ other => return Err(SourceError::UnsupportedEncoding(other.to_string())),
183
+ };
184
+ match encoding.decode_without_bom_handling_and_without_replacement(source) {
185
+ Some(decoded) => Ok(decoded.into_owned().into_bytes()),
186
+ None => Err(SourceError::Encoding),
187
+ }
188
+ }
189
+
190
+ /// Each byte is the character in `characters`, else the code point with the
191
+ /// same number.
192
+ fn transcode_single_byte(source: &[u8], characters: &[(u8, Option<char>)]) -> Result<Vec<u8>, SourceError> {
193
+ let mut table: [Option<char>; 256] = std::array::from_fn(|byte| char::from_u32(byte as u32));
194
+ for (byte, character) in characters {
195
+ table[usize::from(*byte)] = *character;
196
+ }
197
+ let text: Option<String> = source.iter().map(|byte| table[usize::from(*byte)]).collect();
198
+ text.map(String::into_bytes).ok_or(SourceError::Encoding)
199
+ }
200
+
201
+ /// `Buffer.recognize_encoding`: the encoding named by a BOM or by an
202
+ /// encoding comment on the first line (the second after a shebang).
203
+ fn recognize_encoding(source: &[u8]) -> Result<Option<&'static str>, SourceError> {
204
+ if source.is_empty() {
205
+ return Ok(None);
206
+ }
207
+ // `string =~ /\A(.*)\n?(.*\n)?/`
208
+ let (first_line, rest) = match source.iter().position(|byte| *byte == b'\n') {
209
+ Some(index) => (&source[..index], &source[index + 1..]),
210
+ None => (source, &source[source.len()..]),
211
+ };
212
+ let second_line = rest.iter().position(|byte| *byte == b'\n').map(|index| &rest[..=index]);
213
+
214
+ if first_line.starts_with(b"\xef\xbb\xbf") {
215
+ return Ok(Some("UTF-8"));
216
+ }
217
+ let encoding_line = if first_line.starts_with(b"#!") { second_line } else { Some(first_line) };
218
+ let Some(encoding_line) = encoding_line else { return Ok(None) };
219
+ if encoding_line.first() != Some(&b'#') {
220
+ return Ok(None);
221
+ }
222
+
223
+ let encoding_re = RubyRegexp::new(ENCODING_RE, "x").expect("encoding regexp");
224
+ let Some(groups) = encoding_re.captures(encoding_line) else { return Ok(None) };
225
+ // `result[3] || result[4] || result[6]`
226
+ let (start, end) = groups[3].or(groups[4]).or(groups[6]).expect("ENCODING_RE captures a name");
227
+ let name = String::from_utf8_lossy(&encoding_line[start..end]).to_lowercase();
228
+ match ENCODINGS.iter().find(|(alias, _, _)| *alias == name) {
229
+ Some((_, canonical, _)) => Ok(Some(canonical)),
230
+ // `Encoding.find` raises `ArgumentError`, re-raised as
231
+ // `Parser::UnknownEncodingInMagicComment`.
232
+ None => Err(SourceError::Incomprehensible(format!("unknown encoding name - {name}"))),
233
+ }
234
+ }
235
+
236
+ fn validate_utf8(source: &[u8]) -> Result<Vec<u8>, SourceError> {
237
+ match std::str::from_utf8(source) {
238
+ Ok(_) => Ok(source.to_vec()),
239
+ Err(_) => Err(SourceError::Encoding),
240
+ }
241
+ }
242
+
243
+ fn replace_crlf(source: &[u8]) -> Vec<u8> {
244
+ let mut out = Vec::with_capacity(source.len());
245
+ let mut index = 0;
246
+ while index < source.len() {
247
+ if source[index] == b'\r' && source.get(index + 1) == Some(&b'\n') {
248
+ index += 1;
249
+ continue;
250
+ }
251
+ out.push(source[index]);
252
+ index += 1;
253
+ }
254
+ out
255
+ }
256
+
257
+ #[cfg(test)]
258
+ mod tests {
259
+ use super::*;
260
+
261
+ #[test]
262
+ fn recognizes_magic_comments() {
263
+ assert_eq!(recognize_encoding(b"# encoding: binary\n"), Ok(Some("ASCII-8BIT")));
264
+ assert_eq!(recognize_encoding(b"#!/usr/bin/env ruby\n# -*- coding: utf-8 -*-\n"), Ok(Some("UTF-8")));
265
+ assert_eq!(recognize_encoding(b"#!/usr/bin/env ruby\n# coding: utf-8"), Ok(None));
266
+ assert_eq!(recognize_encoding(b"x = 1 # encoding: binary\n"), Ok(None));
267
+ assert!(matches!(recognize_encoding(b"# encoding: utf8\n"), Err(SourceError::Incomprehensible(_))));
268
+ }
269
+
270
+ #[test]
271
+ fn invalid_utf8_is_an_encoding_error() {
272
+ assert!(matches!(decode(b"x = \"\xff\"\n"), Err(SourceError::Encoding)));
273
+ assert!(decode(b"# encoding: binary\nx = \"\xff\"\n").unwrap().binary);
274
+ }
275
+
276
+ #[test]
277
+ fn crlf_becomes_lf() {
278
+ assert_eq!(decode(b"a\r\nb\r\r\n").unwrap().bytes, b"a\nb\r\n");
279
+ }
280
+ }